Compare commits

...
Author SHA1 Message Date
Timon 6015864c1f Animate the glide of moved nodes and the hover of connectors in the graph UI 2026-12-06 18:00:24 +00:00
Timon 64a767b94e Draw overlays that change without new artwork, and composite once per overlay change while the graph is open 2026-12-06 17:57:47 +00:00
Timon 2e26ebf123 Pass no graph UI config in the clipping tests (fixup for the graph UI commit on the new master) 2026-12-06 17:57:47 +00:00
Timon df1434ddff Implement Graphene base graph UI 2026-12-06 17:57:47 +00:00
Timon 13bb1687b9 Add the graph-ui crate, which draws the node graph with Graphene 2026-12-06 17:57:47 +00:00
Timon 674221fbc3 Add transient nodes that are exempt from versions and migration checks (#5098)
* Add the transient node attribute for nodes that are never saved

* Refuse to save transient nodes

* Leave transient nodes out of the migration checks and the corpus coverage

* Mark the render chain, scope and resource nodes as transient

* Document the transient attribute
2026-12-06 17:23:44 +00:00
Dennis Kobert 1300b4f92a Identify conversion nodes via node macro annotations (#5083)
Flag adapter nodes and register them by identifier
2026-12-06 13:57:52 +00:00
Timon c0778752ab Fix running out of GPU memory from textures allocated outside the shared texture cache (#5070)
* Give the Vello renderer the executor and pool textures with mip levels

* Take split and grown render targets from the texture pool (fixup #4821, #5063)

* Take the premultiplied render target from the texture pool (fixup #4807)

* Premultiply textures drawn as images into texture pool copies (fixup #4807)

* Take effect textures from the texture pool (fixup #4976, #5023)

* Park generator tiles in the texture pool (fixup #5008, #5009, #5010)

* Park image uploads and adjusted copies in the texture pool (fixup #4807, #4855, #4908, #4997, #5037)

* Park adjustment uploads in the texture pool (fixup #4997)

* Take effect row textures and Mandelbrot reference orbits from the texture pool (fixup #5010)

* Review
2026-12-06 13:49:37 +00:00
Timon 27cded81af Utilize executor multi-output capabilities in runtime (#5084)
* Free executor nodes once no output reaches them, and let an export keep its output instead of blocking the runtime

* Answer an export on a channel of its own, so the viewport's answers stay in order

* Render a copy's SVG as an export of the copied layers' own network

* Record in the executor which paths' types changed, to be taken with take_type_changes

* Prepare every network in the node graph executor, and send the runtime the thumbnail sources instead of the previews and layers
2026-12-06 13:48:46 +00:00
d5fdb12320 Desktop: Fix rendering getting stuck on stale WGPU surfaces (#4966)
Reconfigure WGPU surface and request redraw on Outdated

Co-authored-by: Carlos Ferrabone <[email protected]>
Co-authored-by: Timon <[email protected]>
2026-12-06 13:42:47 +00:00
Dennis Kobert 436c943196 Hash vector modifications deterministically instead of with a random ID (#5082) 2026-12-05 12:33:12 +01:00
Keavon Chambers 5add0191f4 Make middle-clicking a node toggle its visibility in the node graph, Inspector, and Layers panels (#5080) 2026-12-04 16:22:27 -08:00
Timon c7e9aaa016 Fix value nodes leaking source map rows on every graph compile (#5078)
* Fix value nodes leaking source map rows on every graph compile

* Update the flatten test for value nodes without a document path
2026-12-04 19:22:18 +00:00
Keavon Chambers 9c9b393420 Rename the 'Add Noise' node to 'Speckle' (#5073) 2026-12-04 10:27:02 +00:00
Keavon Chambers 01c5455ecf Fix the 'Clipping Mask' node not clipping endless color, gradient, and generator layers (#5072) 2026-12-04 01:21:12 -08:00
Keavon Chambers 41586d6967 Add the blend modes Linear Burn, Darker Color, Linear Dodge (Add), Lighter Color, Vivid Light, Linear Light, Pin Light, Hard Mix, Subtract, and Divide (#5067)
Allow layers to use every blend mode
2026-12-03 15:56:34 -08:00
Keavon Chambers 7c37cc504b Fix how Darker Color, Lighter Color, Hard Mix, and Color Dodge blend (#5066) 2026-12-03 14:48:39 -08:00
Keavon Chambers e30bf2e987 New node: 'Blend If' (#5065)
Add Blend If, hiding content by its own tones and those beneath it
2026-12-03 04:03:46 -08:00
Timon c8e8fbf8d1 Park render cache tiles out of view in the texture pool (#5060) 2026-12-03 11:28:26 +00:00
Keavon Chambers 9517b006fa New node: 'Background Blur' (#5063)
Add a Background Blur effect that blurs what lies beneath the content
2026-12-03 02:35:26 -08:00
Keavon Chambers cfb45f2d54 Make snap targets woken during a drag go back to sleep when the drag ends (#5064) 2026-12-02 17:05:58 -08:00
Keavon Chambers e27119b58b Change the 'Mask' node's Luminance weights to 0.3, 0.59, 0.11, and add a Luminance (SVG) mode (#5062) 2026-12-02 14:50:26 -08:00
Aditya Amol Kuchekar ebc49b40fc Fix removing a history step after a node's inputs shrink (#5029)
The repair emitted a write to an input index the node no longer had, and
strict application of repair ops rejected it, so the whole step removal
failed and the History panel did nothing.
2026-12-02 13:04:36 +00:00
Keavon Chambers 2cb8aed218 Add Noise and Jitter to the 'Outer Glow' and 'Inner Glow' nodes (#5059)
Add Noise and Jitter to the Outer Glow and Inner Glow effects
2026-12-02 02:59:54 -08:00
Keavon Chambers 91b4072df6 New nodes: 'Pixelate' and 'Color Halftone' (#5057)
Add Pixelate and Color Halftone effects to any graphic
2026-12-02 01:21:10 -08:00
Keavon Chambers bb2514d816 Add a strength percentage to the 'Make Opaque' node (#5058) 2026-12-02 00:03:39 -08:00
Keavon Chambers 19df13ad1d New node: 'Warp' (#5056)
Add a Warp effect bending any graphic into 15 preset shapes
2026-12-01 22:52:49 -08:00
Keavon Chambers a412979a7f New nodes: 'Ripple', 'Wave', and 'Displace' (#5055)
Add Ripple, Wave, and Displace effects
2026-12-01 17:03:33 -08:00
Keavon Chambers 738ea6ac20 New nodes: 'Twirl', 'Pinch', 'Spherize', and 'Polar Coordinates' (#5042)
Add Twirl, Pinch, Spherize, and Polar Coordinates effects
2026-12-01 16:32:11 -08:00
Keavon Chambers d6ee55b86a Fix the 'Noise Pattern' node to use gamma so its 0.5 values show as middle gray (#5053)
Fix 'Noise Pattern' so its value of 0.5 shows as middle gray, like 'Mandelbrot'
2026-12-01 20:14:40 +00:00
TimonandDennis Kobert 33dd5e545a Move the node graph's hit testing and bounds to the layout (#5049)
* Cache the measured width of a layer's name along with the layer's width

* Derive network bounds and import/export clearance from the layout

* Hit-test node graph nodes with analytic click targets built from the layout

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-12-01 13:21:21 +00:00
Keavon Chambers 4f0d8c7f4c Update the website roadmap further 2026-11-30 19:27:43 -08:00
Keavon Chambers 1335e9a0f8 Make effect paints fit gradients like Fill and draw images where they're placed (#5047)
* Make effect paints draw images where they're placed rather than stretched

* Make effect paints fit gradients like Fill, including across text
2026-11-30 19:22:13 -08:00
Timon 89238b669a Remove the node graph's Alt+C overlay, hide viewport overlays while the graph is open, and move compositing out of run_viewport (#5048)
* Move the node graph executor's test-only functions into its test module

* Drop the unused serde derives from the graph runtime's request types

* Composite the viewport frame once per run and execute the render output through its handle

* Draw no viewport overlays while the node graph is open

* Remove the Alt+C click target debug overlay from the node graph
2026-11-30 17:55:00 +00:00
Timon da2c5a2d13 Prepare the executor and runtime for a node graph drawn by Graphene (#5044)
* Borrow the input in LazyInput::eval, as Node::eval does

* Allow wrapping a network in scope without the render node

* Implement CacheHash for BTreeMap

* Replace the CanvasFrame render output with canvas info on the response

* Add OwnedContextImpl::with_varargs for a context with several varargs
2026-11-30 17:43:42 +00:00
Keavon Chambers c75ebbd143 Anchor the Motion Blur node's shear at the content's local origin instead of its bounds (#5046)
Anchor Motion Blur's shear at the content's local origin
2026-11-29 17:04:43 -08:00
Keavon Chambers addba860d3 Fix the Satin effect's contour shaping the difference instead of each copy (#5043)
Apply the Satin effect's contour to each copy before their difference
2026-11-29 16:21:01 -08:00
Keavon Chambers 9526711aa2 New nodes: 'Motion Blur' and 'Radial Blur' (#5040)
Add Motion Blur and Radial Blur effects to any graphic
2026-11-29 15:48:02 -08:00
Keavon Chambers d8b9f67adb Update the website roadmap 2026-11-28 11:26:23 -08:00
Keavon Chambers b149248db9 New nodes: 'Add Noise' and 'Dissolve' (#5039)
Add seeded Add Noise and Dissolve filters fixed in place on the content
2026-11-28 03:29:08 -08:00
Keavon Chambers 7b4dc4d8a7 New nodes: 'Sharpen' and 'High Pass' (#5038)
Add Sharpen and High Pass filters, and Apply to Alpha to Convolution Kernel
2026-11-28 01:44:59 -08:00
Keavon Chambers feea64170a Fix images with adjustments breaking apart when zoomed out on WebGL (#5037) 2026-11-27 23:18:06 -08:00
Keavon Chambers 6541449a4a New nodes: 'Emboss', 'Find Edges', 'Solarize', and 'Minimum/Maximum' (#5036)
Add Emboss, Find Edges, Solarize, and neighborhood min/max filters
2026-11-27 22:17:27 -08:00
Keavon Chambers 5e92356578 New node: 'Convolution Kernel' (#5034)
* Add a Convolution Kernel filter weighting pixels by a grid of numbers

* Make the 'Blur' node's Box Blur exact in SVG and with a Radius Mask
2026-11-27 19:23:00 -08:00
Keavon Chambers 3ca1376f93 Make clipped layers follow their base's filters but not its cast styles (#5035) 2026-11-27 17:11:39 -08:00
Dennis Kobert 93d2738a23 Restore group indentation when removing layers and revise Ctrl-dragging (#5032)
* Keep a removed layer's offset on the layer replacing it

* Move a layer's chain and stack when dragging with Ctrl

* Follow the wire's route with its center line

* Only write a node's layer flag when it changes
2026-11-27 16:09:43 -08:00
Keavon Chambers 9557c6adfc Allow the 'Blur' node to vary its radius by a mask (#5033) 2026-11-26 23:40:15 -08:00
Keavon Chambers 6c3232ee8c Add a "New Custom Node" button to replace the 'Custom Node' catalog node (#5030) 2026-11-26 04:37:18 -08:00
267 changed files with 46293 additions and 7326 deletions

No files matched your search

+1 -7
View File
@@ -150,20 +150,14 @@ jobs:
run: cargo run build web${{ inputs.debug && ' debug' || '' }} run: cargo run build web${{ inputs.debug && ' debug' || '' }}
- name: 📤 Publish to Cloudflare Pages - name: 📤 Publish to Cloudflare Pages
if: inputs.merge_queue == false if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
id: cloudflare id: cloudflare
continue-on-error: ${{ github.event_name != 'push' }}
env: env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
# Passed through the environment so a branch name can't inject shell syntax # Passed through the environment so a branch name can't inject shell syntax
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }} HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
run: | run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
echo "No Cloudflare API token available (fork PR), skipping deploy."
exit 0
fi
if [ "${{ github.event_name }}" = "push" ]; then if [ "${{ github.event_name }}" = "push" ]; then
DEPLOY_BRANCH="master" DEPLOY_BRANCH="master"
else else
+7 -2
View File
@@ -7,6 +7,8 @@ on:
push: push:
branches: branches:
- master - master
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
workflow_dispatch: {}
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other) # Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
concurrency: concurrency:
@@ -245,7 +247,8 @@ jobs:
permissions: permissions:
contents: read contents: read
env: env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} # A manual run has no base commit of its own, so it compares against master
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
steps: steps:
- name: 📥 Clone repository - name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -259,7 +262,9 @@ jobs:
rustflags: "" rustflags: ""
- name: 📥 Fetch the base commit - name: 📥 Fetch the base commit
run: git fetch --depth=1 origin "$BASE_SHA" run: |
git fetch --depth=1 origin "$BASE_REF"
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
- name: 🔬 Check migrations against the base commit - name: 🔬 Check migrations against the base commit
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA" run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
@@ -51,6 +51,8 @@ jobs:
with: with:
# Cache on Cargo.lock file # Cache on Cargo.lock file
cache-on-failure: true cache-on-failure: true
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
save-if: ${{ github.event_name == 'push' }}
- name: Install gungraun-runner and valgrind - name: Install gungraun-runner and valgrind
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3 uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
Generated
+43
View File
@@ -590,6 +590,7 @@ dependencies = [
"node-macro", "node-macro",
"raster-kernels", "raster-kernels",
"serde", "serde",
"text-nodes",
"vector-types", "vector-types",
] ]
@@ -2497,6 +2498,7 @@ dependencies = [
"futures", "futures",
"glam", "glam",
"graph-craft", "graph-craft",
"graph-ui-types",
"graphene-animation", "graphene-animation",
"graphene-application-io", "graphene-application-io",
"graphene-canvas-utils", "graphene-canvas-utils",
@@ -2534,6 +2536,44 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "graph-ui"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graph-craft",
"graph-ui-icons",
"graph-ui-types",
"graphene-std",
"graphic-types",
"node-macro",
"rendering",
"svg-convert",
"text-nodes",
"vector-types",
"vello_gpu",
]
[[package]]
name = "graph-ui-icons"
version = "0.0.0"
[[package]]
name = "graph-ui-types"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"graph-layout",
"graphene-hash",
"graphic-types",
"serde",
"tsify",
"wasm-bindgen",
]
[[package]] [[package]]
name = "graphene-animation" name = "graphene-animation"
version = "0.0.0" version = "0.0.0"
@@ -2872,6 +2912,7 @@ dependencies = [
"glam", "glam",
"graph-craft", "graph-craft",
"graph-layout", "graph-layout",
"graph-ui",
"graphene-hash", "graphene-hash",
"graphene-std", "graphene-std",
"graphite-proc-macros", "graphite-proc-macros",
@@ -5745,6 +5786,7 @@ dependencies = [
"glam", "glam",
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"half",
"log", "log",
"raster-types", "raster-types",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -6019,6 +6061,7 @@ dependencies = [
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"kurbo", "kurbo",
"linesweeper",
"log", "log",
"num-traits", "num-traits",
"parley", "parley",
+6
View File
@@ -34,6 +34,9 @@ members = [
"node-graph/libraries/*", "node-graph/libraries/*",
"node-graph/nodes/*", "node-graph/nodes/*",
"node-graph/graph-craft", "node-graph/graph-craft",
"node-graph/graph-ui",
"node-graph/graph-ui/icons",
"node-graph/graph-ui/types",
"node-graph/graphene-cli", "node-graph/graphene-cli",
"node-graph/nodes/gstd", "node-graph/nodes/gstd",
"node-graph/interpreted-executor", "node-graph/interpreted-executor",
@@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
math-nodes = { path = "node-graph/nodes/math" } math-nodes = { path = "node-graph/nodes/math" }
path-bool-nodes = { path = "node-graph/nodes/path-bool" } path-bool-nodes = { path = "node-graph/nodes/path-bool" }
graph-craft = { path = "node-graph/graph-craft" } graph-craft = { path = "node-graph/graph-craft" }
graph-ui = { path = "node-graph/graph-ui" }
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
graph-ui-types = { path = "node-graph/graph-ui/types" }
document-format = { path = "document/format" } document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false } document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" } document-container = { path = "document/container" }
+5 -2
View File
@@ -234,7 +234,11 @@ impl RenderState {
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true), WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
WgpuCurrentSurfaceTexture::Occluded => return Ok(()), WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost), WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated), WgpuCurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.executor.context().device, &self.config);
window.request_redraw();
return Ok(());
}
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout), WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation), WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
}; };
@@ -327,7 +331,6 @@ impl RenderState {
pub(crate) enum RenderError { pub(crate) enum RenderError {
OutdatedUITextureError, OutdatedUITextureError,
SurfaceLost, SurfaceLost,
SurfaceOutdated,
SurfaceTimeout, SurfaceTimeout,
SurfaceValidation, SurfaceValidation,
} }
+7 -1
View File
@@ -44,6 +44,8 @@ pub enum ConversionError {
IndexOverflow(usize), IndexOverflow(usize),
#[error("Node ID {0} is used by more than one node in the document")] #[error("Node ID {0} is used by more than one node in the document")]
DuplicateNodeId(u64), DuplicateNodeId(u64),
#[error("The transient node {0} cannot be saved")]
TransientNode(String),
} }
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for /// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
@@ -559,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
} }
// Nodes the binary doesn't register, such as in tests, are at their first version // Nodes the binary doesn't register, such as in tests, are at their first version
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1); let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
let (version, flags) = registered.unwrap_or((1, Default::default()));
if flags.transient {
return Err(ConversionError::TransientNode(identifier_str));
}
let EncodedDeclaration { id, hash, bytes, proto } = let EncodedDeclaration { id, hash, bytes, proto } =
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?; EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
+5 -3
View File
@@ -406,9 +406,11 @@ fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input:
match slot { match slot {
Slot::Input(id, index) => { Slot::Input(id, index) => {
let Some(input) = input else { return }; let Some(input) = input else { return };
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) { // A chain the line no longer holds the slot for, as shrinking a node's inputs leaves, is not written back
slot.input = input.clone(); let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) else {
} return;
};
slot.input = input.clone();
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input }); ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
} }
Slot::Export(id, index) => { Slot::Export(id, index) => {
@@ -2,7 +2,7 @@
//! operation mixed in. After every operation nothing may name a node the document no longer has. //! operation mixed in. After every operation nothing may name a node the document no longer has.
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value}; use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session}; use crate::{Implementation, InputSlot, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp};
/// A slot that can name a node. /// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -94,14 +94,16 @@ impl Scenario for Branching {
node.inputs[1].input = second; node.inputs[1].input = second;
node node
}; };
// Nodes that still have an input past the primary one, the only ones an edit may write there
let wide: Vec<NodeId> = nodes.iter().copied().filter(|id| registry.node_instances[id].inputs.len() > 1).collect();
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind // Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
let plain: Vec<NodeId> = nodes let plain: Vec<NodeId> = wide
.iter() .iter()
.copied() .copied()
.filter(|id| !matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. }))) .filter(|id| !matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect(); .collect();
match random.below(12) { match random.below(14) {
// Draw a node on top of the chain off the export // Draw a node on top of the chain off the export
0..=2 => { 0..=2 => {
let id = session.next_node_id(); let id = session.next_node_id();
@@ -122,7 +124,7 @@ impl Scenario for Branching {
} }
// Hang a node on an input past the primary one, over whatever is there already // Hang a node on an input past the primary one, over whatever is there already
3..=5 => { 3..=5 => {
let Some(host) = random.pick(&nodes) else { return Vec::new() }; let Some(host) = random.pick(&wide) else { return Vec::new() };
let id = session.next_node_id(); let id = session.next_node_id();
let first = match place_value(&registry, Place::Input(host, 1)) { let first = match place_value(&registry, Place::Input(host, 1)) {
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index }, Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
@@ -179,6 +181,25 @@ impl Scenario for Branching {
new_input: value(random.below(100)), new_input: value(random.below(100)),
}] }]
} }
// Rewrite a node's whole input list, which an index-addressed write cannot express
11..=12 => {
let Some(node) = random.pick(&nodes) else { return Vec::new() };
let mut inputs = registry.node_instances[&node].inputs.clone();
match random.below(3) {
// Swap the first two, so what the node rested on moves past its primary input
0 if inputs.len() > 1 => inputs.swap(0, 1),
// One input more, holding a value
1 if inputs.len() < 4 => inputs.push(InputSlot {
input: value(random.below(100)),
timestamp: TimeStamp::ORIGIN,
attributes: Default::default(),
}),
// One input fewer, as removing a subgraph's import slot leaves the nodes wrapping it
_ if inputs.len() > 1 => _ = inputs.pop(),
_ => return Vec::new(),
}
vec![RegistryDelta::SetNodeInputs { id: node, inputs }]
}
// Cut the chain off an input past the primary one, taking its nodes with it // Cut the chain off an input past the primary one, taking its nodes with it
_ => { _ => {
let hosts: Vec<NodeId> = nodes let hosts: Vec<NodeId> = nodes
@@ -657,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored"); assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
} }
#[test]
fn a_transient_node_is_rejected() {
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
let metadata = NodeMetadata {
display_name: "Transient",
category: "",
icon: None,
fields: Vec::new(),
description: "",
inspector: None,
context_features: Vec::new(),
flags: NodeFlags {
transient: true,
..Default::default()
},
version: 1,
output_fields: None,
};
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
let mut network = create_simple_network();
network.nodes.insert(
NodeId(100),
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
},
);
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
}
/// A node input referencing a node in a different network can't be remapped to a valid local runtime /// A node input referencing a node in a different network can't be remapped to a valid local runtime
/// ID, so conversion must reject it rather than emit a dangling reference. /// ID, so conversion must reject it rather than emit a dangling reference.
#[test] #[test]
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV2, &contract());
check_undo(&BevelAndEmbossV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV2);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -0,0 +1,69 @@
use migration_core::{Inputs, NodeInput, encode, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
TypeDefault(Type),
}
/// Frozen mirror of the `Type` an empty list of graphics stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
List(Box<Type>),
}
#[derive(Serialize, Deserialize)]
struct TypeDescriptor {
name: String,
}
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
pub fn blur_v2(inputs: &mut Inputs) {
inputs.insert(2, empty_radius_mask());
}
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
fn empty_radius_mask() -> NodeInput {
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
name: "graphic_types::graphic::Graphic".to_string(),
}))));
NodeInput::Value {
value: encode(&no_graphics),
exposed: false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlurV2, &contract());
check_undo(&BlurV2, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BlurV2);
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
let migrated = fixture.migrate(&BlurV2).unwrap();
let mut expected = inputs;
expected.insert(2, empty_radius_mask());
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
assert_eq!(fixture.inputs(&migrated, blur), expected);
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
}
}
@@ -0,0 +1,43 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ConvolutionKernelV1, &contract());
check_undo(&ConvolutionKernelV1, &contract());
}
#[test]
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&ConvolutionKernelV1);
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
}
}
@@ -0,0 +1,48 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Integer(i64),
}
/// 'Inner Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
#[migration("blending_nodes::effects::InnerGlowNode"@2 => @3)]
pub fn inner_glow_v2(inputs: &mut Inputs) {
inputs.insert(8, literal(Tagged::Number(0.)));
inputs.insert(9, literal(Tagged::Number(0.)));
inputs.insert(10, literal(Tagged::Integer(0)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerGlowV2, &contract());
check_undo(&InnerGlowV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerGlowV2);
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@2), inputs.clone());
let migrated = fixture.migrate(&InnerGlowV2).unwrap();
let mut expected = inputs;
expected.splice(8..8, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@3)));
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
}
}
@@ -1,13 +1,21 @@
//! Migrations of the nodes in `blending_nodes`. //! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1; mod bevel_and_emboss_v1;
mod bevel_and_emboss_v2;
mod blur_v2;
mod convolution_kernel_v1;
mod drop_shadow_v1; mod drop_shadow_v1;
mod inner_glow_v1; mod inner_glow_v1;
mod inner_glow_v2;
mod inner_shadow_v1; mod inner_shadow_v1;
mod mask_by_any_graphic; mod mask_by_any_graphic;
mod outer_glow_v1; mod outer_glow_v1;
mod outer_glow_v2;
mod outline_v1; mod outline_v1;
mod outline_v2; mod outline_v2;
mod outline_v3;
mod paint_overlay_from_color_overlay; mod paint_overlay_from_color_overlay;
mod paint_overlay_v2;
mod radial_blur_v1;
mod renames; mod renames;
mod satin_v1; mod satin_v1;
@@ -0,0 +1,48 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Integer(i64),
}
/// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
#[migration("blending_nodes::effects::OuterGlowNode"@2 => @3)]
pub fn outer_glow_v2(inputs: &mut Inputs) {
inputs.insert(7, literal(Tagged::Number(0.)));
inputs.insert(8, literal(Tagged::Number(0.)));
inputs.insert(9, literal(Tagged::Integer(0)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OuterGlowV2, &contract());
check_undo(&OuterGlowV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OuterGlowV2);
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@2), inputs.clone());
let migrated = fixture.migrate(&OuterGlowV2).unwrap();
let mut expected = inputs;
expected.splice(7..7, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@3)));
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
}
}
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Outline' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
pub fn outline_v3(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV3, &contract());
check_undo(&OutlineV3, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV3);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
let migrated = fixture.migrate(&OutlineV3).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
pub fn paint_overlay_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PaintOverlayV2, &contract());
check_undo(&PaintOverlayV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&PaintOverlayV2);
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
assert_eq!(fixture.inputs(&migrated, overlay), expected);
}
}
@@ -0,0 +1,92 @@
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
const CENTER: u32 = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
DVec2([f64; 2]),
DAffine2([f64; 6]),
}
/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps.
/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin.
#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)]
pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
let Some(center) = node.inputs().get(CENTER as usize) else {
return Err(MigrationError::invariant("Radial Blur has a Center input"));
};
inputs.set(CENTER, transform_input(&center.input));
Ok(())
}
/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired.
fn transform_input(center: &NodeInput) -> NodeInput {
let ([x, y], exposed) = match center {
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(center) {
Some(Tagged::DVec2(center)) => (center, *exposed),
_ => ([0., 0.], *exposed),
},
_ => ([0., 0.], true),
};
NodeInput::Value {
value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])),
exposed,
}
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const CENTER_SLOT: usize = CENTER as usize;
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])),
_ => literal(random.below(10) as f64),
})
}
fn radial_blur_inputs(center: NodeInput) -> Vec<NodeInput> {
let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
inputs[CENTER_SLOT] = center;
inputs
}
#[test]
fn rewrites_history() {
check_commutation(&RadialBlurV1, &contract());
check_undo(&RadialBlurV1, &contract());
}
#[test]
fn the_center_becomes_the_translation_of_the_transform_in_its_place() {
let mut fixture = Fixture::new(&RadialBlurV1);
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.]))));
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.])));
assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2)));
assert_eq!(fixture.inputs(&migrated, radial_blur), expected);
}
#[test]
fn a_wired_center_becomes_the_identity_shown_in_the_graph() {
let mut fixture = Fixture::new(&RadialBlurV1);
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 }));
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
let identity = NodeInput::Value {
value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
exposed: true,
};
assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity));
}
}
@@ -3,3 +3,4 @@
use migration_core::rename; use migration_core::rename;
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2); rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
@@ -1,3 +1 @@
//! Migrations of the nodes in `graphene_std`. //! Migrations of the nodes in `graphene_std`.
mod renames;
@@ -1,13 +0,0 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
rename!("graphene_std::render_node::RenderNode"@1 => @2);
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
rename!("graphene_std::render_node::RenderNode"@2 => @3);
@@ -0,0 +1,43 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
}
/// 'Make Opaque' gained a Strength percentage, set to 100% to keep making the content fully opaque.
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
pub fn make_opaque_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Number(100.)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MakeOpaqueV1, &contract());
check_undo(&MakeOpaqueV1, &contract());
}
#[test]
fn keeps_the_content_and_adds_full_strength() {
let content = literal(1.);
let mut fixture = Fixture::new(&MakeOpaqueV1);
let make_opaque = fixture.add(decl!("raster_nodes::adjustments::MakeOpaqueNode"@1), vec![content.clone()]);
let migrated = fixture.migrate(&MakeOpaqueV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, make_opaque), Some(decl!("raster_nodes::adjustments::MakeOpaqueNode"@2)));
assert_eq!(fixture.inputs(&migrated, make_opaque), [content, literal(Tagged::Number(100.))]);
}
}
@@ -1,8 +1,10 @@
//! Migrations of the nodes in `raster_nodes`. //! Migrations of the nodes in `raster_nodes`.
mod make_opaque_v1;
mod mandelbrot_v1; mod mandelbrot_v1;
mod mandelbrot_v2; mod mandelbrot_v2;
mod mix_colors_from_mix_node; mod mix_colors_from_mix_node;
mod noise_pattern_v1; mod noise_pattern_v1;
mod noise_pattern_v2;
mod pattern_square; mod pattern_square;
mod renames; mod renames;
@@ -0,0 +1,185 @@
use migration_core::attr::node::VISIBLE;
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
}
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let gamma_correction = downstream.add_node(NewNode {
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
});
for consumer in consumers {
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !node.attributes().get_or(VISIBLE, true) {
attributes.set(gamma_correction, VISIBLE, &false);
}
// The Gamma Correction takes the pattern's place, with the pattern before it
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(gamma_correction, POSITION, &stored);
}
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
use migration_core::Declaration;
use migration_core::attr::node::ui::IS_LAYER;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
fn contract() -> SourceContract {
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
}
fn noise_inputs() -> Vec<NodeInput> {
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn rewrites_history() {
check_commutation(&NoisePatternV2, &contract());
check_undo(&NoisePatternV2, &contract());
}
#[test]
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
fixture.export(wire(noise));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
panic!("the consumer should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
assert_eq!(migrated.node_instances.len(), 4);
}
#[test]
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
let visibility_of_gamma_correction = |visible: bool| {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
if !visible {
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
}
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
panic!("the consumer should read a node")
};
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
};
// Visible is the default, so only a disabled pattern writes it
assert_eq!(visibility_of_gamma_correction(false), Some(false));
assert_eq!(visibility_of_gamma_correction(true), None);
}
#[test]
fn an_unread_pattern_gains_no_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(migrated.node_instances.len(), 1);
}
#[test]
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
let mut fixture = Fixture::new(&NoisePatternV2);
// A custom subgraph exporting the pattern, read by the root network's export
let (subgraph, instance) = (NetworkId(100), NodeId(100));
fixture.registry.networks.insert(subgraph, Network::default());
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
fixture.registry.node_instances.insert(instance, instance_node);
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
fixture.export_from(subgraph, wire(noise));
fixture.export(wire(instance));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
panic!("the subgraph's export should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
}
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
let (reader, slot) = if read_by_layer {
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
(layer, 1)
} else {
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
};
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
panic!("slot {slot} of the reader should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
}
#[test]
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
}
}
}
+15 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES))); let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
// Removal failing only leaves a temporary directory behind // Removal failing only leaves a temporary directory behind
let _ = std::fs::remove_dir_all(&directory); let _ = std::fs::remove_dir_all(&directory);
let baseline_nodes = baseline_nodes?; let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
let problems = api_problems(&baseline_nodes, &current, &migrations); let problems = api_problems(&baseline_nodes, &current, &migrations);
if !problems.is_empty() { if !problems.is_empty() {
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
// Moving a module keeps the function and its API, which is what a rename looks like // Moving a module keeps the function and its API, which is what a rename looks like
let moved = current let moved = current
.iter() .iter()
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature); .find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
problems.push(match moved { problems.push(match moved {
Some(new) => format!( Some(new) => format!(
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`", "`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
}); });
continue; continue;
}; };
if new.transient {
continue;
}
if new.version < version { if new.version < version {
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version)); problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
@@ -123,6 +126,7 @@ mod tests {
NodeSource { NodeSource {
identifier: identifier.to_string(), identifier: identifier.to_string(),
version, version,
transient: false,
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(), function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
file: PathBuf::from("lib.rs"), file: PathBuf::from("lib.rs"),
signature: signature.to_string(), signature: signature.to_string(),
@@ -168,6 +172,15 @@ mod tests {
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]); assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
} }
#[test]
fn a_node_turned_transient_needs_no_migration() {
let transient = NodeSource {
transient: true,
..node("a::b", 1, "(x: f64, y: f64)")
};
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
}
#[test] #[test]
fn a_bump_needs_a_migration_from_the_baseline_version() { fn a_bump_needs_a_migration_from_the_baseline_version() {
let bumped = [node("a::b", 3, "(x: f64)")]; let bumped = [node("a::b", 3, "(x: f64)")];
+1
View File
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))? let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
.into_iter() .into_iter()
.filter(|node| !node.transient)
.map(|node| (node.identifier, node.version)) .map(|node| (node.identifier, node.version))
.collect(); .collect();
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?; let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
+24
View File
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
/// function name with a `Node` suffix. /// function name with a `Node` suffix.
pub identifier: String, pub identifier: String,
pub version: u32, pub version: u32,
pub transient: bool,
pub function: String, pub function: String,
pub file: PathBuf, pub file: PathBuf,
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit. /// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
let mut path = module_path.join("::"); let mut path = module_path.join("::");
let mut version = 1; let mut version = 1;
let mut transient = false;
for argument in arguments { for argument in arguments {
transient |= argument.path().is_ident("transient");
let syn::Meta::List(list) = argument else { continue }; let syn::Meta::List(list) = argument else { continue };
if list.path.is_ident("path") { if list.path.is_ident("path") {
path = list.tokens.to_string().replace(' ', ""); path = list.tokens.to_string().replace(' ', "");
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
Some(NodeSource { Some(NodeSource {
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)), identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
version, version,
transient,
function: function_name, function: function_name,
file: file.to_path_buf(), file: file.to_path_buf(),
signature, signature,
@@ -171,4 +175,24 @@ mod tests {
assert!(!node.signature.contains("cache"), "{}", node.signature); assert!(!node.signature.contains("cache"), "{}", node.signature);
assert!(node.signature.contains("image"), "{}", node.signature); assert!(node.signature.contains("image"), "{}", node.signature);
} }
#[test]
fn the_transient_attribute_is_read() {
let transient: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(transient, memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let saved: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(category(""), memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
assert!(node(&transient).transient);
assert!(!node(&saved).transient);
}
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node, /// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename. /// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> { pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
let nodes = find_nodes(&workspace.join(NODE_CRATES))?; let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
let migrations = workspace.join(MIGRATIONS); let migrations = workspace.join(MIGRATIONS);
match (command, arguments) { match (command, arguments) {
+2 -1
View File
@@ -14,7 +14,7 @@ publish.workspace = true
workspace = true workspace = true
[features] [features]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"] wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "graph-ui/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
@@ -35,6 +35,7 @@ preprocessor = { workspace = true }
math-parser = { workspace = true } math-parser = { workspace = true }
snapping = { workspace = true } snapping = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
graph-ui = { workspace = true, features = ["serde"] }
# Workspace dependencies # Workspace dependencies
js-sys = { workspace = true } js-sys = { workspace = true }
+1 -3
View File
@@ -1,5 +1,5 @@
// GRAPH // GRAPH
pub const GRID_SIZE: u32 = 24; pub const GRID_SIZE: u32 = graph_ui::metrics::GRID_SIZE as u32;
pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2; pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2;
pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72; pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120; pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120;
@@ -11,8 +11,6 @@ pub const STACK_VERTICAL_GAP: i32 = 3;
pub const LAYER_INDENT_OFFSET: i32 = 8; pub const LAYER_INDENT_OFFSET: i32 = 8;
/// Horizontal grid width of a non-layer node in a chain. /// Horizontal grid width of a non-layer node in a chain.
pub const NODE_CHAIN_WIDTH: i32 = 7; pub const NODE_CHAIN_WIDTH: i32 = 7;
/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance.
pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
// VIEWPORT // VIEWPORT
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.; pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
+1 -3
View File
@@ -80,10 +80,8 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateLayerPanel, NodeGraphMessageDiscriminant::UpdateLayerPanel,
))), ))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateVisibleNodes, NodeGraphMessageDiscriminant::UpdateLayersInView,
))), ))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::SendSelectedNodes, NodeGraphMessageDiscriminant::SendSelectedNodes,
@@ -665,6 +665,18 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}"); assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
} }
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
let mut editor = create_editor_with_three_layers().await;
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
}
/// - paste /// - paste
/// - assert that ellipse was copied /// - assert that ellipse was copied
#[tokio::test] #[tokio::test]
@@ -1,8 +1,8 @@
use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE}; use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE};
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode; use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graph_ui::wire::WireStyle;
#[derive(ExtractField)] #[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> { pub struct PreferencesDialogMessageContext<'a> {
@@ -254,16 +254,16 @@ impl PreferencesDialogMessageHandler {
.widget_instance(), .widget_instance(),
]; ];
let graph_wire_style = RadioInput::new(vec![ let graph_wire_style = RadioInput::new(vec![
RadioEntryData::new(GraphWireStyle::Direct.to_string()) RadioEntryData::new("Direct")
.label(GraphWireStyle::Direct.to_string()) .label("Direct")
.tooltip_label(GraphWireStyle::Direct.to_string()) .tooltip_label("Direct")
.tooltip_description(GraphWireStyle::Direct.tooltip_description()) .tooltip_description("Wires bend to run at an angle directly between nodes.")
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::Direct }.into()), .on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::Direct }.into()),
RadioEntryData::new(GraphWireStyle::GridAligned.to_string()) RadioEntryData::new("Grid-Aligned")
.label(GraphWireStyle::GridAligned.to_string()) .label("Grid-Aligned")
.tooltip_label(GraphWireStyle::GridAligned.to_string()) .tooltip_label("Grid-Aligned")
.tooltip_description(GraphWireStyle::GridAligned.tooltip_description()) .tooltip_description("Wires follow the grid, running in straight lines between nodes.")
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()), .on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::GridAligned }.into()),
]) ])
.selected_index(Some(preferences.graph_wire_style as u32)) .selected_index(Some(preferences.graph_wire_style as u32))
.sizing(WidgetSizing::default().shrink(false)) .sizing(WidgetSizing::default().shrink(false))
@@ -5,11 +5,9 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm
use crate::messages::input_mapper::utility_types::misc::ActionShortcut; use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions; use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::node_graph::graph_ui::GraphNameField;
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic, use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuInformation, FrontendNodeType, FrontendRemoteCursor};
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry}; use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction}; use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction};
use crate::messages::portfolio::utility_types::WorkspacePanelLayout; use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*; use crate::messages::prelude::*;
@@ -65,8 +63,6 @@ pub enum FrontendMessage {
SendUIMetadata { SendUIMetadata {
#[serde(rename = "nodeDescriptions")] #[serde(rename = "nodeDescriptions")]
node_descriptions: Vec<(String, String)>, node_descriptions: Vec<(String, String)>,
#[serde(rename = "nodeIcons")]
node_icons: Vec<(String, IconName)>,
#[serde(rename = "nodeTypes")] #[serde(rename = "nodeTypes")]
node_types: Vec<FrontendNodeType>, node_types: Vec<FrontendNodeType>,
}, },
@@ -121,11 +117,6 @@ pub enum FrontendMessage {
preferences: PreferencesMessageHandler, preferences: PreferencesMessageHandler,
}, },
TriggerTextCommit, TriggerTextCommit,
/// Asks the frontend to enter inline-rename mode for a layer in the graph view.
TriggerEditLayerNameInGraph {
#[serde(rename = "nodeId")]
node_id: NodeId,
},
TriggerVisitLink { TriggerVisitLink {
url: String, url: String,
}, },
@@ -158,34 +149,11 @@ pub enum FrontendMessage {
ColorPickerStartHistoryTransaction, ColorPickerStartHistoryTransaction,
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event. /// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
ColorPickerCommitHistoryTransaction, ColorPickerCommitHistoryTransaction,
UpdateImportsExports {
/// If the primary import is not visible, then it is None.
imports: Vec<Option<FrontendGraphOutput>>,
/// If the primary export is not visible, then it is None.
exports: Vec<Option<FrontendGraphInput>>,
/// The primary import location.
#[serde(rename = "importPosition")]
import_position: (i32, i32),
/// The primary export location.
#[serde(rename = "exportPosition")]
export_position: (i32, i32),
/// The document network does not have an add import or export button.
#[serde(rename = "addImportExport")]
add_import_export: bool,
},
UpdateInSelectedNetwork {
#[serde(rename = "inSelectedNetwork")]
in_selected_network: bool,
},
/// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable. /// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable.
UpdateNetworkReadOnly { UpdateNetworkReadOnly {
#[serde(rename = "readOnly")] #[serde(rename = "readOnly")]
read_only: bool, read_only: bool,
}, },
UpdateBox {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateRemoteCursors { UpdateRemoteCursors {
cursors: Vec<FrontendRemoteCursor>, cursors: Vec<FrontendRemoteCursor>,
}, },
@@ -196,13 +164,17 @@ pub enum FrontendMessage {
#[serde(rename = "contextMenuInformation")] #[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>, context_menu_information: Option<ContextMenuInformation>,
}, },
UpdateClickTargets {
#[serde(rename = "clickTargets")]
click_targets: Option<FrontendClickTargets>,
},
UpdateGraphViewOverlay { UpdateGraphViewOverlay {
open: bool, open: bool,
}, },
UpdateGraphTooltip {
label: String,
description: String,
},
UpdateGraphNameField {
field: Option<GraphNameField>,
opens: bool,
},
UpdateWorkspacePanelLayout { UpdateWorkspacePanelLayout {
#[serde(rename = "panelLayout")] #[serde(rename = "panelLayout")]
panel_layout: WorkspacePanelLayout, panel_layout: WorkspacePanelLayout,
@@ -229,36 +201,6 @@ pub enum FrontendMessage {
source: String, source: String,
result: Option<String>, result: Option<String>,
}, },
UpdateImportReorderIndex {
#[serde(rename = "importIndex")]
index: Option<usize>,
},
UpdateExportReorderIndex {
#[serde(rename = "exportIndex")]
index: Option<usize>,
},
/// The wire a dragged node would be inserted onto if dropped now, keyed by the node and index of the input it feeds (the max node ID for an export).
UpdateWireInsertionPreview {
wire: Option<(NodeId, usize)>,
},
/// How far each node, and the imports and exports, gliding into the place it moved to is drawn from that place, in node graph space.
UpdateGlideOffsets {
nodes: Vec<(NodeId, (f64, f64))>,
imports: (f64, f64),
exports: (f64, f64),
},
/// The connector a press at the pointer would grab, by its center in node graph space.
UpdateHoveredConnector {
center: Option<(f64, f64)>,
},
UpdateLayerWidths {
#[serde(rename = "layerWidths")]
layer_widths: HashMap<NodeId, u32>,
#[serde(rename = "chainWidths")]
chain_widths: HashMap<NodeId, u32>,
#[serde(rename = "hasLeftInputWire")]
has_left_input_wire: HashMap<NodeId, bool>,
},
UpdateDocumentArtwork { UpdateDocumentArtwork {
svg: String, svg: String,
}, },
@@ -304,25 +246,9 @@ pub enum FrontendMessage {
#[serde(rename = "setColorChoice")] #[serde(rename = "setColorChoice")]
set_color_choice: Option<PrimarySecondary>, set_color_choice: Option<PrimarySecondary>,
}, },
UpdateGraphFadeArtwork {
percentage: f64,
},
UpdateMouseCursor { UpdateMouseCursor {
cursor: MouseCursorIcon, cursor: MouseCursorIcon,
}, },
UpdateNodeGraphNodes {
nodes: Vec<FrontendNode>,
},
UpdateNodeGraphErrorDiagnostics {
errors: Vec<NodeGraphErrorDiagnostic>,
},
UpdateVisibleNodes {
nodes: Vec<NodeId>,
},
UpdateNodeGraphWires {
wires: Vec<WirePathUpdate>,
},
ClearAllNodeGraphWires,
UpdateNodeGraphSelection { UpdateNodeGraphSelection {
selected: Vec<NodeId>, selected: Vec<NodeId>,
}, },
@@ -339,27 +265,15 @@ pub enum FrontendMessage {
height: u32, height: u32,
pixels: serde_bytes::ByteBuf, pixels: serde_bytes::ByteBuf,
}, },
UpdateNodeThumbnailCanvases { UpdateNodeThumbnailCanvas {
id: NodeId, id: NodeId,
#[serde(rename = "layersPanelCanvasId")] #[serde(rename = "canvasId")]
layers_panel_canvas_id: u64, canvas_id: u64,
#[serde(rename = "nodeGraphCanvasId")]
node_graph_canvas_id: u64,
}, },
UpdateOpenDocumentsList { UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")] #[serde(rename = "openDocuments")]
open_documents: Vec<DocumentInfo>, open_documents: Vec<DocumentInfo>,
}, },
UpdateWirePathInProgress {
#[serde(rename = "wirePath")]
wire_path: Option<WirePath>,
/// Where the wire meets the connector it's dragged from, in node graph space.
#[serde(rename = "draggedFrom")]
dragged_from: Option<(f64, f64)>,
/// Where the wire's loose end meets a connector it has snapped onto, in node graph space.
#[serde(rename = "snappedTo")]
snapped_to: Option<(f64, f64)>,
},
UpdatePlatform { UpdatePlatform {
platform: AppWindowPlatform, platform: AppWindowPlatform,
}, },
@@ -87,9 +87,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility), entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked), entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes), entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes), entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }), entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }), entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }), entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
@@ -878,6 +878,22 @@ pub struct SliderMarker {
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position. /// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
#[serde(rename = "betweenNeighbors")] #[serde(rename = "betweenNeighbors")]
between_neighbors: bool, between_neighbors: bool,
/// How this marker and the next may pass each other.
#[serde(rename = "overlapNext")]
overlap_next: MarkerOverlap,
}
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MarkerOverlap {
/// Neither may pass the other.
#[default]
Never,
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
NextOnly,
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
Freely,
} }
impl SliderMarker { impl SliderMarker {
@@ -890,6 +906,7 @@ impl SliderMarker {
paired_with_next: false, paired_with_next: false,
dashed_to_next: false, dashed_to_next: false,
between_neighbors: false, between_neighbors: false,
overlap_next: MarkerOverlap::Never,
} }
} }
@@ -907,6 +924,11 @@ impl SliderMarker {
self.dashed_to_next = true; self.dashed_to_next = true;
self self
} }
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
self.overlap_next = overlap;
self
}
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -0,0 +1,262 @@
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::application_io::Texture;
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List};
use graphene_std::math_nodes::{color_value, gradient_value};
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::style::RenderMode;
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
#[derive(Clone, Copy, Debug)]
enum Base {
VectorLayer,
ImageLayer,
/// A group holding a vector layer, with the effect on the group.
Group,
}
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
if effect == blur::IDENTIFIER {
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
.upstream_node_id_from_protonode(effect)
.expect("the layer has its blur");
let value = Box::new(TaggedValue::Number(10.));
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id,
input_index: blur::RadiusInput::INDEX,
value,
})
.await;
}
}
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
match base {
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
Base::VectorLayer | Base::Group => {
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
}
}
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
if !matches!(base, Base::Group) {
add_effect(&mut editor, base_layer, effect.clone()).await;
}
editor.select_tool(ToolType::Select).await;
editor.select_primary_color(red).await;
editor.select_secondary_color(red).await;
editor.draw_rect(20., 20., 200., 200.).await;
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
editor
.handle_message(GraphOperationMessage::FillColorSet {
layer: clipped_layer,
color: Some(red),
})
.await;
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
// Grouped once the red is clipped, the group takes the base's place beneath it
if let Base::Group = base {
let nodes = vec![base_layer.to_node()];
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
let group_folder_type = GroupFolderType::Layer;
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
let group = editor.get_selected_layer().await.expect("the group is selected");
add_effect(&mut editor, group, effect).await;
}
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
stack.push(clipped);
stack
}
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
// The clip's def in SVG carries out the blur but not the shadow
let mut render = SvgRender::new();
graphic.render_svg(
&mut render,
&RenderParams {
for_export: true,
..Default::default()
},
);
let body = render.svg.to_svg_string();
let reference = body.rfind("url(#mask-").expect("the red is clipped");
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
let defs = &render.svg_defs;
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
let def_end = ["</mask>", "</clipPath>"]
.iter()
.filter_map(|closing| defs[def_start..].find(closing))
.min()
.expect("the clip's def is closed");
let clip = &defs[def_start..def_start + def_end];
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
let size = UVec2::new(256, 256);
let executor = gpu_executor();
let texture = executor
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
.expect("the clip renders");
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
let pixel = |x: u32, y: u32| -> [u8; 4] {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
let within = pixel(90, 90);
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
}
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
#[derive(Clone, Copy, Debug)]
enum Endless {
Color,
Gradient,
NoisePattern,
}
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
editor
}
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
let node = match endless {
Endless::Color => color_value::IDENTIFIER,
Endless::Gradient => gradient_value::IDENTIFIER,
Endless::NoisePattern => noise_pattern::IDENTIFIER,
};
let node_type = DefinitionIdentifier::ProtoNode(node);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
}
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.expect("a document is open");
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).expect("the active document exists");
let submitted = executor
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO, None)
.expect("the evaluation is submitted");
let mut messages = editor.dispatch(submitted);
editor.runtime.update();
let frame = editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
(messages, frame)
}
#[tokio::test]
async fn endless_layers_clip_to_the_shape_beneath_them() {
let size = UVec2::new(256, 256);
let frame_pixels = async |editor: &mut EditorTestUtils| {
let (_, frame) = evaluate_viewport(editor, size).await;
let frame = frame.expect("the viewport presents a frame");
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
};
let pixel = |pixels: &[u8], x: u32, y: u32| {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
let rectangle_alone = frame_pixels(&mut editor).await;
add_clipped_endless_layer(&mut editor, endless).await;
let clipped = frame_pixels(&mut editor).await;
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
assert_eq!(
pixel(&clipped, x, y),
pixel(&rectangle_alone, x, y),
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
);
}
// In SVG Preview, the endless content is drawn only within the rectangle's mask
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
add_clipped_endless_layer(&mut editor, endless).await;
let (messages, _) = evaluate_viewport(&mut editor, size).await;
let svg = messages
.into_iter()
.find_map(|message| match message {
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
_ => None,
})
.expect("the viewport's artwork is sent as SVG");
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
assert!(
!draws_endless_content(unmasked) && draws_endless_content(masked),
"{endless:?}: the content is drawn within the mask: {svg}"
);
}
}
#[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
let stack = clipped_stack(base, effect.clone()).await;
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
// Flattened into one list of vectors, the base clips its sibling by the same rule
if let Base::VectorLayer = base {
let flattened: List<Vector> = stack.into_flattened_list();
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
}
}
}
}
@@ -7,6 +7,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use crate::node_graph_executor::InspectedContext; use crate::node_graph_executor::InspectedContext;
use glam::{Affine2, DAffine2, Vec2}; use glam::{Affine2, DAffine2, Vec2};
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::WarpStyle;
use graphene_std::animation::RealTimeMode; use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode; use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
@@ -34,9 +35,10 @@ use graphene_std::vector::style::{
}; };
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector}; use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{ use graphene_std::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic, Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
MaskMode, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
}; };
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
use kurbo::BezPath; use kurbo::BezPath;
use std::any::Any; use std::any::Any;
use std::ops::Range; use std::ops::Range;
@@ -1271,16 +1273,23 @@ impl_table_item_layout_for_choice_enum!(
BevelDirection, BevelDirection,
BevelTechnique, BevelTechnique,
BevelStyle, BevelStyle,
RadialBlurMethod,
WarpStyle,
WaveType,
DisplaceMode,
BlendIfChannel,
EffectKind, EffectKind,
Generator, Generator,
GlowSource, GlowSource,
MaskMode, MaskMode,
MinimumMaximumMode,
GradientForm, GradientForm,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
GradientInterpolation, GradientInterpolation,
GlowTechnique, GlowTechnique,
NoiseDistribution,
StrokeJoin, StrokeJoin,
StrokeAlign, StrokeAlign,
StrokeCap, StrokeCap,
@@ -1456,9 +1465,15 @@ macro_rules! known_item_types {
EffectKind, EffectKind,
GlowSource, GlowSource,
MaskMode, MaskMode,
MinimumMaximumMode,
BevelStyle, BevelStyle,
BevelDirection, BevelDirection,
BevelTechnique, BevelTechnique,
RadialBlurMethod,
WarpStyle,
WaveType,
DisplaceMode,
BlendIfChannel,
DashPattern, DashPattern,
BoxCorners, BoxCorners,
TransferCurve, TransferCurve,
@@ -1469,6 +1484,7 @@ macro_rules! known_item_types {
GradientHueDirection, GradientHueDirection,
GradientInterpolation, GradientInterpolation,
GlowTechnique, GlowTechnique,
NoiseDistribution,
StrokeJoin, StrokeJoin,
StrokeAlign, StrokeAlign,
StrokeCap, StrokeCap,
@@ -10,7 +10,7 @@ use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate,
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate}; use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
use crate::messages::portfolio::utility_types::PanelType; use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, IVec2, UVec2}; use glam::{DAffine2, DVec2, IVec2, UVec2};
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::Appearance; use graphene_std::Appearance;
use graphene_std::list::Item; use graphene_std::list::Item;
@@ -211,11 +211,6 @@ pub enum DocumentMessage {
SetGraphFadeArtwork { SetGraphFadeArtwork {
percentage: f64, percentage: f64,
}, },
/// Renames a layer in the network the node graph is showing, which may be a subgraph.
SetLayerNameInGraph {
node_id: NodeId,
name: String,
},
SetLayersPanelHoveredLayer { SetLayersPanelHoveredLayer {
id: Option<NodeId>, id: Option<NodeId>,
}, },
@@ -334,6 +329,7 @@ pub enum DocumentMessage {
}, },
UpdateEffectsReach { UpdateEffectsReach {
effects_reach: HashMap<NodeId, f64>, effects_reach: HashMap<NodeId, f64>,
effects_frames: HashMap<NodeId, [DVec2; 2]>,
}, },
Undo, Undo,
UngroupSelectedLayers, UngroupSelectedLayers,
@@ -1,4 +1,5 @@
use super::DocumentHistory; use super::DocumentHistory;
use super::node_graph::graph_ui::GraphUiPart;
use super::node_graph::{document_node_definitions, node_inspector}; use super::node_graph::{document_node_definitions, node_inspector};
use super::utility_types::error::EditorError; use super::utility_types::error::EditorError;
use super::utility_types::layers_in_view::LayersInView; use super::utility_types::layers_in_view::LayersInView;
@@ -199,7 +200,7 @@ pub struct DocumentMessageHandler {
/// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport. /// The layer under the pointer in the Layers panel, which gets a hover outline in the viewport.
#[serde(skip)] #[serde(skip)]
layers_panel_hovered_layer: Option<LayerNodeIdentifier>, layers_panel_hovered_layer: Option<LayerNodeIdentifier>,
/// The layers the frontend shows in view, the only ones it's sent the details and thumbnails of. /// The layers in view in the Layers panel or the node graph, the only ones thumbnails are rendered for.
#[serde(skip)] #[serde(skip)]
pub layers_in_view: LayersInView, pub layers_in_view: LayersInView,
/// 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. /// 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.
@@ -304,8 +305,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let visibility_settings = self.overlays_visibility_settings; let visibility_settings = self.overlays_visibility_settings;
// Send the overlays message to the overlays message handler // Send the overlays message to the overlays message handler
self.overlays_message_handler self.overlays_message_handler.process_message(
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport }); message,
responses,
OverlaysMessageContext {
visibility_settings,
viewport,
graph_open: self.graph_view_overlay_open,
},
);
} }
DocumentMessage::Inspector(message) => { DocumentMessage::Inspector(message) => {
let context = InspectorMessageContext { let context = InspectorMessageContext {
@@ -673,7 +681,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.breadcrumb_network_path.push(node_id); self.breadcrumb_network_path.push(node_id);
self.selection_network_path.clone_from(&self.breadcrumb_network_path); self.selection_network_path.clone_from(&self.breadcrumb_network_path);
self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path); self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::ZoomCanvasToFitAll); responses.add(DocumentMessage::ZoomCanvasToFitAll);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth); responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
@@ -692,20 +699,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.network_interface.cancel_drag(&self.selection_network_path); self.network_interface.cancel_drag(&self.selection_network_path);
self.node_graph_handler.select_if_not_dragged = None; self.node_graph_handler.select_if_not_dragged = None;
self.node_graph_handler.nodes_added_in_drag = false; self.node_graph_handler.nodes_added_in_drag = false;
self.node_graph_handler.stop_gliding(&self.network_interface, responses); self.node_graph_handler.graph_ui.stop_animations(responses);
responses.add(NodeGraphMessage::UpdateWireInsertionPreview); responses.add(NodeGraphMessage::UpdateWireInsertionPreview);
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
} }
// Abort dragging a dot out of a connector, before the dot has appeared // Abort dragging a dot out of a connector, before the dot has appeared
else if self.node_graph_handler.dot_drag_out.is_some() { else if self.node_graph_handler.dot_drag_out.is_some() {
self.node_graph_handler.dot_drag_out = None; self.node_graph_handler.dot_drag_out = None;
} }
// Abort box selection // Abort box selection
else if self.node_graph_handler.box_selection_start.is_some() { else if self.node_graph_handler.box_selection.is_some() {
self.node_graph_handler.box_selection_start = None;
responses.add(NodeGraphMessage::SelectedNodesSet { responses.add(NodeGraphMessage::SelectedNodesSet {
nodes: self.node_graph_handler.selection_before_pointer_down.clone(), nodes: self.node_graph_handler.selection_before_pointer_down.clone(),
}); });
responses.add(FrontendMessage::UpdateBox { box_selection: None }); self.node_graph_handler.set_box_selection(None, responses);
} }
// Abort wire in progress of being connected // Abort wire in progress of being connected
else if self.node_graph_handler.wire_in_progress_from_connector.is_some() { else if self.node_graph_handler.wire_in_progress_from_connector.is_some() {
@@ -737,7 +744,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.selection_network_path.clone_from(&self.breadcrumb_network_path); self.selection_network_path.clone_from(&self.breadcrumb_network_path);
} }
self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path); self.network_interface.unload_import_export_ports(&self.breadcrumb_network_path);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::SendGraph);
responses.add(DocumentMessage::PTZUpdate); responses.add(DocumentMessage::PTZUpdate);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth); responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
@@ -793,24 +799,21 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::GraphViewOverlay { open } => { DocumentMessage::GraphViewOverlay { open } => {
let opened = !self.graph_view_overlay_open && open; let opened = !self.graph_view_overlay_open && open;
self.graph_view_overlay_open = open; self.graph_view_overlay_open = open;
self.node_graph_handler.graph_ui.graph_view_toggled(responses);
responses.add(FrontendMessage::UpdateGraphViewOverlay { open }); responses.add(FrontendMessage::UpdateGraphViewOverlay { open });
responses.add(FrontendMessage::UpdateGraphFadeArtwork {
percentage: self.graph_fade_artwork_percentage,
});
// Update the tilt menu bar buttons to be disabled when the graph is open // Update the tilt menu bar buttons to be disabled when the graph is open
responses.add(MenuBarMessage::SendLayout); responses.add(MenuBarMessage::SendLayout);
responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderRulers);
responses.add(DocumentMessage::RenderScrollbars); responses.add(DocumentMessage::RenderScrollbars);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
if opened { if opened {
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::UpdateNodeGraphWidth); responses.add(NodeGraphMessage::UpdateNodeGraphWidth);
} }
if open { if open {
responses.add(ToolMessage::DeactivateTools); responses.add(ToolMessage::DeactivateTools);
responses.add(OverlaysMessage::Draw); // Clear the overlays
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. }); responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
responses.add(NodeGraphMessage::UpdateGraphBarRight); responses.add(NodeGraphMessage::UpdateGraphBarRight);
responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::SendGraph);
@@ -820,6 +823,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
if self.end_node_graph_wire_in_progress(responses) { if self.end_node_graph_wire_in_progress(responses) {
responses.add(DocumentMessage::AbortTransaction); responses.add(DocumentMessage::AbortTransaction);
} }
self.node_graph_handler.abort_node_drag(&mut self.network_interface, &self.selection_network_path, responses);
responses.add(ToolMessage::ActivateTool { tool_type: *current_tool }); responses.add(ToolMessage::ActivateTool { tool_type: *current_tool });
responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed responses.add(OverlaysMessage::Draw); // Redraw overlays when graph is closed
@@ -1538,6 +1542,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.chain_node_range_selection_reference = Some(node_id); self.chain_node_range_selection_reference = Some(node_id);
} }
DocumentMessage::SetActivePanel { active_panel } => { DocumentMessage::SetActivePanel { active_panel } => {
let selection_network_path = self.selection_network_path.clone();
match active_panel { match active_panel {
PanelType::Document => { PanelType::Document => {
if self.graph_view_overlay_open { if self.graph_view_overlay_open {
@@ -1551,7 +1556,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
} }
responses.add(InspectorMessage::Refresh); responses.add(InspectorMessage::Refresh);
responses.add(NodeGraphMessage::UpdateLayerPanel); responses.add(NodeGraphMessage::UpdateLayerPanel);
responses.add(NodeGraphMessage::UpdateInSelectedNetwork); if self.graph_view_overlay_open && self.selection_network_path != selection_network_path {
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
} }
DocumentMessage::SetBlendModeForSelectedLayers { blend_mode } => { DocumentMessage::SetBlendModeForSelectedLayers { blend_mode } => {
for layer in self.network_interface.selected_nodes().selected_layers_except_artboards(&self.network_interface) { for layer in self.network_interface.selected_nodes().selected_layers_except_artboards(&self.network_interface) {
@@ -1560,15 +1567,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
} }
DocumentMessage::SetGraphFadeArtwork { percentage } => { DocumentMessage::SetGraphFadeArtwork { percentage } => {
self.graph_fade_artwork_percentage = percentage; self.graph_fade_artwork_percentage = percentage;
responses.add(FrontendMessage::UpdateGraphFadeArtwork { percentage }); responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
DocumentMessage::SetLayerNameInGraph { node_id, name } => {
responses.add(NodeGraphMessage::SetDisplayName {
node_id,
network_path: self.breadcrumb_network_path.clone(),
alias: name,
skip_adding_history_step: false,
});
} }
DocumentMessage::SetLayersPanelHoveredLayer { id } => { DocumentMessage::SetLayersPanelHoveredLayer { id } => {
let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked); let layer = id.filter(|id| self.network_interface.is_layer(id, &[])).map(LayerNodeIdentifier::new_unchecked);
@@ -1945,13 +1944,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect(); .collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes); self.network_interface.update_appearance_attributes(layer_appearance_attributes);
} }
DocumentMessage::UpdateEffectsReach { effects_reach } => { DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames } => {
let is_document_layer = |node_id: &NodeId| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]);
let layer_effects_reach = effects_reach let layer_effects_reach = effects_reach
.into_iter() .into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[])) .filter(|(node_id, _)| is_document_layer(node_id))
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach)) .map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
.collect(); .collect();
self.network_interface.update_effects_reach(layer_effects_reach); let layer_effects_frames = effects_frames
.into_iter()
.filter(|(node_id, _)| is_document_layer(node_id))
.map(|(node_id, frames)| (LayerNodeIdentifier::new(node_id, &self.network_interface), frames))
.collect();
self.network_interface.update_effects_reach(layer_effects_reach, layer_effects_frames);
} }
DocumentMessage::Undo => { DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() { if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
@@ -2073,6 +2079,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::UpdateBoxSelection); responses.add(NodeGraphMessage::UpdateBoxSelection);
responses.add(NodeGraphMessage::UpdateHoveredConnector); responses.add(NodeGraphMessage::UpdateHoveredConnector);
responses.add(NodeGraphMessage::UpdateImportsExports); responses.add(NodeGraphMessage::UpdateImportsExports);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
responses.add(FrontendMessage::UpdateNodeGraphTransform { responses.add(FrontendMessage::UpdateNodeGraphTransform {
translation: transform.translation.into(), translation: transform.translation.into(),
@@ -2680,7 +2687,6 @@ impl DocumentMessageHandler {
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) { fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
for path in self.network_interface.paths_reaching(&reconciled.networks) { for path in self.network_interface.paths_reaching(&reconciled.networks) {
self.network_interface.unload_import_export_ports(&path); self.network_interface.unload_import_export_ports(&path);
self.network_interface.unload_all_nodes_bounding_box(&path);
self.network_interface.unload_outward_wires(&path); self.network_interface.unload_outward_wires(&path);
} }
self.network_interface.load_structure(); self.network_interface.load_structure();
@@ -2698,8 +2704,6 @@ impl DocumentMessageHandler {
responses.add(PortfolioMessage::UpdateOpenDocumentsList); responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph); responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
} }
/// Keeps the graph showing the open network across a reconcile, which can rebuild its view state or remove it. /// Keeps the graph showing the open network across a reconcile, which can rebuild its view state or remove it.
@@ -2755,8 +2759,6 @@ impl DocumentMessageHandler {
responses.add(PortfolioMessage::UpdateOpenDocumentsList); responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph); responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
} }
pub fn serialize_document(&self) -> String { pub fn serialize_document(&self) -> String {
@@ -3054,9 +3056,6 @@ impl DocumentMessageHandler {
} }
pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) { pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
// Settled before storage moves, so the glide's offsets don't outlive the step
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string); let stored_name = self.stored_name().map(str::to_string);
// Alone, the step enters history first so it stays on the History panel once undone // Alone, the step enters history first so it stays on the History panel once undone
if !self.is_in_session() { if !self.is_in_session() {
@@ -3069,8 +3068,6 @@ impl DocumentMessageHandler {
} }
pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) { pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string); let stored_name = self.stored_name().map(str::to_string);
if self.history.redo() { if self.history.redo() {
self.follow_storage_changes(stored_name, responses); self.follow_storage_changes(stored_name, responses);
@@ -3080,8 +3077,6 @@ impl DocumentMessageHandler {
/// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo. /// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo.
fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) { fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified; let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified;
if open_transaction_has_edits { if open_transaction_has_edits {
// Staged so they are taken back with the steps before them // Staged so they are taken back with the steps before them
@@ -3110,7 +3105,6 @@ impl DocumentMessageHandler {
return; return;
} }
self.end_history_preview(viewport, responses); self.end_history_preview(viewport, responses);
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort); responses.add(EventMessage::ToolAbort);
self.apply_history_line_change(document_id, rev, change, byte_store, responses); self.apply_history_line_change(document_id, rev, change, byte_store, responses);
} }
@@ -3125,7 +3119,7 @@ impl DocumentMessageHandler {
} }
let Some(past) = self.history.interface_at(rev) else { return }; let Some(past) = self.history.interface_at(rev) else { return };
self.node_graph_handler.stop_gliding(&self.network_interface, responses); self.node_graph_handler.graph_ui.stop_animations(responses);
responses.add(EventMessage::ToolAbort); responses.add(EventMessage::ToolAbort);
let replaced = self.install_history_snapshot(past, viewport); let replaced = self.install_history_snapshot(past, viewport);
let current = self.history_preview.take().map_or(replaced, |preview| preview.current); let current = self.history_preview.take().map_or(replaced, |preview| preview.current);
@@ -3178,8 +3172,6 @@ impl DocumentMessageHandler {
fn show_installed_interface(&self, responses: &mut VecDeque<Message>) { fn show_installed_interface(&self, responses: &mut VecDeque<Message>) {
responses.add(NodeGraphMessage::SelectedNodesUpdated); responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph); responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
responses.add(DocumentMessage::DocumentStructureChanged); responses.add(DocumentMessage::DocumentStructureChanged);
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged); responses.add(EventMessage::SelectionChanged);
@@ -3215,6 +3207,7 @@ impl DocumentMessageHandler {
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`. /// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) { fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
self.node_graph_handler.graph_ui.stop_animations(responses);
if let Some(gdd) = self.history.storage_mut() { if let Some(gdd) = self.history.storage_mut() {
let changes = gdd.take_remote_changes(); let changes = gdd.take_remote_changes();
self.pending_remote.extend(changes); self.pending_remote.extend(changes);
@@ -4125,7 +4118,7 @@ impl DocumentMessageHandler {
}) })
.unwrap_or((None, None, None)); .unwrap_or((None, None, None));
let blend_mode_menu_entries = BlendMode::list_svg_subset() let blend_mode_menu_entries = BlendMode::list()
.iter() .iter()
.map(|modes| { .map(|modes| {
modes modes
@@ -4142,7 +4135,7 @@ impl DocumentMessageHandler {
let widgets = vec![ let widgets = vec![
DropdownInput::new(blend_mode_menu_entries) 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)) .selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
.disabled(disabled) .disabled(disabled)
.draw_icon(false) .draw_icon(false)
.sizing(WidgetSizing::default().grow(false)) .sizing(WidgetSizing::default().grow(false))
@@ -5115,7 +5108,7 @@ mod document_message_handler_tests {
let document = portfolio.documents.get_mut(&document_id).unwrap(); let document = portfolio.documents.get_mut(&document_id).unwrap();
portfolio portfolio
.executor .executor
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO) .submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO, None)
.unwrap(); .unwrap();
editor.runtime.update(); editor.runtime.update();
editor.runtime.run().await; editor.runtime.run().await;
@@ -807,9 +807,6 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
// Set positions for all imported descendants in a single O(n) pass // Set positions for all imported descendants in a single O(n) pass
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO); let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map); set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
// Invalidate caches once after all positions are set
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
} }
usvg::Node::Path(path) => { usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info); import_usvg_path(modify_inputs, node, path, layer, gradient_info);
@@ -1,4 +1,6 @@
#[cfg(test)] #[cfg(test)]
mod clipping_tests;
#[cfg(test)]
pub(crate) mod document_diff; pub(crate) mod document_diff;
mod document_history; mod document_history;
mod document_message; mod document_message;
@@ -1,11 +1,11 @@
use crate::application::Environment; use crate::application::Environment;
use crate::consts::{ use crate::consts::{
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN, DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR, VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
}; };
use crate::messages::frontend::utility_types::MouseCursorIcon; use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion}; use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition; use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation; use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ; use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface; use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
@@ -34,6 +34,8 @@ pub struct NavigationMessageHandler {
abortable_pan_start: Option<f64>, abortable_pan_start: Option<f64>,
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself. /// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
artwork_behind_graph: bool, artwork_behind_graph: bool,
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
graph_middle_click_start: Option<ViewportPosition>,
} }
#[message_handler_data] #[message_handler_data]
@@ -99,6 +101,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
return; return;
}; };
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan }; self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
} }
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => { NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else { let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
@@ -341,6 +347,13 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
responses.add(ToolMessage::UpdateCursor); responses.add(ToolMessage::UpdateCursor);
responses.add(ToolMessage::UpdateHints); responses.add(ToolMessage::UpdateHints);
responses.add(NavigateToolMessage::End); responses.add(NavigateToolMessage::End);
// Not a pan after all, but a middle click in the graph
let middle_click_start = self.graph_middle_click_start.take();
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
responses.add(NodeGraphMessage::MiddleClick);
}
} }
NavigationMessage::EndCanvasPTZWithClick { commit_key } => { NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
self.finish_operation_with_click = false; self.finish_operation_with_click = false;
@@ -417,6 +430,10 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
} }
} }
NavigationMessage::PointerMove { snap } => { NavigationMessage::PointerMove { snap } => {
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
self.graph_middle_click_start = None;
}
match self.navigation_operation { match self.navigation_operation {
NavigationOperation::None => {} NavigationOperation::None => {}
NavigationOperation::Pan { .. } => { NavigationOperation::Pan { .. } => {
@@ -3,7 +3,6 @@ mod document_node_derive;
use super::node_inspector::choice::enum_choice; use super::node_inspector::choice::enum_choice;
use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange}; use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
use super::utility_types::{FrontendNodeType, InputTypeConstraint}; use super::utility_types::{FrontendNodeType, InputTypeConstraint};
use crate::messages::frontend::IconName;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{ use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride, InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
@@ -139,18 +138,6 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA /// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> { fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![ let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
},
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
inspector: None,
},
DocumentNodeDefinition { DocumentNodeDefinition {
identifier: "Merge", identifier: "Merge",
version: 1, version: 1,
@@ -688,6 +675,7 @@ fn static_node_inspector() -> NodeInspector {
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector)); map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector)); map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector)); map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector)); map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector)); map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector)); map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
@@ -701,6 +689,8 @@ fn static_node_inspector() -> NodeInspector {
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector)); map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector)); map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector)); map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
map.insert("displace_inspector".to_string(), Box::new(node_inspector::displace_inspector));
map map
} }
@@ -709,6 +699,15 @@ type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspect
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar // TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector); static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
/// The metadata of the proto node's field at `index`, cloned so the lock is released before the row is built, which locks the node metadata again.
fn proto_node_field(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> Option<registry::FieldMetadata> {
context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned())
}
/// Defines the logic for inputs to display a custom Inspector widget. /// Defines the logic for inputs to display a custom Inspector widget.
fn static_input_inspector() -> InputInspector { fn static_input_inspector() -> InputInspector {
let mut map: InputInspector = HashMap::new(); let mut map: InputInspector = HashMap::new();
@@ -873,15 +872,10 @@ fn static_input_inspector() -> InputInspector {
}), }),
); );
map.insert( map.insert(
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them // A slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
"wrapping_range_slider".to_string(), "wrapping_slider".to_string(),
Box::new(|node_id, index, context| { Box::new(|node_id, index, context| {
// The field is cloned so the lock is released before building the row below, which locks the node metadata again let field = proto_node_field(node_id, index, context);
let field = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
let mut number_input = NumberInput::default().mode_increment(); let mut number_input = NumberInput::default().mode_increment();
let mut period = None; let mut period = None;
@@ -902,10 +896,51 @@ fn static_input_inspector() -> InputInspector {
let row = match period { let row = match period {
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => { Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
let default = node_inspector::definition_default_number(&parameter_widgets_info); let default = node_inspector::definition_default_number(&parameter_widgets_info);
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default }) node_inspector::wrapping_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
} }
_ => { _ => {
log::error!("A wrapping range slider needs finite soft bounds at both ends"); log::error!("A wrapping slider needs finite soft bounds at both ends");
node_inspector::number_widget(parameter_widgets_info, number_input)
}
};
Ok(vec![LayoutGroup::row(row)])
}),
);
map.insert(
// A slider across the soft bounds (or the hard ones where a soft one is absent), beside a number input that types past them up to the hard bounds
"slider".to_string(),
Box::new(|node_id, index, context| {
let field = proto_node_field(node_id, index, context);
let mut number_input = NumberInput::default().mode_increment();
let mut extent = None;
if let Some(field) = field {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
if let Some(display_decimal_places) = field.number_display_decimal_places {
number_input = number_input.display_decimal_places(display_decimal_places);
}
if let Some(number_step) = field.number_step {
number_input = number_input.step(number_step);
}
if let Some(min) = field.number_hard_min {
number_input = number_input.min(min);
}
if let Some(max) = field.number_hard_max {
number_input = number_input.max(max);
}
extent = field.number_soft_min.or(field.number_hard_min).zip(field.number_soft_max.or(field.number_hard_max));
}
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
let row = match extent {
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
let default = node_inspector::definition_default_number(&parameter_widgets_info);
node_inspector::slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
}
_ => {
log::error!("A slider needs finite bounds at both ends");
node_inspector::number_widget(parameter_widgets_info, number_input) node_inspector::number_widget(parameter_widgets_info, number_input)
} }
}; };
@@ -1070,7 +1105,7 @@ fn static_input_inspector() -> InputInspector {
"noise_inspector_fractal_weighted_strength".to_string(), "noise_inspector_fractal_weighted_strength".to_string(),
Box::new(|node_id, index, context| { Box::new(|node_id, index, context| {
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?; let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
let fractal_weighted_strength = node_inspector::range_slider_widget( let fractal_weighted_strength = node_inspector::slider_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context), ParameterWidgetsInfo::at_index(node_id, index, true, context),
NumberInput::default() NumberInput::default()
.min(0.) .min(0.)
@@ -1605,13 +1640,6 @@ pub fn network_node_identifiers() -> impl Iterator<Item = &'static str> {
}) })
} }
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 { impl DocumentNodeDefinition {
/// Converts the [DocumentNodeDefinition] type to a [NodeTemplate], using the provided `input_override` and falling back to the default inputs. /// 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. /// `input_override` does not have to be the correct length.
@@ -0,0 +1,514 @@
mod animation;
mod name_field;
mod pointer;
pub use name_field::{GraphName, GraphNameField, edited_name};
pub use pointer::{PointerHits, connector_under_pointer, tooltip_target};
use super::node_graph_message_handler::NodeGraphMessageHandler;
use super::utility_types::FrontendGraphDataType;
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NetworkConnectorKey, NodeNetworkInterface, OutputConnector, Previewing};
use crate::messages::prelude::{Message, PortfolioMessage, Responses};
use glam::DVec2;
use graph_craft::document::NodeId;
use graph_ui::GraphUiConfig;
use graph_ui::animation::{Glided, Glides};
use graph_ui::card::{Card, Connector, DataType, Selection};
use graph_ui::dot::Dot;
use graph_ui::error_badge::ErrorBadge;
use graph_ui::geometry::NodeGeometry;
use graph_ui::highlights::{self, Highlights, NodePart};
use graph_ui::layer::Layer;
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind, network_connector_row_offset};
use graph_ui::placed::Placed;
use graph_ui::replicated_map::{Keyed, ReplicatedMap, ReplicatedMapEdit};
use graph_ui::scene::GraphUiSceneEdit;
use graph_ui::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle};
use pointer::TooltipTarget;
use std::collections::{BTreeSet, HashMap, VecDeque};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ConnectorKey {
Input(InputConnector),
Output(OutputConnector),
}
impl From<NetworkConnectorKey> for ConnectorKey {
fn from(connector: NetworkConnectorKey) -> Self {
match connector {
NetworkConnectorKey::Import(index) => ConnectorKey::Output(OutputConnector::Import(index)),
NetworkConnectorKey::Export(index) => ConnectorKey::Input(InputConnector::Export(index)),
}
}
}
impl From<ConnectorKey> for highlights::ConnectorKey {
fn from(connector: ConnectorKey) -> Self {
match connector {
ConnectorKey::Input(input) => highlights::ConnectorKey::Input(input_key(input)),
ConnectorKey::Output(output) => highlights::ConnectorKey::Output(output_key(output)),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GraphUiPart {
All,
NetworkConnectors,
Errors,
InsertionTarget,
Moved { nodes: Vec<NodeId> },
}
pub struct GraphUiSceneBuilder<'a> {
network_interface: &'a NodeNetworkInterface,
network_path: &'a [NodeId],
node_graph_handler: &'a NodeGraphMessageHandler,
selected_nodes: Vec<NodeId>,
selected: Selection,
}
impl<'a> GraphUiSceneBuilder<'a> {
pub fn of(document: &'a DocumentMessageHandler) -> Self {
let network_interface = &document.network_interface;
let network_path = document.breadcrumb_network_path();
Self {
network_interface,
network_path,
node_graph_handler: &document.node_graph_handler,
selected_nodes: network_interface.selected_nodes_in_nested_network(network_path).unwrap_or_default().0,
selected: if network_path == document.selection_network_path() {
Selection::Active
} else {
Selection::Inactive
},
}
}
pub fn update(&self, part: GraphUiPart, scene: &mut GraphUiSceneEdit) {
match part {
GraphUiPart::All => {
let dragging = self.network_interface.dragging(self.network_path);
let glides = &self.node_graph_handler.graph_ui.glides;
replace_rows(self.cards(), dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards);
replace_rows(self.layers(), dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers);
replace_rows(self.dots(), dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots);
place_wires(self.wires(), scene);
scene.network_connectors.replace_all(self.network_connectors());
scene.errors.replace_all(self.errors());
}
GraphUiPart::NetworkConnectors => scene.network_connectors.replace_all(self.network_connectors()),
GraphUiPart::Errors => scene.errors.replace_all(self.errors()),
GraphUiPart::InsertionTarget => self.update_insertion_target(scene),
GraphUiPart::Moved { nodes } => self.update_moved(scene, nodes),
}
}
fn nodes(&self) -> impl Iterator<Item = NodeId> + '_ {
self.network_interface.nested_network(self.network_path).into_iter().flat_map(|network| network.nodes.keys().copied())
}
fn selection(&self, key: NodeId) -> Selection {
if self.selected_nodes.contains(&key) { self.selected } else { Selection::None }
}
fn cards(&self) -> Vec<Placed<Card>> {
self.nodes().filter_map(|key| self.card(key)).collect()
}
fn card(&self, key: NodeId) -> Option<Placed<Card>> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
if network_interface.is_layer(&key, network_path) || network_interface.is_redirect_dot(&key, network_path) {
return None;
}
let NodeGeometry { cell, shape, .. } = self.geometry(key)?;
let name = network_interface.display_name(&key, network_path);
let look = Card {
key,
shape,
name,
icon: network_interface.node_icon(&key, network_path),
primary_input: self.input(key, 0),
primary_output: self.output(key, 0),
secondary_inputs: (1..network_interface.number_of_inputs(&key, network_path)).filter_map(|index| self.input(key, index)).collect(),
secondary_outputs: (1..network_interface.number_of_outputs(&key, network_path)).filter_map(|index| self.output(key, index)).collect(),
selection: self.selection(key),
visible: network_interface.is_visible(&key, network_path),
previewed: network_interface.previewing(network_path).previews(key),
};
Some(Placed { cell, look })
}
fn geometry(&self, key: NodeId) -> Option<NodeGeometry> {
self.network_interface.with_layout(self.network_path, |layout| layout.geometry(&key)).flatten()
}
fn layers(&self) -> Vec<Placed<Layer>> {
self.nodes().filter_map(|key| self.layer(key)).collect()
}
fn layer(&self, key: NodeId) -> Option<Placed<Layer>> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
if !network_interface.is_layer(&key, network_path) {
return None;
}
let NodeGeometry { cell, chain_length, shape, .. } = self.geometry(key)?;
let look = Layer {
key,
shape,
chain_length,
name: network_interface.display_name(&key, network_path),
renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::Layer(key)),
has_left_input_wire: network_interface.has_left_input_wire(&key, network_path),
primary_input: self.input(key, 0),
primary_output: self.output(key, 0),
secondary_input: (1..network_interface.number_of_inputs(&key, network_path)).find_map(|index| self.input(key, index)),
primary_input_connected_to_layer: network_interface.primary_input_connected_to_layer(&key, network_path),
primary_output_connected_to_layer: network_interface.primary_output_connected_to_layer(&key, network_path),
visible: network_interface.is_visible(&key, network_path),
read_only: network_interface.is_read_only(network_path),
selection: self.selection(key),
previewed: network_interface.previewing(network_path).previews(key),
};
Some(Placed { cell, look })
}
fn dots(&self) -> Vec<Placed<Dot>> {
self.nodes().filter_map(|key| self.dot(key)).collect()
}
fn dot(&self, key: NodeId) -> Option<Placed<Dot>> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
if !network_interface.is_redirect_dot(&key, network_path) {
return None;
}
let input = self.input(key, 0);
let output = self.output(key, 0);
let NodeGeometry { cell, shape, .. } = self.geometry(key)?;
let look = Dot {
key,
shape,
data_type: output.as_ref().map_or(DataType::General, |output| output.data_type),
wired: input.is_some_and(|input| input.connected) || output.is_some_and(|output| output.connected),
selected: self.selected_nodes.contains(&key),
previewed: network_interface.previewing(network_path).previews(key),
};
Some(Placed { cell, look })
}
fn wires(&self) -> Vec<Wire> {
let inputs = self.network_interface.node_graph_input_connectors(self.network_path).into_iter();
inputs.filter_map(|input| self.wire(input)).chain(self.preview_wire()).collect()
}
fn wire(&self, input: InputConnector) -> Option<Wire> {
let output = self.network_interface.upstream_output_connector(&input, self.network_path)?;
let to = input_key(input);
Some(self.wire_row(WireKey::Input(to), output, to))
}
fn preview_wire(&self) -> Option<Wire> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let input = InputConnector::Export(0);
let Previewing::Yes { previewed } = network_interface.previewing(network_path) else { return None };
if network_interface.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
return None;
}
Some(self.wire_row(WireKey::Preview, previewed.to_connector(), input_key(input)))
}
fn wire_row(&self, key: WireKey, output: OutputConnector, to: InputKey) -> Wire {
let output_type = self.network_interface.output_type(&output, self.network_path);
Wire {
key,
from: output_key(output),
to,
data_type: data_type(output_type.displayed_type()),
list: output_type.is_list(),
insertion_target: Some(key) == self.insertion_target(),
}
}
fn insertion_target(&self) -> Option<WireKey> {
self.node_graph_handler.wire_insertion_preview.map(|input| WireKey::Input(input_key(input)))
}
fn network_connectors(&self) -> Vec<NetworkConnector> {
[NetworkConnectorKind::Import, NetworkConnectorKind::Export]
.into_iter()
.flat_map(|kind| self.network_connectors_of(kind))
.collect()
}
fn network_connectors_of(&self, kind: NetworkConnectorKind) -> Vec<NetworkConnector> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let count = match kind {
NetworkConnectorKind::Import => network_interface.number_of_imports(network_path),
NetworkConnectorKind::Export => network_interface.number_of_exports(network_path),
};
let row = |key: NetworkConnectorKey, position: DVec2, connector: Option<Connector>| NetworkConnector {
key,
position: position.as_ivec2(),
connector,
editable: !network_path.is_empty(),
renaming: self.node_graph_handler.graph_ui.editing_name == Some(GraphName::NetworkConnector(key)),
};
let named = (0..count).filter_map(|index| {
let key = NetworkConnectorKey::new(kind, index);
Some(row(key, self.position(key.into())?, Some(self.connector(key.into())?)))
});
let empty = network_interface.empty_import_export_connectors(kind == NetworkConnectorKind::Import, network_path);
named
.chain(empty.into_iter().map(|(index, position)| row(NetworkConnectorKey::new(kind, index), position, None)))
.collect()
}
fn errors(&self) -> Vec<ErrorBadge> {
let errors = self.node_graph_handler.node_graph_errors(self.network_interface, self.network_path);
errors.into_iter().map(|(key, text)| ErrorBadge { key, text }).collect()
}
fn update_moved(&self, scene: &mut GraphUiSceneEdit, nodes: Vec<NodeId>) {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let downstream_layers = nodes.iter().filter_map(|node| network_interface.downstream_layer_for_chain_node(node, network_path));
let rows: BTreeSet<NodeId> = nodes.iter().copied().chain(downstream_layers).collect();
self.place_node_rows(rows, scene);
scene.network_connectors.replace_all(self.network_connectors());
place_wires(all_wires(scene), scene);
}
fn place_node_rows(&self, nodes: impl IntoIterator<Item = NodeId>, scene: &mut GraphUiSceneEdit) {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let dragging = network_interface.dragging(network_path);
let glides = &self.node_graph_handler.graph_ui.glides;
for node in nodes {
let Some(NodeGeometry { cell, chain_length, .. }) = self.geometry(node) else { continue };
let placed = replace_row(node, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards, |card| {
(card.cell != cell).then(|| Placed { cell, look: card.look.clone() })
}) || replace_row(node, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers, |layer| {
let has_left_input_wire = network_interface.has_left_input_wire(&node, network_path);
let changed = (layer.cell, layer.look.chain_length, layer.look.has_left_input_wire) != (cell, chain_length, has_left_input_wire);
let look = || Layer {
chain_length,
has_left_input_wire,
..layer.look.clone()
};
changed.then(|| Placed { cell, look: look() })
}) || replace_row(node, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots, |dot| {
(dot.cell != cell).then(|| Placed { cell, look: dot.look.clone() })
});
if !placed {
self.put_node_rows(node, dragging, scene);
}
}
}
fn put_node_rows(&self, node: NodeId, dragging: bool, scene: &mut GraphUiSceneEdit) {
let glides = &self.node_graph_handler.graph_ui.glides;
if let Some(card) = self.card(node) {
place_row(card, dragging, glides, &mut scene.settled.cards, &mut scene.moving.cards);
}
if let Some(layer) = self.layer(node) {
place_row(layer, dragging, glides, &mut scene.settled.layers, &mut scene.moving.layers);
}
if let Some(dot) = self.dot(node) {
place_row(dot, dragging, glides, &mut scene.settled.dots, &mut scene.moving.dots);
}
}
fn input(&self, node: NodeId, index: usize) -> Option<Connector> {
self.connector(ConnectorKey::Input(InputConnector::node_at_index(node, index)))
}
fn output(&self, node: NodeId, index: usize) -> Option<Connector> {
self.connector(ConnectorKey::Output(OutputConnector::node(node, index)))
}
fn connector(&self, key: ConnectorKey) -> Option<Connector> {
let (network_interface, network_path) = (self.network_interface, self.network_path);
let (name, connector_type, connected) = match key {
ConnectorKey::Input(input) => network_interface.graph_ui_input(&input, network_path),
ConnectorKey::Output(output) => network_interface.graph_ui_output(&output, network_path),
}?;
Some(Connector {
index: match key {
ConnectorKey::Input(input) => input.input_index(),
ConnectorKey::Output(output) => output.index(),
} as u32,
name,
data_type: data_type(connector_type.displayed_type()),
connected,
})
}
fn position(&self, key: ConnectorKey) -> Option<DVec2> {
match key {
ConnectorKey::Input(input) => self.network_interface.input_position(&input, self.network_path),
ConnectorKey::Output(output) => self.network_interface.output_position(&output, self.network_path),
}
}
fn update_insertion_target(&self, scene: &mut GraphUiSceneEdit) {
let target = self.insertion_target();
let wires = all_wires(scene).into_iter().map(|wire| Wire {
insertion_target: Some(wire.key) == target,
..wire
});
place_wires(wires.collect(), scene);
}
}
fn stays<T: Keyed<Key = NodeId> + PartialEq>(row: &T, dragging: bool, glides: &Glides, settled: &ReplicatedMap<T>) -> bool {
!glides.rows.contains_key(&Glided::Node(row.key())) && (!dragging || settled.get(&row.key()) == Some(row))
}
fn replace_rows<T: Keyed<Key = NodeId> + PartialEq>(rows: Vec<T>, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit<T>, moving: &mut ReplicatedMapEdit<T>) {
let (still, moved): (Vec<T>, Vec<T>) = rows.into_iter().partition(|row| stays(row, dragging, glides, settled));
settled.replace_all(still);
moving.replace_all(moved);
}
fn place_row<T: Keyed<Key = NodeId> + PartialEq>(row: T, dragging: bool, glides: &Glides, settled: &mut ReplicatedMapEdit<T>, moving: &mut ReplicatedMapEdit<T>) {
let key = row.key();
if stays(&row, dragging, glides, settled) {
moving.remove(&key);
settled.put(row);
} else {
settled.remove(&key);
moving.put(row);
}
}
fn replace_row<T: Keyed<Key = NodeId> + PartialEq>(
node: NodeId,
dragging: bool,
glides: &Glides,
settled: &mut ReplicatedMapEdit<T>,
moving: &mut ReplicatedMapEdit<T>,
replaced: impl FnOnce(&T) -> Option<T>,
) -> bool {
let Some(row) = moving.get(&node).or_else(|| settled.get(&node)) else { return false };
if let Some(row) = replaced(row) {
place_row(row, dragging, glides, settled, moving);
}
true
}
fn all_wires(scene: &GraphUiSceneEdit) -> Vec<Wire> {
scene.settled.wires.iter().chain(scene.moving.wires.iter()).cloned().collect()
}
fn place_wires(wires: Vec<Wire>, scene: &mut GraphUiSceneEdit) {
let settled = |node: NodeId| scene.settled.cards.get(&node).is_some() || scene.settled.layers.get(&node).is_some() || scene.settled.dots.get(&node).is_some();
let between_settled_nodes = |wire: &Wire| match (wire.from, wire.to) {
(OutputKey::Node { node: from, .. }, InputKey::Node { node: to, .. }) => settled(from) && settled(to),
_ => false,
};
let (tiled, loose): (Vec<Wire>, Vec<Wire>) = wires.into_iter().partition(|wire| !wire.insertion_target && between_settled_nodes(wire));
scene.settled.wires.replace_all(tiled);
scene.moving.wires.replace_all(loose);
}
#[derive(Clone, Debug, Default)]
pub struct GraphUiState {
highlights: Highlights,
glides: Glides,
animating: bool,
pub(super) time: f64,
tooltip: Option<(Option<TooltipTarget>, String, String)>,
editing_name: Option<GraphName>,
name_field: Option<(GraphName, GraphNameField)>,
error_text_sizes: HashMap<String, DVec2>,
}
impl GraphUiState {
pub fn change_highlights(&mut self, change: impl FnOnce(&mut Highlights), responses: &mut VecDeque<Message>) {
let mut highlights = self.highlights.clone();
change(&mut highlights);
if self.highlights != highlights {
self.start_grows(&mut highlights);
self.highlights = highlights;
self.follow_animations(responses);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
}
}
pub fn config(document: &DocumentMessageHandler, wire_style: WireStyle) -> Option<GraphUiConfig> {
let node_graph_handler = &document.node_graph_handler;
let graph_metadata = document.network_interface.network_metadata(document.breadcrumb_network_path());
graph_metadata.filter(|_| document.graph_view_overlay_open).map(|metadata| {
let view = metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
GraphUiConfig {
view,
fade_artwork: document.graph_fade_artwork_percentage / 100.,
wire_in_progress: wire_in_progress(node_graph_handler),
reorder_bar: reorder_bar(document),
box_selection: node_graph_handler
.box_selection
.filter(|(_, dragged)| *dragged)
.map(|(corners, _)| corners.map(|corner| view.transform_point2(corner).max(DVec2::ZERO).floor())),
highlights: node_graph_handler.graph_ui.highlights.clone(),
wire_style,
glides: node_graph_handler.graph_ui.glides.clone(),
}
})
}
fn reorder_bar(document: &DocumentMessageHandler) -> Option<(NetworkConnectorKind, DVec2)> {
let node_graph_handler = &document.node_graph_handler;
let index = node_graph_handler.end_index?;
let kind = if node_graph_handler.reordering_import.is_some() {
NetworkConnectorKind::Import
} else if node_graph_handler.reordering_export.is_some() {
NetworkConnectorKind::Export
} else {
return None;
};
let (imports, exports) = document.network_interface.import_export_position(document.breadcrumb_network_path())?;
let first_row_center = match kind {
NetworkConnectorKind::Import => imports,
NetworkConnectorKind::Export => exports,
};
Some((kind, first_row_center.as_dvec2() + DVec2::new(0., network_connector_row_offset(index))))
}
fn wire_in_progress(node_graph_handler: &NodeGraphMessageHandler) -> Option<WireInProgress> {
Some(WireInProgress {
ends: node_graph_handler.wire_in_progress_ends?,
data_type: data_type(node_graph_handler.wire_in_progress_type),
})
}
fn output_key(output: OutputConnector) -> OutputKey {
match output {
OutputConnector::Node { node_id, output_index } => OutputKey::Node { node: node_id, index: output_index },
OutputConnector::Import(index) => OutputKey::Import(index),
}
}
fn input_key(input: InputConnector) -> InputKey {
match input {
InputConnector::Node { node_id, input_index } => InputKey::Node { node: node_id, index: input_index },
InputConnector::Export(index) => InputKey::Export(index),
}
}
fn data_type(data_type: FrontendGraphDataType) -> DataType {
match data_type {
FrontendGraphDataType::General => DataType::General,
FrontendGraphDataType::Number => DataType::Number,
FrontendGraphDataType::Artboard => DataType::Artboard,
FrontendGraphDataType::Graphic => DataType::Graphic,
FrontendGraphDataType::Raster => DataType::Raster,
FrontendGraphDataType::Vector => DataType::Vector,
FrontendGraphDataType::Color => DataType::Color,
FrontendGraphDataType::Gradient => DataType::Gradient,
FrontendGraphDataType::Typography => DataType::Typography,
FrontendGraphDataType::Invalid => DataType::Invalid,
}
}
@@ -0,0 +1,88 @@
use super::*;
use crate::messages::prelude::{BroadcastMessage, EventMessage, NodeGraphMessage};
use graph_ui::animation::{Animation, GROW_DURATION, Glided};
use graph_ui::highlights::ConnectorKey;
impl GraphUiState {
pub fn glide(&mut self, moves: impl IntoIterator<Item = (Glided, DVec2)>, responses: &mut VecDeque<Message>) {
for (row, moved) in moves {
let from = moved + self.glides.offset(row, self.time);
match Animation::glide(from, self.time) {
Some(glide) => self.glides.rows.insert(row, glide),
None => self.glides.rows.remove(&row),
};
}
self.follow_animations(responses);
}
pub fn stop_animations(&mut self, responses: &mut VecDeque<Message>) {
if !self.glides.rows.is_empty() {
self.glides.rows.clear();
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
if !self.highlights.grows.is_empty() {
self.highlights.grows.clear();
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
self.follow_animations(responses);
}
pub fn animation_tick(&mut self, graph_open: bool, responses: &mut VecDeque<Message>) {
if !self.animating {
responses.add(animation_frames(false));
return;
}
if !graph_open {
self.stop_animations(responses);
return;
}
let time = self.time;
self.highlights.grows.retain(|_, grow| !ended(grow, time));
if !self.glides.rows.is_empty() && self.glides.rows.values().all(|glide| ended(glide, time)) {
self.glides.rows.clear();
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
self.follow_animations(responses);
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
pub(super) fn start_grows(&self, highlights: &mut Highlights) {
let keys: BTreeSet<ConnectorKey> = self.highlights.connectors().chain(highlights.connectors()).collect();
for key in keys {
let grows = highlights.connector(key).is_grown();
if self.highlights.connector(key).is_grown() == grows {
continue;
}
let (from, to) = (self.highlights.grown(key, self.time), if grows { 1. } else { 0. });
let grow = Animation {
from,
to,
start: self.time,
end: self.time + GROW_DURATION * (to - from).abs(),
};
highlights.grows.insert(key, grow);
}
}
pub(super) fn follow_animations(&mut self, responses: &mut VecDeque<Message>) {
let animating = !self.glides.rows.is_empty() || !self.highlights.grows.is_empty();
if self.animating == animating {
return;
}
self.animating = animating;
responses.add(animation_frames(animating));
}
}
fn animation_frames(subscribed: bool) -> BroadcastMessage {
let (on, send) = (EventMessage::AnimationFrame, Box::new(NodeGraphMessage::AnimationTick.into()));
match subscribed {
true => BroadcastMessage::SubscribeEvent { on, send },
false => BroadcastMessage::UnsubscribeEvent { on, send },
}
}
fn ended<T>(animation: &Animation<T>, time: f64) -> bool {
time >= animation.end || time < animation.start
}
@@ -0,0 +1,108 @@
use super::*;
use crate::messages::prelude::FrontendMessage;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum GraphName {
Layer(NodeId),
NetworkConnector(NetworkConnectorKey),
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct GraphNameField {
pub name: String,
pub x: f64,
pub top: f64,
#[serde(rename = "alignRight")]
pub align_right: bool,
pub dimmed: bool,
}
impl GraphUiSceneBuilder<'_> {
fn name_field(&self, name: GraphName) -> Option<GraphNameField> {
match name {
GraphName::Layer(key) => {
let layer = self.layer(key)?;
let [top_left, _] = layer.name_box();
Some(GraphNameField {
name: layer.look.name,
x: top_left.x,
top: top_left.y,
align_right: false,
dimmed: !layer.look.visible,
})
}
GraphName::NetworkConnector(key) => self.network_connector_name_field(key),
}
}
fn network_connector_name_field(&self, key: NetworkConnectorKey) -> Option<GraphNameField> {
let row = self.network_connectors().into_iter().find(|row| row.key == key && row.editable)?;
let connector = row.connector.as_ref()?;
let [top_left, _] = row.name_box(0.);
Some(GraphNameField {
name: connector.name.clone(),
x: top_left.x,
top: top_left.y,
align_right: key.kind() == NetworkConnectorKind::Import,
dimmed: false,
})
}
}
impl GraphUiState {
pub fn begin_name_edit(&mut self, name: GraphName, responses: &mut VecDeque<Message>) {
if self.editing_name != Some(name) {
self.editing_name = Some(name);
responses.add(PortfolioMessage::UpdateGraphUi { part: GraphUiPart::All });
}
}
pub fn end_name_edit(&mut self) -> Option<GraphName> {
self.editing_name.take()
}
pub fn update_name_field(&mut self, field: Option<GraphNameField>, responses: &mut VecDeque<Message>) {
let shown = self.name_field.as_ref();
let same_row = |(name, field): &(GraphName, GraphNameField)| match (name, shown) {
(GraphName::NetworkConnector(_), Some((shown, shown_field))) if shown == name => shown_field.name == field.name,
_ => true,
};
let edited = self.editing_name.zip(field).filter(same_row);
if edited.is_none() {
self.editing_name = None;
}
if edited == self.name_field {
return;
}
let sent = self.name_field.as_ref().map(|(name, _)| *name);
let opens = edited.as_ref().is_some_and(|(name, _)| sent != Some(*name));
self.name_field.clone_from(&edited);
responses.add(FrontendMessage::UpdateGraphNameField {
field: edited.map(|(_, field)| field),
opens,
});
}
pub fn leave_network(&mut self, responses: &mut VecDeque<Message>) {
if self.editing_name.is_some() || self.name_field.is_some() {
self.drop_name_edit(responses);
}
}
pub fn graph_view_toggled(&mut self, responses: &mut VecDeque<Message>) {
self.tooltip = None;
self.drop_name_edit(responses);
}
fn drop_name_edit(&mut self, responses: &mut VecDeque<Message>) {
self.editing_name = None;
self.name_field = None;
responses.add(FrontendMessage::UpdateGraphNameField { field: None, opens: false });
}
}
pub fn edited_name(document: &DocumentMessageHandler) -> Option<GraphNameField> {
let name = document.node_graph_handler.graph_ui.editing_name?;
GraphUiSceneBuilder::of(document).name_field(name)
}
@@ -0,0 +1,260 @@
use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::LayerClickTargetTypes;
use crate::messages::prelude::FrontendMessage;
use graph_ui::metrics::{CARD_ROW_PADDING, GRID_SIZE};
use graph_ui::{error_badge, error_text_size};
use std::cell::OnceCell;
impl GraphUiState {
pub fn part_under_pointer(&mut self, hits: &PointerHits, errors: &[(NodeId, String)], pointer_free: bool) -> Option<NodePart> {
if let Some(badge) = self.error_badge_under(hits, errors) {
return Some(NodePart::ErrorBadge(badge));
}
let (network_interface, network_path) = (hits.network_interface, hits.network_path);
let dot = hits.node().filter(|node_id| network_interface.is_redirect_dot(node_id, network_path));
if let Some(dot) = dot {
if !pointer_free {
return None;
}
if hits.output() == Some(OutputConnector::node(dot, 0)) {
return Some(NodePart::DotOutput(dot));
}
let pulls_a_wire_in = hits.input() == Some(InputConnector::node_at_index(dot, 0));
return (!pulls_a_wire_in).then_some(NodePart::Dot(dot));
}
let visibility = hits.visibility().map(NodePart::Visibility);
let lock = || hits.lock().map(NodePart::Lock);
let grip = || hits.grip().map(NodePart::Grip);
visibility.or_else(lock).or_else(grip)
}
fn error_badge_under(&mut self, hits: &PointerHits, errors: &[(NodeId, String)]) -> Option<NodeId> {
let mut badges: Vec<&(NodeId, String)> = errors.iter().collect();
badges.sort_by_key(|(key, _)| (self.highlights.badge_hovered(*key), *key));
let text_sizes = &mut self.error_text_sizes;
text_sizes.retain(|text, _| badges.iter().any(|(_, badge_text)| badge_text == text));
let mut text_size = |text: &String| match text_sizes.get(text) {
Some(size) => *size,
None => *text_sizes.entry(text.clone()).or_insert_with(|| error_text_size(text)),
};
let geometry = |key: &NodeId| hits.network_interface.with_layout(hits.network_path, |layout| layout.geometry(key)).flatten();
let mut covers = |(key, text): &(NodeId, String)| geometry(key).is_some_and(|geometry| error_badge::covers(geometry.error_badge_anchor(), text_size(text), hits.point));
badges.into_iter().rev().find(|badge| covers(badge)).map(|(key, _)| *key)
}
pub fn set_tooltip(&mut self, target: Option<TooltipTarget>, network_interface: &NodeNetworkInterface, network_path: &[NodeId], responses: &mut VecDeque<Message>) {
let (label, description) = target.map(|target| tooltip_text(target, network_interface, network_path)).unwrap_or_default();
let tooltip = (target, label, description);
if self.tooltip.as_ref() == Some(&tooltip) {
return;
}
let (_, label, description) = self.tooltip.insert(tooltip).clone();
responses.add(FrontendMessage::UpdateGraphTooltip { label, description });
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TooltipTarget {
Name(NetworkConnectorKey),
AddConnector(NetworkConnectorKey),
Connector(ConnectorKey),
Visibility(NodeId),
Lock(NodeId),
Grip(NodeId),
Dot(NodeId),
Row { node: NodeId, row: usize },
Node(NodeId),
}
pub struct PointerHits<'a> {
network_interface: &'a NodeNetworkInterface,
network_path: &'a [NodeId],
viewport_location: DVec2,
point: DVec2,
found: FoundHits,
}
#[derive(Default)]
struct FoundHits {
name: OnceCell<Option<NetworkConnectorKey>>,
empty_connector: OnceCell<Option<NetworkConnectorKey>>,
node: OnceCell<Option<NodeId>>,
visibility: OnceCell<Option<NodeId>>,
lock: OnceCell<Option<NodeId>>,
grip: OnceCell<Option<NodeId>>,
input: OnceCell<Option<InputConnector>>,
output: OnceCell<Option<OutputConnector>>,
}
impl<'a> PointerHits<'a> {
pub fn new(network_interface: &'a NodeNetworkInterface, network_path: &'a [NodeId], viewport_location: DVec2, point: DVec2) -> Self {
Self {
network_interface,
network_path,
viewport_location,
point,
found: FoundHits::default(),
}
}
fn name(&self) -> Option<NetworkConnectorKey> {
*self.found.name.get_or_init(|| self.network_interface.import_export_name_from_point(self.point, self.network_path))
}
fn empty_connector(&self) -> Option<NetworkConnectorKey> {
*self.found.empty_connector.get_or_init(|| {
let empty = |is_import| self.network_interface.empty_import_export_connector_at(self.point, is_import, self.network_path);
let import = empty(true).map(|(index, _)| NetworkConnectorKey::Import(index));
import.or_else(|| empty(false).map(|(index, _)| NetworkConnectorKey::Export(index)))
})
}
fn node(&self) -> Option<NodeId> {
*self.found.node.get_or_init(|| self.network_interface.node_from_click(self.viewport_location, self.network_path))
}
fn visibility(&self) -> Option<NodeId> {
self.layer_button(&self.found.visibility, LayerClickTargetTypes::Visibility)
}
fn lock(&self) -> Option<NodeId> {
self.layer_button(&self.found.lock, LayerClickTargetTypes::Lock)
}
fn grip(&self) -> Option<NodeId> {
self.layer_button(&self.found.grip, LayerClickTargetTypes::Grip)
}
fn layer_button(&self, found: &OnceCell<Option<NodeId>>, button: LayerClickTargetTypes) -> Option<NodeId> {
*found.get_or_init(|| self.network_interface.layer_click_target_from_click(self.viewport_location, button, self.network_path))
}
fn input(&self) -> Option<InputConnector> {
*self.found.input.get_or_init(|| self.network_interface.input_port_from_click(self.viewport_location, self.network_path))
}
fn output(&self) -> Option<OutputConnector> {
*self
.found
.output
.get_or_init(|| self.network_interface.output_port_from_click(self.viewport_location, self.network_path))
}
}
pub fn connector_under_pointer(hits: &PointerHits) -> Option<ConnectorKey> {
if hits.name().is_some() || hits.visibility().is_some() || hits.lock().is_some() {
return None;
}
let input = || hits.input().map(ConnectorKey::Input);
let output = || hits.output().map(ConnectorKey::Output);
hits.empty_connector().map(ConnectorKey::from).or_else(input).or_else(output)
}
pub fn tooltip_target(hits: &PointerHits) -> Option<TooltipTarget> {
let (network_interface, network_path) = (hits.network_interface, hits.network_path);
if let Some(name) = hits.name() {
return Some(TooltipTarget::Name(name));
}
if let Some(add) = hits.empty_connector() {
return Some(TooltipTarget::AddConnector(add));
}
let node = hits.node();
if let Some(dot) = node.filter(|node| network_interface.is_redirect_dot(node, network_path)) {
return Some(TooltipTarget::Dot(dot));
}
let input = || hits.input().map(|input| TooltipTarget::Connector(ConnectorKey::Input(input)));
let output = || hits.output().map(|output| TooltipTarget::Connector(ConnectorKey::Output(output)));
let part = hits
.visibility()
.map(TooltipTarget::Visibility)
.or_else(|| hits.lock().map(TooltipTarget::Lock))
.or_else(input)
.or_else(output)
.or_else(|| hits.grip().map(TooltipTarget::Grip));
if part.is_some() {
return part;
}
let node = node?;
if network_interface.is_layer(&node, network_path) {
return Some(TooltipTarget::Node(node));
}
let point = hits.point;
let [min, max] = network_interface.node_bounding_box(&node, network_path)?;
let row = ((point.y - min.y) / GRID_SIZE).floor();
let on_row_name = point.x >= min.x + CARD_ROW_PADDING && point.x <= max.x - CARD_ROW_PADDING;
Some(if row >= 1. && on_row_name {
TooltipTarget::Row { node, row: row as usize }
} else {
TooltipTarget::Node(node)
})
}
fn tooltip_text(target: TooltipTarget, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> (String, String) {
let input = |input: InputConnector| network_interface.input_tooltip(&input, network_path);
let output = |output: OutputConnector| network_interface.output_tooltip(&output, network_path);
let input_tooltip = |key: InputConnector| {
let lists_no_types = matches!(key, InputConnector::Node { .. });
input(key).map(|input| connector_tooltip(input.name, &input.description, input.resolved_type, &input.valid_types, input.connected, lists_no_types))
};
let output_tooltip = |key: OutputConnector| output(key).map(|output| connector_tooltip(output.name, &output.description, output.resolved_type, &output.possible_types, output.connected, false));
let label_only = |text: &str| (text.to_string(), String::new());
match target {
TooltipTarget::Name(NetworkConnectorKey::Import(index)) => (network_interface.displayed_import_name(index, network_path), network_interface.import_description(index, network_path)),
TooltipTarget::Name(NetworkConnectorKey::Export(index)) => (network_interface.displayed_export_name(index, network_path), network_interface.export_description(index, network_path)),
TooltipTarget::AddConnector(add) => {
let (label, description) = match add {
NetworkConnectorKey::Import(index) => (
if index == 0 { "Add Primary Import" } else { "Add Import" },
"Drag a wire from here and connect it to an input, or drop one here from an input.",
),
NetworkConnectorKey::Export(index) => (
if index == 0 { "Add Primary Export" } else { "Add Export" },
"Drag a wire from here and connect it to an output, or drop one here from an output.",
),
};
(label.to_string(), description.to_string())
}
TooltipTarget::Connector(ConnectorKey::Input(key)) => input_tooltip(key).unwrap_or_default(),
TooltipTarget::Connector(ConnectorKey::Output(key)) => output_tooltip(key).unwrap_or_default(),
TooltipTarget::Visibility(layer) => label_only(if network_interface.is_visible(&layer, network_path) { "Hide" } else { "Show" }),
TooltipTarget::Lock(_) => label_only("Unlock"),
TooltipTarget::Grip(_) => (String::new(), "Drag only this layer without pushing others outside the stack".to_string()),
TooltipTarget::Dot(dot) => output_tooltip(OutputConnector::node(dot, 0)).unwrap_or_else(|| label_only(&network_interface.display_name(&dot, network_path))),
TooltipTarget::Row { node, row } => {
let exposed = |index: &usize| network_interface.graph_ui_input(&InputConnector::node_at_index(node, *index), network_path).is_some();
let input_index = (1..network_interface.number_of_inputs(&node, network_path)).filter(exposed).nth(row - 1);
let named_input = input_index.map(|index| network_interface.displayed_input_name_and_description(&node, index, network_path));
let named_output = || {
network_interface
.graph_ui_output(&OutputConnector::node(node, row), network_path)
.map(|(name, ..)| (name, network_interface.output_description(&node, row, network_path)))
};
named_input.or_else(named_output).unwrap_or_default()
}
TooltipTarget::Node(node) => {
let (name, implementation_name) = (network_interface.display_name(&node, network_path), network_interface.implementation_name(&node, network_path));
let label = if name == implementation_name { name } else { format!("{implementation_name} ({name})") };
let definition = network_interface.reference(&node, network_path).and_then(|reference| resolve_document_node_type(&reference));
(label, definition.map(|definition| definition.description.trim().to_string()).unwrap_or_default())
}
}
}
fn connector_tooltip(name: String, description: &str, resolved_type: String, types: &[String], connected: bool, lists_no_types: bool) -> (String, String) {
let wired_type = connected.then(|| format!("Wired Type:\n`{resolved_type}`"));
let possible_types = if types.is_empty() {
lists_no_types.then(|| "Possible Types:\nNone".to_string())
} else {
Some(format!("Possible Types:\n{}", types.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join("\n")))
};
let types = [wired_type, possible_types].into_iter().flatten().collect::<Vec<_>>().join("\n\n");
let description = [description.trim().to_string(), types].into_iter().filter(|part| !part.is_empty()).collect::<Vec<_>>().join("\n---\n");
(if name.is_empty() { resolved_type } else { name }, description)
}
@@ -1,4 +1,5 @@
pub mod document_node_definitions; pub mod document_node_definitions;
pub mod graph_ui;
mod node_graph_message; mod node_graph_message;
mod node_graph_message_handler; mod node_graph_message_handler;
pub mod node_inspector; pub mod node_inspector;
@@ -1,8 +1,9 @@
use super::graph_ui::GraphName;
use super::utility_types::{Direction, NodeEvaluationError}; use super::utility_types::{Direction, NodeEvaluationError};
use crate::messages::input_mapper::utility_types::keyboard::Key; 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::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, InputConnector, NetworkConnectorKey, NodeTemplate, OutputConnector};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::IVec2; use glam::IVec2;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
@@ -45,6 +46,11 @@ pub enum NodeGraphMessage {
xy: Option<(i32, i32)>, xy: Option<(i32, i32)>,
add_transaction: bool, add_transaction: bool,
}, },
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
CreateEmptySubgraph {
node_id: Option<NodeId>,
xy: Option<(i32, i32)>,
},
CreateWire { CreateWire {
output_connector: OutputConnector, output_connector: OutputConnector,
input_connector: InputConnector, input_connector: InputConnector,
@@ -73,7 +79,7 @@ pub enum NodeGraphMessage {
}, },
/// Disconnects every wire an import feeds, or the wire feeding an export. /// Disconnects every wire an import feeds, or the wire feeding an export.
DisconnectImportExport { DisconnectImportExport {
index: ImportOrExport, index: NetworkConnectorKey,
}, },
EnterNestedNetwork, EnterNestedNetwork,
DuplicateSelectedNodes, DuplicateSelectedNodes,
@@ -165,12 +171,11 @@ pub enum NodeGraphMessage {
PointerOutsideViewport { PointerOutsideViewport {
shift: Key, shift: Key,
}, },
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
MiddleClick,
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes. /// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
WireHoverTick, WireHoverTick,
/// Sends where everything gliding into place is drawn, along with the wires that follow it. AnimationTick,
SendGlide,
/// Sent every frame while nodes glide into their grid cells, to bring them closer.
GlideTick,
ShakeNode, ShakeNode,
UpdateNodeGraphWidth, UpdateNodeGraphWidth,
RemoveImport { RemoveImport {
@@ -181,7 +186,7 @@ pub enum NodeGraphMessage {
}, },
/// Removes an import or export, or hides it if it's the primary, since the primary slot always remains. /// Removes an import or export, or hides it if it's the primary, since the primary slot always remains.
RemoveImportExport { RemoveImportExport {
index: ImportOrExport, index: NetworkConnectorKey,
}, },
ReorderImport { ReorderImport {
start_index: usize, start_index: usize,
@@ -202,13 +207,8 @@ pub enum NodeGraphMessage {
SelectedNodesSet { SelectedNodesSet {
nodes: Vec<NodeId>, nodes: Vec<NodeId>,
}, },
SendClickTargets, UpdateLayersInView,
EndSendClickTargets,
UnloadWires,
SendWires,
UpdateVisibleNodes,
SendGraph, SendGraph,
SendNodePositions,
SetInputValue { SetInputValue {
node_id: NodeId, node_id: NodeId,
input_index: usize, input_index: usize,
@@ -218,10 +218,11 @@ pub enum NodeGraphMessage {
input_connector: InputConnector, input_connector: InputConnector,
input: NodeInput, input: NodeInput,
}, },
/// Asks the frontend to enter inline-rename mode for the given layer's display name in the graph view. BeginEditName {
/// Triggered by double-clicking the layer's name area. name: GraphName,
BeginEditLayerName { },
node_id: NodeId, EndEditName {
name: Option<String>,
}, },
SetDisplayName { SetDisplayName {
node_id: NodeId, node_id: NodeId,
@@ -253,15 +254,11 @@ pub enum NodeGraphMessage {
NudgeSelectedNodes { NudgeSelectedNodes {
direction: Direction, direction: Direction,
}, },
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
ShiftSelectedNodes { ShiftSelectedNodes {
direction: Direction, direction: Direction,
glide: bool,
}, },
/// With `glide`, whatever the shift moves glides to where it lands, rather than jumping there.
ShiftSelectedNodesByAmount { ShiftSelectedNodesByAmount {
graph_delta: IVec2, graph_delta: IVec2,
glide: bool,
}, },
/// Draws the dragged nodes `offset` grid cells from where the drag started, stored once the drag finishes. /// Draws the dragged nodes `offset` grid cells from where the drag started, stored once the drag finishes.
DragSelectedNodes { DragSelectedNodes {
@@ -275,19 +272,19 @@ pub enum NodeGraphMessage {
}, },
SetImportExportName { SetImportExportName {
name: String, name: String,
index: ImportOrExport, index: NetworkConnectorKey,
}, },
SetImportExportNameImpl { SetImportExportNameImpl {
name: String, name: String,
index: ImportOrExport, index: NetworkConnectorKey,
}, },
SetImportExportDescription { SetImportExportDescription {
description: String, description: String,
index: ImportOrExport, index: NetworkConnectorKey,
}, },
SetImportExportDescriptionImpl { SetImportExportDescriptionImpl {
description: String, description: String,
index: ImportOrExport, index: NetworkConnectorKey,
}, },
ToggleSelectedAsLayersOrNodes, ToggleSelectedAsLayersOrNodes,
ToggleSelectedLocked, ToggleSelectedLocked,
@@ -324,7 +321,6 @@ pub enum NodeGraphMessage {
network_path: Vec<NodeId>, network_path: Vec<NodeId>,
}, },
UpdateBoxSelection, UpdateBoxSelection,
/// Shows hovered the connector a press at the pointer would grab, or none.
UpdateHoveredConnector, UpdateHoveredConnector,
/// Highlights the wire a dragged node would be inserted onto if dropped where it is, or stops highlighting one. /// Highlights the wire a dragged node would be inserted onto if dropped where it is, or stops highlighting one.
UpdateWireInsertionPreview, UpdateWireInsertionPreview,
@@ -349,7 +345,6 @@ pub enum NodeGraphMessage {
}, },
UpdateActionButtons, UpdateActionButtons,
UpdateGraphBarRight, UpdateGraphBarRight,
UpdateInSelectedNetwork,
UpdateHints, UpdateHints,
SendSelectedNodes, SendSelectedNodes,
} }
@@ -377,12 +372,14 @@ impl NodeGraphMessage {
| Self::MergeSelectedNodes | Self::MergeSelectedNodes
| Self::ReorderImport { .. } | Self::ReorderImport { .. }
| Self::ReorderExport { .. } | Self::ReorderExport { .. }
| Self::BeginEditName { .. }
| Self::SetImportExportName { .. } | Self::SetImportExportName { .. }
| Self::SetImportExportNameImpl { .. } | Self::SetImportExportNameImpl { .. }
| Self::SetImportExportDescription { .. } | Self::SetImportExportDescription { .. }
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path), | Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
Self::AddNodes { .. } Self::AddNodes { .. }
| Self::CreateNodeFromContextMenu { .. } | Self::CreateNodeFromContextMenu { .. }
| Self::CreateEmptySubgraph { .. }
| Self::CreateWire { .. } | Self::CreateWire { .. }
| Self::CreateWires { .. } | Self::CreateWires { .. }
| Self::ConnectUpstreamOutputToInput { .. } | Self::ConnectUpstreamOutputToInput { .. }
@@ -412,7 +409,6 @@ impl NodeGraphMessage {
| Self::RemoveImportExport { .. } | Self::RemoveImportExport { .. }
| Self::SetInputValue { .. } | Self::SetInputValue { .. }
| Self::SetInput { .. } | Self::SetInput { .. }
| Self::BeginEditLayerName { .. }
| Self::MakeUnique { .. } | Self::MakeUnique { .. }
| Self::SetToNodeOrLayer { .. } | Self::SetToNodeOrLayer { .. }
| Self::ShiftNodePosition { .. } | Self::ShiftNodePosition { .. }
@@ -433,22 +429,18 @@ impl NodeGraphMessage {
| Self::PointerMove { .. } | Self::PointerMove { .. }
| Self::PointerUp | Self::PointerUp
| Self::PointerOutsideViewport { .. } | Self::PointerOutsideViewport { .. }
| Self::MiddleClick
| Self::WireHoverTick | Self::WireHoverTick
| Self::SendGlide | Self::AnimationTick
| Self::GlideTick
| Self::UpdateNodeGraphWidth | Self::UpdateNodeGraphWidth
| Self::RunDocumentGraph | Self::RunDocumentGraph
| Self::ForceRunDocumentGraph | Self::ForceRunDocumentGraph
| Self::SelectedNodesAdd { .. } | Self::SelectedNodesAdd { .. }
| Self::SelectedNodesRemove { .. } | Self::SelectedNodesRemove { .. }
| Self::SelectedNodesSet { .. } | Self::SelectedNodesSet { .. }
| Self::SendClickTargets | Self::UpdateLayersInView
| Self::EndSendClickTargets
| Self::UnloadWires
| Self::SendWires
| Self::UpdateVisibleNodes
| Self::SendGraph | Self::SendGraph
| Self::SendNodePositions | Self::EndEditName { .. }
| Self::TogglePreview { .. } | Self::TogglePreview { .. }
| Self::TogglePreviewImpl { .. } | Self::TogglePreviewImpl { .. }
| Self::UpdateBoxSelection | Self::UpdateBoxSelection
@@ -462,7 +454,6 @@ impl NodeGraphMessage {
| Self::UpdateEvaluationErrors { .. } | Self::UpdateEvaluationErrors { .. }
| Self::UpdateActionButtons | Self::UpdateActionButtons
| Self::UpdateGraphBarRight | Self::UpdateGraphBarRight
| Self::UpdateInSelectedNetwork
| Self::UpdateHints | Self::UpdateHints
| Self::SendSelectedNodes => None, | Self::SendSelectedNodes => None,
} }
File diff suppressed because it is too large. Load diff
@@ -20,6 +20,7 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete, item}; use graph_craft::{Type, concrete, item};
use graphene_std::WarpStyle;
use graphene_std::animation::RealTimeMode; use graphene_std::animation::RealTimeMode;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::raster::{ use graphene_std::raster::{
@@ -40,7 +41,8 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation, build_transform_with_y_preservation,
}; };
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector}; use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
use graphene_std::{NodeParameter, ParameterRef}; use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError}; use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf; use std::path::PathBuf;
@@ -342,7 +344,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
match (number_input.min, number_input.max) { match (number_input.min, number_input.max) {
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => { (Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
let default = definition_default_number(&default_info); let default = definition_default_number(&default_info);
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into() slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
} }
_ => number_widget(default_info, number_input).into(), _ => number_widget(default_info, number_input).into(),
} }
@@ -393,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
false => text_widget(default_info).into(), false => text_widget(default_info).into(),
}, },
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false), Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets), Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)), Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()), Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
@@ -453,9 +455,16 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(), Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(), Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<WarpStyle>(x) => enum_choice::<WarpStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<WaveType>(x) => enum_choice::<WaveType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<DisplaceMode>(x) => enum_choice::<DisplaceMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(), Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(), Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(), Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(), Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(), Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -786,8 +795,10 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
last.clone() last.clone()
} }
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup { /// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info; let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
let size_unit = size_unit.unwrap_or("x");
let mut location_widgets = start_widgets(&parameter_widgets_info); let mut location_widgets = start_widgets(&parameter_widgets_info);
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance()); location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
@@ -854,7 +865,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
scale_widgets.extend_from_slice(&[ scale_widgets.extend_from_slice(&[
NumberInput::new(Some(scale.x)) NumberInput::new(Some(scale.x))
.label("W") .label("W")
.unit("x") .unit(size_unit)
.on_update(update_value_at_index( .on_update(update_value_at_index(
move |w: &NumberInput| { move |w: &NumberInput| {
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix; let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
@@ -868,7 +879,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
Separator::new(SeparatorStyle::Related).widget_instance(), Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(scale.y)) NumberInput::new(Some(scale.y))
.label("H") .label("H")
.unit("x") .unit(size_unit)
.on_update(update_value_at_index( .on_update(update_value_at_index(
move |h: &NumberInput| { move |h: &NumberInput| {
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix; let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
@@ -1212,7 +1223,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
let number_props = number_props.disabled(enabled == Some(false)); let number_props = number_props.disabled(enabled == Some(false));
let mut widgets = match slider { let mut widgets = match slider {
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider), Some(slider) => slider_widget(parameter_widgets_info, number_props, slider),
None => number_widget(parameter_widgets_info, number_props), None => number_widget(parameter_widgets_info, number_props),
}; };
@@ -1326,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
return LayoutGroup::row(vec![]); return LayoutGroup::row(vec![]);
}; };
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() { if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
let entries = BlendMode::list_svg_subset() let entries = BlendMode::list()
.iter() .iter()
.map(|category| { .map(|category| {
category category
@@ -1343,9 +1354,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
widgets.extend_from_slice(&[ widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(entries) DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
.widget_instance(),
]); ]);
} }
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.") LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
@@ -1906,6 +1915,8 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
enum MarkerScale { enum MarkerScale {
/// A 0..100 percentage, placed linearly. /// A 0..100 percentage, placed linearly.
Percent, Percent,
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
LevelPercent,
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center. /// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
Gamma, Gamma,
/// A hue of 0..360 degrees, placed linearly on a track that wraps around. /// A hue of 0..360 degrees, placed linearly on a track that wraps around.
@@ -1915,7 +1926,7 @@ enum MarkerScale {
impl MarkerScale { impl MarkerScale {
fn position(self, value: f64) -> f64 { fn position(self, value: f64) -> f64 {
match self { match self {
Self::Percent => value / 100., Self::Percent | Self::LevelPercent => value / 100.,
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(), Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(), Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
Self::Degrees => { Self::Degrees => {
@@ -1929,7 +1940,7 @@ impl MarkerScale {
fn value(self, position: f64) -> f64 { fn value(self, position: f64) -> f64 {
match self { match self {
Self::Percent => (position * 100.).clamp(0., 100.), Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99), Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.), Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
Self::Degrees => (position * 360.).clamp(0., 360.), Self::Degrees => (position * 360.).clamp(0., 360.),
@@ -1939,6 +1950,7 @@ impl MarkerScale {
fn number_input(self) -> NumberInput { fn number_input(self) -> NumberInput {
match self { match self {
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0), Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2), Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0), Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
} }
@@ -1963,6 +1975,8 @@ struct SliderSectionParam {
dash_to_next: bool, dash_to_next: bool,
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move. /// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
between_neighbors: bool, between_neighbors: bool,
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
overlap_next: MarkerOverlap,
} }
impl SliderSectionParam { impl SliderSectionParam {
@@ -1975,6 +1989,7 @@ impl SliderSectionParam {
pair_with_next: false, pair_with_next: false,
dash_to_next: false, dash_to_next: false,
between_neighbors: false, between_neighbors: false,
overlap_next: MarkerOverlap::Never,
} }
} }
@@ -1992,11 +2007,52 @@ impl SliderSectionParam {
self.dash_to_next = true; self.dash_to_next = true;
self self
} }
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
self.overlap_next = overlap;
self
}
}
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
let mut lower = 0_f64;
let mut upper = 1_f64;
// A neighbor bounds the marker unless they overlap
if overlap(previous) == MarkerOverlap::Never
&& let Some(previous) = position(previous)
{
lower = lower.max(previous);
}
if overlap(Some(index)) == MarkerOverlap::Never
&& let Some(next) = position(next)
{
upper = upper.min(next);
}
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
if bounds_beyond(overlap(previous), overlap(before_previous))
&& let Some(before_previous) = position(before_previous)
{
lower = lower.max(before_previous);
}
if bounds_beyond(overlap(Some(index)), overlap(next))
&& let Some(after_next) = position(after_next)
{
upper = upper.min(after_next);
}
(lower, upper)
} }
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row /// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display. /// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do. /// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) { fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
// Snapshot exposure and values before the mutable-borrow loop // Snapshot exposure and values before the mutable-borrow loop
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) { let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
@@ -2024,6 +2080,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
let mut marker_scales = Vec::new(); let mut marker_scales = Vec::new();
let mut marker_positions = Vec::new(); let mut marker_positions = Vec::new();
let mut marker_between = Vec::new(); let mut marker_between = Vec::new();
let mut marker_overlaps = Vec::new();
let mut marker_colors_and_links = Vec::new(); let mut marker_colors_and_links = Vec::new();
for (i, param) in params.iter().enumerate() { for (i, param) in params.iter().enumerate() {
let (exposed, value) = exposure_and_value[i]; let (exposed, value) = exposure_and_value[i];
@@ -2036,13 +2093,21 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
marker_default_positions.push(param.scale.position(param.default_value)); marker_default_positions.push(param.scale.position(param.default_value));
marker_scales.push(param.scale); marker_scales.push(param.scale);
marker_between.push(param.between_neighbors); marker_between.push(param.between_neighbors);
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker)); marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
} }
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence. // Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span. // A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
let cyclic = params.iter().any(|param| param.scale.cyclic()); let cyclic = params.iter().any(|param| param.scale.cyclic());
if !cyclic { let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
if overlapping {
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
for i in 0..marker_positions.len() {
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
marker_positions[i] = marker_positions[i].max(lower);
}
} else if !cyclic {
let mut floor = 0.; let mut floor = 0.;
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) { for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
if between { if between {
@@ -2063,8 +2128,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
let slider_markers: Vec<SliderMarker> = marker_positions let slider_markers: Vec<SliderMarker> = marker_positions
.iter() .iter()
.zip(&marker_colors_and_links) .zip(&marker_colors_and_links)
.zip(&marker_between) .zip(marker_between.iter().zip(&marker_overlaps))
.map(|((&position, &(handle_color, paired, dashed)), &between)| { .map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
let mut marker = SliderMarker::new(position, 0.5, handle_color); let mut marker = SliderMarker::new(position, 0.5, handle_color);
if paired { if paired {
marker = marker.pair_with_next(); marker = marker.pair_with_next();
@@ -2075,6 +2140,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
if between { if between {
marker = marker.between_neighbors(); marker = marker.between_neighbors();
} }
marker = marker.overlap_next(overlap);
marker marker
}) })
.collect(); .collect();
@@ -2096,6 +2162,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
let marker_scales = marker_scales.clone(); let marker_scales = marker_scales.clone();
let marker_positions = marker_positions.clone(); let marker_positions = marker_positions.clone();
let marker_between = marker_between.clone(); let marker_between = marker_between.clone();
let marker_overlaps = marker_overlaps.clone();
move |update: &SliderInputUpdate| { move |update: &SliderInputUpdate| {
let i = match update { let i = match update {
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize, SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
@@ -2110,8 +2177,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the // The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
// nearest markers that bound it, which a marker placed between its neighbors never does // nearest markers that bound it, which a marker placed between its neighbors never does
let bounding = |j: usize| between || !marker_between[j]; let bounding = |j: usize| between || !marker_between[j];
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]); let (left, right) = if overlapping {
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]); overlap_bounds(&marker_positions, &marker_overlaps, i)
} else {
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
(left, right)
};
let scale_position = match update { let scale_position = match update {
SliderInputUpdate::MoveMarker { position, .. } if between => { SliderInputUpdate::MoveMarker { position, .. } if between => {
@@ -2440,7 +2512,7 @@ fn slider_row(
} }
/// A slider row running linearly across `slider`'s bounds. /// A slider row running linearly across `slider`'s bounds.
pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> { pub(crate) fn slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
slider_row( slider_row(
parameter_widgets_info, parameter_widgets_info,
number_props, number_props,
@@ -2452,7 +2524,7 @@ pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo,
} }
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them. /// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> { pub(crate) fn wrapping_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
slider_row( slider_row(
parameter_widgets_info, parameter_widgets_info,
number_props, number_props,
@@ -2536,6 +2608,105 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
layout layout
} }
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::blending_nodes::blend_if::blend_if::*;
let channel = enum_choice::<BlendIfChannel>()
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
.inspector_row();
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
Some(TaggedValue::BlendIfChannel(channel)) => channel,
_ => BlendIfChannel::Gray,
};
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
BlendIfChannel::Gray => (
[
[
ContentFalloffStartInput.into(),
ContentRangeStartInput.into(),
ContentRangeEndInput.into(),
ContentFalloffEndInput.into(),
],
[
UnderlyingFalloffStartInput.into(),
UnderlyingRangeStartInput.into(),
UnderlyingRangeEndInput.into(),
UnderlyingFalloffEndInput.into(),
],
],
Color::WHITE,
),
BlendIfChannel::Red => (
[
[
RedContentFalloffStartInput.into(),
RedContentRangeStartInput.into(),
RedContentRangeEndInput.into(),
RedContentFalloffEndInput.into(),
],
[
RedUnderlyingFalloffStartInput.into(),
RedUnderlyingRangeStartInput.into(),
RedUnderlyingRangeEndInput.into(),
RedUnderlyingFalloffEndInput.into(),
],
],
Color::RED,
),
BlendIfChannel::Green => (
[
[
GreenContentFalloffStartInput.into(),
GreenContentRangeStartInput.into(),
GreenContentRangeEndInput.into(),
GreenContentFalloffEndInput.into(),
],
[
GreenUnderlyingFalloffStartInput.into(),
GreenUnderlyingRangeStartInput.into(),
GreenUnderlyingRangeEndInput.into(),
GreenUnderlyingFalloffEndInput.into(),
],
],
Color::GREEN,
),
BlendIfChannel::Blue => (
[
[
BlueContentFalloffStartInput.into(),
BlueContentRangeStartInput.into(),
BlueContentRangeEndInput.into(),
BlueContentFalloffEndInput.into(),
],
[
BlueUnderlyingFalloffStartInput.into(),
BlueUnderlyingRangeStartInput.into(),
BlueUnderlyingRangeEndInput.into(),
BlueUnderlyingFalloffEndInput.into(),
],
],
Color::BLUE,
),
};
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
let track = Gradient::from(vec![Color::BLACK, track_color]);
let mut layout = vec![channel];
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
let params = [
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
.dash_to_next()
.overlap_next(MarkerOverlap::Freely),
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
];
build_shared_slider_section(node_id, context, &track, &params, &mut layout);
}
layout
}
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> { pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::raster::vibrance::*; use graphene_std::raster::vibrance::*;
@@ -2545,8 +2716,8 @@ pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorCon
max: 100., max: 100.,
default: Some(0.), default: Some(0.),
}; };
let vibrance = range_slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider); let vibrance = slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
let saturation = range_slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider); let saturation = slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)] vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)]
} }
@@ -2906,7 +3077,7 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> { pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::raster::exposure::*; use graphene_std::raster::exposure::*;
let exposure = range_slider_widget( let exposure = slider_widget(
ParameterWidgetsInfo::new(node_id, ExposureInput, true, context), ParameterWidgetsInfo::new(node_id, ExposureInput, true, context),
NumberInput::default().min(-20.).max(20.), NumberInput::default().min(-20.).max(20.),
SliderRange { SliderRange {
@@ -2915,7 +3086,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
default: Some(0.), default: Some(0.),
}, },
); );
let offset = range_slider_widget( let offset = slider_widget(
ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), ParameterWidgetsInfo::new(node_id, OffsetInput, true, context),
NumberInput::default().min(-0.5).max(0.5), NumberInput::default().min(-0.5).max(0.5),
SliderRange { SliderRange {
@@ -3768,6 +3939,61 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)] vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
} }
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::blending_nodes::filters::sharpen::*;
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
let edges_only = get_document_node(node_id, context)
.ok()
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
}
pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::blending_nodes::distortions::displace::*;
// Each mode shows only the maps and distances it reads, and a wired mode shows both sets
let mode = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ModeInput)) {
Some(TaggedValue::DisplaceMode(mode)) => Some(*mode),
_ => None,
};
let mut layout = vec![enum_choice::<DisplaceMode>().for_socket(ParameterWidgetsInfo::new(node_id, ModeInput, true, context)).inspector_row()];
if !matches!(mode, Some(DisplaceMode::XAndY)) {
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, DisplacementInput, true, context), ColorInput::default()));
let number_input = NumberInput::default().mode_range().unit("°").range_min(Some(-180.)).range_max(Some(180.));
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, AngleInput, true, context), number_input)));
let number_input = NumberInput::default().unit(" px");
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input)));
}
if !matches!(mode, Some(DisplaceMode::Angle)) {
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
}
let edge_mode = enum_choice::<GradientSpread>()
.for_socket(ParameterWidgetsInfo::new(node_id, EdgeModeInput, true, context))
.inspector_row();
layout.push(edge_mode);
layout
}
pub struct ParameterWidgetsInfo<'a> { pub struct ParameterWidgetsInfo<'a> {
document_id: DocumentId, document_id: DocumentId,
network_interface: &'a NodeNetworkInterface, network_interface: &'a NodeNetworkInterface,
@@ -43,71 +43,27 @@ impl FrontendGraphDataType {
} }
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct InputTooltip {
pub struct FrontendGraphInput {
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
pub name: String, pub name: String,
pub description: String, pub description: String,
#[serde(rename = "resolvedType")]
pub resolved_type: String, pub resolved_type: String,
#[serde(rename = "validTypes")]
pub valid_types: Vec<String>, pub valid_types: Vec<String>,
/// Whether a wire feeds this input. /// Whether a wire feeds this input.
pub connected: bool, pub connected: bool,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[derive(Clone, Debug, Eq, PartialEq)]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct OutputTooltip {
pub struct FrontendGraphOutput {
#[serde(rename = "dataType")]
pub data_type: FrontendGraphDataType,
pub name: String, pub name: String,
pub description: String, pub description: String,
#[serde(rename = "resolvedType")]
pub resolved_type: String, pub resolved_type: String,
/// Every type this output could produce given its node's current inputs, or empty where that isn't known. /// Every type this output could produce given its node's current inputs, or empty where that isn't known.
#[serde(rename = "possibleTypes")]
pub possible_types: Vec<String>, pub possible_types: Vec<String>,
/// Whether this output feeds at least one wire. /// Whether this output feeds at least one wire.
pub connected: bool, pub connected: bool,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendNode {
pub id: graph_craft::document::NodeId,
#[serde(rename = "isLayer")]
pub is_layer: bool,
#[serde(rename = "canBeLayer")]
pub can_be_layer: bool,
/// Whether the node is a redirect dot, which is a Passthrough node drawn as a small dot bending the wire running through it.
#[serde(rename = "isRedirectDot")]
pub is_redirect_dot: bool,
pub reference: Option<String>,
#[serde(rename = "displayName")]
pub display_name: String,
#[serde(rename = "implementationName")]
pub implementation_name: String,
#[serde(rename = "primaryInput")]
pub primary_input: Option<FrontendGraphInput>,
#[serde(rename = "exposedInputs")]
pub exposed_inputs: Vec<FrontendGraphInput>,
#[serde(rename = "primaryOutput")]
pub primary_output: Option<FrontendGraphOutput>,
#[serde(rename = "exposedOutputs")]
pub exposed_outputs: Vec<FrontendGraphOutput>,
#[serde(rename = "primaryInputConnectedToLayer")]
pub primary_input_connected_to_layer: bool,
#[serde(rename = "primaryOutputConnectedToLayer")]
pub primary_output_connected_to_layer: bool,
pub position: (i32, i32),
pub previewed: bool,
pub visible: bool,
pub locked: bool,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum InputTypeConstraint { pub enum InputTypeConstraint {
@@ -135,19 +91,6 @@ pub struct DragStart {
pub stored: IVec2, pub stored: IVec2,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BoxSelection {
#[serde(rename = "startX")]
pub start_x: u32,
#[serde(rename = "startY")]
pub start_y: u32,
#[serde(rename = "endX")]
pub end_x: u32,
#[serde(rename = "endY")]
pub end_y: u32,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data")] #[serde(tag = "type", content = "data")]
@@ -180,6 +123,10 @@ pub enum ContextMenuData {
exposed: bool, exposed: bool,
/// Whether any wire is attached to it within the subgraph. /// Whether any wire is attached to it within the subgraph.
connected: bool, connected: bool,
description: String,
/// Where the description popover points, in node graph coordinates.
#[serde(rename = "descriptionAnchor")]
description_anchor: (f64, f64),
}, },
} }
@@ -196,39 +143,12 @@ pub struct ContextMenuInformation {
pub context_menu_data: ContextMenuData, pub context_menu_data: ContextMenuData,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct NodeGraphErrorDiagnostic {
/// The node the error is shown beside, which it follows as the node glides into place.
#[serde(rename = "nodeId")]
pub node_id: NodeId,
pub position: (i32, i32),
pub error: String,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeEvaluationError { pub struct NodeEvaluationError {
pub node_path: Vec<NodeId>, pub node_path: Vec<NodeId>,
pub message: String, pub message: String,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct FrontendClickTargets {
#[serde(rename = "nodeClickTargets")]
pub node_click_targets: Vec<String>,
#[serde(rename = "layerClickTargets")]
pub layer_click_targets: Vec<String>,
#[serde(rename = "connectorClickTargets")]
pub connector_click_targets: Vec<String>,
#[serde(rename = "iconClickTargets")]
pub icon_click_targets: Vec<String>,
#[serde(rename = "allNodesBoundingBox")]
pub all_nodes_bounding_box: String,
#[serde(rename = "importExportNames")]
pub import_export_names: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Direction { pub enum Direction {
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
pub struct OverlaysMessageContext<'a> { pub struct OverlaysMessageContext<'a> {
pub visibility_settings: OverlaysVisibilitySettings, pub visibility_settings: OverlaysVisibilitySettings,
pub viewport: &'a ViewportMessageHandler, pub viewport: &'a ViewportMessageHandler,
pub graph_open: bool,
} }
#[derive(Debug, Clone, Default, ExtractField)] #[derive(Debug, Clone, Default, ExtractField)]
@@ -23,6 +24,9 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
OverlaysMessage::Draw => { OverlaysMessage::Draw => {
use super::utility_types::OverlayContext; use super::utility_types::OverlayContext;
if context.graph_open {
return;
}
let overlay_context = OverlayContext::new(*viewport, visibility_settings); let overlay_context = OverlayContext::new(*viewport, visibility_settings);
if visibility_settings.all() { if visibility_settings.all() {
@@ -1,9 +1,11 @@
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand. //! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
use super::test_support::open_demo; use super::test_support::open_demo;
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::Part;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use glam::DVec2; use glam::DVec2;
use graph_ui::geometry::WireEnd;
use graph_ui::router::route;
use graph_ui::wire::WireStyle;
use graphene_std::uuid::NodeId; use graphene_std::uuid::NodeId;
use std::time::Instant; use std::time::Instant;
@@ -19,26 +21,6 @@ const DEMOS: [&str; 8] = [
]; ];
const REPETITIONS: u32 = 200; const REPETITIONS: u32 = 200;
#[test]
fn wire_anchors_match_the_ports_of_every_demo_node() {
for demo in DEMOS {
let document = open_demo(demo);
let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() {
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
for index in 0..interface.number_of_inputs(node_id, &[]) {
let input = InputConnector::node_at_index(*node_id, index);
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
}
for index in 0..interface.number_of_outputs(node_id, &[]) {
let output = OutputConnector::node(*node_id, index);
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
}
}
}
}
#[test] #[test]
#[ignore] #[ignore]
fn time_the_layout_click_targets_and_hit_tests() { fn time_the_layout_click_targets_and_hit_tests() {
@@ -60,7 +42,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now(); let start = Instant::now();
for _ in 0..REPETITIONS { for _ in 0..REPETITIONS {
for node_id in &node_ids { for node_id in &node_ids {
std::hint::black_box(interface.node_click_targets(node_id, &[])); std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
} }
} }
let all_click_targets = start.elapsed() / REPETITIONS; let all_click_targets = start.elapsed() / REPETITIONS;
@@ -69,7 +51,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now(); let start = Instant::now();
for _ in 0..REPETITIONS { for _ in 0..REPETITIONS {
for input in &inputs { for input in &inputs {
std::hint::black_box(interface.wire_update_from_input(input, GraphWireStyle::default(), &GlideOffsets::default(), &[])); std::hint::black_box(interface.vector_wire_from_input(input, WireStyle::default(), &[]));
} }
} }
let all_wires = start.elapsed() / REPETITIONS; let all_wires = start.elapsed() / REPETITIONS;
@@ -92,25 +74,16 @@ fn time_the_layout_click_targets_and_hit_tests() {
let types = start.elapsed() / REPETITIONS; let types = start.elapsed() / REPETITIONS;
let endpoints: Vec<_> = connected let endpoints: Vec<_> = connected
.iter() .iter()
.filter_map(|(input, output)| Some((interface.output_position(output, &[])?, interface.input_position(input, &[])?))) .filter_map(|(input, output)| Some([interface.output_position(output, &[])?, interface.input_position(input, &[])?].map(|position| WireEnd { position, vertical: false })))
.collect(); .collect();
let start = Instant::now(); let start = Instant::now();
for _ in 0..REPETITIONS { for _ in 0..REPETITIONS {
for (output, input) in &endpoints { for ends in &endpoints {
std::hint::black_box(crate::messages::portfolio::document::utility_types::wires::build_vector_wire( std::hint::black_box(route(*ends, WireStyle::default()));
*output,
*input,
false,
false,
GraphWireStyle::default(),
));
} }
} }
let paths = start.elapsed() / REPETITIONS; let paths = start.elapsed() / REPETITIONS;
let built: Vec<_> = endpoints let built: Vec<_> = endpoints.iter().map(|ends| route(*ends, WireStyle::default())).collect();
.iter()
.map(|(output, input)| crate::messages::portfolio::document::utility_types::wires::build_vector_wire(*output, *input, false, false, GraphWireStyle::default()))
.collect();
let start = Instant::now(); let start = Instant::now();
for _ in 0..REPETITIONS { for _ in 0..REPETITIONS {
for path in &built { for path in &built {
@@ -35,7 +35,6 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) { if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_absolute_position(*position); node.set_absolute_position(*position);
} }
interface.invalidate_positions(network_path);
} }
} }
@@ -172,14 +171,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
interface.finish_drag(&[]); interface.finish_drag(&[]);
let kept = interface.positions(node_ids.iter().copied(), &[]); let kept = interface.positions(node_ids.iter().copied(), &[]);
let Some((_, indices, graph)) = interface.layout_graph(&[]) else { let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
panic!("the root network is laid out") panic!("the root network is laid out")
}; };
let fresh = graph_layout::Layout::new(&graph); let fresh = graph_layout::Layout::new(&graph);
for (other, position) in kept { for (other, position) in kept {
assert_eq!( assert_eq!(
Some(position), Some(position),
indices.get(&other).map(|index| fresh.node(*index).position), laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it" "After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
); );
} }
@@ -53,6 +53,8 @@ pub struct DocumentMetadata {
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>, pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects. /// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
/// The bounding box of the frames that each layer's effects paint anywhere in, in document pixels, for the layers with such effects.
pub layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
/// Transform from document space to viewport space. /// Transform from document space to viewport space.
pub document_to_viewport: DAffine2, pub document_to_viewport: DAffine2,
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include. /// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
@@ -364,7 +366,7 @@ impl DocumentMetadata {
} }
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered /// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a /// stroke geometry when the layer is a vector with a stroke style, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes. /// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> { pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
let stroked = self.layer_vector_data.get(&layer).and_then(|item| { let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
@@ -372,7 +374,8 @@ impl DocumentMetadata {
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths()); let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref()) item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
}); });
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?; let frames = self.layer_effects_frames.get(&layer).copied();
let [min, max] = [stroked, self.bounding_box_document(layer), frames].into_iter().flatten().reduce(Quad::combine_bounds)?;
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default(); let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
Some([min - reach, max + reach]) Some([min - reach, max + reach])
@@ -751,6 +754,25 @@ mod tests {
assert_eq!((min.x, max.x), (0., 110.)); assert_eq!((min.x, max.x), (0., 110.));
} }
#[test]
fn bounds_with_effects_hold_the_frames_the_effects_paint_in() {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
let mut square = BezPath::new();
square.move_to((-30., -30.));
square.line_to((30., -30.));
square.line_to((30., 30.));
square.line_to((-30., 30.));
square.close_path();
// A layer 30 across each way from its middle, with effects painting anywhere in a frame reaching 40 from it, and 2 past that
let mut metadata = DocumentMetadata::default();
metadata.click_targets.insert(layer, vec![Arc::new(ClickTarget::new_with_path(square, 0.))]);
metadata.layer_effects_frames.insert(layer, [DVec2::splat(-40.), DVec2::splat(40.)]);
metadata.layer_effects_reach.insert(layer, 2.);
assert_eq!(metadata.bounding_box_document_with_stroke_and_effects(layer), Some([DVec2::splat(-42.), DVec2::splat(42.)]));
}
#[test] #[test]
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() { fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3)); let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
@@ -2,13 +2,13 @@ use crate::messages::prelude::*;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
/// The layers the frontend shows in view, as rows of the Layers panel and as nodes in the node graph, which are the only ones it's sent the thumbnails of. /// The layers in view in the Layers panel and the node graph, which the graph runtime renders thumbnails for.
/// The latest thumbnail of every layer waits here for whenever the layer comes into view. /// The latest thumbnail of each waits here, and goes to the frontend while its layer has a row in view in the Layers panel.
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct LayersInView { pub struct LayersInView {
/// The layers with a row in view in the Layers panel, which is also sent their details. /// The layers with a row in view in the Layers panel, which is also sent their details.
layers_panel: HashSet<NodeId>, layers_panel: HashSet<NodeId>,
/// The nodes in view in the node graph while it's open. /// The layers in view in the node graph while it's open.
node_graph: HashSet<NodeId>, node_graph: HashSet<NodeId>,
/// The message with the latest thumbnail of each layer, as rendered by the graph runtime. /// The message with the latest thumbnail of each layer, as rendered by the graph runtime.
thumbnails: HashMap<NodeId, FrontendMessage>, thumbnails: HashMap<NodeId, FrontendMessage>,
@@ -29,27 +29,26 @@ impl LayersInView {
/// Sets the layers with a row in view in the Layers panel, sending the thumbnails it lacks for them. /// Sets the layers with a row in view in the Layers panel, sending the thumbnails it lacks for them.
pub fn set_layers_panel(&mut self, layers: HashSet<NodeId>, responses: &mut VecDeque<Message>) { pub fn set_layers_panel(&mut self, layers: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
self.layers_panel = layers; self.layers_panel = layers;
self.send_thumbnails_in_view(responses); self.send_thumbnails_in_layers_panel(responses);
responses.add(PortfolioMessage::SubmitThumbnailsInView); responses.add(PortfolioMessage::SubmitThumbnailsInView);
} }
/// Sets the nodes in view in the node graph, sending the thumbnails it lacks for those that are layers. /// Sets the nodes in view in the node graph, which draws the thumbnails of those that are layers itself.
pub fn set_node_graph(&mut self, nodes: HashSet<NodeId>, responses: &mut VecDeque<Message>) { pub fn set_node_graph(&mut self, nodes: HashSet<NodeId>, responses: &mut VecDeque<Message>) {
self.node_graph = nodes; self.node_graph = nodes;
self.send_thumbnails_in_view(responses);
responses.add(PortfolioMessage::SubmitThumbnailsInView); responses.add(PortfolioMessage::SubmitThumbnailsInView);
} }
pub fn thumbnail_layer(message: &FrontendMessage) -> Option<NodeId> { pub fn thumbnail_layer(message: &FrontendMessage) -> Option<NodeId> {
match message { match message {
FrontendMessage::UpdateNodeThumbnailCanvases { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id), FrontendMessage::UpdateNodeThumbnailCanvas { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id),
_ => None, _ => None,
} }
} }
/// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view. /// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view in the Layers panel.
pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: FrontendMessage, responses: &mut VecDeque<Message>) { pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: FrontendMessage, responses: &mut VecDeque<Message>) {
if self.in_view(&layer) { if self.layers_panel.contains(&layer) {
responses.add(thumbnail.clone()); responses.add(thumbnail.clone());
self.thumbnails_sent.insert(layer); self.thumbnails_sent.insert(layer);
} else { } else {
@@ -79,13 +78,8 @@ impl LayersInView {
} }
} }
fn in_view(&self, layer: &NodeId) -> bool { fn send_thumbnails_in_layers_panel(&mut self, responses: &mut VecDeque<Message>) {
self.layers_panel.contains(layer) || self.node_graph.contains(layer) for &layer in &self.layers_panel {
}
// O(layers in view)
fn send_thumbnails_in_view(&mut self, responses: &mut VecDeque<Message>) {
for &layer in self.layers_panel.iter().chain(&self.node_graph) {
if self.thumbnails_sent.contains(&layer) { if self.thumbnails_sent.contains(&layer) {
continue; continue;
} }
@@ -136,7 +130,7 @@ mod tests {
assert_eq!(thumbnails_sent(responses), vec![(layer, "latest".to_string())], "coming into view, only the latest thumbnail is sent"); assert_eq!(thumbnails_sent(responses), vec![(layer, "latest".to_string())], "coming into view, only the latest thumbnail is sent");
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
layers_in_view.set_node_graph(HashSet::from([layer]), &mut responses); layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
assert!(thumbnails_sent(responses).is_empty(), "a thumbnail the frontend already has isn't sent again"); assert!(thumbnails_sent(responses).is_empty(), "a thumbnail the frontend already has isn't sent again");
} }
@@ -6,4 +6,3 @@ pub mod network_interface;
pub mod nodes; pub mod nodes;
pub mod text_metrics; pub mod text_metrics;
pub mod transformation; pub mod transformation;
pub mod wires;
@@ -9,12 +9,12 @@ pub(crate) use catalog::shipped_node_id;
pub(crate) use derived_ids::derived_node_id; pub(crate) use derived_ids::derived_node_id;
#[cfg(test)] #[cfg(test)]
mod characterization_tests; mod characterization_tests;
mod connectors;
mod derived_ids; mod derived_ids;
mod deserialization; mod deserialization;
pub mod editor_delta; pub mod editor_delta;
#[cfg(test)] #[cfg(test)]
mod editor_delta_tests; mod editor_delta_tests;
mod frontend;
mod geometry; mod geometry;
mod hit_tests; mod hit_tests;
mod invalidation; mod invalidation;
@@ -35,6 +35,7 @@ mod validation;
mod view; mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange}; pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use graph_ui::geometry::{Part, PartTarget};
pub use layout_pass::NetworkLayout; pub use layout_pass::NetworkLayout;
pub use reconcile::{ReconcileError, Reconciled}; pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded; use store::Guarded;
@@ -48,14 +49,11 @@ use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelati
use super::misc::PTZ; use super::misc::PTZ;
use super::nodes::SelectedNodes; use super::nodes::SelectedNodes;
use crate::consts::{ use crate::consts::{
EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, HALF_GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP, EXPORTS_TO_TOP_EDGE_PIXEL_GAP, GRID_SIZE, IMPORTS_TO_LEFT_EDGE_PIXEL_GAP, IMPORTS_TO_TOP_EDGE_PIXEL_GAP, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, STACK_VERTICAL_GAP,
STACK_VERTICAL_GAP,
}; };
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput}; use crate::messages::portfolio::document::node_graph::utility_types::{InputTooltip, OutputTooltip};
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes; use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode; use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata; use deserialization::deserialize_node_persistent_metadata;
@@ -64,6 +62,9 @@ use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId; use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, LiftedNetwork, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, LiftedNetwork, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graph_ui::geometry::is_thick_wire;
use graph_ui::router::route;
use graph_ui::wire::WireStyle;
use graphene_std::Appearance; use graphene_std::Appearance;
use graphene_std::math::quad::Quad; use graphene_std::math::quad::Quad;
use graphene_std::registry::MULTI_OUTPUT_NODES; use graphene_std::registry::MULTI_OUTPUT_NODES;
@@ -477,8 +478,8 @@ mod network_interface_tests {
let mut interface = NodeNetworkInterface::from_trees(network, network_metadata); let mut interface = NodeNetworkInterface::from_trees(network, network_metadata);
assert_eq!(interface.validate_invariants(), Vec::<String>::new()); assert_eq!(interface.validate_invariants(), Vec::<String>::new());
interface.set_import_export_name("Shared".into(), ImportOrExport::Import(0), &[NodeId(10)]); interface.set_import_export_name("Shared".into(), NetworkConnectorKey::Import(0), &[NodeId(10)]);
interface.set_import_export_name("Result".into(), ImportOrExport::Export(0), &[NodeId(10)]); interface.set_import_export_name("Result".into(), NetworkConnectorKey::Export(0), &[NodeId(10)]);
let view = interface.view(&[]).unwrap(); let view = interface.view(&[]).unwrap();
assert_eq!(view.persistent_input_metadata(&NodeId(11), 0).unwrap().input_name, "Shared"); assert_eq!(view.persistent_input_metadata(&NodeId(11), 0).unwrap().input_name, "Shared");
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
EditorDelta::NodeMetadata { network, node_id, change } => { EditorDelta::NodeMetadata { network, node_id, change } => {
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return }; let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
match change { match change {
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()), NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()), NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
NodeMetadataChange::Locked(locked) => node.set_locked(*locked), NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned), NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
@@ -74,48 +74,15 @@ impl NodeNetworkInterface {
} }
} }
pub fn glide_offsets(&self, network_path: &[NodeId]) -> GlideOffsets { /// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
self.network_metadata(network_path)
.map(|network_metadata| network_metadata.transient_metadata.glide_offsets.borrow().clone())
.unwrap_or_default()
}
pub fn set_glide_offsets(&self, glide_offsets: GlideOffsets, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in set_glide_offsets");
return;
};
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
}
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
self.load_import_export_ports(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
}
/// Reads the import/export ports through &self, loading them first if needed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> { pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
self.network_metadata(network_path)? let generation = self.with_layout(network_path, NetworkLayout::generation)?;
.transient_metadata let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
.import_export_ports if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
.with_loaded_or(|| self.compute_import_export_ports(network_path), read) cache.unload();
} }
pub fn load_import_export_ports(&self, network_path: &[NodeId]) { cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
} }
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) { pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
@@ -126,78 +93,13 @@ impl NodeNetworkInterface {
transient.import_export_ports.unload(); transient.import_export_ports.unload();
} }
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
return None;
};
let bounding_box = network_metadata
.transient_metadata
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
/// The combined bounds of every node in the network, in node graph space. /// The combined bounds of every node in the network, in node graph space.
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> { pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let network_metadata = self.network_metadata(network_path)?; self.with_layout(network_path, NetworkLayout::bounds)
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
Some(
nodes
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
)
}
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
return;
};
transient.all_nodes_bounding_box.unload();
transient.import_export_clearance.unload();
self.unload_import_export_ports(network_path);
} }
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> { pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let Some(network_metadata) = self.network_metadata(network_path) else { self.with_layout(network_path, NetworkLayout::clearance)
log::error!("Could not get nested network_metadata in import_export_clearance");
return None;
};
network_metadata
.transient_metadata
.import_export_clearance
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
}
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let network_metadata = self.network_metadata(network_path)?;
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut clearance = ImportExportClearance::default();
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
continue;
};
if self.is_redirect_dot(node_id, network_path) {
let center = (top_left.x + bottom_right.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
}
}
Some(clearance)
} }
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> { pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
@@ -363,7 +265,7 @@ impl NodeNetworkInterface {
} }
} }
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> { pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else { let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in layer_width"); log::error!("Could not get nested node_metadata in layer_width");
return None; return None;
@@ -376,7 +278,7 @@ impl NodeNetworkInterface {
node_metadata node_metadata
.transient_metadata .transient_metadata
.layer_width .layer_width
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width) .with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
} }
/// Unloads layer width if the node is a layer. /// Unloads layer width if the node is a layer.
@@ -392,29 +294,6 @@ impl NodeNetworkInterface {
} }
} }
pub fn get_input_center(&self, input: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
self.input_position(input, network_path)
}
pub fn get_output_center(&self, output: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
self.output_position(output, network_path)
}
/// The wire into the input as the frontend draws it, with its ends following anything drawn gliding into place.
pub fn wire_update_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let wire = self.wire_path_from_input(input, graph_wire_style, false, glide_offsets, network_path)?;
let (id, input_index) = match input {
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
};
Some(WirePathUpdate {
id,
input_index,
wire_path_update: Some(wire),
})
}
pub fn all_input_connectors(&self, network_path: &[NodeId]) -> Vec<InputConnector> { pub fn all_input_connectors(&self, network_path: &[NodeId]) -> Vec<InputConnector> {
let mut input_connectors = Vec::new(); let mut input_connectors = Vec::new();
let Some(network) = self.nested_network(network_path) else { let Some(network) = self.nested_network(network_path) else {
@@ -439,127 +318,25 @@ impl NodeNetworkInterface {
.collect() .collect()
} }
/// Maps to the frontend representation of a wire start. Includes disconnected value wire inputs. /// Returns the wire subpath and whether the wire should be thick, or None if nothing feeds the input.
pub fn node_graph_wire_inputs(&self, network_path: &[NodeId]) -> Vec<(NodeId, usize)> { pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: WireStyle, network_path: &[NodeId]) -> Option<(BezPath, bool)> {
self.node_graph_input_connectors(network_path) let Some(to) = self.input_end(input, network_path) else {
.iter()
.map(|input| match input {
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
})
.chain(std::iter::once((NodeId(u64::MAX), u32::MAX as usize)))
.collect()
}
/// The dashed wire from the previewed node to the export, drawn alongside the export's own wire.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
if self.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in preview: {input:?}");
return None;
};
let input_position = input_position + glide_offsets.input(&input);
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
return None;
};
let output_position = output_position + glide_offsets.output(&upstream_output);
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
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,
is_list,
center_path_string,
});
Some(WirePathUpdate {
id: NodeId(u64::MAX),
input_index: u32::MAX as usize,
wire_path_update,
})
}
/// Returns the wire subpath, its thick center-line subpath, and whether the wire should be thick.
pub fn vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
self.gliding_vector_wire_from_input(input, wire_style, &GlideOffsets::default(), network_path)
}
/// Like [`Self::vector_wire_from_input`], but with its ends following anything drawn gliding into place.
pub(crate) fn gliding_vector_wire_from_input(&self, input: &InputConnector, wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<(BezPath, BezPath, bool)> {
let Some(input_position) = self.get_input_center(input, network_path) else {
log::error!("Could not get dom rect for wire end: {input:?}"); log::error!("Could not get dom rect for wire end: {input:?}");
return None; return None;
}; };
let input_position = input_position + glide_offsets.input(input); let upstream_output = self.upstream_output_connector(input, network_path)?;
// An upstream output could not be found, so the wire does not exist, but it should still be loaded as as empty vector let Some(from) = self.output_end(&upstream_output, network_path) else {
let Some(upstream_output) = self.upstream_output_connector(input, network_path) else {
return Some((BezPath::new(), BezPath::new(), false));
};
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output port for wire start: {upstream_output:?}"); log::error!("Could not get output port for wire start: {upstream_output:?}");
return None; return None;
}; };
let output_position = output_position + glide_offsets.output(&upstream_output); Some((route([from, to], wire_style), is_thick_wire([from, to])))
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
Some((vector_wire, center_line, thick))
}
pub fn wire_path_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, dashed: bool, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePath> {
let (vector_wire, center_line, thick) = self.gliding_vector_wire_from_input(input, graph_wire_style, glide_offsets, network_path)?;
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
let (data_type, is_list) = self
.upstream_output_connector(input, network_path)
.map(|output| {
let output_type = self.output_type(&output, network_path);
(output_type.displayed_type(), output_type.is_list())
})
.unwrap_or((FrontendGraphDataType::General, false));
Some(WirePath {
path_string,
data_type,
thick,
dashed,
is_list,
center_path_string,
})
} }
/// The node's body, ports, and handles, built where it is drawn now. /// The node's body, ports, and handles, built where it is drawn now.
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> { /// The box around the node's body where it sits in its grid cell, in node graph space.
self.compute_node_click_targets(node_id, network_path)
}
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> { pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box()) let body = self.with_layout(network_path, |layout| layout.geometry(node_id)).flatten()?.body();
.flatten() Some([body.min, body.max])
} }
} }
@@ -1,4 +1,4 @@
use super::template::NodeTemplateImplementation; use super::template::{NodeTemplate, NodeTemplateImplementation};
use super::{InputConnector, OutputConnector, catalog}; use super::{InputConnector, OutputConnector, catalog};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd; use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() { async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await; editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]); assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
let custom = NodeId::new(); let custom = NodeId::new();
let blend = NodeId::new(); let blend = NodeId::new();
let interface = &mut editor.active_document_mut().network_interface; let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]); interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]); interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else { let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
panic!("the Blend should name a table entry") panic!("the Blend should name a table entry")
@@ -1,16 +1,16 @@
use super::{ use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, ChainInsertionPoint, FlowType, InputConnector, LayerClickTargetTypes, NetworkConnectorKey, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
}; };
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState; use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction}; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeInput}; use graph_craft::document::{DocumentNodeImplementation, NodeInput};
use graph_ui::wire::WireStyle;
use graphene_std::uuid::NodeId; use graphene_std::uuid::NodeId;
fn assert_invariants(editor: &EditorTestUtils, context: &str) { fn assert_invariants(editor: &EditorTestUtils, context: &str) {
@@ -330,7 +330,6 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
} }
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3)))); let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative); network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
network_interface.invalidate_positions(&[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7))); assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
@@ -1191,12 +1190,7 @@ async fn a_stack_closes_up_over_a_deleted_layer_and_a_nudge_moves_the_rest_one_r
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third] }).await; editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third] }).await;
let network_interface = &editor.active_document().network_interface; let network_interface = &editor.active_document().network_interface;
let before = network_interface.position(&third, &[]).expect("Surviving layer should have a position"); let before = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
editor editor.handle_message(NodeGraphMessage::ShiftSelectedNodes { direction: Direction::Down }).await;
.handle_message(NodeGraphMessage::ShiftSelectedNodes {
direction: Direction::Down,
glide: false,
})
.await;
let network_interface = &editor.active_document().network_interface; let network_interface = &editor.active_document().network_interface;
let after = network_interface.position(&third, &[]).expect("Surviving layer should have a position"); let after = network_interface.position(&third, &[]).expect("Surviving layer should have a position");
assert_eq!(after.y - before.y, 1, "A single nudge should move the layer exactly one unit"); assert_eq!(after.y - before.y, 1, "A single nudge should move the layer exactly one unit");
@@ -1453,13 +1447,13 @@ async fn editing_import_and_export_descriptions_stores_them_on_the_subgraph_node
editor editor
.handle_message(NodeGraphMessage::SetImportExportDescription { .handle_message(NodeGraphMessage::SetImportExportDescription {
description: "The artwork to add.".to_string(), description: "The artwork to add.".to_string(),
index: ImportOrExport::Import(1), index: NetworkConnectorKey::Import(1),
}) })
.await; .await;
editor editor
.handle_message(NodeGraphMessage::SetImportExportDescription { .handle_message(NodeGraphMessage::SetImportExportDescription {
description: "The combined result.".to_string(), description: "The combined result.".to_string(),
index: ImportOrExport::Export(0), index: NetworkConnectorKey::Export(0),
}) })
.await; .await;
@@ -2443,14 +2437,14 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() {
// Level with the wire between the other two // Level with the wire between the other two
network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]); network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]);
assert_eq!( assert_eq!(
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]),
Some((dragged, 0, InputConnector::node_at_index(consumer, 0))), Some((dragged, 0, InputConnector::node_at_index(consumer, 0))),
"the wire it overlaps is the one a drop would insert it onto" "the wire it overlaps is the one a drop would insert it onto"
); );
network_interface.set_absolute_position(&dragged, IVec2::new(8, 10), &[]); network_interface.set_absolute_position(&dragged, IVec2::new(8, 10), &[]);
assert_eq!( assert_eq!(
NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]),
None, None,
"clear of every wire it previews nothing" "clear of every wire it previews nothing"
); );
@@ -2458,7 +2452,7 @@ fn a_node_dragged_over_exactly_one_wire_previews_being_inserted_onto_it() {
// With a node already taking its output, a drop would not insert it // With a node already taking its output, a drop would not insert it
network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]); network_interface.set_absolute_position(&dragged, IVec2::new(8, 0), &[]);
network_interface.set_input(&InputConnector::node_at_index(source, 0), NodeInput::node(dragged, 0), &[]); network_interface.set_input(&InputConnector::node_at_index(source, 0), NodeInput::node(dragged, 0), &[]);
assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, GraphWireStyle::Direct, &[]), None); assert_eq!(NodeGraphMessageHandler::wire_to_insert_on(&mut network_interface, WireStyle::Direct, &[]), None);
} }
fn passthrough_definition() -> DefinitionIdentifier { fn passthrough_definition() -> DefinitionIdentifier {
@@ -2865,7 +2859,7 @@ async fn double_click_in_graph(editor: &mut EditorTestUtils, point: DVec2, secon
fn wire_middle(network_interface: &NodeNetworkInterface, input: InputConnector) -> DVec2 { fn wire_middle(network_interface: &NodeNetworkInterface, input: InputConnector) -> DVec2 {
use kurbo::ParamCurveArclen; use kurbo::ParamCurveArclen;
let (wire, _, _) = network_interface.vector_wire_from_input(&input, GraphWireStyle::Direct, &[]).expect("the wire should have a path"); let (wire, _) = network_interface.vector_wire_from_input(&input, WireStyle::Direct, &[]).expect("the wire should have a path");
let longest_segment = wire let longest_segment = wire
.segments() .segments()
.max_by(|a, b| a.arclen(kurbo::DEFAULT_ACCURACY).total_cmp(&b.arclen(kurbo::DEFAULT_ACCURACY))) .max_by(|a, b| a.arclen(kurbo::DEFAULT_ACCURACY).total_cmp(&b.arclen(kurbo::DEFAULT_ACCURACY)))
@@ -3119,7 +3113,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let path = [subgraph]; let path = [subgraph];
editor.enter_editable_network(subgraph).await; editor.enter_editable_network(subgraph).await;
@@ -3400,6 +3394,63 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
); );
} }
#[tokio::test]
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
let graph_pan = |editor: &EditorTestUtils| {
editor
.active_document()
.network_interface
.network_metadata(&[])
.unwrap()
.persistent_metadata
.navigation_metadata
.node_graph_ptz
.pan
};
let layer_in_viewport = |editor: &EditorTestUtils| {
let network_interface = &editor.active_document().network_interface;
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
(0..=(max.x - min.x) as i32)
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
.expect("the layer should be pressable")
};
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
editor_position: position,
mouse_keys,
..Default::default()
};
// Pressed and released with a wobble too small to count as a drag
let start = layer_in_viewport(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
// Dragged away and back before the release
let start = layer_in_viewport(&editor);
let pan_before = graph_pan(&editor);
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
editor.handle_message(DocumentMessage::Undo).await;
assert!(is_visible(&editor), "one undo should revert the middle click");
}
#[tokio::test] #[tokio::test]
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() { async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
@@ -3506,7 +3557,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export. /// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) { async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.enter_editable_network(subgraph).await; editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddImport).await; editor.handle_message(NodeGraphMessage::AddImport).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await; editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
@@ -3655,96 +3706,18 @@ fn a_wire_is_found_near_its_path_but_not_away_from_it() {
let input = InputConnector::node_at_index(consumer, 0); let input = InputConnector::node_at_index(consumer, 0);
let on_wire = wire_middle(&network_interface, input); let on_wire = wire_middle(&network_interface, input);
assert_eq!(network_interface.wire_input_from_point(on_wire, 6., GraphWireStyle::Direct, &[]), Some(input)); assert_eq!(network_interface.wire_input_from_point(on_wire, 6., WireStyle::Direct, &[]), Some(input));
assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., GraphWireStyle::Direct, &[]), None); assert_eq!(network_interface.wire_input_from_point(on_wire + DVec2::new(0., 200.), 6., WireStyle::Direct, &[]), None);
}
#[tokio::test]
async fn a_dragged_layer_keeps_its_wires_where_it_is_drawn_in_the_frame_it_moves() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, ..) = layer_with_chain(&mut editor).await;
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
let left_input = InputConnector::layer_secondary_input(layer);
let network_interface = &editor.active_document().network_interface;
let wire_before = network_interface.wire_path_from_input(&left_input, GraphWireStyle::default(), false, &GlideOffsets::default(), &[]);
let bounds = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
let press = DVec2::new(bounds[1].x - 30., (bounds[0].y + bounds[1].y) / 2.);
let node_graph_to_viewport = network_interface
.network_metadata(&[])
.expect("the network should have metadata")
.persistent_metadata
.navigation_metadata
.node_graph_to_viewport;
let pressed = node_graph_to_viewport.transform_point2(press);
editor.move_mouse(pressed.x, pressed.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor
.handle_message(NodeGraphMessage::PointerDown {
shift_click: false,
control_click: false,
alt_click: false,
right_click: false,
})
.await;
// One grid cell right, through the input preprocessor so the frontend messages of the move itself are returned
let moved = node_graph_to_viewport.transform_point2(press + DVec2::new(GRID_SIZE as f64, 0.));
let editor_mouse_state = EditorPointerState {
editor_position: moved,
mouse_keys: MouseKeys::LEFT,
..Default::default()
};
let messages = editor
.handle_message(InputPreprocessorMessage::PointerMove {
editor_mouse_state,
modifier_keys: ModifierKeys::empty(),
})
.await;
// Still drawn a whole cell back as it starts gliding, so the last wire sent to its left input is the one from before the move
let last_wire_sent = messages
.into_iter()
.filter_map(|message| match message {
FrontendMessage::UpdateNodeGraphWires { wires } => Some(wires),
_ => None,
})
.flatten()
.rfind(|wire| wire.id == layer && wire.input_index == 1)
.and_then(|wire| wire.wire_path_update);
assert_eq!(last_wire_sent.map(|wire| wire.path_string), wire_before.map(|wire| wire.path_string));
}
/// Nudges the only node of a new document while its graph is open, so the node starts gliding into the cell it moved to.
async fn gliding_nudged_node(editor: &mut EditorTestUtils) -> NodeId {
editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await;
assert!(
!editor.active_document().network_interface.glide_offsets(&[]).is_empty(),
"the nudged node should be gliding: fixture is wrong"
);
node
}
#[tokio::test]
async fn redoing_a_nudge_undone_while_it_glides_leaves_nothing_gliding() {
let mut editor = EditorTestUtils::create();
gliding_nudged_node(&mut editor).await;
editor.handle_message(DocumentMessage::Undo).await;
editor.handle_message(DocumentMessage::Redo).await;
assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty());
} }
#[tokio::test] #[tokio::test]
async fn undoing_a_nudge_keeps_the_node_it_moved() { async fn undoing_a_nudge_keeps_the_node_it_moved() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
let node = gliding_nudged_node(&mut editor).await; editor.new_document().await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node] }).await;
editor.handle_message(NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }).await;
editor.handle_message(DocumentMessage::Undo).await; editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.position(&node, &[]), Some(IVec2::ZERO)); assert_eq!(editor.active_document().network_interface.position(&node, &[]), Some(IVec2::ZERO));
@@ -3766,17 +3739,6 @@ async fn undoing_right_after_creating_a_node_removes_only_that_node() {
assert_eq!(nodes.keys().copied().collect::<Vec<_>>(), vec![kept]); assert_eq!(nodes.keys().copied().collect::<Vec<_>>(), vec![kept]);
} }
#[tokio::test]
async fn entering_a_node_while_its_network_glides_settles_it() {
let mut editor = EditorTestUtils::create();
gliding_nudged_node(&mut editor).await;
let merge = editor.create_node_by_name_at(merge_definition(), 20, 0).await;
editor.enter_editable_network(merge).await;
assert!(editor.active_document().network_interface.glide_offsets(&[]).is_empty());
}
#[tokio::test] #[tokio::test]
async fn resting_a_wire_on_an_exposed_input_reveals_nothing_that_would_move_it_from_under_the_pointer() { async fn resting_a_wire_on_an_exposed_input_reveals_nothing_that_would_move_it_from_under_the_pointer() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
@@ -4041,18 +4003,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
); );
} }
#[tokio::test]
async fn a_new_subgraph_is_its_own_definition() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &editor.active_document().network_interface;
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
}
#[tokio::test] #[tokio::test]
async fn cannot_preview_node_without_outputs() { async fn cannot_preview_node_without_outputs() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface; let network_interface = &mut editor.active_document_mut().network_interface;
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0); assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
// Attempting to toggle preview on a node without outputs should not enable previewing // Attempting to toggle preview on a node without outputs should not enable previewing
network_interface.toggle_preview(custom_node, &[]); network_interface.toggle_preview(subgraph, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No); assert_eq!(network_interface.previewing(&[]), Previewing::No);
} }
@@ -4216,3 +4190,73 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
assert_eq!(overlapping_layers(&editor), Vec::new()); assert_eq!(overlapping_layers(&editor), Vec::new());
assert_invariants(&editor, "after grouping a group"); assert_invariants(&editor, "after grouping a group");
} }
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
let interface = &editor.active_document().network_interface;
let parent = layer.parent(interface.document_metadata())?;
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
}
#[tokio::test]
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
for x in [0., 50., 100.] {
editor.draw_rect(x, 0., x + 40., 40.).await;
}
let artboard = LayerNodeIdentifier::ROOT_PARENT
.children(editor.active_document().metadata())
.next()
.expect("the artboard should be a layer");
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
group_selected_layers(&mut editor).await;
let group = artboard
.children(editor.active_document().metadata())
.next()
.expect("the group should be the top layer of the artboard");
for insert_index in [0, 2] {
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
for layer in group.children(editor.active_document().metadata()).chain([group]) {
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
}
}
assert_eq!(overlapping_layers(&editor), Vec::new());
}
#[tokio::test]
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
for x in [0., 50., 100., 150.] {
editor.draw_rect(x, 0., x + 40., 40.).await;
}
let artboard = LayerNodeIdentifier::ROOT_PARENT
.children(editor.active_document().metadata())
.next()
.expect("the artboard should be a layer");
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
let interface = &mut editor.active_document_mut().network_interface;
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
for keep_upstream in [false, true] {
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
let before = interface.positions(layers.iter().copied(), &[]);
interface.drag_selected_nodes(offset, keep_upstream, &[]);
let dragging = interface.positions(layers.iter().copied(), &[]);
interface.finish_drag(&[]);
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
}
}
}
@@ -1,56 +1,20 @@
//! The shapes the node graph frontend is sent: one entry per visible port, carrying its type, its //! The connectors the graph UI's rows and tooltips are built from: one entry per visible port, carrying its type,
//! name and whether it's connected. Read-only projections of the graph, rather than a source of truth. //! its name and whether it's connected. Read-only projections of the graph, rather than a source of truth.
use super::resolved_types::TypeSource; use super::resolved_types::TypeSource;
use super::*; use super::*;
impl NodeNetworkInterface { impl NodeNetworkInterface {
pub fn frontend_imports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphOutput>> { /// Returns None if there is an error, it is a hidden primary export, or a hidden or missing input
match network_path.split_last() { pub fn input_tooltip(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<InputTooltip> {
Some((node_id, encapsulating_network_path)) => { let (name, input_type, connected) = self.graph_ui_input(input_connector, network_path)?;
let Some(node) = self.document_node(node_id, encapsulating_network_path) else { let description = match input_connector {
log::error!("Could not get node {node_id} in network {encapsulating_network_path:?}"); InputConnector::Node { node_id, input_index } => self
return Vec::new(); .persistent_input_metadata(node_id, *input_index, network_path)
}; .map(|metadata| metadata.input_description.clone())
let mut frontend_imports = (0..node.inputs.len()) .unwrap_or_default(),
.map(|import_index| self.frontend_output_from_connector(&OutputConnector::Import(import_index), network_path)) InputConnector::Export(export_index) => self.export_description(*export_index, network_path),
.collect::<Vec<_>>();
if frontend_imports.is_empty() {
frontend_imports.push(None);
}
frontend_imports
}
// In the document network display no imports
None => Vec::new(),
}
}
pub fn frontend_exports(&self, network_path: &[NodeId]) -> Vec<Option<FrontendGraphInput>> {
let Some(network) = self.nested_network(network_path) else { return Vec::new() };
let mut frontend_exports = ((0..network.exports.len()).map(|export_index| self.frontend_input_from_connector(&InputConnector::Export(export_index), network_path))).collect::<Vec<_>>();
if frontend_exports.is_empty() {
frontend_exports.push(None);
}
frontend_exports
}
/// Returns None if there is an error, it is a hidden primary export, or a hidden input
pub fn frontend_input_from_connector(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<FrontendGraphInput> {
// Return None if it is a hidden input
if self.input_from_connector(input_connector, network_path).is_some_and(|input| !input.is_exposed()) {
return None;
}
let input_type = self.input_type(input_connector, network_path);
let data_type = input_type.displayed_type();
let resolved_type = input_type.resolved_type_node_string();
let connected = self.upstream_output_connector(input_connector, network_path).is_some();
let (name, description) = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path),
InputConnector::Export(export_index) => (self.displayed_export_name(*export_index, network_path), self.export_description(*export_index, network_path)),
}; };
let valid_types = match input_connector { let valid_types = match input_connector {
InputConnector::Node { .. } => self.potential_valid_input_types(input_connector, network_path), InputConnector::Node { .. } => self.potential_valid_input_types(input_connector, network_path),
// An export takes any type itself, so it's limited only by what its subgraph node's output feeds, or at the document's root, what can be rendered // An export takes any type itself, so it's limited only by what its subgraph node's output feeds, or at the document's root, what can be rendered
@@ -60,22 +24,47 @@ impl NodeNetworkInterface {
.filter(|valid_type| !valid_type.nested_type().is_generic()) .filter(|valid_type| !valid_type.nested_type().is_generic())
.collect(), .collect(),
}; };
let valid_types = distinct_type_names(&valid_types); Some(InputTooltip {
resolved_type: input_type.resolved_type_node_string(),
Some(FrontendGraphInput {
data_type,
resolved_type,
name, name,
description, description,
valid_types, valid_types: distinct_type_names(&valid_types),
connected, connected,
}) })
} }
/// Returns None if there is an error, it is the document network, a hidden primary output or import /// Returns None if there is an error, it is the document network, a hidden primary output or import
pub fn frontend_output_from_connector(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<FrontendGraphOutput> { pub fn output_tooltip(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<OutputTooltip> {
let (name, output_type, connected) = self.graph_ui_output(output_connector, network_path)?;
let description = match output_connector {
OutputConnector::Node { node_id, output_index } => self.output_description(node_id, *output_index, network_path),
OutputConnector::Import(import_index) => self.import_description(*import_index, network_path),
};
Some(OutputTooltip {
resolved_type: output_type.resolved_type_node_string(),
name,
description,
possible_types: distinct_type_names(&self.possible_output_types(output_connector, network_path)),
connected,
})
}
pub fn graph_ui_input(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> {
// Return None if it is a hidden or missing input
if !self.input_from_connector(input_connector, network_path).is_some_and(|input| input.is_exposed()) {
return None;
}
let name = match input_connector {
InputConnector::Node { node_id, input_index } => self.displayed_input_name_and_description(node_id, *input_index, network_path).0,
InputConnector::Export(export_index) => self.displayed_export_name(*export_index, network_path),
};
let connected = self.upstream_output_connector(input_connector, network_path).is_some();
Some((name, self.input_type(input_connector, network_path), connected))
}
pub fn graph_ui_output(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<(String, TypeSource, bool)> {
let output_type = self.output_type(output_connector, network_path); let output_type = self.output_type(output_connector, network_path);
let (name, description) = match output_connector { let name = match output_connector {
OutputConnector::Node { node_id, output_index } => { OutputConnector::Node { node_id, output_index } => {
// Do not display the primary output port for a node if it is a network node with a hidden primary export // Do not display the primary output port for a node if it is a network node with a hidden primary export
if *output_index == 0 && self.hidden_primary_output(node_id, network_path) { if *output_index == 0 && self.hidden_primary_output(node_id, network_path) {
@@ -85,8 +74,7 @@ impl NodeNetworkInterface {
let output_names = self.view(network_path).ok()?.output_names(node_id).ok()?; let output_names = self.view(network_path).ok()?.output_names(node_id).ok()?;
let output_name = output_names.get(*output_index).cloned().unwrap_or_default(); let output_name = output_names.get(*output_index).cloned().unwrap_or_default();
let output_name = if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() }; if !output_name.is_empty() { output_name } else { output_type.resolved_type_node_string() }
(output_name, self.output_description(node_id, *output_index, network_path))
} }
OutputConnector::Import(import_index) => { OutputConnector::Import(import_index) => {
// Return None if it is an import in the document network // Return None if it is an import in the document network
@@ -98,24 +86,13 @@ impl NodeNetworkInterface {
return None; return None;
}; };
(self.displayed_import_name(*import_index, network_path), self.import_description(*import_index, network_path)) self.displayed_import_name(*import_index, network_path)
} }
}; };
let data_type = output_type.displayed_type();
let resolved_type = output_type.resolved_type_node_string();
let possible_types = distinct_type_names(&self.possible_output_types(output_connector, network_path));
let connected = self let connected = self
.with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).is_some_and(|inputs| !inputs.is_empty())) .with_outward_wires(network_path, |outward_wires| outward_wires.get(output_connector).is_some_and(|inputs| !inputs.is_empty()))
.unwrap_or_default(); .unwrap_or_default();
Some((name, output_type, connected))
Some(FrontendGraphOutput {
data_type,
resolved_type,
name,
description,
possible_types,
connected,
})
} }
/// Returns the input name to display in the Inspector. If the input has no name then its type is used. /// Returns the input name to display in the Inspector. If the input has no name then its type is used.
@@ -62,11 +62,21 @@ pub enum NodeMetadataChange {
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which /// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
/// merge independently, so a concurrent move and a concurrent layer toggle both survive. /// merge independently, so a concurrent move and a concurrent layer toggle both survive.
NodeType(NodeTypePersistentMetadata), NodeType(NodeTypePersistentMetadata),
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
Position(NodeTypePersistentMetadata),
DisplayName(String), DisplayName(String),
Locked(bool), Locked(bool),
Pinned(bool), Pinned(bool),
} }
impl NodeMetadataChange {
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
}
}
/// One field of a network's persistent metadata. The navigation transform and width are absent /// One field of a network's persistent metadata. The navigation transform and width are absent
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry. /// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@@ -319,6 +329,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))), node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
] ]
} }
NodeMetadataChange::Position(node_type) => vec![node_attribute(
node_attr::ui::POSITION,
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
)],
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))], NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))], NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))], NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
@@ -3,6 +3,7 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
use super::storage_metadata::StorageMetadataView; use super::storage_metadata::StorageMetadataView;
use super::{InputConnector, NodeTemplate}; use super::{InputConnector, NodeTemplate};
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::delta::compute_deltas; use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session}; use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
@@ -184,7 +185,7 @@ async fn per_field_metadata_edits_match_the_diff() {
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())), metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)), metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)), metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())), metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
EditorDelta::Graph(RuntimeDelta::SetVisibility { EditorDelta::Graph(RuntimeDelta::SetVisibility {
network: None, network: None,
node_id: node, node_id: node,
@@ -283,6 +284,32 @@ async fn unchanged_writes_emit_nothing() {
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}"); assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
} }
#[tokio::test]
async fn moving_a_layer_writes_only_its_position() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 40., 40.).await;
let layer = LayerNodeIdentifier::ROOT_PARENT
.children(editor.active_document().metadata())
.next()
.expect("the rectangle should be a layer")
.to_node();
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
let emitted = committed_deltas(&mut editor);
let written: Vec<String> = construct(&editor, &emitted, &working)
.into_iter()
.filter_map(|op| match op {
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
_ => None,
})
.collect();
assert_eq!(written, [node_attr::ui::POSITION]);
}
/// Structural writes go through the store too, so inserting and deleting a node must be recorded /// Structural writes go through the store too, so inserting and deleting a node must be recorded
/// without the caller saying anything about it. /// without the caller saying anything about it.
#[tokio::test] #[tokio::test]
@@ -4,243 +4,13 @@
//! the caller decides whether to cache the result. //! the caller decides whether to cache the result.
use super::*; use super::*;
use graph_ui::label_width;
use graph_ui::metrics::{LAYER_GRIP_WIDTH, LAYER_NAME_LEFT};
use graph_ui::network_connector::{NetworkConnectorKind, network_connector_name_box, network_connector_row_offset};
impl NodeNetworkInterface { impl NodeNetworkInterface {
pub(super) fn node_input_anchor(&self, node_id: &NodeId, input_index: usize, network_path: &[NodeId]) -> Option<DVec2> {
let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64;
let grid = GRID_SIZE as f64;
let inputs = &self.document_node(node_id, network_path)?.inputs;
if self.is_redirect_dot(node_id, network_path) {
return (input_index == 0).then_some(top_left + DVec2::new(0., grid));
}
if self.is_layer(node_id, network_path) {
return match input_index {
0 => Some(top_left + DVec2::new(2. * grid, 2. * grid + 8.)),
1 if inputs.iter().filter(|input| input.is_exposed()).count() > 1 => Some(top_left + DVec2::new(0., grid)),
_ => None,
};
}
if !inputs.get(input_index)?.is_exposed() {
return None;
}
let row = inputs.iter().take(input_index).enumerate().filter(|(index, input)| *index == 0 || input.is_exposed()).count();
Some(top_left + DVec2::new(0., grid * (row as f64 + 1.)))
}
pub(super) fn node_output_anchor(&self, node_id: &NodeId, output_index: usize, network_path: &[NodeId]) -> Option<DVec2> {
let top_left = self.position(node_id, network_path)?.as_dvec2() * GRID_SIZE as f64;
let grid = GRID_SIZE as f64;
if self.is_redirect_dot(node_id, network_path) {
return (output_index == 0).then_some(top_left + DVec2::new(0., grid));
}
if self.is_layer(node_id, network_path) {
return (output_index == 0).then_some(top_left + DVec2::new(2. * grid, -8.));
}
let hidden = output_index == 0 && self.hidden_primary_output(node_id, network_path);
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
}
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_ports for node {node_id}");
return None;
};
let document_node = self.document_node(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut ports = Ports::new();
if self.is_redirect_dot(node_id, network_path) {
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
} else if !self.is_layer(node_id, network_path) {
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
ports.insert_node_input(input_index, input_row_count, node_top_left);
}
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
ports.insert_node_output(output_index, node_top_left);
}
} else {
ports.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
ports.insert_layer_input(1, node_top_left);
}
ports.insert_layer_output(node_top_left);
}
Some(ports)
}
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
return None;
};
let node_metadata = self.node_metadata(node_id, network_path)?;
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
if self.is_redirect_dot(node_id, network_path) {
const DOT_HALF_WIDTH: f64 = 15.;
const DOT_HALF_HEIGHT: f64 = 8.;
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
let path = rounded_rectangle_path(
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
[DOT_HALF_HEIGHT; 4],
);
return Some(DocumentNodeClickTargets {
node_click_target: ClickTarget::new_with_path(path, 0.),
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
});
}
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
Some(document_node_click_targets)
}
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu. /// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
/// Laid out as the frontend draws them, just past the connector. pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(NetworkConnectorKey, [DVec2; 2])> {
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
// How far past the port's center the name begins
const IMPORT_NAME_INSET: f64 = 8.;
const EXPORT_NAME_INSET: f64 = 9.;
const FONT_SIZE: f64 = 14.;
if network_path.is_empty() { if network_path.is_empty() {
return Vec::new(); return Vec::new();
} }
@@ -259,16 +29,13 @@ impl NodeNetworkInterface {
return Vec::new(); return Vec::new();
}; };
let half_row = DVec2::new(0., HALF_GRID_SIZE as f64);
let imports = import_centers.into_iter().map(|(import_index, center)| { let imports = import_centers.into_iter().map(|(import_index, center)| {
let name_width = text_width(&self.displayed_import_name(import_index, network_path), FONT_SIZE); let name_width = label_width(&self.displayed_import_name(import_index, network_path));
let name_right = center - DVec2::new(IMPORT_NAME_INSET, 0.); (NetworkConnectorKey::Import(import_index), network_connector_name_box(NetworkConnectorKind::Import, center, name_width))
(ImportOrExport::Import(import_index), [name_right - DVec2::new(name_width, 0.) - half_row, name_right + half_row])
}); });
let exports = export_centers.into_iter().map(|(export_index, center)| { let exports = export_centers.into_iter().map(|(export_index, center)| {
let name_width = text_width(&self.displayed_export_name(export_index, network_path), FONT_SIZE); let name_width = label_width(&self.displayed_export_name(export_index, network_path));
let name_left = center + DVec2::new(EXPORT_NAME_INSET, 0.); (NetworkConnectorKey::Export(export_index), network_connector_name_box(NetworkConnectorKind::Export, center, name_width))
(ImportOrExport::Export(export_index), [name_left - half_row, name_left + DVec2::new(name_width, 0.) + half_row])
}); });
imports.chain(exports).collect() imports.chain(exports).collect()
} }
@@ -285,13 +52,13 @@ impl NodeNetworkInterface {
if !network_path.is_empty() { if !network_path.is_empty() {
let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 }; let import_start_index = if self.hidden_primary_import(network_path) { 1 } else { 0 };
for import_index in import_start_index..self.number_of_imports(network_path) { for import_index in import_start_index..self.number_of_imports(network_path) {
import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., import_export_row_offset(import_index))); import_export_ports.insert_output_port_at_center(import_index, import_export_position.0.as_dvec2() + DVec2::new(0., network_connector_row_offset(import_index)));
} }
} }
let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 }; let export_start_index = if self.hidden_primary_export(network_path) { 1 } else { 0 };
for export_index in export_start_index..network.exports.len() { for export_index in export_start_index..network.exports.len() {
import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., import_export_row_offset(export_index))); import_export_ports.insert_input_port_at_center(export_index, import_export_position.1.as_dvec2() + DVec2::new(0., network_connector_row_offset(export_index)));
} }
Some(import_export_ports) Some(import_export_ports)
@@ -320,7 +87,7 @@ impl NodeNetworkInterface {
connectors.push((0, first_row_center)); connectors.push((0, first_row_center));
} }
let next_index = count.max(1); let next_index = count.max(1);
connectors.push((next_index, first_row_center + DVec2::new(0., import_export_row_offset(next_index) + GRID_SIZE as f64))); connectors.push((next_index, first_row_center + DVec2::new(0., network_connector_row_offset(next_index) + GRID_SIZE as f64)));
connectors connectors
} }
@@ -336,27 +103,22 @@ impl NodeNetworkInterface {
if y < first_row_center + GRID_SIZE as f64 { if y < first_row_center + GRID_SIZE as f64 {
return Some(0); return Some(0);
} }
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count)) Some((1..row_count).find(|&row| first_row_center + network_connector_row_offset(row) > y).unwrap_or(row_count))
} }
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached /// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
/// because measuring the name's text is slow. /// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 { pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
let thumbnail_width = 3. * GRID_SIZE as f64;
let layer_text = self.display_name(node_id, network_path); let layer_text = self.display_name(node_id, network_path);
let text_width = text_width(&layer_text, FONT_SIZE); let text_width = label_width(&layer_text);
let grip_padding = 4.; let grip_padding = 4.;
let grip_width = 8.;
let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. }; let lock_icon_width = if self.is_locked(node_id, network_path) { GRID_SIZE as f64 } else { 0. };
let icon_overhang_width = GRID_SIZE as f64 / 2.; let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width; let layer_width_pixels = LAYER_NAME_LEFT + text_width + grip_padding + LAYER_GRIP_WIDTH + lock_icon_width + icon_overhang_width;
((layer_width_pixels / 24.).ceil() as u32).max(8) (((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
} }
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> { pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else { let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
@@ -445,9 +207,3 @@ impl NodeNetworkInterface {
Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2())) Some((rounded_import_top_left.as_ivec2(), rounded_export_top_right.as_ivec2()))
} }
} }
/// How far below the first import or export the one at `index` sits, with a grid cell of space separating the primary from the secondary ones.
fn import_export_row_offset(index: usize) -> f64 {
let rows = if index == 0 { 0 } else { index + 1 };
(rows * GRID_SIZE as usize) as f64
}
@@ -1,4 +1,5 @@
use super::*; use super::*;
use graph_ui::geometry::WireEnd;
use graphene_std::vector::misc::dvec2_to_point; use graphene_std::vector::misc::dvec2_to_point;
use kurbo::{DEFAULT_ACCURACY, ParamCurveNearest}; use kurbo::{DEFAULT_ACCURACY, ParamCurveNearest};
@@ -24,81 +25,6 @@ impl NodeNetworkInterface {
all_selected_nodes all_selected_nodes
} }
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
let mut all_node_click_targets = Vec::new();
let mut connector_click_targets = Vec::new();
let mut icon_click_targets = Vec::new();
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
return FrontendClickTargets::default();
};
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
self.with_import_export_ports(network_path, |import_export_click_targets| {
for port in import_export_click_targets.click_targets() {
if let ClickTargetType::Path(path) = port.target_type() {
connector_click_targets.push(path.to_svg());
}
}
});
nodes.into_iter().for_each(|node_id| {
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
let mut node_path = String::new();
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
node_path.push_str(path.to_svg().as_str())
}
all_node_click_targets.push((node_id, node_path));
for port in node_click_targets.port_click_targets.click_targets() {
if let ClickTargetType::Path(path) = port.target_type() {
connector_click_targets.push(path.to_svg());
}
}
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
// Visibility button (eye icon)
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
icon_click_targets.push(path.to_svg());
}
// Lock button (padlock icon), only when the layer is locked
if let Some(lock_click_target) = &layer_metadata.lock_click_target
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
{
icon_click_targets.push(path.to_svg());
}
// Drag grip (dotted symbol)
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
icon_click_targets.push(path.to_svg());
}
}
});
});
let mut layer_click_targets = Vec::new();
let mut node_click_targets = Vec::new();
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
if self.is_layer(&node_id, network_path) {
layer_click_targets.push(path);
} else {
node_click_targets.push(path);
}
});
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
let import_export_names = self
.import_export_name_bounds(network_path)
.into_iter()
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
.collect();
FrontendClickTargets {
node_click_targets,
layer_click_targets,
connector_click_targets,
icon_click_targets,
all_nodes_bounding_box,
import_export_names,
}
}
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) { pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
self.document_metadata.document_to_viewport = transform; self.document_metadata.document_to_viewport = transform;
} }
@@ -123,6 +49,21 @@ impl NodeNetworkInterface {
Some(&mut navigation.node_graph_ptz) Some(&mut navigation.node_graph_ptz)
} }
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
/// grid cell, and an input by its index rather than the row a node draws it in.
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
self.with_layout(network_path, |layout| {
layout.find_part(node_id, |geometry, target| {
let part = match target.part {
Part::Input(place) => Part::Input(geometry.input_at(place)? as u32),
part => part,
};
find(part, target)
})
})
.flatten()
}
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets. /// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> { pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
let Some(network_metadata) = self.network_metadata(network_path) else { let Some(network_metadata) = self.network_metadata(network_path) else {
@@ -131,18 +72,13 @@ impl NodeNetworkInterface {
}; };
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
// Each node is pressed where it's drawn, even while gliding into its grid cell let reaching = self.nodes_reaching(point, network_path);
let glide_offsets = self.glide_offsets(network_path); let clicked_nodes = self.with_layout(network_path, |layout| {
let clicked_nodes = self reaching
.nodes_reaching(point, network_path) .into_iter()
.iter() .filter(|node_id| layout.geometry(node_id).is_some_and(|geometry| geometry.body().contains(point)))
.filter(|node_id| { .collect::<Vec<_>>()
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { })?;
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
}) == Some(true)
})
.cloned()
.collect::<Vec<_>>();
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order // Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
let drawing_layer = |node_id: &NodeId| { let drawing_layer = |node_id: &NodeId| {
if self.is_redirect_dot(node_id, network_path) { if self.is_redirect_dot(node_id, network_path) {
@@ -163,53 +99,34 @@ impl NodeNetworkInterface {
}; };
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
self.nodes_reaching(point, network_path) let wanted = match click_target_type {
.iter() LayerClickTargetTypes::Visibility => Part::Visibility,
.filter_map(|node_id| { LayerClickTargetTypes::Lock => Part::Lock,
let point = point - glide_offsets.node(node_id); LayerClickTargetTypes::Grip => Part::Grip,
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { LayerClickTargetTypes::Name => Part::Name,
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata { };
match click_target_type {
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id), self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)), self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id), .is_some()
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)), })
}
} else {
None
}
})
.flatten()
})
.next()
} }
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center. /// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
pub fn empty_import_export_connector_at(&self, point: DVec2, is_import: bool, network_path: &[NodeId]) -> Option<(usize, DVec2)> { pub fn empty_import_export_connector_at(&self, point: DVec2, is_import: bool, network_path: &[NodeId]) -> Option<(usize, DVec2)> {
let glide_offsets = self.glide_offsets(network_path);
let point = point - if is_import { glide_offsets.imports } else { glide_offsets.exports };
// The same reach as an import (output) or export (input) port's click target // The same reach as an import (output) or export (input) port's click target
self.empty_import_export_connectors(is_import, network_path) self.empty_import_export_connectors(is_import, network_path).into_iter().find(|(index, center)| match is_import {
.into_iter() true => PartTarget::output_port(*center, *index as u32).contains(point),
.find(|(_, center)| port_click_target(side_port_bounds(*center, !is_import)).intersect_point_no_stroke(point)) false => PartTarget::input_port(*center, *index as u32).contains(point),
})
} }
/// The import or export with its name under `point`, given in node graph space. /// The import or export with its name under `point`, given in node graph space.
pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<ImportOrExport> { pub fn import_export_name_from_point(&self, point: DVec2, network_path: &[NodeId]) -> Option<NetworkConnectorKey> {
let glide_offsets = self.glide_offsets(network_path);
self.import_export_name_bounds(network_path) self.import_export_name_bounds(network_path)
.into_iter() .into_iter()
.find(|(import_or_export, [name_min, name_max])| { .find(|(_, [name_min, name_max])| name_min.cmple(point).all() && point.cmple(*name_max).all())
let point = point
- match import_or_export {
ImportOrExport::Import(_) => glide_offsets.imports,
ImportOrExport::Export(_) => glide_offsets.exports,
};
name_min.cmple(point).all() && point.cmple(*name_max).all()
})
.map(|(import_or_export, _)| import_or_export) .map(|(import_or_export, _)| import_or_export)
} }
@@ -237,14 +154,13 @@ impl NodeNetworkInterface {
} }
/// The input fed by a wire passing within `tolerance` of the point (in node graph space), for placing a dot on it. Only wires a dot can bend are found. /// The input fed by a wire passing within `tolerance` of the point (in node graph space), for placing a dot on it. Only wires a dot can bend are found.
pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<InputConnector> { pub fn wire_input_from_point(&self, point: DVec2, tolerance: f64, wire_style: WireStyle, network_path: &[NodeId]) -> Option<InputConnector> {
let target = dvec2_to_point(point); let target = dvec2_to_point(point);
let glide_offsets = self.glide_offsets(network_path);
self.node_graph_input_connectors(network_path) self.node_graph_input_connectors(network_path)
.into_iter() .into_iter()
.filter(|input| self.can_bend_wire_into(input, network_path)) .filter(|input| self.can_bend_wire_into(input, network_path))
.filter_map(|input| { .filter_map(|input| {
let (wire, _, _) = self.gliding_vector_wire_from_input(&input, wire_style, &glide_offsets, network_path)?; let (wire, _) = self.vector_wire_from_input(&input, wire_style, network_path)?;
let distance = wire let distance = wire
.segments() .segments()
.map(|segment| segment.nearest(target, DEFAULT_ACCURACY).distance_sq.sqrt()) .map(|segment| segment.nearest(target, DEFAULT_ACCURACY).distance_sq.sqrt())
@@ -263,27 +179,21 @@ impl NodeNetworkInterface {
}; };
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
let covering_dot = self.redirect_dot_from_click(click, network_path); let covering_dot = self.redirect_dot_from_click(click, network_path);
self.nodes_reaching(point, network_path) self.nodes_reaching(point, network_path)
.iter() .iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id)) .filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| { .filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { self.find_node_part(node_id, network_path, |part, target| match part {
transient_node_metadata Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
.port_click_targets _ => None,
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
.map(|port| InputConnector::node_at_index(*node_id, port))
}) })
.flatten()
}) })
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path)) .find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
.or_else(|| { .or_else(|| {
self.with_import_export_ports(network_path, |import_export_ports| { self.with_import_export_ports(network_path, |import_export_ports| import_export_ports.clicked_input_port_from_point(point).map(InputConnector::Export))
import_export_ports.clicked_input_port_from_point(point - glide_offsets.exports).map(InputConnector::Export) .flatten()
}) .filter(|_| covering_dot.is_none())
.flatten()
.filter(|_| covering_dot.is_none())
}) })
} }
@@ -295,25 +205,21 @@ impl NodeNetworkInterface {
}; };
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
// A redirect dot is drawn above everything else, so where it covers other ports, only its own can be pressed // A redirect dot is drawn above everything else, so where it covers other ports, only its own can be pressed
let covering_dot = self.redirect_dot_from_click(click, network_path); let covering_dot = self.redirect_dot_from_click(click, network_path);
self.nodes_reaching(point, network_path) self.nodes_reaching(point, network_path)
.iter() .iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id)) .filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| { .filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { self.find_node_part(node_id, network_path, |part, target| match part {
transient_node_metadata Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
.port_click_targets _ => None,
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
.map(|output_index| OutputConnector::node(*node_id, output_index))
}) })
.flatten()
}) })
.next() .next()
.or_else(|| { .or_else(|| {
self.with_import_export_ports(network_path, |import_export_ports| { self.with_import_export_ports(network_path, |import_export_ports| {
import_export_ports.clicked_output_port_from_point(point - glide_offsets.imports).map(OutputConnector::Import) import_export_ports.clicked_output_port_from_point(point).map(OutputConnector::Import)
}) })
.flatten() .flatten()
.filter(|_| covering_dot.is_none()) .filter(|_| covering_dot.is_none())
@@ -321,20 +227,30 @@ impl NodeNetworkInterface {
} }
pub fn input_position(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> { pub fn input_position(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<DVec2> {
match input_connector { Some(self.input_end(input_connector, network_path)?.position)
InputConnector::Node { node_id, input_index } => self.node_input_anchor(node_id, *input_index, network_path),
InputConnector::Export(export_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
.flatten(),
}
} }
pub fn output_position(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> { pub fn output_position(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<DVec2> {
Some(self.output_end(output_connector, network_path)?.position)
}
pub fn input_end(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Option<WireEnd> {
match input_connector {
InputConnector::Node { node_id, input_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.input_end(*input_index)).flatten(),
InputConnector::Export(export_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.input_port_position(*export_index))
.flatten()
.map(|position| WireEnd { position, vertical: false }),
}
}
pub fn output_end(&self, output_connector: &OutputConnector, network_path: &[NodeId]) -> Option<WireEnd> {
match output_connector { match output_connector {
OutputConnector::Node { node_id, output_index } => self.node_output_anchor(node_id, *output_index, network_path), OutputConnector::Node { node_id, output_index } => self.with_layout(network_path, |layout| layout.geometry(node_id)?.output_end(*output_index)).flatten(),
OutputConnector::Import(import_index) => self OutputConnector::Import(import_index) => self
.with_import_export_ports(network_path, |import_export_ports| import_export_ports.output_port_position(*import_index)) .with_import_export_ports(network_path, |import_export_ports| import_export_ports.output_port_position(*import_index))
.flatten(), .flatten()
.map(|position| WireEnd { position, vertical: false }),
} }
} }
@@ -394,35 +310,10 @@ impl NodeNetworkInterface {
Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box()) Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box())
} }
pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap<NodeId, u32>, HashMap<NodeId, u32>, HashMap<NodeId, bool>) { pub fn has_left_input_wire(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
let Some(network_metadata) = self.network_metadata(network_path) else { !self
log::error!("Could not get nested network_metadata in collect_layer_widths"); .upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
return (HashMap::new(), HashMap::new(), HashMap::new()); .skip(1)
}; .all(|node_id| self.is_chain(&node_id, network_path))
let nodes = network_metadata
.persistent_metadata
.node_metadata
.keys()
.filter_map(|node_id| if self.is_layer(node_id, network_path) { Some(*node_id) } else { None })
.collect::<Vec<_>>();
let layer_widths = nodes
.iter()
.filter_map(|node_id| self.layer_width(node_id, network_path).map(|layer_width| (*node_id, layer_width)))
.collect::<HashMap<NodeId, u32>>();
let chain_widths = nodes.iter().map(|node_id| (*node_id, self.chain_width(node_id, network_path))).collect::<HashMap<NodeId, u32>>();
let has_left_input_wire = nodes
.iter()
.map(|node_id| {
(
*node_id,
!self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow)
.skip(1)
.all(|node_id| self.is_chain(&node_id, network_path)),
)
})
.collect::<HashMap<NodeId, bool>>();
(layer_widths, chain_widths, has_left_input_wire)
} }
} }
@@ -6,10 +6,6 @@
use super::*; use super::*;
impl NodeNetworkInterface { impl NodeNetworkInterface {
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
self.unload_all_nodes_bounding_box(network_path);
}
/// Unloads the network's import and export ports. /// Unloads the network's import and export ports.
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) { pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
self.unload_import_export_ports(network_path); self.unload_import_export_ports(network_path);
@@ -17,6 +13,5 @@ impl NodeNetworkInterface {
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) { pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path); self.try_unload_layer_width(node_id, network_path);
self.unload_all_nodes_bounding_box(network_path);
} }
} }
@@ -52,7 +52,6 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest. /// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
@@ -145,7 +144,6 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
/// Sets the position of a layer to a stack position /// Sets the position of a layer to a stack position
@@ -159,8 +157,6 @@ impl NodeNetworkInterface {
} else if node.set_stack_position(y_offset) { } else if node.set_stack_position(y_offset) {
self.transaction_modified(); self.transaction_modified();
} }
self.invalidate_positions(network_path);
} }
/// Sets the position of a node to a stack position without changing its y offset /// Sets the position of a node to a stack position without changing its y offset
@@ -371,7 +367,6 @@ impl NodeNetworkInterface {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return }; let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
if node.shift_absolute_position(position - current_position) { if node.shift_absolute_position(position - current_position) {
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
} }
@@ -1,7 +1,10 @@
use super::*; use super::*;
use glam::UVec2; use glam::UVec2;
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire}; use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
use graph_ui::geometry::{NodeGeometry, NodeShape};
use graph_ui::metrics::CARD_GRID_WIDTH;
use std::cell::RefCell; use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
const REACH_MARGIN: f64 = 16.; const REACH_MARGIN: f64 = 16.;
@@ -9,13 +12,53 @@ const REACH_MARGIN: f64 = 16.;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct NetworkLayout { pub struct NetworkLayout {
revision: u64, revision: u64,
generation: u64,
node_ids: Vec<NodeId>, node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>, indices: HashMap<NodeId, NodeIndex>,
graph: Graph, graph: Graph,
shapes: Vec<NodeShape>,
layout: Layout, layout: Layout,
bounds: [DVec2; 2],
clearance: ImportExportClearance,
} }
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
impl NetworkLayout { impl NetworkLayout {
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let mut network_layout = Self {
revision,
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
node_ids,
indices,
graph,
shapes,
layout,
bounds: [DVec2::ZERO; 2],
clearance: ImportExportClearance::default(),
};
network_layout.measure_bounds_and_clearance();
network_layout
}
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
let Self {
node_ids,
indices,
shapes,
graph,
layout,
..
} = self;
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
}
pub fn generation(&self) -> u64 {
self.generation
}
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> { pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
Some(self.node(node_id)?.position) Some(self.node(node_id)?.position)
} }
@@ -48,9 +91,30 @@ impl NetworkLayout {
.sum() .sum()
} }
/// How many nodes the layer's chain holds. /// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
pub fn chain_length(&self, layer: &NodeId) -> u32 { pub fn bounds(&self) -> [DVec2; 2] {
self.node(layer).map_or(0, |node| node.chain_length) self.bounds
}
/// What the imports and exports keep their distance from horizontally.
pub(crate) fn clearance(&self) -> ImportExportClearance {
self.clearance
}
pub fn geometry(&self, node_id: &NodeId) -> Option<NodeGeometry> {
Some(self.geometry_at(*self.indices.get(node_id)?))
}
/// The first of the node's parts, its body last, that `find` picks something from.
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&NodeGeometry, &PartTarget) -> Option<R>) -> Option<R> {
let geometry = self.geometry(node_id)?;
let mut found = None;
geometry.parts(|target| {
if found.is_none() {
found = find(&geometry, &target);
}
});
found
} }
/// Whether `point`, in node graph space, lies within the box around everything the node draws. /// Whether `point`, in node graph space, lies within the box around everything the node draws.
@@ -62,6 +126,38 @@ impl NetworkLayout {
point.cmpge(min).all() && point.cmplt(max).all() point.cmpge(min).all() && point.cmplt(max).all()
} }
fn geometry_at(&self, index: NodeIndex) -> NodeGeometry {
let node = self.layout.node(index);
NodeGeometry {
cell: node.position,
kind: self.graph[index].kind,
chain_length: node.chain_length,
shape: self.shapes[index.index()].clone(),
}
}
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
fn measure_bounds_and_clearance(&mut self) {
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut bounds: Option<[DVec2; 2]> = None;
let mut clearance = ImportExportClearance::default();
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
let body = self.geometry_at(index).body();
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
if self.graph[index].kind == NodeKind::Waypoint {
let center = (body.min.x + body.max.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
}
}
self.bounds = bounds.unwrap_or_default();
self.clearance = clearance;
}
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> { fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
Some(self.layout.node(*self.indices.get(node_id)?)) Some(self.layout.node(*self.indices.get(node_id)?))
} }
@@ -86,12 +182,14 @@ struct DragOrigin {
keep_upstream: bool, keep_upstream: bool,
node_ids: Vec<NodeId>, node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>, indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
start: Graph, start: Graph,
drag: Drag, drag: Drag,
} }
impl DragOrigin { impl DragOrigin {
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self { fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect(); let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
Self { Self {
revision, revision,
@@ -99,6 +197,7 @@ impl DragOrigin {
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream), drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
node_ids, node_ids,
indices, indices,
shapes,
start, start,
} }
} }
@@ -116,11 +215,8 @@ impl NodeNetworkInterface {
} }
pub(crate) fn nodes_reaching(&self, point: DVec2, network_path: &[NodeId]) -> Vec<NodeId> { pub(crate) fn nodes_reaching(&self, point: DVec2, network_path: &[NodeId]) -> Vec<NodeId> {
let glide_offsets = self.glide_offsets(network_path); self.with_layout(network_path, |layout| layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point)).copied().collect())
self.with_layout(network_path, |layout| { .unwrap_or_default()
layout.node_ids.iter().filter(|node_id| layout.reaches(node_id, point - glide_offsets.node(node_id))).copied().collect()
})
.unwrap_or_default()
} }
pub(crate) fn drag_preview(&self, network_path: &[NodeId]) -> (IVec2, bool) { pub(crate) fn drag_preview(&self, network_path: &[NodeId]) -> (IVec2, bool) {
@@ -154,7 +250,10 @@ impl NodeNetworkInterface {
} }
} }
transient.layout.unload(); transient.layout.unload();
self.invalidate_positions(network_path); }
pub(crate) fn dragging(&self, network_path: &[NodeId]) -> bool {
self.network_metadata(network_path).is_some_and(|network_metadata| network_metadata.transient_metadata.drag.is_some())
} }
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag. /// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
@@ -178,9 +277,14 @@ impl NodeNetworkInterface {
.filter(|((before, after), _)| before.placement != after.placement) .filter(|((before, after), _)| before.placement != after.placement)
.map(|((_, after), node_id)| (*node_id, after.placement)) .map(|((_, after), node_id)| (*node_id, after.placement))
.collect(); .collect();
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved) let laid_out = LaidOutNodes {
node_ids: std::mem::take(&mut origin.node_ids),
indices: std::mem::take(&mut origin.indices),
shapes: std::mem::take(&mut origin.shapes),
};
(moved_placements, laid_out, moved)
}); });
let Some((moved_placements, node_ids, indices, graph)) = finished else { return }; let Some((moved_placements, laid_out, graph)) = finished else { return };
let mut stored_all = true; let mut stored_all = true;
for (node_id, placement) in moved_placements { for (node_id, placement) in moved_placements {
@@ -189,13 +293,7 @@ impl NodeNetworkInterface {
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) { if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
let layout = Layout::new(&graph); let layout = Layout::new(&graph);
network_metadata.transient_metadata.layout.store(NetworkLayout { network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
revision: store::revision(),
layout,
graph,
node_ids,
indices,
});
} }
} }
@@ -208,16 +306,15 @@ impl NodeNetworkInterface {
let transient = self.network_transient_mut(network_path)?; let transient = self.network_transient_mut(network_path)?;
let drag = transient.drag.take()?; let drag = transient.drag.take()?;
transient.layout.unload(); transient.layout.unload();
self.invalidate_positions(network_path);
Some(drag) Some(drag)
} }
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> { fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
let mut origin = drag.origin.borrow_mut(); let mut origin = drag.origin.borrow_mut();
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) { if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
let (node_ids, indices, start) = self.layout_graph(network_path)?; let (laid_out, start) = self.layout_graph(network_path)?;
let start_layout = Layout::new(&start); let start_layout = Layout::new(&start);
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision)); *origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
} }
origin.as_mut().map(read) origin.as_mut().map(read)
} }
@@ -227,8 +324,8 @@ impl NodeNetworkInterface {
let cache = &self.network_metadata(network_path)?.transient_metadata.layout; let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?; let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached; let (laid_out, graph, layout) = cached.into_parts();
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision)) Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
} }
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool { fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
@@ -246,40 +343,38 @@ impl NodeNetworkInterface {
}; };
if node.set_node_type(node_type) { if node.set_node_type(node_type) {
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
true true
} }
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> { fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag { let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| { Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
let (graph, mut layout) = origin.drag.moved(drag.offset); let (graph, mut layout) = origin.drag.moved(drag.offset);
layout.snap_chains(&graph); layout.snap_chains(&graph);
(origin.node_ids.clone(), origin.indices.clone(), graph, layout) let laid_out = LaidOutNodes {
node_ids: origin.node_ids.clone(),
indices: origin.indices.clone(),
shapes: origin.shapes.clone(),
};
(laid_out, graph, layout)
})?, })?,
None => { None => {
let (node_ids, indices, graph) = self.layout_graph(network_path)?; let (laid_out, graph) = self.layout_graph(network_path)?;
let layout = Layout::new(&graph); let layout = Layout::new(&graph);
(node_ids, indices, graph, layout) (laid_out, graph, layout)
} }
}; };
Some(NetworkLayout { Some(NetworkLayout::new(revision, laid_out, graph, layout))
revision,
layout,
graph,
node_ids,
indices,
})
} }
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> { pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
let network = self.nested_network(network_path)?; let network = self.nested_network(network_path)?;
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect(); let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect(); let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?; let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
let wires = node_ids let wires = node_ids
.iter() .iter()
.enumerate() .enumerate()
@@ -297,10 +392,10 @@ impl NodeNetworkInterface {
}) })
.collect(); .collect();
Some((node_ids, indices, Graph { nodes, wires })) Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
} }
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> { fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
let metadata = self.node_metadata(node_id, network_path)?; let metadata = self.node_metadata(node_id, network_path)?;
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata { let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => match layer.position { NodeTypePersistentMetadata::Layer(layer) => match layer.position {
@@ -314,17 +409,40 @@ impl NodeNetworkInterface {
}; };
let is_redirect_dot = self.is_redirect_dot(node_id, network_path); let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
let (kind, size) = match (is_layer, is_redirect_dot) { let (layer_width, name_width) = if is_layer {
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)), self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))), } else {
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))), (0, 0.)
}; };
Some(Node { let (kind, size) = match (is_layer, is_redirect_dot) {
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
(false, true) => (NodeKind::Waypoint, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(CARD_GRID_WIDTH, self.node_height(node_id, network_path))),
};
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
let node = Node {
placement, placement,
kind, kind,
size: size.as_ivec2(), size: size.as_ivec2(),
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path), chainable: !is_redirect_dot && !primary_output_hidden,
held: false, held: false,
}) };
let shape = NodeShape {
size,
exposed_inputs: inputs.iter().enumerate().filter(|(_, input)| input.is_exposed()).map(|(index, _)| index).collect(),
outputs: self.number_of_outputs(node_id, network_path) as u32,
primary_output_hidden,
name_width,
locked: self.is_locked(node_id, network_path),
};
Some((node, shape))
} }
} }
pub(crate) struct LaidOutNodes {
pub(crate) node_ids: Vec<NodeId>,
pub(crate) indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
}
@@ -94,11 +94,9 @@ impl NodeNetworkInterface {
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false); self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
} }
// Update the outward wires and bounding box for all nodes in the encapsulating network // Update the outward wires for all nodes in the encapsulating network
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) { if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
encapsulating_transient.outward_wires.unload(); encapsulating_transient.outward_wires.unload();
encapsulating_transient.all_nodes_bounding_box.unload();
encapsulating_transient.import_export_clearance.unload();
} }
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure // An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
@@ -141,7 +139,6 @@ impl NodeNetworkInterface {
// Update the metadata for the encapsulating node // Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path); self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1; affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
} }
if affects_document_structure { if affects_document_structure {
@@ -179,7 +176,6 @@ impl NodeNetworkInterface {
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) { fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
// Update the metadata for the encapsulating node // Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path); self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) { if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false); self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
} }
@@ -572,8 +568,7 @@ impl NodeNetworkInterface {
/// Lightweight version of `set_input` for bulk import operations. /// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions, /// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and /// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) { pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) { if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762"); log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
@@ -673,8 +668,6 @@ impl NodeNetworkInterface {
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector { (NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
// Exposing or hiding a value input changes the node's port count // Exposing or hiding a value input changes the node's port count
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => { InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
self.unload_all_nodes_bounding_box(network_path);
// A nested network draws its interior ports from the encapsulating node's inputs // A nested network draws its interior ports from the encapsulating node's inputs
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) { if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
let nested_path = [network_path, &[*node_id]].concat(); let nested_path = [network_path, &[*node_id]].concat();
@@ -834,10 +827,10 @@ impl NodeNetworkInterface {
/// Wires the output into the inputs through one new redirect dot placed midway between them, which fans out to the inputs. /// Wires the output into the inputs through one new redirect dot placed midway between them, which fans out to the inputs.
fn create_wires_through_dot(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) { fn create_wires_through_dot(&mut self, output_connector: &OutputConnector, input_connectors: &[InputConnector], network_path: &[NodeId]) {
let output_center = self.get_output_center(output_connector, network_path); let output_center = self.output_position(output_connector, network_path);
let input_centers = input_connectors let input_centers = input_connectors
.iter() .iter()
.map(|input_connector| self.get_input_center(input_connector, network_path)) .map(|input_connector| self.input_position(input_connector, network_path))
.collect::<Option<Vec<_>>>(); .collect::<Option<Vec<_>>>();
let center = match output_center.zip(input_centers) { let center = match output_center.zip(input_centers) {
Some((output_center, input_centers)) => { Some((output_center, input_centers)) => {
@@ -904,7 +897,6 @@ impl NodeNetworkInterface {
self.transaction_modified(); self.transaction_modified();
} }
self.unload_all_nodes_bounding_box(network_path);
self.unload_outward_wires(network_path); self.unload_outward_wires(network_path);
} }
@@ -927,7 +919,6 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
previous_entry previous_entry
} }
@@ -1092,7 +1083,6 @@ impl NodeNetworkInterface {
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id))); outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
} }
self.unload_all_nodes_bounding_box(network_path);
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else { let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes"); log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
return; return;
@@ -1126,10 +1116,10 @@ impl NodeNetworkInterface {
} }
} }
let reconnected_offset = reconnect_to_input let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
.as_ref() let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
.and_then(NodeInput::as_node) Some((reconnected, offset))
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?))); });
let mut exports_fed_by_import = Vec::new(); let mut exports_fed_by_import = Vec::new();
@@ -1174,7 +1164,7 @@ impl NodeNetworkInterface {
self.invalidate_node_appearance(node_id, network_path); self.invalidate_node_appearance(node_id, network_path);
} }
pub fn set_import_export_name(&mut self, name: String, index: ImportOrExport, network_path: &[NodeId]) { pub fn set_import_export_name(&mut self, name: String, index: NetworkConnectorKey, network_path: &[NodeId]) {
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else { let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
log::error!("Could not get encapsulating network in set_import_export_name"); log::error!("Could not get encapsulating network in set_import_export_name");
return; return;
@@ -1186,8 +1176,8 @@ impl NodeNetworkInterface {
}; };
let name_changed = match index { let name_changed = match index {
ImportOrExport::Import(import_index) => node.set_input_name(import_index, name), NetworkConnectorKey::Import(import_index) => node.set_input_name(import_index, name),
ImportOrExport::Export(export_index) => node.set_output_name(export_index, name), NetworkConnectorKey::Export(export_index) => node.set_output_name(export_index, name),
}; };
if name_changed { if name_changed {
@@ -1195,7 +1185,7 @@ impl NodeNetworkInterface {
} }
} }
pub fn set_import_export_description(&mut self, description: String, index: ImportOrExport, network_path: &[NodeId]) { pub fn set_import_export_description(&mut self, description: String, index: NetworkConnectorKey, network_path: &[NodeId]) {
let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else { let Some((encapsulating_node_id, encapsulating_network_path)) = network_path.split_last() else {
log::error!("Could not get encapsulating network in set_import_export_description"); log::error!("Could not get encapsulating network in set_import_export_description");
return; return;
@@ -1207,8 +1197,8 @@ impl NodeNetworkInterface {
}; };
let description_changed = match index { let description_changed = match index {
ImportOrExport::Import(import_index) => node.set_input_description(import_index, description), NetworkConnectorKey::Import(import_index) => node.set_input_description(import_index, description),
ImportOrExport::Export(export_index) => node.set_output_description(export_index, description), NetworkConnectorKey::Export(export_index) => node.set_output_description(export_index, description),
}; };
if description_changed { if description_changed {
@@ -1365,7 +1355,6 @@ impl NodeNetworkInterface {
transient.layer_width.unload(); transient.layer_width.unload();
self.transaction_modified(); self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
self.invalidate_import_export(network_path); self.invalidate_import_export(network_path);
self.load_structure(); self.load_structure();
} }
@@ -264,16 +264,6 @@ impl NodeNetworkInterface {
layers layers
} }
/// The width in grid cells of a layer's chain area: one cell plus a chain width per chained node, or zero for a layer without a displayed chain input.
pub fn chain_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
if self.number_of_displayed_inputs(node_id, network_path) <= 1 {
return 0;
}
let chain_length = self.with_layout(network_path, |layout| layout.chain_length(node_id)).unwrap_or_default();
chain_length * NODE_CHAIN_WIDTH as u32 + 1
}
/// Check if the specified node id is connected to the output /// Check if the specified node id is connected to the output
pub fn connected_to_output(&self, target_node_id: &NodeId, network_path: &[NodeId]) -> bool { pub fn connected_to_output(&self, target_node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "connected_to_output", |view| Ok(view.connected_to_output(target_node_id))).unwrap_or_default() self.query(network_path, "connected_to_output", |view| Ok(view.connected_to_output(target_node_id))).unwrap_or_default()
@@ -802,7 +792,7 @@ impl NodeNetworkInterface {
self.query(network_path, "reference", |view| view.reference(node_id)).flatten() 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. /// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str { pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
self.reference(node_id, network_path) self.reference(node_id, network_path)
.and_then(|reference| resolve_document_node_type(&reference)?.icon) .and_then(|reference| resolve_document_node_type(&reference)?.icon)
@@ -875,16 +865,16 @@ impl NodeNetworkInterface {
node.set_widget_override(index, widget_override); node.set_widget_override(index, widget_override);
} }
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type. /// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String { pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id))) self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string()) .unwrap_or_else(|| "Subgraph".to_string())
} }
/// The uneditable name in the Inspector which represents the function name of the node implementation. /// The uneditable name in the Inspector which represents the function name of the node implementation.
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String { pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id))) self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string()) .unwrap_or_else(|| "Subgraph".to_string())
} }
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool { pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
@@ -328,7 +328,10 @@ fn field_deltas(
} }
if current_metadata.node_type_metadata != target_metadata.node_type_metadata { if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone()))); deltas.push(metadata(NodeMetadataChange::placement(
&current_metadata.node_type_metadata,
target_metadata.node_type_metadata.clone(),
)));
} }
if current_metadata.display_name != target_metadata.display_name { if current_metadata.display_name != target_metadata.display_name {
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone()))); deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
@@ -229,13 +229,14 @@ impl NodeMut<'_> {
/// Whether the node is displayed as a layer or a node, together with its position. /// Whether the node is displayed as a layer or a node, together with its position.
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool { pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
let changed = self.metadata.node_type_metadata != node_type; if self.metadata.node_type_metadata == node_type {
self.metadata.node_type_metadata = node_type; return false;
if changed {
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
} }
changed
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
self.metadata.node_type_metadata = node_type;
self.deltas.metadata(change);
true
} }
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface. /// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
@@ -200,10 +200,11 @@ impl NodeNetworkInterface {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes; self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
} }
/// Update how far each layer's effects paint past its content. /// Update how far each layer's effects paint past its content, and the frames they paint anywhere in.
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) { pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) {
self.document_metadata.mark_changed(); self.document_metadata.mark_changed();
self.document_metadata.layer_effects_reach = new_layer_effects_reach; self.document_metadata.layer_effects_reach = new_layer_effects_reach;
self.document_metadata.layer_effects_frames = new_layer_effects_frames;
} }
} }
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
} }
impl NodeTemplate { impl NodeTemplate {
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
pub fn empty_subgraph() -> Self {
Self {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
}
}
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`]. /// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> { pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
self.inputs.get(P::INDEX) self.inputs.get(P::INDEX)
@@ -3,12 +3,7 @@ use graphene_std::ParameterRef;
use graphene_std::vector::misc::dvec2_to_point; use graphene_std::vector::misc::dvec2_to_point;
use kurbo::{DEFAULT_ACCURACY, Shape}; use kurbo::{DEFAULT_ACCURACY, Shape};
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets. /// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
}
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath { pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)); let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
if radii.iter().all(|radius| *radius == 0.) { if radii.iter().all(|radius| *radius == 0.) {
@@ -19,16 +14,6 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY) kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
} }
/// Ellipse inscribed in the box spanning the two opposite corners.
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
path.close_path();
path
}
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document. /// 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)] #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ChainNodeCopy { pub struct ChainNodeCopy {
@@ -131,12 +116,7 @@ impl Iterator for FlowIter<'_> {
} }
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] pub use graph_ui::network_connector::NetworkConnectorKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ImportOrExport {
Import(usize),
Export(usize),
}
/// The primary input (index 0) of any node: a chain node's horizontal wire continuing from the left, or a layer's vertical stack wire from the sibling rendered below it. /// The primary input (index 0) of any node: a chain node's horizontal wire continuing from the left, or a layer's vertical stack wire from the sibling rendered below it.
pub const PRIMARY_INPUT_INDEX: usize = 0; pub const PRIMARY_INPUT_INDEX: usize = 0;
@@ -280,36 +260,10 @@ pub(crate) enum DotSide {
Outgoing, Outgoing,
} }
/// The corners of the click target for a connector on a node or layer's left or right side, or an import or export.
/// It fills its row's height and reaches further away from the node than into it, leaving the node body grabbable.
pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
const INWARD_REACH: f64 = 8.;
const OUTWARD_REACH: f64 = 12.;
const HALF_HEIGHT: f64 = 12.;
// Inputs face left and outputs face right
let (left_reach, right_reach) = if is_input { (OUTWARD_REACH, INWARD_REACH) } else { (INWARD_REACH, OUTWARD_REACH) };
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
}
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
[center - HALF_SIZE, center + HALF_SIZE]
}
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
const CORNER_RADIUS: f64 = 4.;
let path = rounded_rectangle_path(corner1, corner2, [CORNER_RADIUS; 4]);
ClickTarget::new_with_path(path, 0.)
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Ports { pub struct Ports {
pub(crate) input_ports: Vec<(usize, ClickTarget)>, pub(crate) input_ports: Vec<(usize, PartTarget)>,
pub(crate) output_ports: Vec<(usize, ClickTarget)>, pub(crate) output_ports: Vec<(usize, PartTarget)>,
/// Where a wire attaches to an input port with a click target not centered on that point. /// Where a wire attaches to an input port with a click target not centered on that point.
pub(crate) input_anchors: Vec<(usize, DVec2)>, pub(crate) input_anchors: Vec<(usize, DVec2)>,
/// Where a wire attaches to an output port with a click target not centered on that point. /// Where a wire attaches to an output port with a click target not centered on that point.
@@ -332,106 +286,38 @@ impl Ports {
} }
} }
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> { pub fn input_ports(&self) -> impl Iterator<Item = &(usize, PartTarget)> {
self.input_ports
.iter()
.map(|(_, click_target)| click_target)
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
}
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
self.input_ports.iter() self.input_ports.iter()
} }
pub fn output_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> { pub fn output_ports(&self) -> impl Iterator<Item = &(usize, PartTarget)> {
self.output_ports.iter() self.output_ports.iter()
} }
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) { pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true))); self.input_ports.push((input_index, PartTarget::input_port(center, input_index as u32)));
self.input_anchors.push((input_index, center)); self.input_anchors.push((input_index, center));
} }
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
self.input_ports.push((input_index, click_target));
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) { pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false))); self.output_ports.push((output_index, PartTarget::output_port(center, output_index as u32)));
self.output_anchors.push((output_index, center)); self.output_anchors.push((output_index, center));
} }
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
self.output_ports.push((output_index, click_target));
}
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
self.insert_input_port_at_center(input_index, center);
}
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
self.insert_output_port_at_center(output_index, center);
}
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
if input_index == 0 {
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
} else {
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
}
}
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
// The center of the click target is 8 px above the layer, over its thumbnail
let center = node_top_left + DVec2::new(2. * 24., -8.);
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
}
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> { pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port)) self.input_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port))
} }
pub fn clicked_output_port_from_point(&self, point: DVec2) -> Option<usize> { pub fn clicked_output_port_from_point(&self, point: DVec2) -> Option<usize> {
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port)) self.output_ports.iter().find_map(|(port, target)| target.contains(point).then_some(*port))
}
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
const GUTTER_OFFSET: f64 = 10.;
const GUTTER_RADIUS: f64 = 5.;
let gutter = |x_offset: f64| {
let gutter_center = center + DVec2::new(x_offset, 0.);
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
};
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
self.input_anchors.push((0, center));
self.output_anchors.push((0, center));
} }
pub fn input_port_position(&self, index: usize) -> Option<DVec2> { pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) { self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
return Some(*anchor);
}
self.input_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
} }
pub fn output_port_position(&self, index: usize) -> Option<DVec2> { pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) { self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
return Some(*anchor);
}
self.output_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
} }
} }
@@ -747,67 +633,12 @@ impl<T> TransientCache<T> {
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct NodeNetworkTransientMetadata { pub struct NodeNetworkTransientMetadata {
pub selected_nodes: SelectedNodes, pub selected_nodes: SelectedNodes,
/// Cache for the bounding box around all nodes in node graph space.
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
/// Cache for all outward wire connections /// Cache for all outward wire connections
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>, pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
pub(crate) layout: TransientCache<NetworkLayout>, pub(crate) layout: TransientCache<NetworkLayout>,
pub(crate) drag: Option<super::layout_pass::DragPreview>, pub(crate) drag: Option<super::layout_pass::DragPreview>,
/// All export connector click targets /// The import and export connector click targets, with the generation of the layout they were placed by.
pub(crate) import_export_ports: TransientCache<Ports>, pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
}
/// How far the nodes, imports, and exports gliding into the grid cells they just moved to are drawn from those cells, in node graph space.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GlideOffsets {
pub nodes: HashMap<NodeId, DVec2>,
pub imports: DVec2,
pub exports: DVec2,
}
impl GlideOffsets {
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.imports == DVec2::ZERO && self.exports == DVec2::ZERO
}
pub fn node(&self, node_id: &NodeId) -> DVec2 {
self.nodes.get(node_id).copied().unwrap_or_default()
}
pub fn input(&self, input: &InputConnector) -> DVec2 {
match input {
InputConnector::Node { node_id, .. } => self.node(node_id),
InputConnector::Export(_) => self.exports,
}
}
pub fn output(&self, output: &OutputConnector) -> DVec2 {
match output {
OutputConnector::Node { node_id, .. } => self.node(node_id),
OutputConnector::Import(_) => self.imports,
}
}
/// Shrinks every offset to the given fraction of itself, settling those left too small to see.
pub fn shrink(&mut self, remaining_fraction: f64) {
const SMALLEST_VISIBLE_OFFSET: f64 = 0.5;
let shrink = |offset: &mut DVec2| {
*offset *= remaining_fraction;
if offset.length() < SMALLEST_VISIBLE_OFFSET {
*offset = DVec2::ZERO;
}
};
self.nodes.values_mut().for_each(shrink);
self.nodes.retain(|_, offset| *offset != DVec2::ZERO);
shrink(&mut self.imports);
shrink(&mut self.exports);
}
} }
/// What the imports and exports keep their distance from horizontally, in node graph space. They keep a few grid cells from the sides of a node, /// What the imports and exports keep their distance from horizontally, in node graph space. They keep a few grid cells from the sides of a node,
@@ -1173,40 +1004,8 @@ impl From<LegacyNodePosition> for NodePosition {
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields. /// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct DocumentNodeTransientMetadata { pub struct DocumentNodeTransientMetadata {
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers. /// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<u32>, pub(crate) layer_width: TransientCache<(u32, f64)>,
}
#[derive(Debug, Clone)]
pub struct DocumentNodeClickTargets {
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
pub node_click_target: ClickTarget,
/// Stores all port click targets in node graph space.
pub port_click_targets: Ports,
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
pub node_type_metadata: NodeTypeClickTargets,
}
#[derive(Debug, Clone)]
pub enum NodeTypeClickTargets {
Layer(Box<LayerClickTargets>),
Node, // No transient click targets are stored exclusively for nodes
}
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone)]
pub struct LayerClickTargets {
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
pub visibility_click_target: ClickTarget,
/// Cache for the lock icon button, only present when the layer is locked.
pub lock_click_target: Option<ClickTarget>,
/// Cache for the grip icon, which is next to the visibility button.
pub grip_click_target: ClickTarget,
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
/// `None` for layers whose display name is empty.
pub name_click_target: Option<ClickTarget>,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
.ok() .ok()
.flatten() .flatten()
.map(|identifier| identifier.implementation_name_from_identifier()) .map(|identifier| identifier.implementation_name_from_identifier())
.unwrap_or("Custom Node".to_string()) .unwrap_or("Subgraph".to_string())
} }
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed. /// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
@@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
} }
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present. // The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way. // Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths. // Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
.network_interface .network_interface
@@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}) })
.collect(); .collect();
migrate_custom_node_subgraphs(document);
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs // Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
let nodes = document let nodes = document
.network_interface .network_interface
@@ -1899,8 +1901,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
continue; continue;
}; };
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one // The primary input comes before the Clip toggle where there is one, and the noise settings follow it in the current inputs' order
if let Some(clip_index) = clip_index { if let Some(clip_index) = clip_index {
if *clip_index == 1
&& let Some(primary) = old_inputs.first()
{
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), primary.clone(), network_path);
}
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() { for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path); document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
} }
@@ -1912,6 +1919,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) { if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
move_mandelbrot_to_old_origin(document, node_id, network_path); move_mandelbrot_to_old_origin(document, node_id, network_path);
} }
// Only a Noise Pattern old enough to have the Clip toggle is surely from before it wrote gamma-encoded grays
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
read_noise_through_gamma_correction(document, node_id, network_path);
}
} }
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index, // Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
@@ -1984,6 +1996,9 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0))) .and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
.cloned() .cloned()
.unwrap_or_default(); .unwrap_or_default();
if downstream_consumers.is_empty() {
return Some(());
}
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path); let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template()); let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
@@ -2085,6 +2100,48 @@ fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbr
Some(()) Some(())
} }
/// Keeps an old Noise Pattern's look now that it writes its value as the gray at that gamma-encoded level rather than as linear light,
/// with a Gamma Correction at its default gamma of 2.2 turning the new gray back into about the old one wherever the pattern was read.
fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, noise_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*noise_node_id, 0)))
.cloned()
.unwrap_or_default();
if downstream_consumers.is_empty() {
return Some(());
}
let was_in_chain = document.network_interface.is_chain(noise_node_id, network_path);
let position = document.network_interface.position(noise_node_id, network_path);
let gamma_correction_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER))?.default_node_template();
let gamma_correction_id = NodeId::new();
document.network_interface.insert_node(gamma_correction_id, gamma_correction_template, network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(gamma_correction_id, 0), NodeInput::node(*noise_node_id, 0), network_path);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(gamma_correction_id, 0), network_path);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !document.network_interface.is_visible(noise_node_id, network_path) {
document.network_interface.set_visibility(&gamma_correction_id, network_path, false);
}
// The Gamma Correction takes the pattern's place, and the pattern moves before it
if was_in_chain {
document.network_interface.force_set_upstream_to_chain(&gamma_correction_id, network_path);
} else if let Some(position) = position {
document.network_interface.set_absolute_position(&gamma_correction_id, position, network_path);
document.network_interface.set_absolute_position(noise_node_id, position + IVec2::new(-7, 0), network_path);
}
Some(())
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type. /// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> { fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None }; let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -2410,6 +2467,26 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count += 1; inputs_count += 1;
} }
// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth
if reference == DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().take(8).enumerate() {
let index = if index == 7 { 10 } else { index };
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)];
for (index, value) in (7..).zip(smooth) {
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
}
inputs_count = 11;
}
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model // Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform). // 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 { if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
@@ -2988,6 +3065,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 3; inputs_count = 3;
} }
// Make Opaque gained a Strength input, set to 100% to keep making the content fully opaque
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::make_opaque::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(100.), false), network_path);
inputs_count = 2;
}
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on // The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 { if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template(); let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -4045,6 +4134,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(()) Some(())
} }
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in subgraphs {
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
document.network_interface.set_reference(&node_id, &network_path, None);
}
}
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula. /// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) { fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
@@ -4597,6 +4705,45 @@ mod tests {
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}"); assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
} }
#[tokio::test]
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
let document = editor.active_document_mut();
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
panic!("the subgraph should name a definitions table entry")
};
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
let from_merging = NodeId::new();
let instance = NodeTemplate {
implementation: NodeTemplateImplementation::Definition(shared),
..Default::default()
};
document.network_interface.insert_node(from_merging, instance, &[]);
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
for node_id in [from_catalog, from_merging] {
assert!(
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
"the subgraph should still exist"
);
assert_eq!(interface.reference(&node_id, &[]), None);
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
}
}
#[tokio::test] #[tokio::test]
async fn a_rasterize_node_on_the_export_compiles() { async fn a_rasterize_node_on_the_export_compiles() {
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
@@ -5769,6 +5916,10 @@ mod tests {
let mut document = DocumentMessageHandler::default(); let mut document = DocumentMessageHandler::default();
for (index, (identifier, count)) in saved_nodes.iter().enumerate() { for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
let mut inputs = template(identifier).inputs; let mut inputs = template(identifier).inputs;
// Outer Glow's grain inputs came later, ahead of its contour
if *identifier == outer_glow::IDENTIFIER {
inputs.drain(7..10);
}
inputs.remove(2); inputs.remove(2);
inputs.truncate(*count); inputs.truncate(*count);
for (input_index, input) in inputs.iter_mut().enumerate() { for (input_index, input) in inputs.iter_mut().enumerate() {
@@ -5792,7 +5943,9 @@ mod tests {
let name = identifier.as_str(); let name = identifier.as_str();
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape"); assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally"); assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
for (input_index, input) in node.inputs.iter().enumerate().take(count + 1).skip(3) { // Outer Glow's contour, its last saved input, moves past its grain to the end
let shifted = if *identifier == outer_glow::IDENTIFIER { *count } else { count + 1 };
for (input_index, input) in node.inputs.iter().enumerate().take(shifted).skip(3) {
if let Some(TaggedValue::Number(number)) = input.as_value() { if let Some(TaggedValue::Number(number)) = input.as_value() {
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1); assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
} }
@@ -5800,6 +5953,69 @@ mod tests {
} }
} }
#[test]
fn outer_glows_from_before_their_grain_open_smooth() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::blending_nodes::effects::outer_glow;
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER)).expect("the Outer Glow definition should exist");
let template = definition.default_node_template();
// One saved before its blend mode and one saved after it, but before its grain
let mut document = DocumentMessageHandler::default();
for (index, before_blend_mode) in [true, false].into_iter().enumerate() {
let mut inputs = template.inputs.clone();
inputs.drain(7..10);
if before_blend_mode {
inputs.remove(2);
}
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(outer_glow::IDENTIFIER),
inputs,
..Default::default()
};
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
}
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)].map(|value| NodeInput::value(value, false));
for index in 0..2 {
let node = opened.network_interface.document_node(&NodeId(index + 1), &[]).expect("the node should still exist");
assert_eq!(node.inputs.len(), 11);
assert_eq!(node.inputs[7..10], smooth, "the glow should open without grain");
}
}
#[test]
fn make_opaques_from_before_their_strength_open_fully_opaque() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::adjustments::make_opaque;
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(make_opaque::IDENTIFIER)).expect("the Make Opaque definition should exist");
let mut inputs = definition.default_node_template().inputs;
inputs.truncate(1);
let content = inputs.clone();
// Saved with its content alone, before its strength
let mut document = DocumentMessageHandler::default();
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(make_opaque::IDENTIFIER),
inputs,
..Default::default()
};
document.network_interface.insert_node(NodeId(1), node_template, &[]);
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
let node = opened.network_interface.document_node(&NodeId(1), &[]).expect("the node should still exist");
assert_eq!(node.inputs[..1], content, "Make Opaque should keep its content");
assert_eq!(node.inputs[1..], [NodeInput::value(TaggedValue::Number(100.), false)], "Make Opaque should open at full strength");
}
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text // Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
#[test] #[test]
fn removed_nodes_open_as_their_stand_ins() { fn removed_nodes_open_as_their_stand_ins() {
@@ -6351,6 +6567,9 @@ mod tests {
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5)))); assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
read = upstream(read, 0).expect("the origin transform should read the pattern"); read = upstream(read, 0).expect("the origin transform should read the pattern");
} }
if pattern == noise {
read = upstream(read, 0).expect("the Gamma Correction should read the pattern");
}
assert_eq!(read, pattern); assert_eq!(read, pattern);
} }
@@ -6364,6 +6583,130 @@ mod tests {
); );
} }
// Noise Pattern once wrote its value as linear light, so whatever read an old one reads it through a Gamma Correction giving back about the old gray
#[tokio::test]
async fn old_noise_patterns_are_read_through_a_gamma_correction() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::adjustments::gamma_correction;
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::transform_nodes::transform;
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Old patterns read by two nodes and the export, in a layer's chain, disabled, and unread, plus a current one in the new look
let read_thrice = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 0).await;
let readers = [
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 0).await,
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 5).await,
];
let chained = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 15, 20).await;
let layer = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 20, 20).await;
let disabled = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 30).await;
let disabled_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 30).await;
let disabled_primary = editor.create_node_by_name_at(proto(transform::IDENTIFIER), -10, 30).await;
let unread = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 40).await;
let unread_clipped = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 45).await;
let current = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 50).await;
let current_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 50).await;
let interface = &mut editor.active_document_mut().network_interface;
for reader in readers {
interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(read_thrice, 0), &[]);
}
interface.create_wire(&OutputConnector::primary_output(read_thrice), &InputConnector::Export(0), &[]);
interface.set_to_node_or_layer(&layer, &[], true);
interface.create_wire(&OutputConnector::primary_output(chained), &InputConnector::layer_secondary_input(layer), &[]);
interface.set_input(&InputConnector::node_at_index(disabled_reader, 0), NodeInput::node(disabled, 0), &[]);
interface.set_input(&InputConnector::node_at_index(disabled, 0), NodeInput::node(disabled_primary, 0), &[]);
interface.set_visibility(&disabled, &[], false);
interface.set_input(&InputConnector::node_at_index(current_reader, 0), NodeInput::node(current, 0), &[]);
assert!(interface.is_chain(&chained, &[]), "the pattern should be in the layer's chain: fixture is wrong");
// A pattern exported from a subgraph
let subgraph = editor.create_empty_subgraph_at(0, 60).await;
editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
let nested = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 10, 0).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(nested),
input_connector: InputConnector::Export(0),
})
.await;
// Save the old patterns as an older editor did, with their Clip toggle off except on one of the unread ones
let document = editor.active_document_mut();
let old_patterns = [
(read_thrice, vec![], false),
(chained, vec![], false),
(disabled, vec![], false),
(unread, vec![], false),
(unread_clipped, vec![], true),
(nested, vec![subgraph], false),
];
for (node_id, network_path, clip) in old_patterns {
let mut inputs = document.network_interface.document_node(&node_id, &network_path).unwrap().inputs.clone();
inputs.insert(1, NodeInput::value(TaggedValue::Bool(clip), false));
let mut legacy = NodeTemplate { inputs, ..Default::default() };
legacy.normalize_input_metadata();
document.network_interface.replace_inputs(&node_id, &network_path, &mut legacy);
}
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let upstream = |connector: InputConnector, network_path: &[NodeId]| interface.upstream_output_connector(&connector, network_path).and_then(|output| output.node_id());
// The Gamma Correction a reader of `pattern` reads instead, at the default gamma and reading the pattern
let gamma_correction_between = |pattern: NodeId, reader: InputConnector, network_path: &[NodeId]| {
let inserted = upstream(reader, network_path).expect("the reader should read a node");
assert_eq!(interface.reference(&inserted, network_path), Some(proto(gamma_correction::IDENTIFIER)));
let node = interface.document_node(&inserted, network_path).unwrap();
assert_eq!(node.input_value(gamma_correction::GammaInput), Some(&TaggedValue::Number(2.2)));
assert_eq!(node.input_value(gamma_correction::InverseInput), Some(&TaggedValue::Bool(false)));
assert_eq!(upstream(InputConnector::node_at_index(inserted, 0), network_path), Some(pattern));
inserted
};
// Every reader of the pattern read three times shares one Gamma Correction, which takes the pattern's place with the pattern before it
let shared = gamma_correction_between(read_thrice, InputConnector::Export(0), &[]);
for reader in readers {
assert_eq!(upstream(InputConnector::node_at_index(reader, 0), &[]), Some(shared));
}
let position = |node_id: NodeId| interface.position(&node_id, &[]).expect("the node should have a position");
assert_eq!(position(read_thrice) + IVec2::new(7, 0), position(shared));
let in_chain = gamma_correction_between(chained, InputConnector::layer_secondary_input(layer), &[]);
assert!(interface.is_chain(&in_chain, &[]) && interface.is_chain(&chained, &[]), "the layer's chain should hold both");
// Only a disabled pattern's Gamma Correction is disabled too, and the pattern keeps the primary input it passes through
let behind_disabled = gamma_correction_between(disabled, InputConnector::node_at_index(disabled_reader, 0), &[]);
assert!(!interface.is_visible(&behind_disabled, &[]) && interface.is_visible(&shared, &[]));
assert_eq!(upstream(InputConnector::node_at_index(disabled, 0), &[]), Some(disabled_primary));
gamma_correction_between(nested, InputConnector::Export(0), &[subgraph]);
assert_eq!(upstream(InputConnector::node_at_index(current_reader, 0), &[]), Some(current));
// Unread patterns gain nothing reading them, clipped or not
let read = |pattern: NodeId| interface.document_network().nodes.values().any(|node| node.inputs.iter().any(|input| input.as_node() == Some(pattern)));
assert!(!read(unread) && !read(unread_clipped));
// Reopening the upgraded document, as restoring an autosave does, inserts no more
let gamma_corrections = |document: &DocumentMessageHandler| {
let implementation = DocumentNodeImplementation::ProtoNode(gamma_correction::IDENTIFIER);
let nodes = document.network_interface.document_network().recursive_nodes();
nodes.filter(|(_, node, _)| node.implementation == implementation).count()
};
assert_eq!(gamma_corrections(&opened), 4);
let reopened = load_legacy_document(opened.serialize_document(), &HashMapResourceStorage::new(), false).expect("the upgraded document should open");
assert_eq!(gamma_corrections(&reopened), 4);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are // The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
#[tokio::test] #[tokio::test]
async fn marbled_mandelbrot_renders_after_migration() { async fn marbled_mandelbrot_renders_after_migration() {
@@ -1,3 +1,4 @@
use super::document::node_graph::graph_ui::GraphUiPart;
use super::document::utility_types::document_metadata::LayerNodeIdentifier; use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::history::HistoryMessage; use super::history::HistoryMessage;
use super::persistent_state::PersistentStateMessage; use super::persistent_state::PersistentStateMessage;
@@ -157,11 +158,6 @@ pub enum PortfolioMessage {
artboard_name: Option<String>, artboard_name: Option<String>,
artboard_count: usize, artboard_count: usize,
}, },
RenderOverlays {
#[serde(skip, default = "OverlayContext::default")]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
context: OverlayContext,
},
SubmitActiveGraphRender, SubmitActiveGraphRender,
SubmitGraphRender { SubmitGraphRender {
document_id: DocumentId, document_id: DocumentId,
@@ -175,6 +171,14 @@ pub enum PortfolioMessage {
SubmitInspectContextOverrides { SubmitInspectContextOverrides {
overrides: graphene_std::ContextOverrides, overrides: graphene_std::ContextOverrides,
}, },
UpdateGraphUi {
part: GraphUiPart,
},
RenderOverlays {
#[serde(skip, default = "OverlayContext::default")]
#[derivative(Debug = "ignore", PartialEq = "ignore")]
context: OverlayContext,
},
PollNodeGraphEvaluation, PollNodeGraphEvaluation,
ToggleResetNodesToDefinitionsOnOpen, ToggleResetNodesToDefinitionsOnOpen,
ToggleRulers, ToggleRulers,
@@ -14,6 +14,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageContext; use crate::messages::portfolio::document::DocumentMessageContext;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions; use crate::messages::portfolio::document::node_graph::document_node_definitions;
use crate::messages::portfolio::document::node_graph::graph_ui;
use crate::messages::portfolio::document_storage_io::{ use crate::messages::portfolio::document_storage_io::{
DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file, DocumentStoreHandle, attach_container, copy_stored_document, join_stored_session, legacy_path, list_stored_documents, load_legacy_document, load_stored_document, open_document_file,
remove_stored_document, remove_stored_document,
@@ -216,7 +217,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Send the information for tooltips and categories for each node/input. // Send the information for tooltips and categories for each node/input.
responses.add(FrontendMessage::SendUIMetadata { responses.add(FrontendMessage::SendUIMetadata {
node_descriptions: document_node_definitions::collect_node_descriptions(), node_descriptions: document_node_definitions::collect_node_descriptions(),
node_icons: document_node_definitions::collect_node_icons(),
node_types: document_node_definitions::collect_node_types(), node_types: document_node_definitions::collect_node_types(),
}); });
@@ -898,18 +898,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// The document we are leaving won't get the pointer up that ends a wire drag in its graph, so abort the drag there before switching // The document we are leaving won't get the pointer up that ends a wire drag in its graph, so abort the drag there before switching
if self.active_document_id != Some(document_id) if self.active_document_id != Some(document_id)
&& let Some(document) = self.active_document_mut() && let Some(document) = self.active_document_mut()
&& document.end_node_graph_wire_in_progress(responses)
{ {
responses.add(DocumentMessage::AbortTransaction); document.node_graph_handler.graph_ui.stop_animations(responses);
responses.add(PortfolioMessage::SelectDocument { document_id }); let wire_ended = document.end_node_graph_wire_in_progress(responses);
return; if wire_ended {
} responses.add(DocumentMessage::AbortTransaction);
}
// The document we are leaving won't get the frames that settle what glides in its graph, so it settles at once let network_path = document.selection_network_path().to_vec();
if self.active_document_id != Some(document_id) if wire_ended || document.node_graph_handler.abort_node_drag(&mut document.network_interface, &network_path, responses) {
&& let Some(document) = self.active_document_mut() responses.add(PortfolioMessage::SelectDocument { document_id });
{ return;
document.node_graph_handler.stop_gliding(&document.network_interface, responses); }
} }
// Auto-save the document we are leaving // Auto-save the document we are leaving
@@ -958,8 +957,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(DocumentMessage::GraphViewOverlay { open: node_graph_open }); responses.add(DocumentMessage::GraphViewOverlay { open: node_graph_open });
if node_graph_open { if node_graph_open {
responses.add(NodeGraphMessage::UpdateGraphBarRight); responses.add(NodeGraphMessage::UpdateGraphBarRight);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires)
} else { } else {
responses.add(PortfolioMessage::UpdateDocumentWidgets); responses.add(PortfolioMessage::UpdateDocumentWidgets);
} }
@@ -997,7 +994,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
artboard_name, artboard_name,
artboard_count, artboard_count,
}; };
let result = self.executor.submit_document_export(document, document_id, export_config); let result = self.executor.submit_document_export(document, export_config);
if let Err(description) = result { if let Err(description) = result {
responses.add(DialogMessage::DisplayDialogError { responses.add(DialogMessage::DisplayDialogError {
@@ -1012,6 +1009,17 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
responses.add(FrontendMessage::WakeNodeRuntime); responses.add(FrontendMessage::WakeNodeRuntime);
} }
PortfolioMessage::UpdateGraphUi { part } => {
let Some(document) = self.active_document_id.and_then(|id| self.documents.get_mut(&id)) else {
return;
};
let edited = graph_ui::edited_name(document);
document.node_graph_handler.graph_ui.update_name_field(edited, responses);
let builder = graph_ui::GraphUiSceneBuilder::of(document);
if self.executor.update_graph_ui(|scene| builder.update(part, scene)) {
responses.add(PortfolioMessage::SubmitActiveGraphRender);
}
}
PortfolioMessage::SubmitActiveGraphRender => { PortfolioMessage::SubmitActiveGraphRender => {
if let Some(document_id) = self.active_document_id { if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false }); responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false });
@@ -1025,9 +1033,8 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return; return;
}; };
// Skip rendering while a resource is still loading, so its error isn't shown in the meantime. let graph_ui_config = graph_ui::config(document, preferences.graph_wire_style);
// Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left. if graph_ui_config.is_none() && document.resources.awaiting_resources() {
if document.resources.awaiting_resources() {
return; return;
} }
@@ -1051,12 +1058,20 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// TODO: See #3796. // TODO: See #3796.
#[cfg(not(target_family = "wasm"))] #[cfg(not(target_family = "wasm"))]
responses.add_front(FrontendMessage::UpdateViewportHolePunch { responses.add_front(FrontendMessage::UpdateViewportHolePunch {
active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview, active: document.render_mode != graphene_std::vector::style::RenderMode::SvgPreview || graph_ui_config.is_some(),
}); });
let result = self let result = self.executor.submit_node_graph_evaluation(
.executor document,
.submit_node_graph_evaluation(document, document_id, physical_resolution, scale, timing_information, node_to_inspect, ignore_hash, pointer_position); document_id,
physical_resolution,
scale,
timing_information,
node_to_inspect,
ignore_hash,
pointer_position,
graph_ui_config,
);
match result { match result {
Err(description) => { Err(description) => {
@@ -1124,18 +1139,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} }
} }
PortfolioMessage::SubmitClipboardSvg { id } => { PortfolioMessage::SubmitClipboardSvg { id } => {
let layers = self.active_document().map(|document| { let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
let selected = document.partition_selection().layers; responses.add(ClipboardMessage::Rendered { id, svg: None });
let mut layers = document return;
.metadata() };
.all_layers() let selected = document.partition_selection().layers;
.filter(|layer| selected.contains(layer)) let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
.map(|layer| layer.to_node()) layers.reverse();
.collect::<Vec<_>>(); responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
layers.reverse();
layers
});
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
} }
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => { PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open; self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
@@ -1,6 +1,6 @@
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode; use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graph_ui::wire::WireStyle;
#[impl_message(Message, Preferences)] #[impl_message(Message, Preferences)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -22,7 +22,7 @@ pub enum PreferencesMessage {
zoom_with_scroll: bool, zoom_with_scroll: bool,
}, },
GraphWireStyle { GraphWireStyle {
style: GraphWireStyle, style: WireStyle,
}, },
ViewportZoomWheelRate { ViewportZoomWheelRate {
rate: f64, rate: f64,
@@ -1,9 +1,9 @@
use crate::consts::{UI_SCALE_DEFAULT, VIEWPORT_ZOOM_WHEEL_RATE}; use crate::consts::{UI_SCALE_DEFAULT, VIEWPORT_ZOOM_WHEEL_RATE};
use crate::messages::input_mapper::key_mapping::MappingVariant; use crate::messages::input_mapper::key_mapping::MappingVariant;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode; use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::utility_types::ToolType; use crate::messages::tool::utility_types::ToolType;
use graph_ui::wire::WireStyle;
#[derive(ExtractField)] #[derive(ExtractField)]
pub struct PreferencesMessageContext<'a> { pub struct PreferencesMessageContext<'a> {
@@ -17,7 +17,7 @@ pub struct PreferencesMessageHandler {
pub selection_mode: SelectionMode, pub selection_mode: SelectionMode,
pub zoom_with_scroll: bool, pub zoom_with_scroll: bool,
pub brush_tool: bool, pub brush_tool: bool,
pub graph_wire_style: GraphWireStyle, pub graph_wire_style: WireStyle,
pub viewport_zoom_wheel_rate: f64, pub viewport_zoom_wheel_rate: f64,
pub ui_scale: f64, pub ui_scale: f64,
pub disable_ui_acceleration: bool, pub disable_ui_acceleration: bool,
@@ -51,7 +51,7 @@ impl Default for PreferencesMessageHandler {
selection_mode: SelectionMode::Touched, selection_mode: SelectionMode::Touched,
zoom_with_scroll: matches!(MappingVariant::default(), MappingVariant::ZoomWithScroll), zoom_with_scroll: matches!(MappingVariant::default(), MappingVariant::ZoomWithScroll),
brush_tool: false, brush_tool: false,
graph_wire_style: GraphWireStyle::default(), graph_wire_style: WireStyle::default(),
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE, viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT, ui_scale: UI_SCALE_DEFAULT,
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
@@ -126,8 +126,7 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
} }
PreferencesMessage::GraphWireStyle { style } => { PreferencesMessage::GraphWireStyle { style } => {
self.graph_wire_style = style; self.graph_wire_style = style;
responses.add(NodeGraphMessage::UnloadWires); responses.add(PortfolioMessage::SubmitActiveGraphRender);
responses.add(NodeGraphMessage::SendWires);
} }
PreferencesMessage::ViewportZoomWheelRate { rate } => { PreferencesMessage::ViewportZoomWheelRate { rate } => {
self.viewport_zoom_wheel_rate = rate; self.viewport_zoom_wheel_rate = rate;
@@ -175,6 +175,8 @@ pub struct SnapSession {
gesture: Option<Gesture>, gesture: Option<Gesture>,
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest. /// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
awake: Vec<Awake>, awake: Vec<Awake>,
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
woken_in_gesture: Vec<Awake>,
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with. /// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
position_sources: HashMap<u64, Vec<LayerId>>, position_sources: HashMap<u64, Vec<LayerId>>,
rest: Option<Rest>, rest: Option<Rest>,
@@ -495,13 +497,17 @@ impl SnapSession {
landed landed
} }
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. /// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
pub fn end_gesture(&mut self) { pub fn end_gesture(&mut self) {
self.gesture = None; self.gesture = None;
self.constructions = None; self.constructions = None;
self.rest = None; self.rest = None;
self.crossings.clear(); self.crossings.clear();
self.forget(); self.forget();
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
self.awake.retain(|target| !woken_in_gesture.contains(target));
self.forget_targets_gone_to_sleep();
} }
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything. /// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
@@ -545,11 +551,14 @@ impl SnapSession {
if let Awake::Position { id, .. } = target { if let Awake::Position { id, .. } = target {
self.position_sources.insert(id, sources.clone()); self.position_sources.insert(id, sources.clone());
} }
if self.gesture.is_some() {
self.woken_in_gesture.push(target);
}
self.awake.push(target); self.awake.push(target);
} }
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT); let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
self.awake.drain(..over_the_limit); self.awake.drain(..over_the_limit);
self.forget_sources_of_sleeping_positions(); self.forget_targets_gone_to_sleep();
self.constructions = None; self.constructions = None;
true true
@@ -563,6 +572,7 @@ impl SnapSession {
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves. /// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
pub fn sleep_all(&mut self) { pub fn sleep_all(&mut self) {
self.awake.clear(); self.awake.clear();
self.woken_in_gesture.clear();
self.position_sources.clear(); self.position_sources.clear();
self.constructions = None; self.constructions = None;
@@ -583,10 +593,12 @@ impl SnapSession {
.collect() .collect()
} }
fn forget_sources_of_sleeping_positions(&mut self) { /// Lets go of what is kept about woken targets that have since gone back to sleep.
fn forget_targets_gone_to_sleep(&mut self) {
let awake = &self.awake; let awake = &self.awake;
self.position_sources self.position_sources
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id))); .retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
self.woken_in_gesture.retain(|target| awake.contains(target));
} }
/// The woken targets, oldest first. /// The woken targets, oldest first.
@@ -721,7 +733,7 @@ impl SnapSession {
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer), Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))), Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
}); });
self.forget_sources_of_sleeping_positions(); self.forget_targets_gone_to_sleep();
} }
} }
@@ -1100,6 +1112,45 @@ mod tests {
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE)); assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
} }
#[tokio::test]
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(100., 100., 300., 240.).await;
editor.draw_rect(500., 100., 700., 240.).await;
let mut session = SnapSession::default();
let input = InputPreprocessorMessageHandler::default();
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
for (index, position) in along_edges.into_iter().enumerate() {
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
}
assert_eq!(session.woken_in_gesture, session.awake);
}
#[tokio::test]
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(100., 100., 300., 240.).await;
let mut session = SnapSession::default();
// The top edge is woken before the gesture, and the right edge during it
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
let woken_before = session.awake.clone();
let input = InputPreprocessorMessageHandler::default();
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
assert_eq!(session.awake.len(), 2);
session.end_gesture();
assert_eq!(session.awake, woken_before);
}
#[tokio::test] #[tokio::test]
async fn only_the_latest_few_woken_targets_stay_awake() { async fn only_the_latest_few_woken_targets_stay_awake() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
+319 -193
View File
@@ -1,23 +1,30 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError; use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface}; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::list;
use graph_craft::proto::GraphErrors; use graph_craft::proto::GraphErrors;
use graph_ui::GraphUiConfig;
use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit};
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List}; use graphene_std::list::{Item, List};
use graphene_std::math::quad::Quad;
use graphene_std::raster::{CPU, Raster}; use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes}; use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter}; use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender}; use std::sync::mpsc::{Receiver, Sender};
@@ -27,10 +34,11 @@ mod recompile_tests;
mod runtime; mod runtime;
pub use runtime::*; pub use runtime::*;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone)]
pub struct ExecutionRequest { pub struct ExecutionRequest {
execution_id: u64, execution_id: u64,
render_config: RenderConfig, render_config: RenderConfig,
graph_ui_config: Option<GraphUiConfig>,
} }
pub struct ExecutionResponse { pub struct ExecutionResponse {
@@ -41,6 +49,15 @@ pub struct ExecutionResponse {
dropped_thumbnails: Vec<NodeId>, dropped_thumbnails: Vec<NodeId>,
/// The latest result of each observation. /// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>, observations: HashMap<ObservationKey, InspectResult>,
/// The canvas the frame was presented to
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info: Option<ViewportCanvasInfo>,
}
#[cfg(all(target_family = "wasm", feature = "wasm"))]
struct ViewportCanvasInfo {
id: u64,
resolution: DVec2,
} }
/// Names an observation so it can be changed or stopped without touching the others. /// Names an observation so it can be changed or stopped without touching the others.
@@ -88,7 +105,8 @@ impl std::fmt::Display for EvaluationErrors {
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
pub struct CompilationResponse { pub struct CompilationResponse {
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>, result: Result<(), String>,
resolved_types: ResolvedDocumentNodeTypesDelta,
node_graph_errors: GraphErrors, node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors, node_graph_warnings: GraphErrors,
} }
@@ -103,20 +121,26 @@ pub enum NodeGraphUpdate {
}, },
/// The latest result of each observation, sent outside an execution after one of them changed. /// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>), Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg { Export {
id: u64, id: u64,
svg: Option<String>, result: Box<ExecutionResult>,
}, },
} }
#[derive(Debug)] #[derive(Debug)]
pub struct NodeGraphExecutor { pub struct NodeGraphExecutor {
sender: Sender<GraphRuntimeRequest>, sender: Sender<GraphRuntimeRequest>,
receiver: Receiver<NodeGraphUpdate>, receiver: Receiver<NodeGraphUpdate>,
current_execution_id: u64, current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>, futures: VecDeque<(u64, ExecutionContext)>,
pending: Option<(u64, ExecutionContext)>, pending: Option<(u64, ExecutionContext)>,
current_export_id: u64,
exports: HashMap<u64, ExportTarget>,
node_graph_hash: u64, node_graph_hash: u64,
graph_ui_scene: GraphUiScene,
/// The document whose network the graph runtime was last sent. /// The document whose network the graph runtime was last sent.
node_graph_document: Option<DocumentId>, node_graph_document: Option<DocumentId>,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected. /// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
@@ -137,9 +161,14 @@ pub struct NodeGraphExecutor {
gradient_migration_attempted: HashSet<DocumentId>, gradient_migration_attempted: HashSet<DocumentId>,
} }
#[derive(Debug)]
enum ExportTarget {
File(ExportConfig),
Clipboard(u64),
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct ExecutionContext { struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId, document_id: DocumentId,
/// The view the render was asked for, which the footprints it reports back are measured in. /// The view the render was asked for, which the footprints it reports back are measured in.
document_to_viewport: DAffine2, document_to_viewport: DAffine2,
@@ -174,7 +203,10 @@ impl NodeGraphExecutor {
futures: Default::default(), futures: Default::default(),
pending: None, pending: None,
current_execution_id: 0, current_execution_id: 0,
current_export_id: 0,
exports: HashMap::new(),
node_graph_hash: 0, node_graph_hash: 0,
graph_ui_scene: GraphUiScene::default(),
node_graph_document: None, node_graph_document: None,
previous_node_to_inspect: Vec::new(), previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(), inspect_context_overrides: ContextOverrides::default(),
@@ -187,33 +219,35 @@ impl NodeGraphExecutor {
(node_executor, node_runtime) (node_executor, node_runtime)
} }
/// Forgets which canvas images the frontend holds, for a frontend that started over without them.
pub fn forget_canvas_images(&mut self) {
self.canvas_images_sent.clear();
}
/// Allows the test runner to see if any more executions have been queued.
#[cfg(test)]
pub fn current_execution_id(&self) -> u64 {
self.current_execution_id
}
/// Allows the test runner to access last executions evaluation errors.
#[cfg(test)]
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
self.evaluation_errors.take()
}
/// Execute the network by flattening it and creating a borrow stack. /// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 { fn queue_execution(&mut self, render_config: RenderConfig, graph_ui_config: Option<GraphUiConfig>) -> u64 {
let execution_id = self.current_execution_id; let execution_id = self.current_execution_id;
self.current_execution_id += 1; self.current_execution_id += 1;
let request = ExecutionRequest { execution_id, render_config }; let request = ExecutionRequest {
execution_id,
render_config,
graph_ui_config,
};
self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request"); self.sender.send(GraphRuntimeRequest::ExecutionRequest(request)).expect("Failed to send generation request");
execution_id execution_id
} }
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
let id = self.current_export_id;
self.current_export_id += 1;
let request = GraphRuntimeRequest::Export {
id,
render_config,
network,
resources,
};
self.sender.send(request).map_err(|e| e.to_string())?;
self.exports.insert(id, target);
Ok(())
}
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) { pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) { if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
log::error!("Failed to send the overlays: {error}"); log::error!("Failed to send the overlays: {error}");
@@ -232,13 +266,29 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides"); .expect("Failed to send the context overrides");
} }
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message { pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
if document_id.is_none() || self.node_graph_document != document_id { let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
return ClipboardMessage::Rendered { id, svg: None }.into(); let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
} return no_svg;
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request"); let viewport = Footprint {
Message::NoOp resolution: (max - min).round().as_uvec2(),
transform: DAffine2::from_translation(-min),
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: 1.,
export_format: ExportFormat::Svg,
for_export: true,
..Default::default()
};
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
Ok(()) => Message::NoOp,
Err(_) => no_svg,
}
} }
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) { pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -248,34 +298,12 @@ impl NodeGraphExecutor {
} }
let layers = document.layers_in_view.all_in_view(); let layers = document.layers_in_view.all_in_view();
let layers_panel = document.layers_in_view.layers_panel().clone();
self.sender self.sender
.send(GraphRuntimeRequest::ThumbnailsInView { layers, document_id }) .send(GraphRuntimeRequest::ThumbnailsInView { layers, layers_panel, document_id })
.expect("Failed to send the thumbnails in view"); .expect("Failed to send the thumbnails in view");
} }
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
#[cfg(test)]
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network);
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
}
/// Update the cached network if necessary. /// Update the cached network if necessary.
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> { fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect; let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
@@ -286,9 +314,11 @@ impl NodeGraphExecutor {
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash()); let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash { if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes(); let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths(); let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &previewed, &layers);
let thumbnails = thumbnail_sources(&network, &layers);
self.node_graph_hash = graph_hash; self.node_graph_hash = graph_hash;
self.node_graph_document = Some(document_id); self.node_graph_document = Some(document_id);
@@ -298,8 +328,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed, thumbnails,
layers,
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -332,6 +361,7 @@ impl NodeGraphExecutor {
} }
/// Adds an evaluate request for whatever current network is cached. /// Adds an evaluate request for whatever current network is cached.
#[allow(clippy::too_many_arguments)]
pub(crate) fn submit_current_node_graph_evaluation( pub(crate) fn submit_current_node_graph_evaluation(
&mut self, &mut self,
document: &mut DocumentMessageHandler, document: &mut DocumentMessageHandler,
@@ -340,6 +370,7 @@ impl NodeGraphExecutor {
viewport_scale: f64, viewport_scale: f64,
time: TimingInformation, time: TimingInformation,
pointer: DVec2, pointer: DVec2,
graph_ui_config: Option<GraphUiConfig>,
) -> Result<Message, String> { ) -> Result<Message, String> {
let viewport = Footprint { let viewport = Footprint {
transform: document.metadata().document_to_viewport, transform: document.metadata().document_to_viewport,
@@ -358,12 +389,11 @@ impl NodeGraphExecutor {
}; };
// Execute the node graph // Execute the node graph
let execution_id = self.queue_execution(render_config); let execution_id = self.queue_execution(render_config, graph_ui_config);
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
@@ -385,9 +415,10 @@ impl NodeGraphExecutor {
node_to_inspect: Vec<NodeId>, node_to_inspect: Vec<NodeId>,
ignore_hash: bool, ignore_hash: bool,
pointer: DVec2, pointer: DVec2,
graph_ui_config: Option<GraphUiConfig>,
) -> Result<Message, String> { ) -> Result<Message, String> {
self.update_node_graph(document, document_id, node_to_inspect, ignore_hash)?; self.update_node_graph(document, document_id, node_to_inspect, ignore_hash)?;
self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer) self.submit_current_node_graph_evaluation(document, document_id, viewport_resolution, viewport_scale, time, pointer, graph_ui_config)
} }
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
@@ -425,12 +456,11 @@ impl NodeGraphExecutor {
}; };
// Execute the node graph // Execute the node graph
let execution_id = self.queue_execution(render_config); let execution_id = self.queue_execution(render_config, None);
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
@@ -441,10 +471,9 @@ impl NodeGraphExecutor {
} }
/// Evaluates a node graph for export /// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> { pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes(); prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
let resources = document.resources.registry.clone();
let export_format = if export_config.file_type == FileType::Svg { let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg graphene_std::application_io::ExportFormat::Svg
@@ -478,34 +507,12 @@ impl NodeGraphExecutor {
time: Default::default(), time: Default::default(),
pointer: DVec2::ZERO, pointer: DVec2::ZERO,
export_format, export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal, render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true, for_export: true,
for_eyedropper: false, for_eyedropper: false,
}; };
// Execute the node graph self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: Some(export_config),
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
},
));
Ok(())
} }
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile. /// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
@@ -517,8 +524,8 @@ impl NodeGraphExecutor {
} }
let mut all_dropped_thumbnails = Vec::new(); let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter(); let results = self.receiver.try_iter().collect::<Vec<_>>();
for response in results.by_ref() { for response in results {
match response { match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => { NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse { let ExecutionResponse {
@@ -527,6 +534,8 @@ impl NodeGraphExecutor {
responses: existing_responses, responses: existing_responses,
dropped_thumbnails, dropped_thumbnails,
mut observations, mut observations,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info,
} = *execution_response; } = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -540,7 +549,7 @@ impl NodeGraphExecutor {
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) { let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked"); let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { if execution_context.measure_fill.is_none() {
self.pending = Some((execution_id, execution_context.clone())); self.pending = Some((execution_id, execution_context.clone()));
} }
execution_context execution_context
@@ -563,16 +572,41 @@ impl NodeGraphExecutor {
if let Some(bake_target) = execution_context.measure_fill { if let Some(bake_target) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) { if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
let measured = observations.remove(&ObservationKey::FillMeasurement); let measured = observations.remove(&ObservationKey::FillMeasurement);
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten(); let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Fallback(..))
.then_some(measured)
.flatten();
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses); self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
} }
continue; continue;
} }
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let mut result = result;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
if let Some(canvas) = viewport_canvas_info {
let placeholder = format!(
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
canvas.resolution.x, canvas.resolution.y, canvas.id,
);
match result.render_output() {
Some(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => {
let end = svg.rfind("</svg>").unwrap_or(svg.len());
svg.insert_str(end, &placeholder);
}
_ => {
let svg = format!("<svg>{placeholder}</svg>");
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
}
}
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
// A pending graph keeps the last frame, and the errors shown with it // A pending graph keeps the last frame, and the errors shown with it; a provisional frame keeps the errors
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) { if !matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) {
let errors = match &result { let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => { ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| { let in_document = |path: &&[NodeId]| {
@@ -645,11 +679,8 @@ impl NodeGraphExecutor {
log::error!("Node graph evaluation failed:\n{message}"); log::error!("Node graph evaluation failed:\n{message}");
} }
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
}
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break; continue;
} }
}; };
@@ -667,10 +698,8 @@ impl NodeGraphExecutor {
} }
document.network_interface.update_vector_modify(path_contents(&observations)); document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) { if let Some(node_graph_output) = node_graph_output {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(None, _) => {}
} }
responses.add(DeferMessage::TriggerGraphRun { responses.add(DeferMessage::TriggerGraphRun {
execution_id, execution_id,
@@ -692,49 +721,42 @@ impl NodeGraphExecutor {
node_graph_errors, node_graph_errors,
node_graph_warnings, node_graph_warnings,
result, result,
resolved_types,
} = execution_response; } = execution_response;
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend // The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
if self.gradient_migration.is_some() { if self.gradient_migration.is_some() {
if let Err((_, e)) = &result { if let Err(e) = &result {
log::trace!("Gradient migration measurement compile: {e}"); log::trace!("Gradient migration measurement compile: {e}");
} }
continue; continue;
} }
let type_delta = match result { if let Err(e) = &result {
Err((incomplete_delta, e)) => { // Clear the click targets while the graph is in an un-renderable state
// Clear the click targets while the graph is in an un-renderable state
document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others // The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() { if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}"); log::error!("The node graph failed to compile:\n{e}");
} else { } else {
log::trace!("{e}"); log::trace!("{e}");
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: incomplete_delta,
node_graph_errors,
node_graph_warnings,
});
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
} }
Ok(result) => result, }
};
responses.add(NodeGraphMessage::UpdateTypes { responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: type_delta, resolved_types,
node_graph_errors, node_graph_errors,
node_graph_warnings, node_graph_warnings,
}); });
if result.is_err() {
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
}
} }
NodeGraphUpdate::EyedropperPreview(raster) => { NodeGraphUpdate::EyedropperPreview(raster) => {
let (data, width, height) = raster.to_flat_u8(); let (data, width, height) = raster.to_flat_u8();
@@ -757,33 +779,7 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses); Self::receive_thumbnails(document, thumbnails, responses);
} }
} }
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }), NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
}
}
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let execution_context = self.execution_context(execution_response.execution_id);
if execution_context.is_some_and(|context| context.document_id == document_id) {
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
}
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
responses.add(export_failure_dialog(None));
}
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
}
NodeGraphUpdate::Thumbnails {
responses: thumbnails,
document_id: thumbnails_document,
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
_ => {}
} }
} }
@@ -799,15 +795,6 @@ impl NodeGraphExecutor {
} }
} }
/// What an execution was submitted for, while it's still queued or pending.
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
self.futures
.iter()
.chain(&self.pending)
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
.map(|(_, execution_context)| execution_context)
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running. /// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still /// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
@@ -842,6 +829,23 @@ impl NodeGraphExecutor {
true true
} }
pub fn update_graph_ui(&mut self, change: impl FnOnce(&mut GraphUiSceneEdit)) -> bool {
let mut edit = std::mem::take(&mut self.graph_ui_scene).edit();
change(&mut edit);
let (scene, delta) = edit.finish();
self.graph_ui_scene = scene;
let changed = !delta.is_empty();
if changed {
self.sender.send(GraphRuntimeRequest::GraphUi(delta)).expect("Failed to send the graph UI delta");
}
changed
}
pub fn forget_canvas_images(&mut self) {
self.canvas_images_sent.clear();
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Run the graph with its export chain redirected down to the (possibly nested) Fill at `network_path`/`fill_node_id` /// Run the graph with its export chain redirected down to the (possibly nested) Fill at `network_path`/`fill_node_id`
/// (so its branch evaluates even when hidden or orphaned) and that node inspected, so its evaluated geometry returns /// (so its branch evaluates even when hidden or orphaned) and that node inspected, so its evaluated geometry returns
@@ -877,6 +881,10 @@ impl NodeGraphExecutor {
return; return;
} }
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
let fill_measurement = Observation { let fill_measurement = Observation {
node_path: full_path, node_path: full_path,
@@ -888,8 +896,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed: Vec::new(), thumbnails,
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]), observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
})) }))
.is_err() .is_err()
@@ -917,11 +924,10 @@ impl NodeGraphExecutor {
for_export: false, for_export: false,
for_eyedropper: false, for_eyedropper: false,
}; };
let execution_id = self.queue_execution(render_config); let execution_id = self.queue_execution(render_config, None);
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: Some((network_path, fill_node_id, gradient)), measure_fill: Some((network_path, fill_node_id, gradient)),
@@ -1036,11 +1042,6 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use }); responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
responses.add(FrontendMessage::UpdateDocumentArtwork { svg }); responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
} }
#[cfg(target_family = "wasm")]
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
let svg = format!("<svg>{}</svg>", viewport_canvas_placeholder(canvas_id, resolution));
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
RenderOutputType::Texture { .. } => {} RenderOutputType::Texture { .. } => {}
RenderOutputType::Buffer { width, height, .. } => { RenderOutputType::Buffer { width, height, .. } => {
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer"); log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
@@ -1061,6 +1062,7 @@ impl NodeGraphExecutor {
vector_data, vector_data,
appearance_attributes, appearance_attributes,
effects_reach, effects_reach,
effects_frames,
backgrounds: _, backgrounds: _,
} = render_output.metadata; } = render_output.metadata;
@@ -1077,7 +1079,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClipTargets { clip_targets }); responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data }); responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes }); responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach }); responses.add(DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames });
responses.add(DocumentMessage::RenderScrollbars); responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
@@ -1085,6 +1087,51 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status }); responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
} }
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let Some(target) = self.exports.remove(&export_id) else { return };
let failure = match (result, &target) {
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
return match target {
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
ExportTarget::Clipboard(id) => {
let svg = match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Some(svg),
_ => None,
};
responses.add(ClipboardMessage::Rendered { id, svg });
}
};
}
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
(ExecutionResult::Panic(payload), _) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Some(format!("Panicked: {}", message.unwrap_or("no message")))
}
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
};
if let Some(message) = &failure {
log::error!("Node graph evaluation failed:\n{message}");
}
match target {
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}),
ExportTarget::Clipboard(id) => {
responses.add(ClipboardMessage::Rendered { id, svg: None });
if let Some(description) = failure {
let title = "Unable to copy as SVG".to_string();
responses.add(DialogMessage::DisplayDialogError { title, description });
}
}
}
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) { fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let ExportConfig { let ExportConfig {
file_type, file_type,
@@ -1184,6 +1231,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
} }
} }
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
apply_previews(network, previewed);
write_layer_paths(network, layers);
}
/// Replaces each network's primary export with its previewed node.
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
for (network_path, previewed) in previewed {
let Some(nested) = network.nested_network_mut(network_path) else { continue };
let Some(export) = nested.exports.first_mut() else { continue };
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
}
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
// O(layers * depth)
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
layers.iter().filter_map(source).collect()
}
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
let metadata = interface.document_metadata();
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
artboards if artboards == layers.len() => list!(Artboard),
_ => return None,
};
let mut network = interface.document_network().clone();
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
let mut below = NodeInput::type_default(stack, true);
let mut bounds = None;
for &layer in layers {
let mut node = network.nodes.get(&layer.to_node())?.clone();
*node.inputs.first_mut()? = below;
let copy = NodeId::new();
network.nodes.insert(copy, node);
below = NodeInput::node(copy, 0);
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
true => metadata.downstream_transform_to_document(layer).inverse(),
false => DAffine2::IDENTITY,
};
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
}
network.exports = vec![below];
Some((network, bounds?))
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform. /// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> { fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
@@ -1205,23 +1307,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None None
} }
/// The SVG element the frontend replaces with the viewport canvas, covering the viewport at its logical `resolution`.
#[cfg(target_family = "wasm")]
fn viewport_canvas_placeholder(canvas_id: u64, resolution: DVec2) -> String {
format!(
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
resolution.x, resolution.y, canvas_id,
)
}
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> { fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER)); let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
@@ -1268,6 +1353,47 @@ mod test {
use graphene_std::list::Item; use graphene_std::list::Item;
use test_prelude::LayerNodeIdentifier; use test_prelude::LayerNodeIdentifier;
impl NodeGraphExecutor {
/// Allows the test runner to see if any more executions have been queued.
pub fn current_execution_id(&self) -> u64 {
self.current_execution_id
}
/// Allows the test runner to access last executions evaluation errors.
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
self.evaluation_errors.take()
}
pub fn graph_ui_scene(&self) -> &GraphUiScene {
&self.graph_ui_scene
}
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network);
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
thumbnails,
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
}
}
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received. /// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
#[derive(Default)] #[derive(Default)]
pub struct Instrumented { pub struct Instrumented {
@@ -11,15 +11,15 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap(); let document = documents.get_mut(&document_id).unwrap();
executor executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO) .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None)
.unwrap(); .unwrap();
editor.runtime.update(); editor.runtime.update();
editor.runtime.run().await; editor.runtime.run().await;
editor.dispatch(Message::Wake); editor.dispatch(Message::Wake);
} }
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops /// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
/// for one more update, so a first update clears those of the graph before it. /// an update replaces for one more update, so a first update clears the nodes of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> { async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await; compile_and_run(editor).await;
compile_and_run(editor).await; compile_and_run(editor).await;
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout; use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi; use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::document::NodeId;
use graphene_std::application_io::{ApplicationIo, Texture}; use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::gradient::Gradient; use graphene_std::gradient::Gradient;
@@ -12,13 +12,12 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle}; use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; use graphene_std::renderer::Render;
use graphene_std::transform::{Footprint, RenderQuality}; use graphene_std::transform::Footprint;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic}; use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::layer_content; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc; use std::sync::Arc;
mod atlas; mod atlas;
@@ -41,22 +40,17 @@ pub struct Thumbnails {
sources: HashMap<NodeId, NodeId>, sources: HashMap<NodeId, NodeId>,
/// The layers whose content changed since their thumbnail was last rendered. /// The layers whose content changed since their thumbnail was last rendered.
stale: HashSet<NodeId>, stale: HashSet<NodeId>,
/// The layers whose thumbnails the frontend shows, the only ones rendered.
in_view: HashSet<NodeId>, in_view: HashSet<NodeId>,
in_layers_panel: HashSet<NodeId>,
stale_in_layers_panel: HashSet<NodeId>,
/// The device pixel ratio thumbnails are rendered at. /// The device pixel ratio thumbnails are rendered at.
scale: f64, scale: f64,
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
canvases: HashMap<NodeId, ThumbnailCanvases>, canvases: HashMap<NodeId, CanvasHandle>,
/// The layers whose thumbnails were sent to a page that can't show the runtime's canvases. /// The layers whose thumbnails were sent to a page that can't show the runtime's canvases.
#[cfg(not(all(target_family = "wasm", feature = "wasm")))] #[cfg(not(all(target_family = "wasm", feature = "wasm")))]
sent: HashSet<NodeId>, sent: HashSet<NodeId>,
} graphics: Arc<BTreeMap<NodeId, Graphic>>,
/// A layer's thumbnail is shown in both the Layers panel and the node graph, but a canvas element can only be in one place.
#[cfg(all(target_family = "wasm", feature = "wasm"))]
struct ThumbnailCanvases {
layers_panel: CanvasHandle,
node_graph: CanvasHandle,
} }
impl Thumbnails { impl Thumbnails {
@@ -64,8 +58,14 @@ impl Thumbnails {
Self { scale: 1., ..Default::default() } Self { scale: 1., ..Default::default() }
} }
pub fn set_in_view(&mut self, layers: HashSet<NodeId>) { pub fn set_in_view(&mut self, layers: HashSet<NodeId>, layers_panel: HashSet<NodeId>) {
self.stale.extend(self.stale_in_layers_panel.extract_if(|layer| layers_panel.contains(layer)));
self.in_view = layers; self.in_view = layers;
self.in_layers_panel = layers_panel;
}
pub fn graphics(&self) -> Arc<BTreeMap<NodeId, Graphic>> {
self.graphics.clone()
} }
/// Whether the layer's thumbnail is waiting to be rendered. /// Whether the layer's thumbnail is waiting to be rendered.
@@ -83,17 +83,15 @@ impl Thumbnails {
} }
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale. /// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) { pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
// O(layers * depth) let source_map = executor.tree().source_map();
let sources: HashMap<NodeId, NodeId> = layer_paths let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
.iter()
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
.collect();
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content // A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source)); let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
self.stale.extend(changed.map(|(layer, _)| *layer)); self.stale.extend(changed.map(|(layer, _)| *layer));
self.stale.retain(|layer| sources.contains_key(layer)); self.stale.retain(|layer| sources.contains_key(layer));
self.stale_in_layers_panel.retain(|layer| sources.contains_key(layer));
self.sources = sources; self.sources = sources;
} }
@@ -115,11 +113,13 @@ impl Thumbnails {
#[cfg(not(all(target_family = "wasm", feature = "wasm")))] #[cfg(not(all(target_family = "wasm", feature = "wasm")))]
self.sent.retain(|layer| keep_sourced(layer)); self.sent.retain(|layer| keep_sourced(layer));
Arc::make_mut(&mut self.graphics).retain(|layer, _| sources.contains_key(layer));
dropped dropped
} }
/// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view. /// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view.
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) { pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) -> bool {
let mut contents = HashMap::new(); let mut contents = HashMap::new();
for layer in std::mem::take(&mut self.stale) { for layer in std::mem::take(&mut self.stale) {
let Some(&source) = self.sources.get(&layer) else { continue }; let Some(&source) = self.sources.get(&layer) else { continue };
@@ -136,10 +136,12 @@ impl Thumbnails {
contents.insert(layer, content); contents.insert(layer, content);
} }
if contents.is_empty() { if contents.is_empty() {
return; return false;
} }
self.stale_in_layers_panel.extend(contents.keys().filter(|layer| !self.in_layers_panel.contains(layer)));
self.render_with_vello(&contents, editor_api, responses).await; self.render_with_vello(&contents, editor_api, responses).await;
true
} }
/// Renders the thumbnails into atlases with Vello and shows them. /// Renders the thumbnails into atlases with Vello and shows them.
@@ -167,39 +169,55 @@ impl Thumbnails {
} }
}; };
self.show_atlas(&layout, texture, executor, responses).await; self.keep_cells(&layout, &texture, executor);
let shown: Vec<(usize, NodeId)> = layout.layers.iter().copied().enumerate().filter(|(_, layer)| self.in_layers_panel.contains(layer)).collect();
if !shown.is_empty() {
self.show_atlas(&layout, &shown, texture, executor, responses).await;
}
} }
} }
/// Reads the atlas back and draws each cell into the canvases the layer's rows show. /// Copies each layer's cell out of the atlas into a texture of its own for the node graph.
fn keep_cells(&mut self, layout: &ThumbnailAtlasLayout, atlas: &Texture, executor: &wgpu_executor::WgpuExecutor) {
let mut encoder = executor.context().device.create_command_encoder(&Default::default());
for (index, &layer) in layout.layers.iter().enumerate() {
let cell = executor.request_texture(layout.cell_size);
let mut source = atlas.as_image_copy();
let origin = layout.cell_origin(index);
(source.origin.x, source.origin.y) = (origin.x, origin.y);
encoder.copy_texture_to_texture(source, cell.as_image_copy(), cell.size());
Arc::make_mut(&mut self.graphics).insert(layer, Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(cell))));
}
executor.context().queue.submit([encoder.finish()]);
}
/// Reads the atlas back and draws each shown cell into the canvas the layer's row in the Layers panel shows.
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) { async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await; let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8(); let (pixels, _, _) = raster.to_flat_u8();
for (index, &layer) in layout.layers.iter().enumerate() { for &(index, layer) in shown {
let cell_pixels = layout.cell_pixels(&pixels, index); let cell_pixels = layout.cell_pixels(&pixels, index);
let Ok(image) = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&cell_pixels), layout.cell_size.x, layout.cell_size.y) else { let Ok(image) = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&cell_pixels), layout.cell_size.x, layout.cell_size.y) else {
continue; continue;
}; };
let canvases = self.canvases(layer); let canvas = self.canvas(layer);
for canvas in [&mut canvases.layers_panel, &mut canvases.node_graph] { canvas.set_resolution(layout.cell_size);
canvas.set_resolution(layout.cell_size); let _ = canvas.context().put_image_data(&image, 0, 0);
let _ = canvas.context().put_image_data(&image, 0, 0);
}
responses.push_back(canvases.update_message(layer)); responses.push_back(canvas_message(layer, canvas));
} }
} }
/// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each layer its cell's pixels. /// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each shown layer its cell's pixels.
#[cfg(not(all(target_family = "wasm", feature = "wasm")))] #[cfg(not(all(target_family = "wasm", feature = "wasm")))]
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) { async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, shown: &[(usize, NodeId)], atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await; let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8(); let (pixels, _, _) = raster.to_flat_u8();
for (index, &layer) in layout.layers.iter().enumerate() { for &(index, layer) in shown {
self.sent.insert(layer); self.sent.insert(layer);
responses.push_back(FrontendMessage::UpdateNodeThumbnailPixels { responses.push_back(FrontendMessage::UpdateNodeThumbnailPixels {
id: layer, id: layer,
@@ -211,23 +229,14 @@ impl Thumbnails {
} }
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
fn canvases(&mut self, layer: NodeId) -> &mut ThumbnailCanvases { fn canvas(&mut self, layer: NodeId) -> &mut CanvasHandle {
self.canvases.entry(layer).or_insert_with(|| ThumbnailCanvases { self.canvases.entry(layer).or_insert_with(CanvasHandle::new)
layers_panel: CanvasHandle::new(),
node_graph: CanvasHandle::new(),
})
} }
} }
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
impl ThumbnailCanvases { fn canvas_message(layer: NodeId, canvas: &mut CanvasHandle) -> FrontendMessage {
fn update_message(&mut self, layer: NodeId) -> FrontendMessage { FrontendMessage::UpdateNodeThumbnailCanvas { id: layer, canvas_id: canvas.id() }
FrontendMessage::UpdateNodeThumbnailCanvases {
id: layer,
layers_panel_canvas_id: self.layers_panel.id(),
node_graph_canvas_id: self.node_graph.id(),
}
}
} }
enum ThumbnailContent { enum ThumbnailContent {
@@ -276,11 +285,11 @@ impl ThumbnailContent {
} }
} }
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out. /// The area the content covers once rendered, counting the effects drawn through maps and images.
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox { fn content_bounds(&self) -> RenderBoundingBox {
match self { match self {
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach // Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved), Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
// The clipping rectangles rather than the content, since the renderer clips content to them // The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards), Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY), Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
@@ -289,7 +298,7 @@ impl ThumbnailContent {
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio. /// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] { fn bounds(&self) -> [DVec2; 2] {
let bounds = match self.content_bounds(true) { let bounds = match self.content_bounds() {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds, RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE], _ => [DVec2::ZERO, DVec2::ONE],
}; };
@@ -297,45 +306,6 @@ impl ThumbnailContent {
} }
} }
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
let contents: Vec<ThumbnailContent> = layers
.iter()
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
.collect();
let bounds = contents
.iter()
.filter_map(|content| match content.content_bounds(false) {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
_ => None,
})
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
let render_params = RenderParams {
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
for content in &contents {
content.graphic().render_svg(&mut render, &render_params);
}
if render.svg.is_empty() {
return None;
}
render.format_svg(bounds[0], bounds[1]);
Some(render.svg.to_svg_string())
}
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?;
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
/// Converts the other kinds of graphical content into a graphic. /// Converts the other kinds of graphical content into a graphic.
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> { fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
macro_rules! downcast_into_graphic { macro_rules! downcast_into_graphic {
@@ -411,7 +381,7 @@ mod tests {
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents); let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap(); let document = documents.get_mut(&document_id).unwrap();
executor executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO) .submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO, None)
.unwrap(); .unwrap();
editor.runtime.update(); editor.runtime.update();
editor.runtime.run().await; editor.runtime.run().await;
+45 -27
View File
@@ -75,7 +75,7 @@ impl EditorTestUtils {
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))), Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
}; };
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) { if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO, None) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}"))); return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
} }
self.runtime.update(); self.runtime.update();
@@ -90,13 +90,22 @@ impl EditorTestUtils {
return Err(TestGraphError::Evaluation(errors)); return Err(TestGraphError::Evaluation(errors));
} }
for message in frontend_messages { self.check_node_graph_errors();
message.check_node_graph_error();
}
Ok(instrumented) Ok(instrumented)
} }
fn check_node_graph_errors(&self) {
let document = self.active_document();
if !document.graph_view_overlay_open {
return;
}
let errors = document.node_graph_handler.node_graph_errors(&document.network_interface, document.breadcrumb_network_path());
if !errors.is_empty() {
panic!("errors: {errors:?}");
}
}
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages. /// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> { pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
const MAX_ITERATIONS: usize = 16; const MAX_ITERATIONS: usize = 16;
@@ -283,12 +292,11 @@ impl EditorTestUtils {
/// Sets the clock to a time in milliseconds and runs one animation frame, as the frontend does on each `requestAnimationFrame`. /// Sets the clock to a time in milliseconds and runs one animation frame, as the frontend does on each `requestAnimationFrame`.
pub async fn animation_frame(&mut self, timestamp: u64) { pub async fn animation_frame(&mut self, timestamp: u64) {
let messages = Box::new([ self.handle_message(animation_frame_batch(timestamp)).await;
InputPreprocessorMessage::CurrentTime { timestamp }.into(), }
AnimationMessage::IncrementFrameCounter.into(),
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(), pub fn dispatch_animation_frame(&mut self, timestamp: u64) {
]); self.dispatch(animation_frame_batch(timestamp));
self.handle_message(Message::Batched { messages }).await;
} }
pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) { pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
@@ -423,6 +431,17 @@ impl EditorTestUtils {
self.create_node(node_type, Some((x, y))).await self.create_node(node_type, Some((x, y))).await
} }
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
node_id: Some(node_id),
xy: Some((x, y)),
})
.await;
node_id
}
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId { async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
let node_id = NodeId::new(); let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu { self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
@@ -436,17 +455,13 @@ impl EditorTestUtils {
} }
} }
pub trait FrontendMessageTestUtils { fn animation_frame_batch(timestamp: u64) -> Message {
fn check_node_graph_error(&self); let messages = Box::new([
} InputPreprocessorMessage::CurrentTime { timestamp }.into(),
AnimationMessage::IncrementFrameCounter.into(),
impl FrontendMessageTestUtils for FrontendMessage { BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
fn check_node_graph_error(&self) { ]);
let FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors } = self else { return }; Message::Batched { messages }
if !errors.is_empty() {
panic!("errors: {errors:?}");
}
}
} }
#[derive(Debug)] #[derive(Debug)]
@@ -509,14 +524,18 @@ fn init_test_logger() {
}); });
} }
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow. /// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
/// Panics if no adapter is found, since tests render on the GPU like the app does. /// Panics if no adapter is found, since tests render on the GPU like the app does.
fn gpu_application_io() -> PlatformApplicationIo { pub fn gpu_executor() -> <PlatformApplicationIo as ApplicationIo>::Executor {
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned()); static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
let executor = GPU_EXECUTOR.clone().expect( GPU_EXECUTOR.clone().expect(
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).", "Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
); )
PlatformApplicationIo::new_with_executor(executor) }
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
fn gpu_application_io() -> PlatformApplicationIo {
PlatformApplicationIo::new_with_executor(gpu_executor())
} }
/// Runs `operation`, returning its result along with the errors it logged. /// Runs `operation`, returning its result along with the errors it logged.
@@ -539,7 +558,6 @@ impl Spawn for BlockingSpawner {
#[cfg(test)] #[cfg(test)]
pub mod test_prelude { pub mod test_prelude {
pub use super::FrontendMessageTestUtils;
pub use crate::application::Editor; pub use crate::application::Editor;
pub use crate::float_eq; pub use crate::float_eq;
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys}; pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
+2 -16
View File
@@ -680,7 +680,7 @@
{:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)} {:else if ["Fallback", "Error", "Panic"].includes($document.renderStatus)}
<div class="render-status-outline failed"></div> <div class="render-status-outline failed"></div>
{/if} {/if}
{#if $document.renderStatus === "Error"} {#if $document.renderStatus === "Error" && !$document.graphViewOverlayOpen}
<LayoutCol class="render-status-overlay"> <LayoutCol class="render-status-overlay">
<TextLabel> <TextLabel>
<p> <p>
@@ -703,7 +703,7 @@
{/if} {/if}
</div> </div>
<div class="graph-view" class:open={$document.graphViewOverlayOpen} style:--fade-artwork={`${$document.fadeArtwork}%`} data-graph> <div class="graph-view" class:open={$document.graphViewOverlayOpen}>
<Graph /> <Graph />
</div> </div>
</LayoutCol> </LayoutCol>
@@ -1005,7 +1005,6 @@
.graph-view { .graph-view {
pointer-events: none; pointer-events: none;
transition: opacity 0.2s;
opacity: 0; opacity: 0;
&.open { &.open {
@@ -1013,21 +1012,8 @@
pointer-events: auto; pointer-events: auto;
opacity: 1; opacity: 1;
} }
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--color-2-mildblack);
opacity: var(--fade-artwork);
pointer-events: none;
}
} }
.fade-artwork,
.graph { .graph {
position: absolute; position: absolute;
top: 0; top: 0;
@@ -2,6 +2,8 @@
import { getContext, onMount, onDestroy } from "svelte"; import { getContext, onMount, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte"; import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte"; import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
import type { DragToggleListener } from "/src/managers/drag-toggle";
import { inspectorLayout } from "/src/stores/portfolio"; import { inspectorLayout } from "/src/stores/portfolio";
import { createAutoScroller } from "/src/utility-functions/auto-scroll"; import { createAutoScroller } from "/src/utility-functions/auto-scroll";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper"; import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
@@ -23,7 +25,15 @@
let lastDragClientY = 0; let lastDragClientY = 0;
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY)); const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
// Everything one middle-button drag across the section headers paints is one history step
const dragToggleListener: DragToggleListener = {
groups: ["inspector-section-visibility"],
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
};
onMount(() => { onMount(() => {
createDragToggleManager(dragToggleListener);
addEventListener("pointermove", draggingPointerMove); addEventListener("pointermove", draggingPointerMove);
addEventListener("pointerup", draggingPointerUp); addEventListener("pointerup", draggingPointerUp);
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it // A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
@@ -36,6 +46,8 @@
}); });
onDestroy(() => { onDestroy(() => {
destroyDragToggleManager(dragToggleListener);
removeEventListener("pointermove", draggingPointerMove); removeEventListener("pointermove", draggingPointerMove);
removeEventListener("pointerup", draggingPointerUp); removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointercancel", abortDrag); removeEventListener("pointercancel", abortDrag);
+24 -1
View File
@@ -331,6 +331,7 @@
} }
const dragToggleListener: DragToggleListener = { const dragToggleListener: DragToggleListener = {
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
activeGroupChanged: (group) => { activeGroupChanged: (group) => {
activeDragToggleGroup = group; activeDragToggleGroup = group;
}, },
@@ -342,6 +343,15 @@
editor.toggleNodeVisibilityLayerPanel(id); editor.toggleNodeVisibilityLayerPanel(id);
} }
// Middle-clicking one of the chain's node buttons toggles that node's visibility
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
if (e.button !== 1) return;
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
}
function toggleLayerLock(id: bigint) { function toggleLayerLock(id: bigint) {
editor.toggleLayerLock(id); editor.toggleLayerLock(id);
} }
@@ -1194,6 +1204,7 @@
on:pointerdown={(e) => layerPointerDown(e, listing)} on:pointerdown={(e) => layerPointerDown(e, listing)}
on:click={(e) => selectLayerWithModifiers(e, listing)} on:click={(e) => selectLayerWithModifiers(e, listing)}
on:dblclick={(e) => chainIconsDoubleClick(e, listing)} on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
on:pointerenter={() => hoverRow(index)} on:pointerenter={() => hoverRow(index)}
on:pointerleave={() => (hoveredRowIndex = undefined)} on:pointerleave={() => (hoveredRowIndex = undefined)}
> >
@@ -1236,7 +1247,7 @@
{/if} {/if}
<div class="thumbnail"> <div class="thumbnail">
{#if $nodeGraph.thumbnailCanvases.has(listing.id)} {#if $nodeGraph.thumbnailCanvases.has(listing.id)}
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)?.layersPanelCanvasId} /> <ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)} />
{:else if $thumbnailImages.has(listing.id)} {:else if $thumbnailImages.has(listing.id)}
<ThumbnailImage image={$thumbnailImages.get(listing.id)} /> <ThumbnailImage image={$thumbnailImages.get(listing.id)} />
{/if} {/if}
@@ -1343,6 +1354,8 @@
data-chain-node={slot.nodeIndex} data-chain-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition} data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1} data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
/> />
{/if} {/if}
{/if} {/if}
@@ -1359,12 +1372,17 @@
: entry.chainExpanded : entry.chainExpanded
? "Stop listing this layer's chain one node per row." ? "Stop listing this layer's chain one node per row."
: "List this layer's chain one node per row, beneath the layer."} : "List this layer's chain one node per row, beneath the layer."}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
on:click={(e) => { on:click={(e) => {
// Without a chain to expand, a click selects the layer as it does elsewhere in the row // Without a chain to expand, a click selects the layer as it does elsewhere in the row
if (entry.chainNodes.length === 0) return; if (entry.chainNodes.length === 0) return;
e.stopPropagation(); e.stopPropagation();
editor.toggleLayerChainExpanded(listing.id); editor.toggleLayerChainExpanded(listing.id);
}} }}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
}}
> >
<IconLabel <IconLabel
icon={entry.iconName} icon={entry.iconName}
@@ -1395,10 +1413,15 @@
data-chain-row-node={slot.nodeIndex} data-chain-row-node={slot.nodeIndex}
data-chain-gap-before={slot.reorderablePosition} data-chain-gap-before={slot.reorderablePosition}
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1} data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
data-middle-drag-toggle-group="layer-chain-visibility"
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
on:pointerdown={(e) => { on:pointerdown={(e) => {
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode); if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
}} }}
on:click={(e) => chainNodeClick(e, listing, chainNode.id)} on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
on:auxclick={(e) => {
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
}}
on:dblclick={(e) => { on:dblclick={(e) => {
// Only the node's icon opens it in the graph // Only the node's icon opens it in the graph
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id); if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
File diff suppressed because it is too large. Load diff
@@ -1,28 +0,0 @@
<script lang="ts">
import type { Readable } from "svelte/store";
import type { WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
export let wire: Readable<WirePath>;
export let thick: boolean;
export let undimmed: boolean;
$: dataColor = `var(--color-data-${$wire.dataType.toLowerCase()})`;
$: dataColorDim = `var(--color-data-${$wire.dataType.toLowerCase()}-dim)`;
$: dasharray = `3,${$wire.dashed ? 2 : 0}`;
</script>
{#if $wire.thick === thick}
<g class:dashed={$wire.dashed} class:undimmed>
{#if thick}
<path d={$wire.pathString} style:--data-line-width="8px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
<!-- A thin inner line splits the layer-stack wire down the middle reaching past the ends into the cleaved connector slots -->
<path d={$wire.centerPathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={dasharray} />
{:else if $wire.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={$wire.pathString} style:--data-line-width="4px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
<path d={$wire.pathString} style:--data-line-width="2px" style:--data-color="#444444" style:--data-color-dim="#444444" style:--data-dasharray={dasharray} />
{:else}
<path d={$wire.pathString} style:--data-line-width="2px" style:--data-color={dataColor} style:--data-color-dim={dataColorDim} style:--data-dasharray={dasharray} />
{/if}
</g>
{/if}
@@ -41,6 +41,12 @@
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey; const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel); editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
} }
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
if (e.button !== 1 || widgetData.disabled) return;
editor.toggleNodeVisibilityInspector(widgetData.id);
}
</script> </script>
<!-- TODO: Implement collapsable sections with the Inspector system --> <!-- TODO: Implement collapsable sections with the Inspector system -->
@@ -76,7 +82,16 @@
{/if} {/if}
{/each} {/each}
{:else} {:else}
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}> <button
class="header"
class:expanded
class:expandable
data-inspector-reorder-handle={reorderable ? "" : undefined}
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
onclick={toggleExpandedWithModifiers}
onauxclick={toggleVisibilityWithMiddleClick}
>
<div <div
class="icon-slot" class="icon-slot"
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"} data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
@@ -140,7 +140,9 @@
const reorder = allowReorder && allowSelect; const reorder = allowReorder && allowSelect;
let held = position; let held = position;
if (!reorder && !allowWrap) { if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) {
held = holdWithOverlaps(first, last, position);
} else if (!reorder && !allowWrap) {
const lower = neighborBound(first, -1) ?? 0; const lower = neighborBound(first, -1) ?? 0;
const upper = (neighborBound(last, 1) ?? 1) - spacing; const upper = (neighborBound(last, 1) ?? 1) - spacing;
held = Math.max(lower, Math.min(upper, position)); held = Math.max(lower, Math.min(upper, position));
@@ -156,6 +158,33 @@
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held)); return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
} }
// Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them
function holdWithOverlaps(first: number, last: number, position: number): number {
const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last);
const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never");
const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely";
let lower = 0;
let upper = 1;
for (let k = first; k <= last; k += 1) {
const offset = markers[k].position - markers[first].position;
lower = Math.max(lower, -offset);
upper = Math.min(upper, 1 - offset);
// A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it
const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1];
const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1];
lowerBounds.filter(outsideRun).forEach((i) => {
lower = Math.max(lower, markers[i].position - offset);
});
upperBounds.filter(outsideRun).forEach((i) => {
upper = Math.min(upper, markers[i].position - offset);
});
}
return Math.max(lower, Math.min(upper, position));
}
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead // The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
function neighborBound(index: number, step: -1 | 1): number | undefined { function neighborBound(index: number, step: -1 | 1): number | undefined {
for (let i = index + step; i >= 0 && i < markers.length; i += step) { for (let i = index + step; i >= 0 && i < markers.length; i += step) {
@@ -657,7 +686,10 @@
} }
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation); $: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext); $: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext); // A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter(
({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position,
);
onMount(() => { onMount(() => {
document.addEventListener("keydown", deleteShortcut); document.addEventListener("keydown", deleteShortcut);
+81 -25
View File
@@ -8,21 +8,30 @@
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain // The gesture only engages once the pointer crosses from the source into a different sibling, so plain
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling // clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
// the pointer enters whose state still matches the source's recorded starting state is also clicked. // the pointer enters whose state still matches the source's recorded starting state is also clicked.
//
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
// rather than a click. Their gesture engages on the press, which toggles the source at once.
export type DragToggleListener = { export type DragToggleListener = {
// The groups whose gestures this listener is told about
groups: string[];
// Given the group of the pressed button, and undefined once the press ends // Given the group of the pressed button, and undefined once the press ends
activeGroupChanged?: (activeGroup: string | undefined) => void; activeGroupChanged?: (activeGroup: string | undefined) => void;
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step // Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
engagedChanged?: (engaged: boolean) => void; engagedChanged?: (engaged: boolean) => void;
}; };
const MIDDLE_BUTTON = 1;
const listeners = new Set<DragToggleListener>(); const listeners = new Set<DragToggleListener>();
let activeGroup: string | undefined = undefined; let activeGroup: string | undefined = undefined;
let middleButtonGesture = false;
let source: HTMLElement | undefined = undefined; let source: HTMLElement | undefined = undefined;
let startingState: string | undefined = undefined; let startingState: string | undefined = undefined;
let visited = new WeakSet<Element>(); let visited = new WeakSet<Element>();
let engaged = false; let engaged = false;
let suppressNextClickFromSource: HTMLElement | undefined = undefined; let suppressNextClickFromSource: HTMLElement | undefined = undefined;
let suppressNextAuxClick = false;
export function createDragToggleManager(listener: DragToggleListener) { export function createDragToggleManager(listener: DragToggleListener) {
listeners.add(listener); listeners.add(listener);
@@ -38,12 +47,13 @@ export function createDragToggleManager(listener: DragToggleListener) {
window.addEventListener("blur", onPointerUp); window.addEventListener("blur", onPointerUp);
// Capture phase on click suppresses the natural source-click before the button's handler runs // Capture phase on click suppresses the natural source-click before the button's handler runs
window.addEventListener("click", onClickCapture, true); window.addEventListener("click", onClickCapture, true);
window.addEventListener("auxclick", onAuxClickCapture, true);
} }
} }
export function destroyDragToggleManager(listener: DragToggleListener) { export function destroyDragToggleManager(listener: DragToggleListener) {
// A consumer leaving mid-gesture still hears it end // A consumer leaving mid-gesture still hears it end
if (engaged) listener.engagedChanged?.(false); if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
listeners.delete(listener); listeners.delete(listener);
// Uninstall the window event listeners only once the last consumer leaves // Uninstall the window event listeners only once the last consumer leaves
@@ -54,83 +64,120 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
window.removeEventListener("pointercancel", onPointerUp); window.removeEventListener("pointercancel", onPointerUp);
window.removeEventListener("blur", onPointerUp); window.removeEventListener("blur", onPointerUp);
window.removeEventListener("click", onClickCapture, true); window.removeEventListener("click", onClickCapture, true);
window.removeEventListener("auxclick", onAuxClickCapture, true);
activeGroup = undefined; activeGroup = undefined;
middleButtonGesture = false;
source = undefined; source = undefined;
startingState = undefined; startingState = undefined;
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
suppressNextClickFromSource = undefined; suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
} }
} }
function notifyActiveGroupChange(group: string | undefined) { function listenersOfGroup(group: string): DragToggleListener[] {
activeGroup = group; return Array.from(listeners).filter((listener) => listener.groups.includes(group));
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
} }
function findMember(target: EventTarget | undefined): HTMLElement | undefined { function notifyActiveGroupChange(group: string | undefined) {
const previousGroup = activeGroup;
activeGroup = group;
const notifiedGroup = group || previousGroup;
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
}
function groupAttribute(middleButton: boolean): string {
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
}
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
if (!(target instanceof Element)) return undefined; if (!(target instanceof Element)) return undefined;
const found = target.closest("[data-drag-toggle-group]"); const found = target.closest(`[${groupAttribute(middleButton)}]`);
return found instanceof HTMLElement ? found : undefined; return found instanceof HTMLElement ? found : undefined;
} }
function onPointerDown(e: PointerEvent) { function memberState(member: HTMLElement): string | undefined {
if (e.button !== 0) return; return member.getAttribute("data-drag-toggle-state") || undefined;
suppressNextClickFromSource = undefined; }
const found = findMember(e.target || undefined); function toggle(member: HTMLElement) {
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
else member.click();
}
function engage() {
if (!activeGroup || !source) return;
engaged = true;
visited.add(source);
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
if (memberState(source) === startingState) toggle(source);
}
function onPointerDown(e: PointerEvent) {
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
const middleButton = e.button === MIDDLE_BUTTON;
const found = findMember(e.target || undefined, middleButton);
if (!found) return; if (!found) return;
// Stop the event so sibling drag/select handlers on ancestors don't also engage // Stop the event so sibling drag/select handlers on ancestors don't also engage
e.stopPropagation(); e.stopPropagation();
middleButtonGesture = middleButton;
source = found; source = found;
startingState = found.getAttribute("data-drag-toggle-state") || undefined; startingState = memberState(found);
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined); notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
if (middleButton) engage();
} }
function onPointerMove(e: PointerEvent) { function onPointerMove(e: PointerEvent) {
if (!activeGroup || !source) return; if (!activeGroup || !source) return;
const member = findMember(e.target || undefined); const member = findMember(e.target || undefined, middleButtonGesture);
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return; if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger // Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
if (member === source || visited.has(member)) return; if (member === source || visited.has(member)) return;
// First crossing engages the drag and toggles the source as part of the operation // First crossing engages the drag and toggles the source as part of the operation
if (!engaged) { if (!engaged) engage();
engaged = true;
visited.add(source);
listeners.forEach((listener) => listener.engagedChanged?.(true));
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
}
// Toggle only peers still in the starting state, so we don't flip ones already at the target state // Toggle only peers still in the starting state, so we don't flip ones already at the target state
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return; if (memberState(member) !== startingState) return;
visited.add(member); visited.add(member);
member.click(); toggle(member);
} }
function onPointerUp(e: Event) { function onPointerUp(e: Event) {
if (!activeGroup) return; if (!activeGroup) return;
const endedGroup = activeGroup;
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again // An engaged drag already toggled the source, so its release's click won't toggle it again
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source; if (engaged && source && e.type === "pointerup") {
if (middleButtonGesture) suppressNextAuxClick = true;
else suppressNextClickFromSource = source;
}
const wasEngaged = engaged; const wasEngaged = engaged;
middleButtonGesture = false;
source = undefined; source = undefined;
startingState = undefined; startingState = undefined;
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
notifyActiveGroupChange(undefined); notifyActiveGroupChange(undefined);
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false)); if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
} }
function onClickCapture(e: Event) { function onClickCapture(e: Event) {
@@ -141,6 +188,15 @@ function onClickCapture(e: Event) {
suppressNextClickFromSource = undefined; suppressNextClickFromSource = undefined;
} }
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
function onAuxClickCapture(e: MouseEvent) {
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
suppressNextAuxClick = false;
e.stopPropagation();
e.preventDefault();
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
const carried = Array.from(listeners); const carried = Array.from(listeners);
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff. Show more