Compare commits

..
263 changed files with 9962 additions and 48108 deletions

No files matched your search

+2 -5
View File
@@ -29,8 +29,6 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
const MAX_RUN_PAGES = 10; const MAX_RUN_PAGES = 10;
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name // The workflow step that fails only when a run reached a verdict against its title, by the end of its name
const VERDICT_STEP_NAME = "Fail for the title's verdict"; const VERDICT_STEP_NAME = "Fail for the title's verdict";
// The workflow step that passes a run whose title changed while it ran, without a verdict, by the end of its name
const SUPERSEDED_STEP_NAME = "Pass for a newer run's review";
const MAX_VERDICT_LOOKUPS = 5; const MAX_VERDICT_LOOKUPS = 5;
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens // How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
@@ -177,15 +175,14 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
return newestFirst(runs); return newestFirst(runs);
} }
// The newest finished run that reached a verdict on its title, skipping those that didn't (as when a service was unreachable or the title changed mid-run) // The newest of the finished runs that reached a verdict on its title, skipping failures that didn't (such as when GitHub or the review service couldn't be reached)
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> { async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) { for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
const run = finishedRunsNewestFirst[i]; const run = finishedRunsNewestFirst[i];
if (run.conclusion === "success") return run;
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`); const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
const steps = jobs.flatMap((job) => job.steps || []); const steps = jobs.flatMap((job) => job.steps || []);
if (steps.some((step) => step.name.endsWith(SUPERSEDED_STEP_NAME) && step.conclusion === "success")) continue;
if (run.conclusion === "success") return run;
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run; if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
} }
+3 -4
View File
@@ -37,7 +37,6 @@ const pullRequestNumber = readEvent().pull_request.number;
const decision = readDecision(); const decision = readDecision();
const retried = RETRIED_OUTCOMES.includes(decision.outcome); const retried = RETRIED_OUTCOMES.includes(decision.outcome);
const passed = PASSING_OUTCOMES.includes(decision.outcome); const passed = PASSING_OUTCOMES.includes(decision.outcome);
const superseded = decision.outcome === "superseded";
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be // New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) { if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
@@ -48,10 +47,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
} }
} }
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`); console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
// Later runs tell verdicts, retries, and superseded runs apart by which of the workflow's last steps each one ran // The workflow fails a different step for a verdict against the title than for an outcome to retry, which later runs read back to tell them apart
const result = passed ? "approved" : superseded ? "superseded" : retried ? "retry" : "verdict"; const result = passed ? "approved" : retried ? "retry" : "verdict";
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`); fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
function readDecision(): Decision { function readDecision(): Decision {
+7 -1
View File
@@ -150,14 +150,20 @@ 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 && !github.event.pull_request.head.repo.fork if: inputs.merge_queue == false
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
+2 -9
View File
@@ -7,8 +7,6 @@ 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:
@@ -176,8 +174,6 @@ jobs:
env: env:
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml` # `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis" RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
# GPU tests made through `for_tests()` fail rather than skip when the software Vulkan driver above can't make a device
WGPU_BACKEND: vulkan
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features` # The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
run: >- run: >-
cargo test --workspace --all-features cargo test --workspace --all-features
@@ -249,8 +245,7 @@ jobs:
permissions: permissions:
contents: read contents: read
env: env:
# A manual run has no base commit of its own, so it compares against master BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
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
@@ -264,9 +259,7 @@ jobs:
rustflags: "" rustflags: ""
- name: 📥 Fetch the base commit - name: 📥 Fetch the base commit
run: | run: git fetch --depth=1 origin "$BASE_SHA"
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,8 +51,6 @@ 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
+1 -6
View File
@@ -64,12 +64,7 @@ jobs:
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }} if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
run: exit 1 run: exit 1
# A run whose title changed mid-run passes and leaves the check to the newer run, which skips it by this name (see `SUPERSEDED_STEP_NAME` in `gather.ts`)
- name: ⏭️ Pass for a newer run's review
if: ${{ !cancelled() && steps.report.outputs.result == 'superseded' }}
run: echo "A newer run reviews the changed title"
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly # Later runs review the title again after this failure, as they do when a step above fails unexpectedly
- name: 🔁 Fail without a verdict - name: 🔁 Fail without a verdict
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }} if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
run: exit 1 run: exit 1
Generated
+19 -12
View File
@@ -585,15 +585,12 @@ name = "blending-nodes"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"futures",
"glam", "glam",
"graphic-types", "graphic-types",
"node-macro", "node-macro",
"raster-kernels", "raster-kernels",
"serde", "serde",
"text-nodes",
"vector-types", "vector-types",
"wgpu-executor",
] ]
[[package]] [[package]]
@@ -2537,6 +2534,18 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "graph-text"
version = "0.0.0"
dependencies = [
"convert_case 0.12.0",
"core-types",
"glam",
"log",
"proc-macro2",
"syn 3.0.9",
]
[[package]] [[package]]
name = "graphene-animation" name = "graphene-animation"
version = "0.0.0" version = "0.0.0"
@@ -2667,6 +2676,7 @@ dependencies = [
"futures", "futures",
"glam", "glam",
"graph-craft", "graph-craft",
"graph-text",
"graphene-application-io", "graphene-application-io",
"graphene-canvas-utils", "graphene-canvas-utils",
"graphene-core", "graphene-core",
@@ -2677,6 +2687,7 @@ dependencies = [
"math-nodes", "math-nodes",
"node-macro", "node-macro",
"path-bool-nodes", "path-bool-nodes",
"raster-kernels",
"raster-nodes", "raster-nodes",
"rendering", "rendering",
"repeat-nodes", "repeat-nodes",
@@ -5438,11 +5449,9 @@ dependencies = [
"glam", "glam",
"graph-craft", "graph-craft",
"graphene-std", "graphene-std",
"graphic-types",
"interpreted-executor", "interpreted-executor",
"log", "log",
"node-macro", "node-macro",
"wgpu-executor",
] ]
[[package]] [[package]]
@@ -5749,6 +5758,7 @@ dependencies = [
"glam", "glam",
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"log",
"raster-types", "raster-types",
"thiserror 2.0.21", "thiserror 2.0.21",
"vector-types", "vector-types",
@@ -5773,14 +5783,12 @@ dependencies = [
"node-macro", "node-macro",
"raster-kernels", "raster-kernels",
"raster-types", "raster-types",
"rendering",
"serde", "serde",
"thiserror 2.0.21", "thiserror 2.0.21",
"tokio", "tokio",
"tsify", "tsify",
"vector-types", "vector-types",
"wasm-bindgen", "wasm-bindgen",
"wgpu-executor",
] ]
[[package]] [[package]]
@@ -6024,7 +6032,6 @@ dependencies = [
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"kurbo", "kurbo",
"linesweeper",
"log", "log",
"num-traits", "num-traits",
"parley", "parley",
@@ -8079,6 +8086,7 @@ dependencies = [
"log", "log",
"node-macro", "node-macro",
"ollev", "ollev",
"raster-kernels",
"raster-types", "raster-types",
"vector-types", "vector-types",
] ]
@@ -8086,7 +8094,7 @@ dependencies = [
[[package]] [[package]]
name = "vello_common" name = "vello_common"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"fearless_simd", "fearless_simd",
@@ -8101,7 +8109,7 @@ dependencies = [
[[package]] [[package]]
name = "vello_gpu" name = "vello_gpu"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"hashbrown 0.17.1", "hashbrown 0.17.1",
@@ -8115,7 +8123,7 @@ dependencies = [
[[package]] [[package]]
name = "vello_gpu_shaders" name = "vello_gpu_shaders"
version = "0.3.0" version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [ dependencies = [
"naga", "naga",
"wesl", "wesl",
@@ -8586,7 +8594,6 @@ dependencies = [
"raster-kernels", "raster-kernels",
"raster-types", "raster-types",
"rendering", "rendering",
"svg-convert",
"thiserror 2.0.21", "thiserror 2.0.21",
"vello_gpu", "vello_gpu",
"web-sys", "web-sys",
+4 -3
View File
@@ -93,6 +93,7 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" } graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" } graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" } core-types = { path = "node-graph/libraries/core-types" }
graph-text = { path = "node-graph/libraries/graph-text" }
raster-types = { path = "node-graph/libraries/raster-types" } raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" } vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" } graphic-types = { path = "node-graph/libraries/graphic-types" }
@@ -315,6 +316,6 @@ debug = true
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2 fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
# TODO: Remove these once the fork's fixes are upstreamed and released # TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
+3 -5
View File
@@ -406,11 +406,9 @@ 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 };
// A chain the line no longer holds the slot for, as shrinking a node's inputs leaves, is not written back if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) else { slot.input = input.clone();
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, InputSlot, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp}; use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
/// 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,16 +94,14 @@ 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> = wide let plain: Vec<NodeId> = nodes
.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(14) { match random.below(12) {
// 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();
@@ -124,7 +122,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(&wide) else { return Vec::new() }; let Some(host) = random.pick(&nodes) 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 },
@@ -181,25 +179,6 @@ 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
@@ -1,53 +0,0 @@
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);
}
}
@@ -1,69 +0,0 @@
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");
}
}
@@ -1,43 +0,0 @@
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());
}
}
@@ -1,48 +0,0 @@
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,21 +1,13 @@
//! 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;
@@ -1,48 +0,0 @@
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);
}
}
@@ -1,53 +0,0 @@
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);
}
}
@@ -1,53 +0,0 @@
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);
}
}
@@ -1,92 +0,0 @@
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,4 +3,3 @@
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,111 +0,0 @@
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
const GRADIENT_FORM: u32 = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
#[serde(alias = "GradientType")]
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
/// 'Fill' gives the gradient it paints the curvatures of a form, rather than the form: 0 and 0 for linear, and -1 and 0.5 for radial.
/// A wired form becomes linear, and the curvatures stay shown in the graph where the form was.
#[migration("graphene_core::vector::FillNode"@1 => @2)]
pub fn fill_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
let Some(form) = node.inputs().get(GRADIENT_FORM as usize) else {
return Err(MigrationError::invariant("Fill has a gradient form input"));
};
let [start, end] = match literal_of::<Tagged>(&form.input) {
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
_ => [0., 0.],
};
let exposed = match form.input {
NodeInput::Value { exposed, .. } => exposed,
_ => true,
};
let curvature = |curvature: f64| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
inputs.set(GRADIENT_FORM, curvature(start));
inputs.insert(GRADIENT_FORM + 1, curvature(end));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const FORM_SLOT: usize = GRADIENT_FORM as usize;
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
#[derive(Serialize)]
enum LegacyTagged {
GradientType(GradientForm),
}
fn form(form: GradientForm) -> NodeInput {
literal(Tagged::GradientForm(form))
}
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| match slot {
FORM_SLOT if random.below(2) == 0 => form(GradientForm::Radial),
FORM_SLOT => form(GradientForm::Linear),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&FillV1, &contract());
check_undo(&FillV1, &contract());
}
#[test]
fn forms_become_their_curvature_presets() {
let other_inputs: Vec<NodeInput> = (0..7).map(|index| literal(Tagged::Number(index as f64))).collect();
let shown_radial = NodeInput::Value {
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
exposed: true,
};
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
// The curvatures stay shown in the graph where an exposed or wired form was, and the inputs after them keep their values
for (old_form, [start, end], exposed) in [
(form(GradientForm::Linear), [0., 0.], false),
(form(GradientForm::Radial), [-1., 0.5], false),
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
(shown_radial, [-1., 0.5], true),
(NodeInput::Import { index: 0 }, [0., 0.], true),
] {
let mut old_inputs = other_inputs.clone();
old_inputs[FORM_SLOT] = old_form;
let mut fixture = Fixture::new(&FillV1);
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@1), old_inputs);
let migrated = fixture.migrate(&FillV1).unwrap();
let mut expected = other_inputs.clone();
expected.splice(FORM_SLOT..=FORM_SLOT, [curvature(start, exposed), curvature(end, exposed)]);
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@2)));
assert_eq!(fixture.inputs(&migrated, fill), expected);
}
}
}
@@ -1,9 +1,5 @@
//! Migrations of the nodes in `graphene_core`. //! Migrations of the nodes in `graphene_core`.
mod fill_v1;
mod passthrough_from_read_attribute_gradient_form_node;
mod passthrough_from_footprint_value;
mod passthrough_from_upload_texture_node; mod passthrough_from_upload_texture_node;
mod renames; mod renames;
mod stroke_v1;
mod vary_colors_from_assign_colors; mod vary_colors_from_assign_colors;
@@ -1,37 +0,0 @@
use migration_core::{Inputs, migration};
/// 'Footprint Value' is gone with the footprint input of 'Rasterize', whose migration takes over the inputs of one feeding it. One read
/// elsewhere passes on its empty primary input instead, since nothing else takes a footprint.
#[migration("math_nodes::FootprintValueNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
pub fn passthrough_from_footprint_value(inputs: &mut Inputs) {
inputs.truncate(1);
}
#[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(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PassthroughFromFootprintValue, &contract());
check_undo(&PassthroughFromFootprintValue, &contract());
}
#[test]
fn keeps_the_primary_input_and_drops_the_transform_and_resolution() {
let (primary, transform, resolution) = (literal(()), literal(1.), literal(2.));
let mut fixture = Fixture::new(&PassthroughFromFootprintValue);
let footprint_value = fixture.add(decl!("math_nodes::FootprintValueNode"@1), vec![primary.clone(), transform, resolution]);
let migrated = fixture.migrate(&PassthroughFromFootprintValue).unwrap();
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
assert_eq!(fixture.inputs(&migrated, footprint_value), [primary]);
}
}
@@ -1,36 +0,0 @@
use migration_core::{Inputs, migration};
/// 'Read Attribute Gradient Form' is gone since no node writes that attribute anymore, so it passes its content on and drops the attribute name.
#[migration("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
pub fn passthrough_from_read_attribute_gradient_form_node(inputs: &mut Inputs) {
inputs.truncate(1);
}
#[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(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PassthroughFromReadAttributeGradientFormNode, &contract());
check_undo(&PassthroughFromReadAttributeGradientFormNode, &contract());
}
#[test]
fn keeps_the_content_and_drops_the_name() {
let (content, name) = (literal(1.), literal("gradient_form".to_string()));
let mut fixture = Fixture::new(&PassthroughFromReadAttributeGradientFormNode);
let read_attribute = fixture.add(decl!("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1), vec![content.clone(), name]);
let migrated = fixture.migrate(&PassthroughFromReadAttributeGradientFormNode).unwrap();
assert_eq!(fixture.declaration_of(&migrated, read_attribute), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
assert_eq!(fixture.inputs(&migrated, read_attribute), [content]);
}
}
@@ -1,48 +0,0 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
PaintMapping(PaintMapping),
}
#[derive(Serialize, Deserialize)]
enum PaintMapping {
Plane,
}
/// 'Stroke' gained Paint Mapping after its dash offset, set to Plane to keep placing the paint in the canvas as it was.
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
pub fn stroke_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::PaintMapping(PaintMapping::Plane)));
}
#[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(&StrokeV1, &contract());
check_undo(&StrokeV1, &contract());
}
#[test]
fn keeps_the_inputs_and_appends_the_plane_paint_mapping() {
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&StrokeV1);
let stroke = fixture.add(decl!("graphene_core::vector::StrokeNode"@1), inputs.clone());
let migrated = fixture.migrate(&StrokeV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, stroke), Some(decl!("graphene_core::vector::StrokeNode"@2)));
assert_eq!(fixture.inputs(&migrated, stroke), [inputs, vec![literal(Tagged::PaintMapping(PaintMapping::Plane))]].concat());
}
}
@@ -1,4 +1,3 @@
//! Migrations of the nodes in `graphene_std`. //! Migrations of the nodes in `graphene_std`.
mod rasterize_v1;
mod renames; mod renames;
@@ -1,276 +0,0 @@
use migration_core::{Declaration, Graph, InputConnector, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
const FOOTPRINT: u32 = 1;
const RASTERIZE: Declaration = decl!("graphene_std::platform_application_io::RasterizeNode"@1);
/// Matched at any version, since naming one would order this migration after the one turning 'Footprint Value' into it, which must come after.
const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode";
/// The default area, a square 1000 px across centered at (500, 500), and its resolution of one pixel per px.
const DEFAULT_TRANSFORM: [f64; 6] = [1000., 0., 0., 1000., 500., 500.];
const DEFAULT_RESOLUTION: [f64; 2] = [1000., 1000.];
/// A translation by half a unit, which moves a unit square anchored at its corner to one centered on the origin.
const CORNER_TO_CENTER: [f64; 6] = [1., 0., 0., 1., 0.5, 0.5];
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
DVec2([f64; 2]),
DAffine2([f64; 6]),
Footprint(Footprint),
}
/// Frozen mirror of the removed `Footprint` value, leaving out the render quality 'Rasterize' ignored.
#[derive(Serialize, Deserialize)]
struct Footprint {
transform: [f64; 6],
resolution: [u32; 2],
}
/// 'Rasterize' takes its footprint's area as a transform placing a unit square centered on its origin, rather than anchored at its corner,
/// then its resolution. A 'Footprint Value' node feeding it, directly or through reroutes, hands over its own inputs and goes once nothing
/// else reads it. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
pub fn rasterize_v1(node: &Node, graph: &Graph, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> {
let Some(footprint) = node.inputs().get(FOOTPRINT as usize) else {
return Err(MigrationError::invariant("Rasterize has a Footprint input"));
};
let footprint = through_reroutes(*graph, &footprint.input);
let (transform, resolution) = match footprint {
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(footprint) {
Some(Tagged::Footprint(footprint)) => (
value(Tagged::DAffine2(centered(footprint.transform)), *exposed),
value(Tagged::DVec2(footprint.resolution.map(f64::from)), *exposed),
),
_ => defaults(*exposed),
},
NodeInput::Node { id, index: 0 } if graph.declaration(*id) == Some(decl!("math_nodes::FootprintValueNode"@1)) => {
let parameters = graph.node(*id).map(|footprint_value| footprint_value.inputs()).and_then(|slots| Some((slots.get(1)?, slots.get(2)?)));
let Some((transform, resolution)) = parameters else {
return Err(MigrationError::invariant("Footprint Value has Transform and Resolution inputs"));
};
// Each Rasterize node it feeds takes over its inputs, so it's only needed by whatever else reads it
let readers = graph.consumers(OutputConnector { node: *id, output: 0 });
let only_feeds_rasterize = readers
.iter()
.all(|reader| matches!(reader, InputConnector::Node { node, input: FOOTPRINT } if graph.declaration(*node) == Some(RASTERIZE)));
if only_feeds_rasterize {
upstream.remove_node(*id);
}
let multiply = decl!("math_nodes::MultiplyNode"@1);
(centered_transform_input(&transform.input, multiply, upstream), resolution.input.clone())
}
_ => defaults(true),
};
inputs.set(FOOTPRINT, transform);
inputs.insert(FOOTPRINT + 1, resolution);
Ok(())
}
/// Where `input` reads from past any 'Passthrough' nodes rerouting it, which pass their content along unchanged.
fn through_reroutes<'a>(graph: Graph<'a>, mut input: &'a NodeInput) -> &'a NodeInput {
let mut visited = HashSet::new();
// A cycle of reroutes leads nowhere else, so revisiting one ends the walk
while let NodeInput::Node { id, index: 0 } = input
&& visited.insert(*id)
&& graph.declaration(*id).is_some_and(|declaration| declaration.identifier == PASSTHROUGH)
&& let Some(content) = graph.node(*id).and_then(|node| node.inputs().first())
{
input = &content.input;
}
input
}
/// The area transform from a 'Footprint Value' node's transform input, through a `multiply` node centering its unit square if it's wired.
fn centered_transform_input(transform: &NodeInput, multiply: Declaration, upstream: &mut Upstream) -> NodeInput {
match transform {
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(transform) {
Some(Tagged::DAffine2(transform)) => value(Tagged::DAffine2(centered(transform)), *exposed),
_ => value(Tagged::DAffine2(DEFAULT_TRANSFORM), *exposed),
},
wire => {
let multiply = upstream.add_node(NewNode {
declaration: multiply,
inputs: vec![wire.clone(), literal(Tagged::DAffine2(CORNER_TO_CENTER))],
});
NodeInput::Node { id: multiply, index: 0 }
}
}
}
/// The transform placing a unit square centered on its origin over the one `transform` places anchored at its corner, which is `transform`
/// followed by a translation of half a unit, computed in the order a `DAffine2` product computes it.
fn centered([x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]: [f64; 6]) -> [f64; 6] {
[
x_axis_x,
x_axis_y,
y_axis_x,
y_axis_y,
x_axis_x * 0.5 + y_axis_x * 0.5 + translation_x,
x_axis_y * 0.5 + y_axis_y * 0.5 + translation_y,
]
}
fn defaults(exposed: bool) -> (NodeInput, NodeInput) {
(value(Tagged::DAffine2(DEFAULT_TRANSFORM), exposed), value(Tagged::DVec2(DEFAULT_RESOLUTION), exposed))
}
fn value(value: Tagged, exposed: bool) -> NodeInput {
NodeInput::Value { value: encode(&value), exposed }
}
#[cfg(test)]
mod tests {
use super::*;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const FOOTPRINT_VALUE: Declaration = decl!("math_nodes::FootprintValueNode"@1);
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::Footprint(Footprint {
transform: [random.below(10) as f64, 0., 0., random.below(10) as f64, random.below(10) as f64, random.below(10) as f64],
resolution: [random.below(10) as u32, random.below(10) as u32],
})),
_ => literal(random.below(10) as f64),
})
}
/// Rasterize's inputs with `footprint` between its artwork and its executor.
fn rasterize_inputs(footprint: NodeInput) -> Vec<NodeInput> {
vec![literal(0.), footprint, NodeInput::Scope("wgpu-executor".into())]
}
/// Rasterize's migrated inputs with `transform` and `resolution` between its artwork and its executor.
fn migrated_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
vec![literal(0.), transform, resolution, NodeInput::Scope("wgpu-executor".into())]
}
fn footprint_value_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
vec![literal(()), transform, resolution]
}
#[test]
fn rewrites_history() {
check_commutation(&RasterizeV1, &contract());
check_undo(&RasterizeV1, &contract());
}
#[test]
fn a_footprint_becomes_the_transform_centered_on_its_area_and_its_resolution() {
// The 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
let footprint = Footprint {
transform: [500., 0., 0., 250., -20., 40.],
resolution: [64, 32],
};
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let expected = migrated_inputs(literal(Tagged::DAffine2([500., 0., 0., 250., 230., 165.])), literal(Tagged::DVec2([64., 32.])));
assert_eq!(fixture.declaration_of(&migrated, rasterize), Some(decl!("graphene_std::platform_application_io::RasterizeNode"@2)));
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
}
#[test]
fn the_default_footprint_becomes_the_default_area_and_resolution() {
let footprint = Footprint {
transform: [1000., 0., 0., 1000., 0., 0.],
resolution: [1000, 1000],
};
let mut fixture = Fixture::new(&RasterizeV1);
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let (transform, resolution) = defaults(false);
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
}
#[test]
fn a_footprint_value_node_hands_over_its_inputs_and_goes() {
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
let mut fixture = Fixture::new(&RasterizeV1);
let resolution_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let resolution = NodeInput::Node { id: resolution_source, index: 0 };
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
let first = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
let second = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
assert_eq!(fixture.inputs(&migrated, first), expected);
assert_eq!(fixture.inputs(&migrated, second), expected);
assert_eq!(fixture.declaration_of(&migrated, footprint_value), None, "nothing else reads the Footprint Value node");
}
#[test]
fn a_footprint_value_node_hands_over_its_inputs_through_reroutes() {
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
let resolution = literal(Tagged::DVec2([30., 20.]));
let mut fixture = Fixture::new(&RasterizeV1);
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
let first_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@1), vec![NodeInput::Node { id: footprint_value, index: 0 }]);
let second_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@2), vec![NodeInput::Node { id: first_reroute, index: 0 }]);
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: second_reroute, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
assert_eq!(
fixture.declaration_of(&migrated, footprint_value),
Some(FOOTPRINT_VALUE),
"the reroute still reads the Footprint Value node"
);
}
#[test]
fn a_wired_footprint_value_transform_reaches_the_area_through_a_multiply_node() {
let mut fixture = Fixture::new(&RasterizeV1);
let transform_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let wire = NodeInput::Node { id: transform_source, index: 0 };
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(wire.clone(), literal(Tagged::DVec2([30., 20.]))));
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let inputs = fixture.inputs(&migrated, rasterize);
let NodeInput::Node { id: multiply, index: 0 } = inputs[1] else {
panic!("the area should be wired from a Multiply node");
};
assert_eq!(inputs, migrated_inputs(NodeInput::Node { id: multiply, index: 0 }, literal(Tagged::DVec2([30., 20.]))));
assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::MultiplyNode"@1)));
assert_eq!(fixture.inputs(&migrated, multiply), [wire, literal(Tagged::DAffine2(CORNER_TO_CENTER))]);
}
#[test]
fn a_footprint_value_node_read_elsewhere_stays() {
let mut fixture = Fixture::new(&RasterizeV1);
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(literal(Tagged::DAffine2(CORNER_TO_CENTER)), literal(Tagged::DVec2([1., 1.]))));
fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
fixture.export(NodeInput::Node { id: footprint_value, index: 0 });
let migrated = fixture.migrate(&RasterizeV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(FOOTPRINT_VALUE));
}
#[test]
fn any_other_wire_leaves_the_defaults_shown_in_the_graph() {
let mut fixture = Fixture::new(&RasterizeV1);
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: source, index: 0 }));
let migrated = fixture.migrate(&RasterizeV1).unwrap();
let (transform, resolution) = defaults(true);
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
}
}
@@ -1,127 +0,0 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
#[serde(alias = "GradientType")]
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
const FORM: u32 = 1;
/// 'Gradient Form' became 'Gradient Curvature', with start and end curvatures taking the presets of the form it set: 0 and 0 for linear, -1 and 0.5 for
/// radial. A wired form becomes linear, the curvatures stay shown in the graph where the form was, and a name it stored as its default is cleared.
#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)]
pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> {
let [_, form] = node.inputs() else {
return Err(MigrationError::invariant("Gradient Form has two inputs"));
};
let [start, end] = match literal_of::<Tagged>(&form.input) {
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
_ => [0., 0.],
};
let exposed = match form.input {
NodeInput::Value { exposed, .. } => exposed,
_ => true,
};
let curvature = |curvature: f64| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
inputs.set(FORM, curvature(start));
inputs.push(curvature(end));
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Gradient Form") {
attributes.remove(node.id(), DISPLAY_NAME);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::TimeStamp;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn form(form: GradientForm) -> NodeInput {
literal(Tagged::GradientForm(form))
}
fn contract() -> SourceContract {
SourceContract {
display_names: &["Gradient Form"],
..SourceContract::new(2, |random, slot| match slot {
1 if random.below(2) == 0 => form(GradientForm::Radial),
1 => form(GradientForm::Linear),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
}
#[test]
fn rewrites_history() {
check_commutation(&GradientCurvatureFromGradientForm, &contract());
check_undo(&GradientCurvatureFromGradientForm, &contract());
}
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
#[derive(Serialize)]
enum LegacyTagged {
GradientType(GradientForm),
}
#[test]
fn forms_become_their_curvature_presets() {
let gradient = literal(Tagged::Number(0.));
let shown_radial = NodeInput::Value {
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
exposed: true,
};
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
// Curvatures stay shown in the graph where an exposed or wired form was
for (old_form, [start, end], exposed) in [
(form(GradientForm::Linear), [0., 0.], false),
(form(GradientForm::Radial), [-1., 0.5], false),
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
(shown_radial, [-1., 0.5], true),
(NodeInput::Import { index: 0 }, [0., 0.], true),
] {
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]);
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2)));
assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), curvature(start, exposed), curvature(end, exposed)]);
}
}
#[test]
fn only_the_old_default_name_is_cleared() {
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
}
}
}
@@ -1,5 +1,4 @@
//! Migrations of the nodes in `math_nodes`. //! Migrations of the nodes in `math_nodes`.
mod gradient_curvature_from_gradient_form;
mod math_formula_from_math_f; mod math_formula_from_math_f;
mod renames; mod renames;
@@ -1,43 +0,0 @@
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,11 +1,8 @@
//! 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 passthrough_from_extend_image_to_bounds;
mod pattern_square; mod pattern_square;
mod renames; mod renames;
@@ -1,185 +0,0 @@
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)]);
}
}
}
@@ -1,36 +0,0 @@
use migration_core::{Inputs, migration};
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
pub fn passthrough_from_extend_image_to_bounds(inputs: &mut Inputs) {
inputs.truncate(1);
}
#[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(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PassthroughFromExtendImageToBounds, &contract());
check_undo(&PassthroughFromExtendImageToBounds, &contract());
}
#[test]
fn keeps_the_image_and_drops_the_bounds() {
let (image, bounds) = (literal(1.), literal(2.));
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
assert_eq!(fixture.inputs(&migrated, extend), [image]);
}
}
@@ -4,12 +4,3 @@ use migration_core::rename;
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout // Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2); rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
@@ -13,7 +13,7 @@ pub enum ClipboardMessage {
CopyLayers, CopyLayers,
CutLayers, CutLayers,
WriteItems { items: Vec<ApplicationDataItem> }, WriteItems { items: Vec<ApplicationDataItem> },
Rendered { id: u64, svg: Result<Option<String>, String> }, Rendered { id: u64, svg: Option<String> },
Loaded { id: u64, content: DataTransfer }, Loaded { id: u64, content: DataTransfer },
PasteItems { items: Vec<ApplicationDataItem> }, PasteItems { items: Vec<ApplicationDataItem> },
PasteLayers { entries: Vec<ApplicationDataLayer> }, PasteLayers { entries: Vec<ApplicationDataLayer> },
@@ -246,15 +246,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else { let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
return; return;
}; };
// The layers still copy, without an SVG
let svg = svg.unwrap_or_else(|error| {
responses.add(DialogMessage::DisplayDialogError {
title: "Unable to copy as SVG".to_string(),
description: error,
});
None
});
self.finish_copy(items, loads, svg, resource_storage, responses); self.finish_copy(items, loads, svg, resource_storage, responses);
} }
ClipboardMessage::Loaded { id, content } => { ClipboardMessage::Loaded { id, content } => {
@@ -674,212 +665,6 @@ 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}");
} }
/// The bounds of what the SVG draws, strokes included, and the size of its frame.
fn drawn_bounds_and_frame(svg: &str) -> (usvg::Rect, usvg::Size) {
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).unwrap_or_else(|error| panic!("the SVG should parse ({error}): {svg}"));
(tree.root().abs_stroke_bounding_box(), tree.size())
}
// A layer is copied as what it adds to the group holding it, so the group's move is left out of both its frame and what it draws
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_frames_a_grouped_layer_without_its_groups_transform() {
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use glam::DAffine2;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 50.).await;
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group = rectangle.parent(editor.active_document().metadata()).expect("the rectangle should be grouped");
editor
.handle_message(GraphOperationMessage::TransformChange {
layer: group,
transform: DAffine2::from_translation(DVec2::new(500., 300.)),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the grouped rectangle should render an SVG");
// The frame grows past the stroke by as far as its miter joins could reach
let (drawn, frame) = drawn_bounds_and_frame(svg);
let within_frame = drawn.left() >= 0. && drawn.top() >= 0. && drawn.right() <= frame.width() && drawn.bottom() <= frame.height();
assert!(within_frame, "the rectangle should be drawn within the frame, at {drawn:?} in {frame:?}: {svg}");
assert!(frame.width() < 120. && frame.height() < 70., "the frame should hold only the rectangle: {svg}");
}
// Any node can be shown as a layer, which adds everything it outputs
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_draws_a_layer_that_is_not_a_merge() {
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 50.).await;
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle").to_node();
let network_interface = &mut editor.active_document_mut().network_interface;
let content_node = network_interface
.upstream_flow_back_from_nodes(vec![rectangle], &[], FlowType::HorizontalFlow)
.nth(1)
.expect("the layer should have a content chain");
network_interface.set_to_node_or_layer(&content_node, &[], true);
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![content_node] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the layer should render an SVG");
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
}
// An artboard holds its own content, so the other layers copied with it are left out of the SVG
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_of_artboards_and_other_layers_draws_only_the_artboards() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 100., ModifierKeys::empty()).await;
editor.draw_rect(500., 500., 600., 600.).await;
let layers = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the artboard should render an SVG");
let (_, frame) = drawn_bounds_and_frame(svg);
assert!(
(frame.width() - 200.).abs() < 1. && (frame.height() - 100.).abs() < 1.,
"the SVG should be framed to the artboard alone: {svg}"
);
}
// The frame keeps the content's exact size, rather than whole pixels that would round a fifth of a unit away to nothing
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_keeps_a_fractional_frame() {
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use glam::DAffine2;
use graphene_std::vector::style::Stroke;
// A square shrunk to a fifth of a unit across, with only a fill
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
editor
.handle_message(GraphOperationMessage::StrokeSet {
layer,
color: None,
stroke: Stroke::default(),
})
.await;
editor
.handle_message(GraphOperationMessage::TransformSet {
layer,
transform: DAffine2::from_scale(DVec2::splat(0.002)),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the square should render an SVG");
let (drawn, frame) = drawn_bounds_and_frame(svg);
assert!(
(frame.width() - 0.2).abs() < 1e-4 && (frame.height() - 0.2).abs() < 1e-4,
"the frame should be the square's size: {svg}"
);
assert!((drawn.width() - 0.2).abs() < 1e-4 && drawn.left().abs() < 1e-4, "the square should fill the frame: {svg}");
}
/// Sets the viewport to `size` pixels and gives back the size of the part of the document it shows.
async fn view_of_size(editor: &mut EditorTestUtils, size: DVec2) -> DVec2 {
use graphene_std::math::quad::Quad;
editor.set_viewport_size(DVec2::ZERO, size).await;
let viewport_to_document = editor.active_document().metadata().document_to_viewport.inverse();
let [min, max] = (viewport_to_document * Quad::from_box([DVec2::ZERO, size])).bounding_box();
max - min
}
// Content drawn for its view, like a brush stroke's image or tiles covering the view, is framed to the view it was copied in
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_frames_content_drawn_for_its_view_to_that_view() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let view = view_of_size(&mut editor, DVec2::new(400., 300.)).await;
let framed_to_view = |svg: &str| {
let (_, frame) = drawn_bounds_and_frame(svg);
(frame.width() as f64 - view.x).abs() < 1e-3 && (frame.height() as f64 - view.y).abs() < 1e-3
};
// A brush stroke
editor.handle_message(PreferencesMessage::BrushTool { enabled: true }).await;
editor.drag_tool(ToolType::Brush, 50., 50., 150., 100., ModifierKeys::empty()).await;
let brush = editor.active_document().metadata().all_layers().next().expect("the brush layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![brush.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the brush layer should render an SVG");
assert!(framed_to_view(svg), "the brush layer should be framed to the {view} view: {svg}");
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "the stroke should be the GPU's image: {svg}");
// A rectangle tiled across the view
editor.draw_rect(0., 0., 20., 20.).await;
let tiled = editor.active_document().metadata().all_layers().next().expect("the rectangle");
let tile = DefinitionIdentifier::ProtoNode(graphene_std::repeat::tile::IDENTIFIER);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type: tile, layer: tiled }).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![tiled.to_node()] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the tiled layer should render an SVG");
assert!(framed_to_view(svg), "the tiled layer should be framed to the {view} view: {svg}");
assert!(svg.matches("<path").count() > 1, "the view should hold several tiles: {svg}");
}
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_draws_generators_as_the_gpus_render() {
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use graph_craft::document::NodeId;
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.create_raster_image(graphene_std::raster::Image::new(1, 1, Color::BLACK), None).await;
let layer = editor.active_document().metadata().all_layers().next().expect("the image layer").to_node();
let mandelbrot = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(mandelbrot),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
xy: None,
add_transaction: true,
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(mandelbrot),
input_connector: InputConnector::node_at_index(layer, 1),
});
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
// The SVG frames the fractal's body, hundreds of units across rather than the image's one, and embeds the GPU's image of it where its placeholder stood
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the Mandelbrot layer should render an SVG");
let (_, frame) = drawn_bounds_and_frame(svg);
assert!(frame.width() > 100., "{svg}");
assert!(svg.matches("data:image/png;base64,").count() == 1 && !svg.contains("deferred-image"), "{svg}");
}
/// - paste /// - paste
/// - assert that ellipse was copied /// - assert that ellipse was copied
#[tokio::test] #[tokio::test]
@@ -6,7 +6,7 @@ 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::utility_types::{
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
}; };
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::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -196,6 +196,10 @@ 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,
}, },
@@ -87,7 +87,9 @@ 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,22 +878,6 @@ 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 {
@@ -906,7 +890,6 @@ 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,
} }
} }
@@ -924,11 +907,6 @@ 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))]
@@ -1,262 +0,0 @@
//! 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)
.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,7 +7,6 @@ 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;
@@ -31,15 +30,13 @@ use graphene_std::vector::misc::{
WeldMethod, WeldMethod,
}; };
use graphene_std::vector::style::{ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, PaintMapping, StrokeAlign, DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
StrokeCap, StrokeJoin,
}; };
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, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, MaskMode,
}; };
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;
@@ -409,6 +406,7 @@ macro_rules! inspectable_types {
List<DVec2>, List<DVec2>,
List<DAffine2>, List<DAffine2>,
List<BlendMode>, List<BlendMode>,
List<GradientForm>,
List<GradientSpread>, List<GradientSpread>,
List<GradientSpace>, List<GradientSpace>,
List<GradientHueDirection>, List<GradientHueDirection>,
@@ -419,7 +417,6 @@ macro_rules! inspectable_types {
List<StrokeJoin>, List<StrokeJoin>,
List<StrokeAlign>, List<StrokeAlign>,
List<StrokeCap>, List<StrokeCap>,
List<PaintMapping>,
List<WeldMethod>, List<WeldMethod>,
List<UnweldMethod>, List<UnweldMethod>,
List<ExtrudeJoiningAlgorithm>, List<ExtrudeJoiningAlgorithm>,
@@ -470,7 +467,6 @@ macro_rules! inspectable_types {
Item<DAffine2>, Item<DAffine2>,
Item<BlendMode>, Item<BlendMode>,
Item<GradientForm>, Item<GradientForm>,
Item<GradientModel>,
Item<GradientSpread>, Item<GradientSpread>,
Item<GradientSpace>, Item<GradientSpace>,
Item<GradientHueDirection>, Item<GradientHueDirection>,
@@ -481,7 +477,6 @@ macro_rules! inspectable_types {
Item<StrokeJoin>, Item<StrokeJoin>,
Item<StrokeAlign>, Item<StrokeAlign>,
Item<StrokeCap>, Item<StrokeCap>,
Item<PaintMapping>,
Item<WeldMethod>, Item<WeldMethod>,
Item<UnweldMethod>, Item<UnweldMethod>,
Item<ExtrudeJoiningAlgorithm>, Item<ExtrudeJoiningAlgorithm>,
@@ -1276,28 +1271,19 @@ 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,
GradientModel,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
GradientInterpolation, GradientInterpolation,
GlowTechnique, GlowTechnique,
NoiseDistribution,
StrokeJoin, StrokeJoin,
StrokeAlign, StrokeAlign,
StrokeCap, StrokeCap,
PaintMapping,
WeldMethod, WeldMethod,
UnweldMethod, UnweldMethod,
ExtrudeJoiningAlgorithm, ExtrudeJoiningAlgorithm,
@@ -1470,31 +1456,22 @@ 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,
BlendMode, BlendMode,
GradientForm, GradientForm,
GradientModel,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
GradientInterpolation, GradientInterpolation,
GlowTechnique, GlowTechnique,
NoiseDistribution,
StrokeJoin, StrokeJoin,
StrokeAlign, StrokeAlign,
StrokeCap, StrokeCap,
PaintMapping,
WeldMethod, WeldMethod,
UnweldMethod, UnweldMethod,
ExtrudeJoiningAlgorithm, ExtrudeJoiningAlgorithm,
@@ -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, DVec2, IVec2, UVec2}; use glam::{DAffine2, 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;
@@ -334,7 +334,6 @@ 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,
@@ -304,15 +304,8 @@ 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.process_message( self.overlays_message_handler
message, .process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
responses,
OverlaysMessageContext {
visibility_settings,
viewport,
graph_open: self.graph_view_overlay_open,
},
);
} }
DocumentMessage::Inspector(message) => { DocumentMessage::Inspector(message) => {
let context = InspectorMessageContext { let context = InspectorMessageContext {
@@ -1952,20 +1945,13 @@ 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, effects_frames } => { DocumentMessage::UpdateEffectsReach { effects_reach } => {
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, _)| is_document_layer(node_id)) .filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_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();
let layer_effects_frames = effects_frames self.network_interface.update_effects_reach(layer_effects_reach);
.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() {
@@ -2694,6 +2680,7 @@ 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();
@@ -4138,7 +4125,7 @@ impl DocumentMessageHandler {
}) })
.unwrap_or((None, None, None)); .unwrap_or((None, None, None));
let blend_mode_menu_entries = BlendMode::list() let blend_mode_menu_entries = BlendMode::list_svg_subset()
.iter() .iter()
.map(|modes| { .map(|modes| {
modes modes
@@ -4155,7 +4142,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()).map(|index| index as u32)) .selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).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))
@@ -26,8 +26,7 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier, layer: LayerNodeIdentifier,
#[serde(skip)] #[serde(skip)]
gradient: Gradient, gradient: Gradient,
/// The form whose curvatures the Fill takes, or `None` to keep its own. gradient_form: GradientForm,
gradient_form: Option<GradientForm>,
gradient_settings: GradientSettings, gradient_settings: GradientSettings,
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes. /// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
transform: Option<DAffine2>, transform: Option<DAffine2>,
@@ -14,7 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graph_craft::list; use graph_craft::list;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path; use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig}; use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, PaintMapping, Stroke, StrokeAlign, StrokeCap, StrokeJoin}; use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color}; use graphene_std::{Artboard, Color};
#[derive(ExtractField)] #[derive(ExtractField)]
@@ -807,6 +807,9 @@ 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);
@@ -991,7 +994,6 @@ fn apply_usvg_stroke(stroke: &usvg::Stroke, modify_inputs: &mut ModifyInputsCont
}, },
join_miter_limit: stroke.miterlimit().get() as f64, join_miter_limit: stroke.miterlimit().get() as f64,
align: StrokeAlign::Center, align: StrokeAlign::Center,
paint_mapping: PaintMapping::Plane,
transform, transform,
}, },
) )
@@ -1035,7 +1037,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma), space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default() ..Default::default()
}; };
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform)); modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
} }
usvg::Paint::RadialGradient(radial) => { usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform()); let gradient_transform = usvg_transform(radial.transform());
@@ -1063,7 +1065,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma), space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default() ..Default::default()
}; };
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform)); modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
} }
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"), usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
}; };
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{ use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain, ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
}; };
use glam::{DAffine2, DVec2, IVec2}; use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId; use graph_craft::application_io::resource::ResourceId;
@@ -450,8 +450,7 @@ impl<'a> ModifyInputsContext<'a> {
} }
} }
/// Paints the layer's Fill with `gradient`, giving its curvatures those of `gradient_form` if that's given, unless the graph feeds them. pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: Option<GradientForm>, settings: GradientSettings, transform: Option<DAffine2>) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false); let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else { let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
return; return;
@@ -491,22 +490,11 @@ impl<'a> ModifyInputsContext<'a> {
} }
} }
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it self.set_input_with_refresh(
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures); InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
if let Some(gradient_form) = gradient_form NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form)) false,
{ );
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let [start_curvature, end_curvature] = gradient_form.curvatures();
self.set_input_with_refresh(
InputConnector::node(fill_node_id, StartCurvatureInput),
NodeInput::value(TaggedValue::Number(start_curvature), false),
true,
);
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
}
self.responses.add(NodeGraphMessage::RunDocumentGraph);
if existing_fill_node_id.is_none() { if existing_fill_node_id.is_none() {
self.restore_default_stroke_order(); self.restore_default_stroke_order();
@@ -773,28 +761,20 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph); self.responses.add(NodeGraphMessage::RunDocumentGraph);
} }
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs /// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched. /// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) { pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
let Some(output_layer) = self.get_output_layer() else { return }; let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface); let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
let create_if_nonexistent = gradient_form != GradientForm::default(); let create_if_nonexistent = gradient_form != GradientForm::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else { let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
return; return;
}; };
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return }; let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
let Some(curvatures) = gradient_curvature_values(node) else { return }; self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
return;
}
let [start, end] = gradient_form.curvatures();
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
} }
/// Set the spread on the chain's gradient value, which is where the ramp carries it. /// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -904,8 +884,6 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true); self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput); let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true); self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintMappingInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::PaintMapping(stroke.paint_mapping), false), true);
} }
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform. /// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -1,6 +1,4 @@
#[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::{
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_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,
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR, 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::{MouseKeys, ViewportPosition}; use crate::messages::input_mapper::utility_types::pointer::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,8 +34,6 @@ 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]
@@ -101,10 +99,6 @@ 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 {
@@ -347,13 +341,6 @@ 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;
@@ -430,10 +417,6 @@ 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 { .. } => {
@@ -5,19 +5,16 @@ 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::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::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::ingest::utility_types::TypeFilter; use crate::messages::portfolio::ingest::utility_types::TypeFilter;
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses}; use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
use crate::node_graph_executor::NodeGraphExecutor; use crate::node_graph_executor::NodeGraphExecutor;
use glam::DVec2; use glam::DVec2;
use graph_craft::ProtoNodeIdentifier; use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graph_craft::document::value::*; use graph_craft::document::value::*;
use graph_craft::document::*; use graph_craft::document::*;
use graph_craft::{concrete, list}; use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
use graphene_std::vector::Vector;
use graphene_std::*; use graphene_std::*;
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?; let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
let widget_override = input_inspector_row.widget_override.clone()?; let widget_override = input_inspector_row.widget_override.clone()?;
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
if matches!(widget_override.as_str(), "number" | "vec2") {
return None;
}
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else { let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override"); log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None; return None;
@@ -54,6 +56,8 @@ impl NodeInspectorContext<'_> {
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2; pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node. /// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3; pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
/// Input position of the clip parameter on the "Artboard" layer template.
pub const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
/// Input position of the control path parameter on the "Blend" network node template. /// Input position of the control path parameter on the "Blend" network node template.
pub const BLEND_PATH_INPUT_INDEX: usize = 4; pub const BLEND_PATH_INPUT_INDEX: usize = 4;
@@ -107,8 +111,7 @@ pub struct DocumentNodeDefinition {
/// Used to create the [`DefinitionIdentifier::Network`] identifier. /// Used to create the [`DefinitionIdentifier::Network`] identifier.
pub identifier: &'static str, pub identifier: &'static str,
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly. /// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
pub version: u32, pub version: u32,
/// The default [`NodeTemplate`] this definition instantiates. /// The default [`NodeTemplate`] this definition instantiates.
@@ -136,529 +139,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry). /// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built. /// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA /// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> { fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![ document_node_derive::derive_definitions()
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
category: "Graphic",
icon: Some("NodeMerge"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
// Primary (bottom) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
..Default::default()
},
// Secondary (left) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
..Default::default()
},
NodeTemplate {
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
input_metadata: vec![
("Base", "The stack of layers below this one, which the content is placed above.").into(),
("Content", "The artwork this layer adds to the stack as a single item.").into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Artboard",
version: 1,
category: "Graphic",
icon: Some("NodeArtboard"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
NodeInput::import(item!(TaggedValue), 2),
NodeInput::import(item!(TaggedValue), 3),
NodeInput::import(item!(TaggedValue), 4),
NodeInput::import(item!(TaggedValue), 5),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
NodeInput::node(NodeId(0), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Artboard), true),
NodeInput::type_default(list!(Graphic), true),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
NodeInput::value(TaggedValue::Bool(true), false),
],
input_metadata: vec![
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
("Content", "Graphics to include within the artboard.").into(),
InputMetadata::with_name_description_override(
"Location",
"Coordinate of the top-left corner of the artboard within the document.",
WidgetOverride::Vec2(Vec2InputSettings {
x: "X".to_string(),
y: "Y".to_string(),
unit: " px".to_string(),
is_integer: true,
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Dimensions",
"Width and height of the artboard within the document.",
WidgetOverride::Vec2(Vec2InputSettings {
x: "W".to_string(),
y: "H".to_string(),
unit: " px".to_string(),
is_integer: true,
..Default::default()
}),
),
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Blend",
version: 1,
category: "Vector: Deform",
icon: Some("NodeBlend"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(16), 0)],
nodes: [
// 0: Separate Paths (split the vector into its individual paths)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
..Default::default()
},
// 1: Count (number of subpaths)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
..Default::default()
},
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: As Number (the integer count enters the network's decimal math)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
// 4: Multiply (total_instances = count × subpath_count)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
..Default::default()
},
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
// 7: Divide (index / count)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
..Default::default()
},
// 8: Floor (floor(index / count) = subpath index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(7), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
..Default::default()
},
// 9: Modulo (index % count = local index within subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
..Default::default()
},
// 10: Path Is Closed (check if current subpath is closed)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
..Default::default()
},
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
..Default::default()
},
// 12: Divide (local_index / denominator = within-subpath fraction)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
..Default::default()
},
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
// 14: Add (subpath_index + clamped fraction = progression)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
..Default::default()
},
// 15: Morph (content, progression, reverse, distribution, path)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
inputs: vec![
NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default()
},
// 16: Repeat
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
..Default::default()
},
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
],
input_metadata: vec![
("Content", "The vector objects to create intermediate shapes between.").into(),
(
"Count",
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
)
.into(),
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
(
"Path",
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
)
.into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Origins to Polyline",
version: 1,
category: "Vector: Path",
icon: Some("NodeOriginsToPolyline"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(7), 0)],
nodes: [
// 0: Read Vector
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
..Default::default()
},
// 1: Extract Transform
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
..Default::default()
},
// 2: Decompose Translation
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
..Default::default()
},
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(2), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
..Default::default()
},
// 4: Flatten Vector
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
..Default::default()
},
// 5: Map
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
..Default::default()
},
// 6: Combine Paths
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
..Default::default()
},
// 7: Points to Polyline
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Vector), true)],
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
output_names: vec!["Vector".to_string()],
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Load Image",
version: 1,
category: "Data: I/O",
icon: Some("NodeLoadImage"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Regex Find",
version: 1,
category: "String: Regex",
icon: Some("NodeRegexFind"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![
// Primary output: the whole match (String)
NodeInput::node(NodeId(1), 0),
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
NodeInput::node(NodeId(2), 0),
],
nodes: [
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
NodeTemplate {
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
input_metadata: vec![
("String", "The string to search within.").into(),
("Pattern", "The regular expression pattern to search for.").into(),
(
"Match Index",
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
)
.into(),
("Case Insensitive", "Match letters regardless of case.").into(),
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
],
output_names: vec!["Match".to_string(), "Captures".to_string()],
output_descriptions: vec![
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
"The text matched by each capture group in the pattern, in order.".to_string(),
],
..Default::default()
},
description: Cow::Borrowed(
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
),
inspector: None,
},
];
document_node_derive::post_process_nodes(custom)
} }
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>; type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
@@ -676,7 +159,6 @@ 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));
@@ -686,13 +168,10 @@ fn static_node_inspector() -> NodeInspector {
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector)); map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector)); map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector)); map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector)); map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
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
} }
@@ -701,15 +180,6 @@ 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();
@@ -739,91 +209,10 @@ fn static_input_inspector() -> InputInspector {
}), }),
); );
map.insert( map.insert(
"number".to_string(),
Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default();
if let Some(unit) = context
.network_interface
.input_data(&node_id, index, "unit", context.selection_network_path)
.and_then(|value| value.as_str())
{
number_input = number_input.unit(unit);
}
if let Some(min) = context
.network_interface
.input_data(&node_id, index, "min", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.min(min);
}
if let Some(max) = context
.network_interface
.input_data(&node_id, index, "max", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.max(max);
}
if let Some(step) = context
.network_interface
.input_data(&node_id, index, "step", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.step(step);
}
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
mode
}) {
number_input = number_input.mode(mode);
}
if let Some(range_min) = context
.network_interface
.input_data(&node_id, index, "range_min", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.range_min(Some(range_min));
}
if let Some(range_max) = context
.network_interface
.input_data(&node_id, index, "range_max", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.range_max(Some(range_max));
}
if let Some(is_integer) = context
.network_interface
.input_data(&node_id, index, "is_integer", context.selection_network_path)
.and_then(|value| value.as_bool())
{
number_input = number_input.is_integer(is_integer);
}
let blank_assist = context
.network_interface
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
.and_then(|value| value.as_bool())
.unwrap_or_else(|| {
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
true
});
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
number_input,
))])
}),
);
map.insert(
// The custom number input settings are only available on proto nodes
"optional_f64".to_string(), "optional_f64".to_string(),
Box::new(|node_id, index, context| { Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default(); let mut number_input = NumberInput::default();
// The field is cloned so the lock is released before building the row below, which locks the node metadata again if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
if let Some(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().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
{
if let Some(unit) = field.unit { if let Some(unit) = field.unit {
number_input = number_input.unit(unit); number_input = number_input.unit(unit);
} }
@@ -874,10 +263,15 @@ fn static_input_inspector() -> InputInspector {
}), }),
); );
map.insert( map.insert(
// 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 // 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
"wrapping_slider".to_string(), "wrapping_range_slider".to_string(),
Box::new(|node_id, index, context| { Box::new(|node_id, index, context| {
let field = proto_node_field(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 = 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;
@@ -898,51 +292,10 @@ 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_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default }) node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
} }
_ => { _ => {
log::error!("A wrapping slider needs finite soft bounds at both ends"); log::error!("A wrapping range 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)
} }
}; };
@@ -954,57 +307,6 @@ fn static_input_inspector() -> InputInspector {
"type_choice".to_string(), "type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])), Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
); );
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
let x = context
.network_interface
.input_data(&node_id, index, "x", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get x for vec2 input");
""
})
.to_string();
let y = context
.network_interface
.input_data(&node_id, index, "y", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get y for vec2 input");
""
})
.to_string();
let unit = context
.network_interface
.input_data(&node_id, index, "unit", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get unit for vec2 input");
""
})
.to_string();
let min = context
.network_interface
.input_data(&node_id, index, "min", context.selection_network_path)
.and_then(|value| value.as_f64());
let is_integer = context
.network_interface
.input_data(&node_id, index, "is_integer", context.selection_network_path)
.and_then(|value| value.as_bool())
.unwrap_or_default();
Ok(vec![node_inspector::vec2_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
&x,
&y,
&unit,
min,
is_integer,
false,
)])
}),
);
map.insert( map.insert(
"noise_inspector_scale".to_string(), "noise_inspector_scale".to_string(),
Box::new(|node_id, index, context| { Box::new(|node_id, index, context| {
@@ -1107,7 +409,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::slider_widget( let fractal_weighted_strength = node_inspector::range_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.)
@@ -1177,6 +479,7 @@ fn static_input_inspector() -> InputInspector {
"Y", "Y",
"", "",
None, None,
None,
false, false,
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.), mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
)]) )])
@@ -1193,6 +496,7 @@ fn static_input_inspector() -> InputInspector {
"Y", "Y",
"", "",
None, None,
None,
false, false,
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.), mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
)]) )])
@@ -1299,6 +603,7 @@ fn static_input_inspector() -> InputInspector {
"Y", "Y",
" px", " px",
None, None,
None,
false, false,
false, false,
)]) )])
@@ -1314,6 +619,7 @@ fn static_input_inspector() -> InputInspector {
"H", "H",
"x", "x",
None, None,
None,
false, false,
false, false,
)]) )])
@@ -1434,7 +740,7 @@ fn static_input_inspector() -> InputInspector {
"vec2_uv".to_string(), "vec2_uv".to_string(),
Box::new(|node_id, index, context| { Box::new(|node_id, index, context| {
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context); let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)]) Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
}), }),
); );
map map
@@ -1682,20 +988,44 @@ mod test {
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
// A graph text node with an inner node that has no definition is left out of the catalog with only a logged error
#[test]
fn every_registered_graph_has_a_definition() {
let sources = graphene_std::registry::GRAPH_SOURCES.lock().unwrap().len();
let graphs = &*graphene_std::graph_text::GRAPHS;
assert!(!graphs.is_empty(), "the graphs in `graphene_std` should be registered");
assert_eq!(graphs.len(), sources, "every registered graph should resolve");
for graph in graphs {
assert!(resolve_network_node_type(graph.identifier).is_some(), "the '{}' graph should have a definition", graph.identifier);
}
}
#[test]
fn input_index_constants_match_the_graphs() {
use graphene_std::graph_text::import_index;
assert_eq!(import_index("Artboard", "location"), Some(super::ARTBOARD_LOCATION_INPUT_INDEX));
assert_eq!(import_index("Artboard", "dimensions"), Some(super::ARTBOARD_DIMENSIONS_INPUT_INDEX));
assert_eq!(import_index("Artboard", "clip"), Some(super::ARTBOARD_CLIP_INPUT_INDEX));
assert_eq!(import_index("Blend", "path"), Some(super::BLEND_PATH_INPUT_INDEX));
}
#[test] #[test]
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() { fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
use glam::DAffine2; use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graphene_std::platform_application_io::rasterize; use graphene_std::platform_application_io::rasterize;
let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition"); let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition");
let transform = definition.node_template.input(rasterize::TransformInput).and_then(|input| input.as_value()); let footprint = definition.node_template.input(rasterize::FootprintInput).and_then(|input| input.as_value());
let resolution = definition.node_template.input(rasterize::ResolutionInput).and_then(|input| input.as_value());
// The square from (0, 0) to (1000, 1000) let expected = Footprint {
let expected_transform = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.)); transform: DAffine2::from_scale(DVec2::splat(1000.)),
assert_eq!(transform, Some(&TaggedValue::DAffine2(expected_transform))); resolution: UVec2::splat(1000),
assert_eq!(resolution, Some(&TaggedValue::DVec2(DVec2::splat(1000.)))); ..Default::default()
};
assert_eq!(footprint, Some(&TaggedValue::Footprint(expected)));
} }
// The executor input the compiler fills in has no type yet, which mustn't rule out every implementation // The executor input the compiler fills in has no type yet, which mustn't rule out every implementation
@@ -1821,21 +1151,36 @@ mod test_type_constraints {
#[test] #[test]
fn every_definition_default_value_satisfies_its_constraint() { fn every_definition_default_value_satisfies_its_constraint() {
let mut violations = Vec::new(); // Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
for definition in super::DOCUMENT_NODE_TYPES.values() { fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
let name = &definition.node_template.display_name; let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() { for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
if let Some(value) = input.as_value() if let Some(value) = input.as_value()
&& !constraint.accepts_default_value(&value.ty()) && !constraint.accepts_default_value(&value.ty())
{ {
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty())); violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
} }
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
}
}
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
for (node_id, inner) in &network.nodes {
check(inner, &format!("{name}, node {node_id}"), violations);
}
} }
} }
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n")); let mut violations = Vec::new();
for definition in super::DOCUMENT_NODE_TYPES.values() {
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
}
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
} }
#[test] #[test]
@@ -1852,7 +1197,7 @@ mod test_type_constraints {
#[test] #[test]
fn single_protonode() { fn single_protonode() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist"); let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name"); let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]); all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
assert!(!constraint[0].satisfies(&concrete!(String))); assert!(!constraint[0].satisfies(&concrete!(String)));
@@ -1866,7 +1211,7 @@ mod test_type_constraints {
#[test] #[test]
fn single_protonode2() { fn single_protonode2() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist"); let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name"); let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]); all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2))); assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
@@ -1875,8 +1220,8 @@ mod test_type_constraints {
#[test] #[test]
fn network() { fn network() {
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist"); let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist"); let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]); let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]); let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let inner_network = NodeNetworkTemplate { let inner_network = NodeNetworkTemplate {
@@ -1,11 +1,17 @@
use super::DocumentNodeDefinition; use super::DocumentNodeDefinition;
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::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride}; use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
};
use glam::IVec2;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::registry::*; use graphene_std::registry::*;
use graphene_std::*; use graphene_std::*;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> { /// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let mut definitions_map = HashMap::new(); let mut definitions_map = HashMap::new();
// Add the protonodes from the macro. // Add the protonodes from the macro.
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs, inputs,
call_argument: input_type.clone(), call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()), implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
// TODO: Store information for input overrides in the node macro input_metadata: input_metadata(fields),
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
output_names, output_names,
..Default::default() ..Default::default()
}, },
@@ -96,25 +93,241 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
); );
} }
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes add_graph_definitions(graph_text::GRAPHS.clone(), &mut definitions_map);
for mut network_node in custom {
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
}
}
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
}
definitions_map definitions_map
} }
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position. /// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
fields
.iter()
.map(|field| {
let (name, description) = (field.name, field.description);
match field.widget_override {
RegistryWidgetOverride::None => (name, description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
}
})
.collect()
}
/// Why a graph text node has no definition yet, or can't have one.
enum GraphDefinitionError {
/// A node inside it has no definition, which may be another graph not yet added.
MissingNode(String),
/// The graph's wiring is invalid, so it's left out of the catalog.
Invalid(String),
}
/// Adds the nodes defined as subgraphs in graph text, each once the definitions of the nodes inside it exist.
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
let mut identifier_counts = HashMap::new();
for graph in &graphs {
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
}
let mut rejected = HashSet::new();
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
.into_iter()
.filter(|graph| {
let taken = identifier_counts[graph.identifier] > 1;
if taken {
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
rejected.insert(graph.identifier);
}
!taken
})
.map(|graph| (graph, String::new()))
.collect();
loop {
let pending_count = pending_graphs.len();
let mut ready = Vec::new();
pending_graphs.retain_mut(|(graph, missing)| {
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
_ => None,
});
if let Some(inner_graph) = rejected_inner_graph {
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
rejected.insert(graph.identifier);
return false;
}
match graph_definition(graph, definitions_map) {
Ok(definition) => {
ready.push(definition);
false
}
Err(GraphDefinitionError::MissingNode(missing_node)) => {
*missing = missing_node;
true
}
Err(GraphDefinitionError::Invalid(reason)) => {
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
rejected.insert(graph.identifier);
false
}
}
});
for definition in ready {
let definition = prepare_network_definition(definition, definitions_map);
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
}
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
break;
}
}
for (graph, missing_node) in pending_graphs {
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
}
}
/// Fills a network definition's nested proto node metadata and points its network at the definition.
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
}
}
network_node
}
/// Builds the catalog definition of a node defined as a subgraph in graph text.
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
let mut nodes = HashMap::new();
for (index, node) in graph.nodes.iter().enumerate() {
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
let (identifier, name) = match &node.implementation {
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
};
let Some(definition) = definitions_map.get(&identifier) else {
return Err(GraphDefinitionError::MissingNode(name));
};
let mut template = definition.default_node_template();
template.visible = !node.hidden;
template.locked = node.locked;
template.pinned = node.pinned;
if let Some(display_name) = node.display_name {
template.display_name = display_name.to_string();
}
let position = IVec2::from(node.position);
template.node_type_metadata = if node.layer {
NodeTypePersistentMetadata::layer(position)
} else {
NodeTypePersistentMetadata::node(position)
};
for (input_index, source) in &node.inputs {
let Some(input) = template.inputs.get_mut(*input_index) else {
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
};
// An input the compiler fills in can't be set
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
return Err(GraphDefinitionError::Invalid(format!(
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
)));
}
*input = graph_input(source, input).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
}
nodes.insert(NodeId(index as u64), template);
}
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
let exports = graph
.exports
.iter()
.map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false)))
.collect::<Result<_, _>>()
.map_err(GraphDefinitionError::Invalid)?;
Ok(DocumentNodeDefinition {
identifier: graph.identifier,
version: graph.version,
category: graph.category,
icon: graph.icon,
description: Cow::Borrowed(graph.description),
inspector: None,
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
inputs,
input_metadata: input_metadata(&graph.imports),
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
node_type_metadata: if graph.layer {
NodeTypePersistentMetadata::layer(IVec2::ZERO)
} else {
NodeTypePersistentMetadata::node(IVec2::ZERO)
},
..Default::default()
},
})
}
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
/// A value must have the type of that default, if it has one.
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
Ok(match source {
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
GraphInputSource::Value { value, exposed } => {
let value = graph_value(value);
if let NodeInput::Value { tagged_value, .. } = default
&& **tagged_value != TaggedValue::None
&& element_type(&tagged_value.ty()) != element_type(&value.ty())
{
return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
}
NodeInput::value(value, exposed.unwrap_or(default.is_exposed()))
}
GraphInputSource::Scope(key) => NodeInput::scope(*key),
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
})
}
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
fn element_type(ty: &Type) -> Type {
let mut element = ty;
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
element = inner;
}
element.clone()
}
fn graph_value(value: &GraphValue) -> TaggedValue {
match value {
GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
GraphValue::Number(number) => TaggedValue::Number(*number),
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
GraphValue::String(string) => TaggedValue::String(string.clone()),
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
GraphValue::Color(color) => TaggedValue::Color(*color),
}
}
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) { fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &mut node_template.implementation { match &mut node_template.implementation {
NodeTemplateImplementation::Network(network_template) => { NodeTemplateImplementation::Network(network_template) => {
@@ -128,13 +341,192 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
return; return;
}; };
// A display name, lock, or pin the network's author gave the node is kept
let definition_template = &definition.node_template; let definition_template = &definition.node_template;
node_template.display_name = definition_template.display_name.clone(); if node_template.display_name.is_empty() {
node_template.display_name = definition_template.display_name.clone();
}
node_template.input_metadata = definition_template.input_metadata.clone(); node_template.input_metadata = definition_template.input_metadata.clone();
node_template.output_names = definition_template.output_names.clone(); node_template.output_names = definition_template.output_names.clone();
node_template.locked = definition_template.locked; node_template.locked |= definition_template.locked;
node_template.pinned = definition_template.pinned; node_template.pinned |= definition_template.pinned;
} }
NodeTemplateImplementation::Definition(_) => {} NodeTemplateImplementation::Definition(_) => {}
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
fn number_import() -> FieldMetadata {
FieldMetadata {
name: "Value",
identifier: "value",
description: "",
internal: false,
exposed: true,
widget_override: RegistryWidgetOverride::None,
value_source: RegistryValueSource::None,
default_colors: None,
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: false,
number_display_decimal_places: None,
number_step: None,
unit: None,
multiline: false,
progression: false,
constant: false,
labels: None,
integer: false,
blank_assist: true,
}
}
/// A graph exporting one node, which is fed by the given inputs.
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
GraphMetadata {
identifier,
path: identifier,
category: "Test",
icon: None,
description: "",
version: 1,
layer: false,
imports: vec![number_import()],
exports: vec![GraphExportMetadata {
name: "Out",
identifier: "out",
description: "",
source: GraphInputSource::Node { node: 0, output: 0 },
}],
nodes: vec![GraphNodeMetadata {
implementation,
inputs,
position: (0, 0),
layer: false,
display_name: None,
hidden: false,
locked: false,
pinned: false,
}],
}
}
fn from_import() -> Vec<(usize, GraphInputSource)> {
let ty = Type::Item(Box::new(concrete!(f64)));
vec![(0, GraphInputSource::Import { index: 0, ty })]
}
/// The definitions a test graph builds on: only the As Number proto node.
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
HashMap::from([(identifier, definition)])
}
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
}
#[test]
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
let inner = one_node_graph("Test Inner", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![outer, inner], &mut definitions_map);
assert!(has_graph(&definitions_map, "Test Inner"));
assert!(has_graph(&definitions_map, "Test Outer"));
}
#[test]
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
let mut inputs = from_import();
inputs.push((
100,
GraphInputSource::Value {
value: GraphValue::Number(1.),
exposed: None,
},
));
let graph = one_node_graph("Test Missing Input", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), inputs);
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map);
assert!(!has_graph(&definitions_map, "Test Missing Input"));
}
#[test]
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
let first = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
assert!(!has_graph(&definitions_map, "Test Twin"));
assert!(!has_graph(&definitions_map, "Test Dependent"));
}
#[test]
fn a_value_must_have_the_type_of_the_input_it_feeds() {
let number_input = NodeInput::value(TaggedValue::Number(0.), false);
let value = |value| GraphInputSource::Value { value, exposed: None };
assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
}
#[test]
fn imports_start_from_their_default_or_type() {
let unit_primary = FieldMetadata {
default_type: Some(concrete!(())),
..number_import()
};
let with_default = FieldMetadata {
value_source: RegistryValueSource::Default("2.5"),
..number_import()
};
let graph = GraphMetadata {
imports: vec![unit_primary, with_default],
..one_node_graph("Test Defaults", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import())
};
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map);
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
assert!(!inputs[0].is_exposed());
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
assert!(inputs[1].is_exposed());
}
#[test]
fn a_graph_nodes_widget_settings_come_from_its_import() {
use crate::messages::prelude::DocumentMessageHandler;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
let location = graphene_std::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
let field = document
.network_interface
.field_metadata(&node_id, location, &[])
.expect("the location input should have its import's settings");
assert_eq!(field.labels, Some(("X", "Y")));
assert!(field.integer);
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
}
}
@@ -170,8 +170,6 @@ 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. /// Sends where everything gliding into place is drawn, along with the wires that follow it.
@@ -209,6 +207,8 @@ pub enum NodeGraphMessage {
SelectedNodesSet { SelectedNodesSet {
nodes: Vec<NodeId>, nodes: Vec<NodeId>,
}, },
SendClickTargets,
EndSendClickTargets,
UnloadWires, UnloadWires,
SendWires, SendWires,
UpdateVisibleNodes, UpdateVisibleNodes,
@@ -439,7 +439,6 @@ impl NodeGraphMessage {
| Self::PointerMove { .. } | Self::PointerMove { .. }
| Self::PointerUp | Self::PointerUp
| Self::PointerOutsideViewport { .. } | Self::PointerOutsideViewport { .. }
| Self::MiddleClick
| Self::WireHoverTick | Self::WireHoverTick
| Self::SendGlide | Self::SendGlide
| Self::GlideTick | Self::GlideTick
@@ -449,6 +448,8 @@ impl NodeGraphMessage {
| Self::SelectedNodesAdd { .. } | Self::SelectedNodesAdd { .. }
| Self::SelectedNodesRemove { .. } | Self::SelectedNodesRemove { .. }
| Self::SelectedNodesSet { .. } | Self::SelectedNodesSet { .. }
| Self::SendClickTargets
| Self::EndSendClickTargets
| Self::UnloadWires | Self::UnloadWires
| Self::SendWires | Self::SendWires
| Self::UpdateVisibleNodes | Self::UpdateVisibleNodes
@@ -24,12 +24,14 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion}; use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo}; use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position; use crate::messages::viewport::Position;
use glam::{DVec2, IVec2}; use glam::{DAffine2, DVec2, IVec2};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath; use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
use graphene_std::*; use graphene_std::*;
use kurbo::{DEFAULT_ACCURACY, Shape}; use kurbo::{DEFAULT_ACCURACY, Shape};
use renderer::Quad;
#[derive(Debug, ExtractField)] #[derive(Debug, ExtractField)]
pub struct NodeGraphMessageContext<'a> { pub struct NodeGraphMessageContext<'a> {
@@ -1752,20 +1754,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.auto_panning.stop(&messages, responses); self.auto_panning.stop(&messages, responses);
} }
} }
// Middle-clicking a node toggles its visibility
NodeGraphMessage::MiddleClick => {
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
return;
}
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
return;
};
responses.add(NodeGraphMessage::ToggleVisibility {
node_id,
network_path: breadcrumb_network_path.to_vec(),
});
}
NodeGraphMessage::WireHoverTick => { NodeGraphMessage::WireHoverTick => {
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses); self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
} }
@@ -2037,6 +2025,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
selected_nodes.set_selected_nodes(nodes); selected_nodes.set_selected_nodes(nodes);
responses.add(EventMessage::SelectionChanged); responses.add(EventMessage::SelectionChanged);
} }
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
}),
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
NodeGraphMessage::UnloadWires => { NodeGraphMessage::UnloadWires => {
self.frontend_wires.clear(); self.frontend_wires.clear();
responses.add(FrontendMessage::ClearAllNodeGraphWires); responses.add(FrontendMessage::ClearAllNodeGraphWires);
@@ -2551,13 +2543,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
HashSet::new() HashSet::new()
}; };
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>(); let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
for node_id in all_nodes { for node_id in all_nodes {
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else { let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
log::error!("Could not get the body of node {node_id}"); log::error!("Could not get transient metadata for node {node_id}");
continue; continue;
}; };
if body.overlaps(selection_min, selection_max) { let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
if alt { if alt {
nodes.remove(&node_id); nodes.remove(&node_id);
} else { } else {
@@ -3219,6 +3211,11 @@ impl NodeGraphMessageHandler {
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList { pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp); let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
// Only development builds draw the click targets, so users don't come across the overlay by accident
if cfg!(debug_assertions) {
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
}
if self.has_selection { if self.has_selection {
common.extend(actions!(NodeGraphMessageDiscriminant; common.extend(actions!(NodeGraphMessageDiscriminant;
Copy, Copy,
@@ -20,7 +20,6 @@ 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::{
@@ -31,18 +30,17 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
use graphene_std::text::{Font, TextAlign}; use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve; use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{ReferencePoint, ScaleType, Transform}; use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::vector::misc::BooleanOperation; use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
}; };
use graphene_std::vector::style::{ use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, PaintMapping, FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
StrokeAlign, StrokeCap, StrokeJoin, 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, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector}; use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, 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;
@@ -240,7 +238,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
} }
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure. /// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)] #[derive(Clone, Copy)]
pub(crate) struct ParameterOptions { pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>, pub soft_min: Option<f64>,
pub soft_max: Option<f64>, pub soft_max: Option<f64>,
@@ -252,10 +250,34 @@ pub(crate) struct ParameterOptions {
pub unit: Option<&'static str>, pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>, pub display_decimal_places: Option<u32>,
pub step: Option<f64>, pub step: Option<f64>,
pub labels: Option<(&'static str, &'static str)>,
pub integer: bool,
pub blank_assist: bool,
} }
impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions { impl Default for ParameterOptions {
fn from(field: &graphene_std::registry::FieldMetadata) -> Self { fn default() -> Self {
Self {
soft_min: None,
soft_max: None,
hard_min: None,
hard_max: None,
slider: false,
multiline: false,
progression: false,
unit: None,
display_decimal_places: None,
step: None,
labels: None,
integer: false,
blank_assist: true,
}
}
}
impl ParameterOptions {
/// The options a proto node's field or a graph's import gives its widget.
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
Self { Self {
soft_min: field.number_soft_min, soft_min: field.number_soft_min,
soft_max: field.number_soft_max, soft_max: field.number_soft_max,
@@ -267,6 +289,9 @@ impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
unit: field.unit, unit: field.unit,
display_decimal_places: field.number_display_decimal_places, display_decimal_places: field.number_display_decimal_places,
step: field.number_step, step: field.number_step,
labels: field.labels,
integer: field.integer,
blank_assist: field.blank_assist,
} }
} }
} }
@@ -322,9 +347,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
unit, unit,
display_decimal_places, display_decimal_places,
step, step,
labels,
integer,
blank_assist,
} = options; } = options;
let mut number_input = NumberInput::default(); let mut number_input = NumberInput::default().is_integer(integer);
if slider { if slider {
number_input = number_input.mode_range(); number_input = number_input.mode_range();
} }
@@ -361,13 +389,13 @@ 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);
slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into() range_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(),
} }
}; };
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context); let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
// A type with no widget can only be supplied through the graph, labeled with a placeholder row // A type with no widget can only be supplied through the graph, labeled with a placeholder row
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| { let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
@@ -411,8 +439,11 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
true => text_area_widget(default_info).into(), true => text_area_widget(default_info).into(),
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) => {
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets), let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
}
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &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()),
@@ -421,6 +452,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// ============ // ============
Some(x) if id_is::<Font>(x) => font_widget(default_info), Some(x) if id_is::<Font>(x) => font_widget(default_info),
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info), Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(), Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(), Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(), Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
@@ -433,7 +465,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// AUTO-GENERATED ENUM TYPES // AUTO-GENERATED ENUM TYPES
// ========================= // =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(), Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
@@ -459,7 +490,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(), Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(), Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(), Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<PaintMapping>(x) => enum_choice::<PaintMapping>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(), Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(), Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(), Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).inspector_row(),
@@ -473,16 +503,9 @@ 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(),
@@ -677,10 +700,144 @@ pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Wi
widgets widgets
} }
/// 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 footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
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 mut location_widgets = start_widgets(&parameter_widgets_info);
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut scale_widgets);
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let mut resolution_widgets = vec![TextLabel::new("").widget_instance()];
add_blank_assist(&mut resolution_widgets);
resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
let Some(document_node) = document_node else { return LayoutGroup::default() };
let Some(input) = document_node.inputs.get(index) else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return Vec::new().into();
};
if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() {
let top_left = footprint.transform.transform_point2(DVec2::ZERO);
let bounds = footprint.scale();
let oversample = footprint.resolution.as_dvec2() / bounds;
location_widgets.extend_from_slice(&[
NumberInput::new(Some(top_left.x))
.label("X")
.unit(" px")
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
let (offset, scale) = {
let diff = DVec2::new(top_left.x - x.value.unwrap_or_default(), 0.);
(top_left - diff, bounds)
};
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
}))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(top_left.y))
.label("Y")
.unit(" px")
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
let (offset, scale) = {
let diff = DVec2::new(0., top_left.y - x.value.unwrap_or_default());
(top_left - diff, bounds)
};
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
}))
.on_commit(commit_value)
.widget_instance(),
]);
scale_widgets.extend_from_slice(&[
NumberInput::new(Some(bounds.x))
.label("W")
.unit(" px")
.on_update(update_value_at_index(
move |x: &NumberInput| {
let (offset, scale) = (top_left, DVec2::new(x.value.unwrap_or_default(), bounds.y));
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
},
node_id,
index,
))
.on_commit(commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(bounds.y))
.label("H")
.unit(" px")
.on_update(update_value_at_index(
move |x: &NumberInput| {
let (offset, scale) = (top_left, DVec2::new(bounds.x, x.value.unwrap_or_default()));
let footprint = Footprint {
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
resolution: (oversample * scale).as_uvec2(),
..footprint
};
TaggedValue::Footprint(footprint)
},
node_id,
index,
))
.on_commit(commit_value)
.widget_instance(),
]);
resolution_widgets.push(
NumberInput::new(Some((footprint.resolution.as_dvec2() / bounds).x * 100.))
.label("Resolution")
.mode_range()
.min(0.)
.range_min(Some(1.))
.range_max(Some(100.))
.unit("%")
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
let resolution = (bounds * x.value.unwrap_or(100.) / 100.).as_uvec2().max((1, 1).into()).min((4000, 4000).into());
let footprint = Footprint { resolution, ..footprint };
TaggedValue::Footprint(footprint)
}))
.on_commit(commit_value)
.widget_instance(),
);
}
let widgets = [LayoutGroup::row(location_widgets), LayoutGroup::row(scale_widgets), LayoutGroup::row(resolution_widgets)];
let (last, rest) = widgets.split_last().expect("Footprint widget should return multiple rows");
*extra_widgets = rest.to_vec();
last.clone()
}
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, 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());
@@ -747,7 +904,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
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(size_unit) .unit("x")
.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;
@@ -761,7 +918,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
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(size_unit) .unit("x")
.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;
@@ -787,7 +944,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
} }
} }
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup { pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info); let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else { let Some(input) = parameter_widgets_info.input() else {
@@ -802,7 +959,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(x) .label(x)
.unit(unit) .unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y)))) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
@@ -813,7 +970,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(y) .label(y)
.unit(unit) .unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap())))) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
@@ -828,7 +985,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(x) .label(x)
.unit(unit) .unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value)))) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
@@ -839,7 +996,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(y) .label(y)
.unit(unit) .unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64))) .min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap())))) .on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
@@ -1105,7 +1262,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) => slider_widget(parameter_widgets_info, number_props, slider), Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
None => number_widget(parameter_widgets_info, number_props), None => number_widget(parameter_widgets_info, number_props),
}; };
@@ -1219,7 +1376,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() let entries = BlendMode::list_svg_subset()
.iter() .iter()
.map(|category| { .map(|category| {
category category
@@ -1236,7 +1393,9 @@ 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).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(), DropdownInput::new(entries)
.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.")
@@ -1797,8 +1956,6 @@ 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.
@@ -1808,7 +1965,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 | Self::LevelPercent => value / 100., Self::Percent => 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 => {
@@ -1822,7 +1979,7 @@ impl MarkerScale {
fn value(self, position: f64) -> f64 { fn value(self, position: f64) -> f64 {
match self { match self {
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.), Self::Percent => (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.),
@@ -1832,7 +1989,6 @@ 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),
} }
@@ -1857,8 +2013,6 @@ 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 {
@@ -1871,7 +2025,6 @@ 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,
} }
} }
@@ -1889,52 +2042,11 @@ 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, except where they may overlap. /// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
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) {
@@ -1962,7 +2074,6 @@ 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];
@@ -1975,21 +2086,13 @@ 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());
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never); if !cyclic {
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 {
@@ -2010,8 +2113,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.iter().zip(&marker_overlaps)) .zip(&marker_between)
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| { .map(|((&position, &(handle_color, paired, dashed)), &between)| {
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();
@@ -2022,7 +2125,6 @@ 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();
@@ -2044,7 +2146,6 @@ 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,
@@ -2059,13 +2160,8 @@ 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, right) = if overlapping { let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
overlap_bounds(&marker_positions, &marker_overlaps, i) let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
} 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 => {
@@ -2394,7 +2490,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 slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> { pub(crate) fn range_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,
@@ -2406,7 +2502,7 @@ pub(crate) fn slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number
} }
/// 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_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> { pub(crate) fn wrapping_range_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,
@@ -2490,105 +2586,6 @@ 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::*;
@@ -2598,8 +2595,8 @@ pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorCon
max: 100., max: 100.,
default: Some(0.), default: Some(0.),
}; };
let vibrance = slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider); let vibrance = range_slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
let saturation = slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider); let saturation = range_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)]
} }
@@ -2841,10 +2838,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
NumberInput::default().label("H").min(0.).unit(" px"), NumberInput::default().label("H").min(0.).unit(" px"),
)); ));
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false); let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
widgets.extend([spacing, angles]); widgets.extend([spacing, angles]);
} else { } else {
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false); let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
widgets.push(spacing); widgets.push(spacing);
} }
} }
@@ -2959,7 +2956,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 = slider_widget( let exposure = range_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 {
@@ -2968,7 +2965,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
default: Some(0.), default: Some(0.),
}, },
); );
let offset = slider_widget( let offset = range_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 {
@@ -3168,80 +3165,6 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)] vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
} }
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::gradient_curvature::*;
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
let curvatures = match get_document_node(node_id, context) {
Ok(document_node) => graph_modification_utils::gradient_curvature_values(document_node),
Err(err) => {
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
return Vec::new();
}
};
// Each form's button sets both curvatures to the form's own, and stands out while they make that form
let mut form = vec![
TextLabel::new("Form")
.tooltip_label("Form")
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
.widget_instance(),
];
add_blank_assist(&mut form);
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
for (label, gradient_form, tooltip) in [
("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."),
(
"Radial",
GradientForm::Radial,
"Sets the start curvature to -1 and the end curvature to 0.5, making circles around the start.",
),
] {
let [start, end] = gradient_form.curvatures();
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures.and_then(GradientForm::from_curvatures) == Some(gradient_form))
.disabled(curvatures.is_none())
.on_update(move |_: &TextButton| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value)
.widget_instance(),
);
}
// The same sliders the parameters would get without this panel
let options = |index: usize| {
let registry = graphene_std::registry::NODE_METADATA.lock().ok();
let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index));
field.map(ParameterOptions::from).unwrap_or_default()
};
let mut row = |index: usize, ty: Type| {
context
.call_widget_override(&node_id, index)
.unwrap_or_else(|| inspector_row_from_type(node_id, index, &ty, options(index), context).unwrap_or_else(|rows| rows))
};
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(row(StartCurvatureInput::INDEX, concrete!(f64)));
layout.extend(row(EndCurvatureInput::INDEX, concrete!(f64)));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> { pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*; use graphene_std::vector::generator_nodes::rectangle::*;
@@ -3381,29 +3304,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
} }
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| { let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else { let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
log::error!("Could not get implementation for node {node_id}"); log::error!("Could not get implementation for node {node_id}");
return Vec::new(); return Vec::new();
}; };
let mut options = ParameterOptions::default();
let input_type = match implementation { let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: { DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below // Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
let proto_node_identifier = proto_node_identifier.clone(); let proto_node_identifier = proto_node_identifier.clone();
let mut default_type = None; if let Some(default) = field.and_then(|field| field.default_type) {
if let Some(field) = graphene_std::registry::NODE_METADATA
.lock()
.unwrap()
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
options = ParameterOptions::from(field);
default_type = field.default_type.clone();
}
if let Some(default) = default_type {
break 'early_return default; break 'early_return default;
} }
@@ -3419,12 +3333,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
let Some(input_type) = input_type else { return Vec::new() }; let Some(input_type) = input_type else { return Vec::new() };
input_type.clone() input_type.clone()
} }
_ => context _ => {
.network_interface // A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path) let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
.compiled_nested_type() Type::Item(element) => *element,
.cloned() declared_type => declared_type,
.unwrap_or(concrete!(())), });
context
.network_interface
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
.compiled_nested_type()
.cloned()
.or(declared_type)
.unwrap_or(concrete!(()))
}
}; };
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value) inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
@@ -3788,25 +3711,9 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
let entries = [GradientForm::Linear, GradientForm::Radial] let entries = [GradientForm::Linear, GradientForm::Radial]
.iter() .iter()
.map(|&gradient_form| { .map(|&gradient_form| {
let [start, end] = gradient_form.curvatures();
RadioEntryData::new(format!("{:?}", gradient_form)) RadioEntryData::new(format!("{:?}", gradient_form))
.label(gradient_form.to_string()) .label(gradient_form.to_string())
.on_update(move |_| Message::Batched { .on_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value) .on_commit(commit_value)
}) })
.collect(); .collect();
@@ -3860,9 +3767,6 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true)); let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
let number_input = disabled_number_input; let number_input = disabled_number_input;
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input); let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
let paint_mapping = enum_choice::<PaintMapping>()
.for_socket(ParameterWidgetsInfo::new(node_id, PaintMappingInput, true, context))
.inspector_row();
vec![ vec![
color, color,
@@ -3873,7 +3777,6 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
LayoutGroup::row(miter_limit), LayoutGroup::row(miter_limit),
LayoutGroup::row(dash_lengths), LayoutGroup::row(dash_lengths),
LayoutGroup::row(dash_offset), LayoutGroup::row(dash_offset),
paint_mapping,
] ]
} }
@@ -3904,61 +3807,6 @@ 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,
@@ -37,7 +37,6 @@ impl FrontendGraphDataType {
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number, "f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed // A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster, "Generator" => Self::Raster,
"Pixels" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster, raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General, _ => Self::General,
} }
@@ -213,6 +212,23 @@ pub struct NodeEvaluationError {
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,7 +5,6 @@ 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)]
@@ -26,7 +25,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
let overlay_context = OverlayContext::new(*viewport, visibility_settings); let overlay_context = OverlayContext::new(*viewport, visibility_settings);
if visibility_settings.all() && !context.graph_open { if visibility_settings.all() {
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() }); responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() }); responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
@@ -1,7 +1,7 @@
//! 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, Part}; use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use glam::DVec2; use glam::DVec2;
use graphene_std::uuid::NodeId; use graphene_std::uuid::NodeId;
@@ -20,32 +20,20 @@ const DEMOS: [&str; 8] = [
const REPETITIONS: u32 = 200; const REPETITIONS: u32 = 200;
#[test] #[test]
fn wire_anchors_lie_on_the_ports_of_every_demo_node() { fn wire_anchors_match_the_ports_of_every_demo_node() {
for demo in DEMOS { for demo in DEMOS {
let document = open_demo(demo); let document = open_demo(demo);
let interface = &document.network_interface; let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() { for node_id in interface.document_network().nodes.keys() {
// A redirect dot's wires attach at its center, between the gutters they're grabbed from let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
let on_port = |wanted: Part, anchor: Option<DVec2>| {
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
match (port, anchor) {
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
(Some(port), Some(anchor)) => port.contains(anchor),
(None, None) => true,
_ => false,
}
};
for index in 0..interface.number_of_inputs(node_id, &[]) { for index in 0..interface.number_of_inputs(node_id, &[]) {
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]); let input = InputConnector::node_at_index(*node_id, index);
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}"); 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, &[]) { for index in 0..interface.number_of_outputs(node_id, &[]) {
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]); let output = OutputConnector::node(*node_id, index);
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}"); assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
} }
} }
} }
@@ -72,7 +60,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.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(()))); std::hint::black_box(interface.node_click_targets(node_id, &[]));
} }
} }
let all_click_targets = start.elapsed() / REPETITIONS; let all_click_targets = start.elapsed() / REPETITIONS;
@@ -35,6 +35,7 @@ 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);
} }
} }
@@ -171,14 +172,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((laid_out, graph)) = interface.layout_graph(&[]) else { let Some((_, indices, 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),
laid_out.indices.get(&other).map(|index| fresh.node(*index).position), 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"
); );
} }
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve"); let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id]; let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape"); assert_eq!(fill_node.inputs.len(), 7, "the legacy Fill should upgrade to the 7-input shape");
let paint = fill_node.input(graphene_std::vector::fill::PaintInput); let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
assert!( assert!(
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })), matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
@@ -1033,13 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve"); let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id]; let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs"); assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
assert_eq!(
curvatures,
[0., 0.].map(|curvature| Some(TaggedValue::Number(curvature))),
"the linear form should become its curvatures"
);
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput); let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
let Some(TaggedValue::GradientRamp(ramp)) = paint else { let Some(TaggedValue::GradientRamp(ramp)) = paint else {
@@ -53,8 +53,6 @@ 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.
@@ -366,7 +364,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, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a /// 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
/// 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| {
@@ -374,8 +372,7 @@ 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 frames = self.layer_effects_frames.get(&layer).copied(); let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
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])
@@ -754,25 +751,6 @@ 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));
@@ -22,7 +22,6 @@ mod layout;
mod layout_pass; mod layout_pass;
mod memo_network; mod memo_network;
mod mutations; mod mutations;
mod node_parts;
mod queries; mod queries;
mod reconcile; mod reconcile;
mod resolved_types; mod resolved_types;
@@ -37,7 +36,6 @@ mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange}; pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use layout_pass::NetworkLayout; pub use layout_pass::NetworkLayout;
pub use node_parts::{Part, PartTarget};
pub use reconcile::{ReconcileError, Reconciled}; pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded; use store::Guarded;
pub use store::NodeLocator; pub use store::NodeLocator;
@@ -54,12 +52,11 @@ use crate::consts::{
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::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput}; use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
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::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::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 deserialization::deserialize_node_persistent_metadata; use deserialization::deserialize_node_persistent_metadata;
use glam::{DAffine2, DVec2, IVec2}; use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type; use graph_craft::Type;
@@ -74,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
use graphene_std::vector::{Vector, VectorModificationType}; use graphene_std::vector::{Vector, VectorModificationType};
use kurbo::BezPath; use kurbo::BezPath;
use memo_network::MemoNetwork; use memo_network::MemoNetwork;
use serde_json::{Value, json}; use serde_json::Value;
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash; use std::hash::Hash;
use std::ops::Deref; use std::ops::Deref;
@@ -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) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()), NodeMetadataChange::NodeType(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),
@@ -88,15 +88,34 @@ impl NodeNetworkInterface {
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets; *network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
} }
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed. pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> { self.load_import_export_ports(network_path);
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
cache.unload();
}
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports)) 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> {
self.network_metadata(network_path)?
.transient_metadata
.import_export_ports
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
}
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
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]) {
@@ -107,13 +126,78 @@ impl NodeNetworkInterface {
transient.import_export_ports.unload(); transient.import_export_ports.unload();
} }
/// The combined bounds of every node in the network, in node graph space.
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> { pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_layout(network_path, NetworkLayout::bounds) 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.
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let network_metadata = self.network_metadata(network_path)?;
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> {
self.with_layout(network_path, NetworkLayout::clearance) let Some(network_metadata) = self.network_metadata(network_path) else {
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>>> {
@@ -280,10 +364,6 @@ impl NodeNetworkInterface {
} }
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> { pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
}
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;
@@ -296,7 +376,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)), |widths| *widths) .with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
} }
/// Unloads layer width if the node is a layer. /// Unloads layer width if the node is a layer.
@@ -395,7 +475,7 @@ impl NodeNetworkInterface {
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path)); 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 thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style); 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, 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 path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg(); let center_path_string = center_line.to_svg();
@@ -443,7 +523,7 @@ impl NodeNetworkInterface {
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path)); 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 thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style); 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, wire_style); let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
Some((vector_wire, center_line, thick)) Some((vector_wire, center_line, thick))
} }
@@ -469,10 +549,17 @@ impl NodeNetworkInterface {
} }
/// 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.
/// The box around the node's body where it sits in its grid cell, in node graph space. pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
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]> {
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?; self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
Some([body.min, body.max]) .flatten()
} }
} }
@@ -2,7 +2,7 @@ use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
}; };
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; use crate::consts::{GRID_SIZE, 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};
@@ -330,6 +330,7 @@ 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)));
@@ -2613,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead // Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await; let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let shaken = editor let shaken = editor
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0) .create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
.await; .await;
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await; let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await; let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
@@ -3399,63 +3400,6 @@ 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();
@@ -4284,73 +4228,3 @@ 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}");
}
}
}
@@ -62,21 +62,11 @@ 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)]
@@ -329,10 +319,6 @@ 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,7 +3,6 @@ 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;
@@ -185,7 +184,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::Position(metadata.node_type_metadata.clone())), metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
EditorDelta::Graph(RuntimeDelta::SetVisibility { EditorDelta::Graph(RuntimeDelta::SetVisibility {
network: None, network: None,
node_id: node, node_id: node,
@@ -284,32 +283,6 @@ 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]
@@ -46,6 +46,193 @@ impl NodeNetworkInterface {
(!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.))) (!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. /// Laid out as the frontend draws them, just past the connector.
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> { pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
@@ -152,9 +339,9 @@ impl NodeNetworkInterface {
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 + import_export_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, and the width of its name. Cached /// The width of a layer in grid units, which covers its thumbnail, its name and its icons. 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, f64) { pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
const GAP_WIDTH: f64 = 8.; const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.; const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.; let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
@@ -169,7 +356,7 @@ impl NodeNetworkInterface {
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 = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width) ((layer_width_pixels / 24.).ceil() as u32).max(8)
} }
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 {
@@ -24,6 +24,81 @@ 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;
} }
@@ -48,24 +123,6 @@ 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> {
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
self.with_layout(network_path, |layout| {
layout.find_part(node_id, |target| {
let part = match target.part {
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? 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 {
@@ -76,13 +133,16 @@ 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 // Each node is pressed where it's drawn, even while gliding into its grid cell
let glide_offsets = self.glide_offsets(network_path); let glide_offsets = self.glide_offsets(network_path);
let reaching = self.nodes_reaching(point, network_path); let clicked_nodes = self
let clicked_nodes = self.with_layout(network_path, |layout| { .nodes_reaching(point, network_path)
reaching .iter()
.into_iter() .filter(|node_id| {
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id)))) self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
.collect::<Vec<_>>() 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) {
@@ -105,18 +165,25 @@ 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 glide_offsets = self.glide_offsets(network_path);
let wanted = match click_target_type { self.nodes_reaching(point, network_path)
LayerClickTargetTypes::Visibility => Part::Visibility, .iter()
LayerClickTargetTypes::Lock => Part::Lock, .filter_map(|node_id| {
LayerClickTargetTypes::Grip => Part::Grip, let point = point - glide_offsets.node(node_id);
LayerClickTargetTypes::Name => Part::Name, self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
}; if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
match click_target_type {
self.nodes_reaching(point, network_path).into_iter().find(|node_id| { LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
let point = point - glide_offsets.node(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.
@@ -202,11 +269,13 @@ impl NodeNetworkInterface {
.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| {
let point = point - glide_offsets.node(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(|| {
@@ -233,11 +302,13 @@ impl NodeNetworkInterface {
.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| {
let point = point - glide_offsets.node(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(|| {
@@ -355,17 +426,3 @@ impl NodeNetworkInterface {
(layer_widths, chain_widths, has_left_input_wire) (layer_widths, chain_widths, has_left_input_wire)
} }
} }
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
let mut current_row = 0;
for (index, input) in inputs.iter().enumerate() {
if input.is_exposed() && current_row == row {
return Some(index);
}
if index == 0 || input.is_exposed() {
current_row += 1;
}
}
None
}
@@ -6,6 +6,10 @@
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);
@@ -13,5 +17,6 @@ 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,6 +52,7 @@ 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.
@@ -144,6 +145,7 @@ 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
@@ -157,6 +159,8 @@ 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
@@ -367,6 +371,7 @@ 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,9 +1,7 @@
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
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 std::cell::RefCell; use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
const REACH_MARGIN: f64 = 16.; const REACH_MARGIN: f64 = 16.;
@@ -11,53 +9,13 @@ 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)
} }
@@ -95,33 +53,6 @@ impl NetworkLayout {
self.node(layer).map_or(0, |node| node.chain_length) self.node(layer).map_or(0, |node| node.chain_length)
} }
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
pub fn bounds(&self) -> [DVec2; 2] {
self.bounds
}
/// What the imports and exports keep their distance from horizontally.
pub(crate) fn clearance(&self) -> ImportExportClearance {
self.clearance
}
/// The node's body where it sits in its grid cell, in node graph space.
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
Some(self.placed(*self.indices.get(node_id)?).body())
}
/// 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(&PartTarget) -> Option<R>) -> Option<R> {
let placed = self.placed(*self.indices.get(node_id)?);
let mut found = None;
placed.parts(|target| {
if found.is_none() {
found = find(&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.
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool { pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
let Some(index) = self.indices.get(node_id) else { return false }; let Some(index) = self.indices.get(node_id) else { return false };
@@ -131,38 +62,6 @@ impl NetworkLayout {
point.cmpge(min).all() && point.cmplt(max).all() point.cmpge(min).all() && point.cmplt(max).all()
} }
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
let node_layout = self.layout.node(index);
PlacedNode {
node: &self.graph[index],
shape: &self.shapes[index.index()],
position: node_layout.position,
chain_length: node_layout.chain_length,
}
}
/// 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.placed(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)?))
} }
@@ -187,14 +86,12 @@ 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(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self { fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, 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,
@@ -202,7 +99,6 @@ 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,
} }
} }
@@ -258,6 +154,7 @@ impl NodeNetworkInterface {
} }
} }
transient.layout.unload(); transient.layout.unload();
self.invalidate_positions(network_path);
} }
/// 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.
@@ -281,14 +178,9 @@ 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();
let laid_out = LaidOutNodes { (moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
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, laid_out, graph)) = finished else { return }; let Some((moved_placements, node_ids, indices, 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 {
@@ -297,7 +189,13 @@ 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::new(store::revision(), laid_out, graph, layout)); network_metadata.transient_metadata.layout.store(NetworkLayout {
revision: store::revision(),
layout,
graph,
node_ids,
indices,
});
} }
} }
@@ -310,15 +208,16 @@ 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 (laid_out, start) = self.layout_graph(network_path)?; let (node_ids, indices, start) = self.layout_graph(network_path)?;
let start_layout = Layout::new(&start); let start_layout = Layout::new(&start);
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision)); *origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
} }
origin.as_mut().map(read) origin.as_mut().map(read)
} }
@@ -328,8 +227,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 (laid_out, graph, layout) = cached.into_parts(); let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision)) Some(DragOrigin::new(node_ids, indices, 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 {
@@ -347,38 +246,40 @@ 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 (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag { let (node_ids, indices, 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);
let laid_out = LaidOutNodes { (origin.node_ids.clone(), origin.indices.clone(), graph, layout)
node_ids: origin.node_ids.clone(),
indices: origin.indices.clone(),
shapes: origin.shapes.clone(),
};
(laid_out, graph, layout)
})?, })?,
None => { None => {
let (laid_out, graph) = self.layout_graph(network_path)?; let (node_ids, indices, graph) = self.layout_graph(network_path)?;
let layout = Layout::new(&graph); let layout = Layout::new(&graph);
(laid_out, graph, layout) (node_ids, indices, graph, layout)
} }
}; };
Some(NetworkLayout::new(revision, laid_out, graph, layout)) Some(NetworkLayout {
revision,
layout,
graph,
node_ids,
indices,
})
} }
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> { pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, 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, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?; let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
let wires = node_ids let wires = node_ids
.iter() .iter()
.enumerate() .enumerate()
@@ -396,10 +297,10 @@ impl NodeNetworkInterface {
}) })
.collect(); .collect();
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires })) Some((node_ids, indices, Graph { nodes, wires }))
} }
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> { fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
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 {
@@ -413,40 +314,17 @@ 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 (layer_width, name_width) = if is_layer {
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
} else {
(0, 0.)
};
let (kind, size) = match (is_layer, is_redirect_dot) { let (kind, size) = match (is_layer, is_redirect_dot) {
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)), (true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))), (false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))), (false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
}; };
Some(Node {
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
let node = Node {
placement, placement,
kind, kind,
size: size.as_ivec2(), size: size.as_ivec2(),
chainable: !is_redirect_dot && !primary_output_hidden, chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
held: false, held: false,
}; })
let shape = NodeShape {
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
outputs: self.number_of_outputs(node_id, network_path) as u32,
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
primary_output_hidden,
name_width,
locked: self.is_locked(node_id, network_path),
};
Some((node, shape))
} }
} }
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
pub(crate) struct LaidOutNodes {
pub(crate) node_ids: Vec<NodeId>,
pub(crate) indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
}
@@ -94,9 +94,11 @@ 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 for all nodes in the encapsulating network // Update the outward wires and bounding box 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
@@ -139,6 +141,7 @@ 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 {
@@ -176,6 +179,7 @@ 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);
} }
@@ -568,7 +572,8 @@ 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` once after all import wiring is complete. /// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
/// `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");
@@ -668,6 +673,8 @@ 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();
@@ -897,6 +904,7 @@ 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);
} }
@@ -919,6 +927,7 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
previous_entry previous_entry
} }
@@ -1083,6 +1092,7 @@ 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;
@@ -1116,10 +1126,10 @@ impl NodeNetworkInterface {
} }
} }
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| { let reconnected_offset = reconnect_to_input
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?; .as_ref()
Some((reconnected, offset)) .and_then(NodeInput::as_node)
}); .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();
@@ -1355,6 +1365,7 @@ 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();
} }
@@ -1,231 +0,0 @@
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
use glam::{DVec2, IVec2};
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
const GRID: f64 = GRID_SIZE as f64;
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
const SIDE_PORT_INWARD_REACH: f64 = 8.;
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
const GRIP_WIDTH: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
/// What a node draws beyond the size the layout gives it.
#[derive(Clone, Copy, Debug, Default)]
pub struct NodeShape {
/// How many inputs have a port, which doesn't count a hidden primary input.
pub inputs: u32,
pub outputs: u32,
/// Whether a node's primary input has no port, though its row is still drawn.
pub primary_input_hidden: bool,
pub primary_output_hidden: bool,
/// The width of a layer's name in pixels.
pub name_width: f64,
pub locked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
/// A rounded rectangle of a node that reacts to the pointer.
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
/// A port on the left side of a node, reaching further out than over the node.
fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Input(input),
}
}
/// A port on the right side of a node, reaching further out than over the node.
fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Output(output),
}
}
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
/// Whether `point` is inside the rounded rectangle.
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
#[derive(Clone, Copy, Debug)]
pub struct PlacedNode<'a> {
pub node: &'a Node,
pub shape: &'a NodeShape,
pub position: IVec2,
pub chain_length: u32,
}
impl PlacedNode<'_> {
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
pub fn body(&self) -> PartTarget {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
match self.node.kind {
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: top_left - DVec2::new(self.chain_width(), 0.),
max: top_left + size,
corner_radius: 10.,
part: Part::Body,
},
NodeKind::Node => {
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
PartTarget {
min: body_top_left,
max: body_top_left + size - DVec2::new(0., GRID),
corner_radius: 3.,
part: Part::Body,
}
}
}
}
/// Calls `visit` with each part, the body last.
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.node.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.top_left() + DVec2::new(0., GRID);
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let width = self.node.size.x as f64 * GRID;
let row_center = |row: u32| GRID * (row as f64 + 1.);
let first_input_row = u32::from(self.shape.primary_input_hidden);
for row in first_input_row..first_input_row + self.shape.inputs {
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
}
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
}
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
let icon_half_size = DVec2::splat(HALF_GRID);
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
if self.shape.locked {
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
}
let icons_width = if self.shape.locked { GRID } else { 0. };
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
let handle_top = top_left.y + HALF_GRID;
let handle_bottom = top_left.y + GRID + HALF_GRID;
visit(PartTarget {
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
max: DVec2::new(grip_right, handle_bottom),
corner_radius: 0.,
part: Part::Grip,
});
let name_left = top_left.x + NAME_LEFT_OFFSET;
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, handle_top),
max: DVec2::new(name_right, handle_bottom),
corner_radius: 3.,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.position.as_dvec2() * GRID
}
fn has_side_input(&self) -> bool {
self.shape.inputs > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
}
}
@@ -1,9 +1,7 @@
use super::*; use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
impl NodeNetworkInterface { impl NodeNetworkInterface {
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None. /// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> { pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
@@ -829,17 +827,26 @@ impl NodeNetworkInterface {
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok()) self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
} }
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph. /// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool { pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else { self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
return false; }
};
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
node_metadata /// The metadata the node macro records for a proto node's parameter, or graph text describes for a graph node's import.
.get(proto_node_identifier) /// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
.and_then(|metadata| metadata.fields.get(index)) pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
.is_some_and(|field| field.internal) if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
}
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
return None;
};
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
let field = graphene_std::graph_text::GRAPHS.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
(field.name == input_name).then(|| field.clone())
} }
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns. /// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
@@ -328,10 +328,7 @@ 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::placement( deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
&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,14 +229,13 @@ 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 {
if self.metadata.node_type_metadata == node_type { let changed = self.metadata.node_type_metadata != node_type;
return false;
}
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
self.metadata.node_type_metadata = node_type; self.metadata.node_type_metadata = node_type;
self.deltas.metadata(change); if changed {
true let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
}
changed
} }
/// 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,11 +200,10 @@ 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, and the frames they paint anywhere in. /// Update how far each layer's effects paint past its content.
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) { pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
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;
} }
} }
@@ -3,7 +3,12 @@ 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};
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left. /// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
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.) {
@@ -14,6 +19,16 @@ 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 {
@@ -277,6 +292,13 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)] [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 { pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
const CORNER_RADIUS: f64 = 4.; const CORNER_RADIUS: f64 = 4.;
@@ -310,6 +332,13 @@ impl Ports {
} }
} }
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
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)> { pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
self.input_ports.iter() self.input_ports.iter()
} }
@@ -319,15 +348,51 @@ impl Ports {
} }
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.input_ports.push((input_index, port_click_target(side_port_bounds(center, true)))); self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
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.output_ports.push((output_index, port_click_target(side_port_bounds(center, false)))); self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
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, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
} }
@@ -336,12 +401,37 @@ impl Ports {
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, click_target)| click_target.intersect_point_no_stroke(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> {
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor) if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
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> {
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor) if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
return Some(*anchor);
}
self.output_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
} }
} }
@@ -657,12 +747,16 @@ 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>,
/// The import and export connector click targets, with the generation of the layout they were placed by. /// All export connector click targets
pub(crate) import_export_ports: TransientCache<(u64, Ports)>, pub(crate) import_export_ports: TransientCache<Ports>,
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for. /// 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>, pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
@@ -773,51 +867,11 @@ impl PartialEq for DocumentNodeMetadata {
} }
} }
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NumberInputSettings {
pub unit: Option<String>,
pub min: Option<f64>,
pub max: Option<f64>,
pub step: Option<f64>,
pub mode: NumberInputMode,
pub range_min: Option<f64>,
pub range_max: Option<f64>,
pub is_integer: bool,
pub blank_assist: bool,
}
impl Default for NumberInputSettings {
fn default() -> Self {
NumberInputSettings {
unit: None,
min: None,
max: None,
step: None,
mode: NumberInputMode::default(),
range_min: None,
range_max: None,
is_integer: false,
blank_assist: true,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct Vec2InputSettings {
pub x: String,
pub y: String,
pub unit: String,
pub min: Option<f64>,
pub is_integer: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum WidgetOverride { pub enum WidgetOverride {
None, None,
Hidden, Hidden,
String(String), String(String),
Number(NumberInputSettings),
Vec2(Vec2InputSettings),
Custom(String), Custom(String),
} }
@@ -854,40 +908,6 @@ impl InputPersistentMetadata {
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector)); self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
self.widget_override = Some("string".to_string()); self.widget_override = Some("string".to_string());
} }
WidgetOverride::Number(mut number_inspector) => {
if let Some(unit) = number_inspector.unit.take() {
self.input_data.insert("unit".to_string(), json!(unit));
}
if let Some(min) = number_inspector.min.take() {
self.input_data.insert("min".to_string(), json!(min));
}
if let Some(max) = number_inspector.max.take() {
self.input_data.insert("max".to_string(), json!(max));
}
if let Some(step) = number_inspector.step.take() {
self.input_data.insert("step".to_string(), json!(step));
}
if let Some(range_min) = number_inspector.range_min.take() {
self.input_data.insert("range_min".to_string(), json!(range_min));
}
if let Some(range_max) = number_inspector.range_max.take() {
self.input_data.insert("range_max".to_string(), json!(range_max));
}
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
self.widget_override = Some("number".to_string());
}
WidgetOverride::Vec2(vec2_inspector) => {
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
if let Some(min) = vec2_inspector.min {
self.input_data.insert("min".to_string(), json!(min));
}
self.widget_override = Some("vec2".to_string());
}
WidgetOverride::Custom(lambda_name) => { WidgetOverride::Custom(lambda_name) => {
self.widget_override = Some(lambda_name); self.widget_override = Some(lambda_name);
} }
@@ -1079,8 +1099,40 @@ 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, and the measured width of its name, 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, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<(u32, f64)>, pub(crate) layer_width: TransientCache<u32>,
}
#[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)]
@@ -1,7 +1,7 @@
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType; use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use glam::{DVec2, IVec2}; use glam::{DVec2, IVec2};
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point}; use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2}; use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
#[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)]
@@ -125,27 +125,23 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing (output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
} }
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the /// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires. /// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath { pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) { if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new(); return BezPath::new();
} }
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style); // The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
return BezPath::new();
};
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
let sign = (input_position.y - output_position.y).signum(); let sign = (input_position.y - output_position.y).signum();
let output_trim = 1.5;
let input_trim = 1.;
let start = output_position + DVec2::new(0., output_trim * sign);
let end = input_position - DVec2::new(0., input_trim * sign);
let mut center_line = BezPath::new(); let mut center_line = BezPath::new();
center_line.move_to(start - Vec2::new(0., 1.5 * sign)); center_line.move_to(dvec2_to_point(start));
center_line.line_to(start); center_line.line_to(dvec2_to_point(end));
for element in wire.elements().iter().skip(1) {
center_line.push(*element);
}
center_line.line_to(end + Vec2::new(0., 2. * sign));
center_line center_line
} }
@@ -584,7 +580,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use kurbo::{Affine, ParamCurveNearest}; use kurbo::{Affine, Vec2};
#[test] #[test]
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() { fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
@@ -607,30 +603,4 @@ mod tests {
} }
} }
} }
#[test]
fn the_center_line_of_a_stack_wire_runs_inside_it() {
let ends = [
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
];
let half_wire_width = 4.;
for (output, input) in ends {
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
let wire = build_vector_wire(output, input, true, true, style);
let center_line = build_thick_wire_center_line(output, input, true, true, style);
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
for sample in samples {
let distance = wire
.segments()
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
.fold(f64::INFINITY, f64::min);
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
}
}
}
}
} }
File diff suppressed because it is too large. Load diff
@@ -1123,10 +1123,20 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
self.executor.submit_thumbnails_in_view(document, document_id); self.executor.submit_thumbnails_in_view(document, document_id);
} }
} }
PortfolioMessage::SubmitClipboardSvg { id } => match self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) { PortfolioMessage::SubmitClipboardSvg { id } => {
Some(document) => self.executor.submit_clipboard_svg(document, viewport.size().into_dvec2(), id), let layers = self.active_document().map(|document| {
None => responses.add(ClipboardMessage::Rendered { id, svg: Ok(None) }), let selected = document.partition_selection().layers;
}, let mut layers = document
.metadata()
.all_layers()
.filter(|layer| selected.contains(layer))
.map(|layer| layer.to_node())
.collect::<Vec<_>>();
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;
responses.add(MenuBarMessage::SendLayout); responses.add(MenuBarMessage::SendLayout);
@@ -7,7 +7,7 @@ use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::utility_types::DocumentToolData; use crate::messages::tool::utility_types::DocumentToolData;
use graphene_std::Color; use graphene_std::Color;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::vector::style::{FillChoice, PaintMapping, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin}; use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar. /// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
pub struct ToolColorOptions { pub struct ToolColorOptions {
@@ -217,7 +217,7 @@ impl DrawingToolState {
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet { Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
layer, layer,
gradient: graphene_std::vector::Gradient::from(&ramp), gradient: graphene_std::vector::Gradient::from(&ramp),
gradient_form: None, gradient_form: Default::default(),
gradient_settings: (&ramp).into(), gradient_settings: (&ramp).into(),
transform: None, transform: None,
}), }),
@@ -242,7 +242,6 @@ impl DrawingToolState {
join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit), join_miter_limit: self.miter_limit.unwrap_or(defaults.miter_limit),
dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()), dash_lengths: self.dash_lengths.clone().unwrap_or_else(|| defaults.dash_lengths.clone()),
dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset), dash_offset: self.dash_offset.unwrap_or(defaults.dash_offset),
paint_mapping: PaintMapping::default(),
transform: glam::DAffine2::IDENTITY, transform: glam::DAffine2::IDENTITY,
}; };
responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke }); responses.add(GraphOperationMessage::StrokeSet { layer, color: Some(color), stroke });
@@ -346,7 +346,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
// A generator discards its primary input, so the chain ends at whichever one is reached // A generator discards its primary input, so the chain ends at whichever one is reached
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER]; let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [ let setters = [
graphene_std::math_nodes::gradient_curvature::IDENTIFIER, graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER, graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER, graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER, graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -428,17 +428,6 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into()) Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
} }
/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed.
pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
&TaggedValue::Number(value) => Some(value),
_ => None,
};
Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?])
}
/// Get the gradient stops of a layer, if any. /// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> { pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
// Try to find the gradient stops value that is created by a Fill node first // Try to find the gradient stops value that is created by a Fill node first
@@ -841,23 +830,9 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
} }
} }
/// A Fill node's curvatures, unless the graph feeds either or exposes it, read like [`gradient_curvature_values`] reads a 'Gradient Curvature' node's.
pub fn fill_node_curvatures(fill_node: &DocumentNode) -> Option<[f64; 2]> {
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
&TaggedValue::Number(value) => Some(value),
_ => None,
};
Some([value(fill_node.input(StartCurvatureInput))?, value(fill_node.input(EndCurvatureInput))?])
}
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`). /// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient { pub struct FillNodeGradient {
pub stops: Gradient, pub stops: Gradient,
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
pub curvatures: Option<[f64; 2]>,
/// The form its curvatures make, which is linear for any that make neither.
pub gradient_form: GradientForm, pub gradient_form: GradientForm,
pub settings: GradientSettings, pub settings: GradientSettings,
pub transform: DAffine2, pub transform: DAffine2,
@@ -874,8 +849,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
}; };
let settings = GradientSettings::from(ramp); let settings = GradientSettings::from(ramp);
let stops = Gradient::from(ramp); let stops = Gradient::from(ramp);
let curvatures = fill_node_curvatures(fill_node); let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default(); Some(&TaggedValue::GradientForm(value)) => value,
_ => GradientForm::default(),
};
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true))); let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value()); let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
let transform = match (has_transform, transform_input) { let transform = match (has_transform, transform_input) {
@@ -886,7 +863,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
Some(FillNodeGradient { Some(FillNodeGradient {
stops, stops,
curvatures,
gradient_form, gradient_form,
settings, settings,
transform, transform,
@@ -1029,6 +1005,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
use graphene_std::vector::fill; use graphene_std::vector::fill;
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER); let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
Some(TaggedValue::GradientForm(value)) => *value,
_ => GradientForm::default(),
};
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true))); let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) { let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
(true, Some(TaggedValue::DAffine2(value))) => *value, (true, Some(TaggedValue::DAffine2(value))) => *value,
@@ -1039,7 +1019,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
responses.add(GraphOperationMessage::FillGradientSet { responses.add(GraphOperationMessage::FillGradientSet {
layer, layer,
gradient: Gradient::from(ramp), gradient: Gradient::from(ramp),
gradient_form: None, gradient_form,
gradient_settings: ramp.into(), gradient_settings: ramp.into(),
transform: Some(transform), transform: Some(transform),
}); });
@@ -175,8 +175,6 @@ 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>,
@@ -497,17 +495,13 @@ impl SnapSession {
landed landed
} }
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it. /// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
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.
@@ -551,14 +545,11 @@ 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_targets_gone_to_sleep(); self.forget_sources_of_sleeping_positions();
self.constructions = None; self.constructions = None;
true true
@@ -572,7 +563,6 @@ 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;
@@ -593,12 +583,10 @@ impl SnapSession {
.collect() .collect()
} }
/// Lets go of what is kept about woken targets that have since gone back to sleep. fn forget_sources_of_sleeping_positions(&mut self) {
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.
@@ -733,7 +721,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_targets_gone_to_sleep(); self.forget_sources_of_sleeping_positions();
} }
} }
@@ -1112,45 +1100,6 @@ 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();
@@ -29,8 +29,6 @@ pub struct GradientTool {
#[derive(Default)] #[derive(Default)]
pub struct GradientOptions { pub struct GradientOptions {
gradient_form: GradientForm, gradient_form: GradientForm,
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
curvature_source: CurvatureSource,
settings: GradientSettings, settings: GradientSettings,
} }
@@ -94,16 +92,12 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options { ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
GradientOptionsUpdate::Form(gradient_form) => { GradientOptionsUpdate::Form(gradient_form) => {
self.options.gradient_form = gradient_form; self.options.gradient_form = gradient_form;
self.options.curvature_source = CurvatureSource::Form;
apply_gradient_update( apply_gradient_update(
&mut self.data, &mut self.data,
context, context,
responses, responses,
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form, |(_gradient, appearance)| appearance.gradient_form != gradient_form,
|(_gradient, appearance)| { |(_gradient, appearance)| appearance.gradient_form = gradient_form,
appearance.gradient_form = gradient_form;
appearance.curvature_source = CurvatureSource::Form;
},
); );
responses.add(ToolMessage::UpdateHints); responses.add(ToolMessage::UpdateHints);
responses.add(ToolMessage::UpdateCursor); responses.add(ToolMessage::UpdateCursor);
@@ -198,19 +192,14 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
let mut needs_refresh = false; let mut needs_refresh = false;
if let Some((_gradient, appearance)) = &current_gradient { if let Some((_gradient, appearance)) = &current_gradient {
if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source { if self.options.gradient_form != appearance.gradient_form {
self.options.gradient_form = appearance.gradient_form; self.options.gradient_form = appearance.gradient_form;
self.options.curvature_source = appearance.curvature_source;
needs_refresh = true; needs_refresh = true;
} }
if self.options.settings != appearance.settings { if self.options.settings != appearance.settings {
self.options.settings = appearance.settings; self.options.settings = appearance.settings;
needs_refresh = true; needs_refresh = true;
} }
} else if self.options.curvature_source != CurvatureSource::Form {
// With no gradient selected, the Form radio shows the form a new one gets
self.options.curvature_source = CurvatureSource::Form;
needs_refresh = true;
} }
let has_gradient = current_gradient.is_some(); let has_gradient = current_gradient.is_some();
@@ -272,11 +261,7 @@ impl LayoutHolder for GradientTool {
} }
.into() .into()
}); });
let selected_form = (self.options.curvature_source == CurvatureSource::Form).then_some(self.options.gradient_form as u32); let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance();
let gradient_form = RadioInput::new(gradient_form_entries)
.selected_index(selected_form)
.disabled(self.options.curvature_source == CurvatureSource::Graph)
.widget_instance();
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors // Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
let stops_value = self let stops_value = self
@@ -396,12 +381,10 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
let fill_node = network_interface.document_network().nodes.get(&fill_id)?; let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?; let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
let (gradient_form, curvature_source) = CurvatureSource::of(gradient.curvatures);
return Some(( return Some((
gradient.stops, gradient.stops,
GradientAppearance { GradientAppearance {
gradient_form, gradient_form: gradient.gradient_form,
curvature_source,
settings: gradient.settings, settings: gradient.settings,
transform: gradient.transform, transform: gradient.transform,
}, },
@@ -421,48 +404,19 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
struct GradientAppearance { struct GradientAppearance {
transform: DAffine2, transform: DAffine2,
gradient_form: GradientForm, gradient_form: GradientForm,
/// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls.
// TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it
curvature_source: CurvatureSource,
settings: GradientSettings, settings: GradientSettings,
} }
/// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CurvatureSource {
/// They make the form, or there's no node and the form's are implied.
#[default]
Form,
/// They're values that make neither form.
Custom,
/// They're fed from the graph or exposed, so only the graph can change them.
Graph,
}
impl CurvatureSource {
/// The form some curvatures make (linear if neither) and where they come from, given them unless the graph feeds them.
fn of(curvatures: Option<[f64; 2]>) -> (GradientForm, Self) {
let form = curvatures.and_then(GradientForm::from_curvatures);
let source = match (curvatures, form) {
(None, _) => Self::Graph,
(Some(_), None) => Self::Custom,
(Some(_), Some(_)) => Self::Form,
};
(form.unwrap_or_default(), source)
}
}
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer. /// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance { fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
let target_input = gradient_chain_target_input(layer, network_interface); let target_input = gradient_chain_target_input(layer, network_interface);
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node()); let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER); let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER); let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new(); let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None; let mut gradient_form: Option<GradientForm> = None;
let mut curvature_source = CurvatureSource::Form;
for node_id in network_interface for node_id in network_interface
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow) .upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
@@ -476,9 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference { if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs)); transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_curvature_reference && gradient_form.is_none() { } else if reference == gradient_form_reference
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node)); && gradient_form.is_none()
(gradient_form, curvature_source) = (Some(form), source); && let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
{
gradient_form = Some(*value);
} }
} }
@@ -488,7 +444,6 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
GradientAppearance { GradientAppearance {
transform: composed_transform, transform: composed_transform,
gradient_form: gradient_form.unwrap_or_default(), gradient_form: gradient_form.unwrap_or_default(),
curvature_source,
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(), settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
} }
} }
@@ -838,15 +793,12 @@ impl SelectedGradient {
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) { pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
if let Some(layer) = self.layer { if let Some(layer) = self.layer {
if self.is_gradient_chain { if self.is_gradient_chain {
// Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
let write_form = self.dragging == GradientDragTarget::New;
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
} else { } else {
// Only a new gradient takes its form from the tool, as with a chain
responses.add(GraphOperationMessage::FillGradientSet { responses.add(GraphOperationMessage::FillGradientSet {
layer, layer,
gradient: self.gradient.clone(), gradient: self.gradient.clone(),
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form), gradient_form: self.appearance.gradient_form,
gradient_settings: self.appearance.settings, gradient_settings: self.appearance.settings,
transform: Some(self.appearance.transform), transform: Some(self.appearance.transform),
}); });
@@ -877,8 +829,8 @@ impl SelectedGradient {
} }
} }
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer, including its form's curvatures if `write_form` is set. /// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, write_form: bool, responses: &mut VecDeque<Message>) { fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
responses.add(GraphOperationMessage::GradientCyclicSet { responses.add(GraphOperationMessage::GradientCyclicSet {
layer, layer,
gradient_cyclic: appearance.settings.cyclic, gradient_cyclic: appearance.settings.cyclic,
@@ -896,12 +848,10 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
layer, layer,
transform: appearance.transform, transform: appearance.transform,
}); });
if write_form && appearance.curvature_source == CurvatureSource::Form { responses.add(GraphOperationMessage::GradientFormSet {
responses.add(GraphOperationMessage::GradientFormSet { layer,
layer, gradient_form: appearance.gradient_form,
gradient_form: appearance.gradient_form, });
});
}
responses.add(GraphOperationMessage::GradientSpreadSet { responses.add(GraphOperationMessage::GradientSpreadSet {
layer, layer,
gradient_spread: appearance.settings.spread, gradient_spread: appearance.settings.spread,
@@ -1572,7 +1522,6 @@ impl Fsm for GradientToolFsmState {
GradientAppearance { GradientAppearance {
transform: DAffine2::IDENTITY, transform: DAffine2::IDENTITY,
gradient_form: tool_options.gradient_form, gradient_form: tool_options.gradient_form,
curvature_source: CurvatureSource::Form,
settings: tool_options.settings, settings: tool_options.settings,
}, },
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted // A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
@@ -1991,13 +1940,12 @@ fn apply_gradient_update(
// Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer // Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() { if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
// Read fresh from the layer, so its form's curvatures change only if the update chose another form dispatch_gradient_chain_writes(layer, &gradient, appearance, responses);
dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses);
} else { } else {
responses.add(GraphOperationMessage::FillGradientSet { responses.add(GraphOperationMessage::FillGradientSet {
layer, layer,
gradient, gradient,
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form), gradient_form: appearance.gradient_form,
gradient_settings: appearance.settings, gradient_settings: appearance.settings,
transform: Some(appearance.transform), transform: Some(appearance.transform),
}); });
@@ -2063,7 +2011,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
responses.add(GraphOperationMessage::FillGradientSet { responses.add(GraphOperationMessage::FillGradientSet {
layer, layer,
gradient: new_gradient.clone(), gradient: new_gradient.clone(),
gradient_form: None, gradient_form: appearance.gradient_form,
gradient_settings: settings, gradient_settings: settings,
transform: Some(appearance.transform), transform: Some(appearance.transform),
}); });
@@ -2160,7 +2108,6 @@ mod test_gradient {
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at}; use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN}; use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState; use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance};
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::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
@@ -2168,8 +2115,8 @@ mod test_gradient {
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id; use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
pub use crate::test_utils::test_prelude::*; pub use crate::test_utils::test_prelude::*;
use glam::DAffine2; use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::NodeParameter; use graphene_std::NodeParameter;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation}; use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
@@ -3419,7 +3366,7 @@ mod test_gradient {
.await; .await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position"); let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire. // Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await; editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await; editor.select_tool(ToolType::Gradient).await;
editor editor
@@ -3428,7 +3375,7 @@ mod test_gradient {
}) })
.await; .await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER); let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_node_id = { let form_node_id = {
let network_interface = &editor.active_document().network_interface; let network_interface = &editor.active_document().network_interface;
network_interface network_interface
@@ -3437,10 +3384,10 @@ mod test_gradient {
.keys() .keys()
.copied() .copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference)) .find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Curvature node should have been inserted") .expect("Gradient Form node should have been inserted")
}; };
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position"); let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after"); let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin"); assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
@@ -3585,347 +3532,6 @@ mod test_gradient {
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write"); assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
} }
/// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to.
async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 {
let document = editor.active_document();
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
let dragged_end = end + offset;
editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await;
editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor
.mouseup(
EditorPointerState {
editor_position: dragged_end,
mouse_keys: MouseKeys::empty(),
..Default::default()
},
ModifierKeys::empty(),
)
.await;
dragged_end
}
/// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses
/// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node.
async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
editor.active_document_mut().snapping_state.snapping_enabled = false;
let layer = create_gradient_list_layer(editor).await;
editor
.handle_message(GraphOperationMessage::GradientTransformSet {
layer,
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
})
.await;
let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let network_interface = &editor.active_document().network_interface;
let curvature_node_id = network_interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference))
.expect("Gradient Curvature node should have been inserted");
assert_eq!(
curvature_inputs(editor, curvature_node_id),
inputs_holding(GradientForm::Radial.curvatures()),
"the inserted node should hold the radial form's curvatures"
);
(layer, curvature_node_id)
}
/// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do.
async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) {
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id: curvature_node_id,
input_index,
value: TaggedValue::Number(curvature).into(),
})
.await;
}
}
/// The start and end curvature inputs of a 'Gradient Curvature' node.
fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option<NodeInput>; 2] {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id];
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
}
/// The curvature inputs holding these values.
fn inputs_holding(curvatures: [f64; 2]) -> [Option<NodeInput>; 2] {
curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false)))
}
/// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages.
fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option<u32>, bool)> {
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
_ => None,
};
frontend_messages
.iter()
.rev()
.filter_map(|message| match message {
FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::ToolOptions,
diff,
} => Some(diff),
_ => None,
})
.flat_map(|diff| diff.iter().rev())
.find_map(|widget_diff| match &widget_diff.new_value {
DiffUpdate::Widget(widget) => form_radio(widget),
DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio),
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio),
})
}
#[tokio::test]
async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() {
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
// Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are
let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
let document = editor.active_document();
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag");
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}");
assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures");
// Choosing a form in the control bar is what sets them
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Form(GradientForm::Linear),
})
.await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding(GradientForm::Linear.curvatures()),
"choosing the linear form should set its curvatures"
);
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(number_node_id),
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
})
.await;
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
editor
.handle_message(GraphOperationMessage::GradientFormSet {
layer,
gradient_form: GradientForm::Radial,
})
.await;
let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id);
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
assert_eq!(
end_input,
inputs_holding(GradientForm::Linear.curvatures())[1],
"the end curvature beside a wired one should stay as it was"
);
}
#[tokio::test]
async fn edits_of_a_fill_gradient_keep_its_curvatures_until_a_form_is_chosen() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.active_document_mut().snapping_state.snapping_enabled = false;
editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await;
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
let document = editor.active_document();
let layer = document
.network_interface
.selected_nodes()
.selected_layers(document.metadata())
.next()
.expect("the rectangle is selected");
let fill_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface).expect("the gradient is held by the Fill");
let curvatures = |editor: &EditorTestUtils| {
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
};
// Curvatures making neither form survive a drag of the gradient's end
for (input_index, curvature) in [(StartCurvatureInput::INDEX, 0.3), (EndCurvatureInput::INDEX, 0.2)] {
let value = TaggedValue::Number(curvature).into();
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: fill_id, input_index, value }).await;
}
drag_gradient_end(&mut editor, layer, DVec2::new(0., 20.)).await;
assert_eq!(curvatures(&editor), inputs_holding([0.3, 0.2]), "a drag shouldn't reset custom curvatures");
// Choosing a form in the control bar is what sets them
let choose_form = |form| GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Form(form),
};
editor.handle_message(choose_form(GradientForm::Radial)).await;
assert_eq!(
curvatures(&editor),
inputs_holding(GradientForm::Radial.curvatures()),
"choosing the radial form should set its curvatures"
);
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(number_node_id),
input_connector: InputConnector::node(fill_id, StartCurvatureInput),
})
.await;
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
editor.handle_message(choose_form(GradientForm::Linear)).await;
let [start_input, end_input] = curvatures(&editor);
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
assert_eq!(
end_input,
inputs_holding(GradientForm::Radial.curvatures())[1],
"the end curvature beside a wired one should stay as it was"
);
}
#[tokio::test]
async fn stop_edits_keep_curvatures_set_while_the_stop_was_selected() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len());
// Clicking the line inserts a stop and selects it, and a double-click opens its color picker
let document = editor.active_document();
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.));
editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await;
editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await;
editor.handle_message(GradientToolMessage::DoubleClick).await;
assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop");
// The Properties panel then adjusts curvatures of neither form while the stop stays selected
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await;
editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([0.5, 0.5]),
"recoloring the stop shouldn't reset the curvatures"
);
editor.press(Key::Delete, ModifierKeys::empty()).await;
assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop");
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([0.5, 0.5]),
"deleting the stop shouldn't reset the curvatures"
);
}
#[tokio::test]
async fn curvatures_already_making_a_form_are_kept_by_writes_of_that_form() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
// The start curvature's slider maximum is the same point as -1, so the tool draws these curvatures as the radial form
set_curvatures(&mut editor, curvature_node_id, [1., 0.5]).await;
let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient");
assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form));
drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([1., 0.5]),
"a drag shouldn't rewrite curvatures making the form"
);
editor
.handle_message(GraphOperationMessage::GradientFormSet {
layer,
gradient_form: GradientForm::Radial,
})
.await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([1., 0.5]),
"setting the form they make shouldn't rewrite them"
);
}
#[tokio::test]
async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
// Reselecting the layer has the tool read its curvatures, which make neither form
let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen");
frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await);
assert_eq!(
latest_form_radio(&frontend_messages),
Some((Some(GradientForm::Linear as u32), false)),
"with nothing selected, the radio should show the linear form a new gradient gets"
);
}
#[tokio::test]
async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() {
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(number_node_id),
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
})
.await;
let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
assert_eq!(
latest_form_radio(&frontend_messages),
Some((None, true)),
"a wired curvature should leave no form chosen and the radio disabled"
);
}
#[tokio::test] #[tokio::test]
async fn drag_on_blank_layer_starts_gradient_chain() { async fn drag_on_blank_layer_starts_gradient_chain() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops; use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
+79 -117
View File
@@ -12,7 +12,6 @@ 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;
@@ -28,7 +27,7 @@ mod recompile_tests;
mod runtime; mod runtime;
pub use runtime::*; pub use runtime::*;
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct ExecutionRequest { pub struct ExecutionRequest {
execution_id: u64, execution_id: u64,
render_config: RenderConfig, render_config: RenderConfig,
@@ -42,15 +41,6 @@ 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.
@@ -115,8 +105,7 @@ pub enum NodeGraphUpdate {
Observations(HashMap<ObservationKey, InspectResult>), Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg { ClipboardSvg {
id: u64, id: u64,
/// The SVG, `None` if the layers add nothing, or why it couldn't be rendered. svg: Option<String>,
svg: Result<Option<String>, String>,
}, },
} }
@@ -203,6 +192,18 @@ impl NodeGraphExecutor {
self.canvas_images_sent.clear(); 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) -> u64 {
let execution_id = self.current_execution_id; let execution_id = self.current_execution_id;
@@ -231,28 +232,13 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides"); .expect("Failed to send the context overrides");
} }
/// Has the runtime render what the selected layers add as an SVG, which it sends back once their content is final. pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
/// The `viewport_size` is in viewport pixels. if document_id.is_none() || self.node_graph_document != document_id {
pub fn submit_clipboard_svg(&self, document: &DocumentMessageHandler, viewport_size: DVec2, id: u64) { return ClipboardMessage::Rendered { id, svg: None }.into();
let network_interface = &document.network_interface; }
let view = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, viewport_size])).bounding_box();
// Painted from the bottom up self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
let selected = document.partition_selection().layers; Message::NoOp
let mut layers: Vec<_> = document.metadata().all_layers().filter(|layer| selected.contains(layer)).map(|layer| layer.to_node()).collect();
layers.reverse();
// The network as it is now, since the runtime applies a graph update sent before this one only after it reads this
let request = ClipboardSvgRequest {
id,
network: network_interface.document_network().clone(),
resources: document.resources.registry.clone(),
previewed: network_interface.previewed_nodes(),
layer_paths: network_interface.layer_paths(),
layers,
view,
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg(request)).expect("Failed to send runtime request");
} }
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) { pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -267,6 +253,29 @@ impl NodeGraphExecutor {
.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;
@@ -452,7 +461,28 @@ impl NodeGraphExecutor {
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id), ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
} }
.ok_or_else(|| "No bounding box".to_string())?; .ok_or_else(|| "No bounding box".to_string())?;
let render_config = export_render_config(bounds, export_config.scale_factor, export_format);
let resolution_in_document_space = bounds[1] - bounds[0];
let export_resolution = resolution_in_document_space * export_config.scale_factor;
let resolution = export_resolution.round().as_uvec2();
let transform = DAffine2::from_translation(bounds[0]).inverse();
let viewport = Footprint {
resolution,
transform,
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: export_config.scale_factor,
time: Default::default(),
pointer: DVec2::ZERO,
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,
for_export: true,
for_eyedropper: false,
};
// Execute the node graph // Execute the node graph
self.sender self.sender
@@ -470,7 +500,7 @@ impl NodeGraphExecutor {
ExecutionContext { ExecutionContext {
export_config: Some(export_config), export_config: Some(export_config),
document_id, document_id,
document_to_viewport: render_config.viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
}, },
)); ));
@@ -497,8 +527,6 @@ 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());
@@ -541,29 +569,6 @@ impl NodeGraphExecutor {
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
@@ -1031,6 +1036,11 @@ 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");
@@ -1051,7 +1061,6 @@ impl NodeGraphExecutor {
vector_data, vector_data,
appearance_attributes, appearance_attributes,
effects_reach, effects_reach,
effects_frames,
backgrounds: _, backgrounds: _,
} = render_output.metadata; } = render_output.metadata;
@@ -1068,7 +1077,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, effects_frames }); responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
responses.add(DocumentMessage::RenderScrollbars); responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers); responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
@@ -1196,26 +1205,13 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None None
} }
/// The render of an export framed to these bounds in document space, drawn at `scale` pixels per unit. /// The SVG element the frontend replaces with the viewport canvas, covering the viewport at its logical `resolution`.
fn export_render_config(bounds: [DVec2; 2], scale: f64, export_format: ExportFormat) -> RenderConfig { #[cfg(target_family = "wasm")]
let resolution = ((bounds[1] - bounds[0]) * scale).round().as_uvec2(); fn viewport_canvas_placeholder(canvas_id: u64, resolution: DVec2) -> String {
let viewport = Footprint { format!(
resolution, r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
transform: DAffine2::from_translation(bounds[0]).inverse(), resolution.x, resolution.y, canvas_id,
..Default::default() )
};
RenderConfig {
viewport,
scale,
time: Default::default(),
pointer: DVec2::ZERO,
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,
for_export: true,
for_eyedropper: false,
}
} }
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile. /// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
@@ -1272,40 +1268,6 @@ 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()
}
/// 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 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)
}
}
/// 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 {
+105 -538
View File
@@ -17,10 +17,10 @@ use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface,
use graphene_std::raster_types::Raster; use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime; use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode; use graphene_std::vector::style::RenderMode;
use graphene_std::{Artboard, Context, ContextFeatures, Generations, NodeError, OwnedContextImpl, Poll}; use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::layer_paths::{export_layers, write_layer_paths}; use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_with_render_node_in_scope; use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer; use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue}; pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
use std::sync::Arc; use std::sync::Arc;
@@ -52,8 +52,6 @@ pub struct NodeRuntime {
pending_export: Option<ExecutionRequest>, pending_export: Option<ExecutionRequest>,
pending_eyedropper: Option<ExecutionRequest>, pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>, pending_thumbnails: Option<DocumentId>,
/// The latest copy's SVG, evaluated from its own network until its content is final.
pending_clipboard: Option<PendingClipboard>,
/// The network the executor last compiled successfully, with previews applied. /// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>, old_graph: Option<NodeNetwork>,
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place. /// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
@@ -61,6 +59,7 @@ pub struct NodeRuntime {
async_runtime: Option<AsyncRuntime>, async_runtime: Option<AsyncRuntime>,
editor_api: Arc<PlatformEditorApi>, editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
node_graph_errors: GraphErrors, node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors, node_graph_warnings: GraphErrors,
thumbnails: Thumbnails, thumbnails: Thumbnails,
@@ -95,7 +94,7 @@ enum ViewportArtwork {
} }
/// Messages passed from the editor thread to the node runtime thread. /// Messages passed from the editor thread to the node runtime thread.
#[derive(Debug)] #[derive(Debug, serde::Serialize, serde::Deserialize)]
pub enum GraphRuntimeRequest { pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate), GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest), ExecutionRequest(ExecutionRequest),
@@ -108,40 +107,14 @@ pub enum GraphRuntimeRequest {
key: ObservationKey, key: ObservationKey,
observation: Option<Observation>, observation: Option<Observation>,
}, },
ClipboardSvg(ClipboardSvgRequest), ClipboardSvg {
id: u64,
layers: Vec<NodeId>,
},
RenderOverlays(OverlayContext), RenderOverlays(OverlayContext),
} }
/// The layers a copy renders as an SVG, with the document network as it was when they were copied. #[derive(Debug, serde::Serialize, serde::Deserialize)]
#[derive(Debug)]
pub struct ClipboardSvgRequest {
pub(super) id: u64,
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
/// The node each network renders in place of its export, paired with that network's path.
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
/// Full path from the root network to every layer.
pub(super) layer_paths: Vec<Vec<NodeId>>,
/// The copied layers, in the order they're painted.
pub(super) layers: Vec<NodeId>,
/// The part of the document in view, which frames content drawn for its view.
pub(super) view: [DVec2; 2],
}
/// A copy's SVG, held until its content is final.
struct PendingClipboard {
id: u64,
/// The output of the network made for the copy, which keeps its nodes compiled through a cut that removes the layers from the document's.
output: OutputHandle,
/// The compiled node giving what the copied layers add, whose bounds frame the SVG.
content: NodeId,
/// The part of the document in view when they were copied.
view: [DVec2; 2],
/// The SVG's frame, once it's known.
frame: Option<[DVec2; 2]>,
}
#[derive(Debug)]
pub struct GraphUpdate { pub struct GraphUpdate {
pub(super) network: NodeNetwork, pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry, pub(super) resources: ResourceRegistry,
@@ -185,9 +158,9 @@ impl NodeRuntime {
pending_export: None, pending_export: None,
pending_eyedropper: None, pending_eyedropper: None,
pending_thumbnails: None, pending_thumbnails: None,
pending_clipboard: None,
old_graph: None, old_graph: None,
compile_failed: false, compile_failed: false,
resources: ResourceRegistry::default(),
async_runtime: None, async_runtime: None,
editor_api: PlatformEditorApi { editor_api: PlatformEditorApi {
@@ -224,7 +197,6 @@ impl NodeRuntime {
} }
let mut graph = None; let mut graph = None;
let mut clipboard = None;
for request in self.receiver.try_iter() { for request in self.receiver.try_iter() {
match request { match request {
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update), GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
@@ -251,8 +223,10 @@ impl NodeRuntime {
self.observations_changed = true; self.observations_changed = true;
} }
}, },
// The clipboard waits only for its latest copy GraphRuntimeRequest::ClipboardSvg { id, layers } => {
GraphRuntimeRequest::ClipboardSvg(request) => clipboard = Some(request), let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
}
GraphRuntimeRequest::RenderOverlays(context) => { GraphRuntimeRequest::RenderOverlays(context) => {
self.overlays = Some(context); self.overlays = Some(context);
self.overlays_stale = true; self.overlays_stale = true;
@@ -260,11 +234,6 @@ impl NodeRuntime {
} }
} }
// Compiled before a graph update that cuts the copied layers lets their nodes go
if let Some(request) = clipboard {
self.compile_clipboard_svg(request);
}
let Some(GraphUpdate { let Some(GraphUpdate {
mut network, mut network,
resources, resources,
@@ -279,8 +248,11 @@ impl NodeRuntime {
apply_previews(&mut network, &previewed); apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layers); write_layer_paths(&mut network, &layers);
self.observer.replace_all(observations); self.observer.replace_all(observations);
self.resources = resources;
let result = self.update_network(network.clone(), &resources); self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
self.compile_failed = result.is_err(); self.compile_failed = result.is_err();
if result.is_ok() { if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor); self.thumbnails.update_sources(&layers, &network, &self.executor);
@@ -330,11 +302,7 @@ impl NodeRuntime {
} }
if let Some(viewport) = viewport { if let Some(viewport) = viewport {
self.run_viewport(viewport).await; texture = self.run_viewport(viewport).await;
}
if dirty && let Some(clipboard) = self.pending_clipboard.take() {
self.run_clipboard(clipboard);
} }
// Overlays that changed without new artwork are drawn over the artwork already shown // Overlays that changed without new artwork are drawn over the artwork already shown
@@ -347,27 +315,63 @@ impl NodeRuntime {
texture texture
} }
async fn run_viewport(&mut self, request: ExecutionRequest) { async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
self.thumbnails.set_scale(request.render_config.scale); self.thumbnails.set_scale(request.render_config.scale);
let Some(mut result) = self.evaluate(request) else { return }; let mut result = self.evaluate(request)?;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
if let Some(RenderOutput { data, metadata }) = result.render_output() { #[cfg(all(target_family = "wasm", feature = "wasm"))]
let content = match data { let resolution = request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale;
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
_ => None,
};
if content.is_some() {
self.viewport_artwork = content;
let path_contents = path_contents(&observations);
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
self.overlays_stale = true;
}
}
self.respond(request, result, observations).await; let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
&& let RenderOutputType::Texture(texture) = data
{
self.viewport_artwork = Some(ViewportArtwork::Texture(texture.clone()));
let path_contents = path_contents(&observations);
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
self.overlays_stale = true;
let frame = self.composite_viewport_frame();
#[cfg(all(target_family = "wasm", feature = "wasm"))]
{
*data = RenderOutputType::CanvasFrame {
canvas_id: self.wasm_canvas_cache.id(),
resolution,
};
}
frame
} else if request.render_config.export_format == ExportFormat::Raster
&& let Some(RenderOutput {
data: RenderOutputType::Svg { .. },
metadata,
}) = result.render_output()
{
// The viewport was rendered as SVG in place of the requested raster, so the frontend draws it beneath the overlays
self.viewport_artwork = Some(ViewportArtwork::Svg);
let path_contents = path_contents(&observations);
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
self.overlays_stale = true;
let frame = self.composite_viewport_frame();
#[cfg(all(target_family = "wasm", feature = "wasm"))]
if let Some(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) = result.render_output()
{
let end = svg.rfind("</svg>").unwrap_or(svg.len());
svg.insert_str(end, &viewport_canvas_placeholder(self.wasm_canvas_cache.id(), resolution));
}
frame
} else {
None
};
self.respond(request.execution_id, result, observations).await;
texture
} }
/// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web. /// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web.
@@ -427,71 +431,7 @@ impl NodeRuntime {
*data = RenderOutputType::Buffer { data: buffer, width, height }; *data = RenderOutputType::Buffer { data: buffer, width, height };
} }
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.respond(request, result, observations).await; self.respond(request.execution_id, result, observations).await;
}
/// Evaluates the copy's network as an export framed to its content, sending its SVG once that's final, and otherwise keeping it to evaluate again when a task lands.
fn run_clipboard(&mut self, mut clipboard: PendingClipboard) {
let generations = self.async_runtime().snapshot();
let frame = match clipboard.frame {
Some(frame) => frame,
None => {
let Some(frame) = self.clipboard_frame(&clipboard, &generations) else {
self.pending_clipboard = Some(clipboard);
return;
};
match frame {
Ok(Some(frame)) => *clipboard.frame.insert(frame),
Ok(None) => return self.send_clipboard_svg(clipboard.id, Ok(None)),
Err(message) => return self.send_clipboard_svg(clipboard.id, Err(message)),
}
}
};
// The render covers whole pixels, rounded outward, while the SVG's frame keeps the content's exact size
let size = frame[1] - frame[0];
let covered = size.ceil();
let context = export_render_config([frame[0], frame[0] + covered], 1., ExportFormat::Svg).into_context_with_generations(generations);
match self.settled(clipboard.output.node(), || self.executor.execute(&clipboard.output, context).map_err(|error| error.to_string())) {
Some(output) => self.send_clipboard_svg(clipboard.id, output.and_then(svg_text).map(|svg| svg.map(|svg| with_frame_size(svg, covered, size)))),
None => self.pending_clipboard = Some(clipboard),
}
}
/// The frame of the copy's SVG once it's known, unless it has no area.
/// Content drawn for its view is framed to the view it was copied in, while other content is framed to its bounds, which are the same in any view.
fn clipboard_frame(&self, clipboard: &PendingClipboard, generations: &Generations) -> Option<Result<Option<[DVec2; 2]>, String>> {
let has_area = |[min, max]: &[DVec2; 2]| (*max - *min).cmpgt(DVec2::ZERO).all();
if self.executor.tree().context_features(clipboard.content).contains(ContextFeatures::FOOTPRINT) {
return Some(Ok(Some(clipboard.view).filter(has_area)));
}
let context = OwnedContextImpl::default()
.with_footprint(export_render_config(clipboard.view, 1., ExportFormat::Svg).viewport)
.with_real_time(0.)
.with_animation_time(0.)
.with_generations(generations.clone())
.into_context();
let content = self.settled(clipboard.content, || self.executor.tree().evaluate(clipboard.content, &context).map_err(|error| error.to_string()))?;
Some(content.map(|content| exported_bounds(content).filter(has_area)))
}
/// The value an evaluation of the node gives once it's final, `None` while it's pending or partial, or else what went wrong.
fn settled<T>(&self, node: NodeId, evaluate: impl FnOnce() -> Result<Poll<T>, String>) -> Option<Result<T, String>> {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(evaluate)).unwrap_or_else(|payload| {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Err(format!("Panicked: {}", message.unwrap_or("no message")))
});
match result {
Ok(Poll::Pending | Poll::Partial(_)) => None,
Ok(Poll::Final(value)) => Some(Ok(value)),
Ok(Poll::Fallback(boxed)) => Some(Ok(boxed.0)),
Ok(Poll::Error(error)) => Some(Err(self.resolve_errors(node, &error).to_string())),
Err(message) => Some(Err(message)),
}
} }
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) { async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
@@ -525,17 +465,17 @@ impl NodeRuntime {
} }
let context = render_config.into_context_with_generations(self.async_runtime().snapshot()); let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) { let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending, Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value), Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value), Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => { Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed; let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(self.output.node(), &error)) ExecutionResult::Fallback(value, self.resolve_errors(&error))
} }
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(self.output.node(), &error)), Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))), Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
Err(payload) => { Err(payload) => {
let response = ExecutionResponse { let response = ExecutionResponse {
execution_id, execution_id,
@@ -543,8 +483,6 @@ impl NodeRuntime {
responses: VecDeque::new(), responses: VecDeque::new(),
dropped_thumbnails: Vec::new(), dropped_thumbnails: Vec::new(),
observations: HashMap::new(), observations: HashMap::new(),
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info: None,
}; };
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None; return None;
@@ -553,37 +491,18 @@ impl NodeRuntime {
Some(result) Some(result)
} }
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) { async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did // While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await }; let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let mut result = result;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let viewport_canvas_info = (!request.render_config.for_export
&& match result.render_output() {
Some(RenderOutput { data, .. }) => match data {
RenderOutputType::Texture(_) => true,
RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster,
RenderOutputType::Buffer { .. } => false,
},
None => false,
})
.then(|| ViewportCanvasInfo {
id: self.wasm_canvas_cache.id(),
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
});
let response = ExecutionResponse { let response = ExecutionResponse {
execution_id: request.execution_id, execution_id,
result, result,
responses, responses,
dropped_thumbnails, dropped_thumbnails,
observations, observations,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info,
}; };
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
} }
@@ -602,121 +521,42 @@ impl NodeRuntime {
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
} }
fn update_network(&mut self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> { fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
self.node_graph_errors.clear(); let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
self.node_graph_warnings.clear();
let CompiledNetwork { network: proto_network, warnings } = match self.compile_network(graph, resources) { if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
Ok(compiled_network) => compiled_network, return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
Err((message, errors)) => {
self.node_graph_errors = errors;
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
}
};
self.node_graph_warnings = warnings;
let result = match self.executor.update(proto_network) {
Ok((output, types)) => {
self.output = output;
Ok(types)
}
Err((types, errors)) => {
let message = format!("{errors:?}");
self.node_graph_errors = errors;
Err((types, message))
}
};
// Every held output's sources, so the tasks they spawn bump their generations when they land
self.async_runtime().update_sources(self.executor.sources());
result
}
/// Compiles the network of the copied layers beside the document's, to be evaluated until its SVG is final.
fn compile_clipboard_svg(&mut self, request: ClipboardSvgRequest) {
let ClipboardSvgRequest {
id,
mut network,
resources,
previewed,
layer_paths,
layers,
view,
} = request;
self.pending_clipboard = None;
// Made as the document's network is, so it shares the document's compiled nodes
apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layer_paths);
let Some(content_node) = export_layers(&mut network, &layers) else {
self.send_clipboard_svg(id, Ok(None));
return;
};
let proto_network = match self.compile_network(network, &resources) {
Ok(compiled_network) => compiled_network.network,
Err((message, _)) => {
self.send_clipboard_svg(id, Err(message));
return;
}
};
// The last of the proto nodes at the stack's path, which may wrap it, gives what the stack outputs
let content_path = Some(vec![content_node]);
let Some(&(content, _)) = proto_network.nodes.iter().rev().find(|(_, node)| node.original_location.path == content_path) else {
self.send_clipboard_svg(id, Err("The copied layers' content didn't compile".to_string()));
return;
};
// The document's updates keep the source map, so the types they send the editor stay whole
let output = match self.executor.insert_beside(proto_network) {
Ok(output) => output,
Err(errors) => {
self.send_clipboard_svg(id, Err(format!("{errors:?}")));
return;
}
};
self.async_runtime().update_sources(self.executor.sources());
self.pending_clipboard = Some(PendingClipboard {
id,
output,
content,
view,
frame: None,
});
self.dirty.store(true, Ordering::Release);
}
fn send_clipboard_svg(&self, id: u64, svg: Result<Option<String>, String>) {
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
}
/// Wraps the network with the render node in its scope, then preprocesses and compiles it, or else gives back why it failed with the errors on its nodes.
fn compile_network(&self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<CompiledNetwork, (String, GraphErrors)> {
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)) {
return Err((e.to_string(), Vec::new()));
} }
// We assume only one output // We assume only one output
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled"); assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {}; let c = Compiler {};
let compiled_network = match c.compile_single(scoped_network) { let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
Ok(compiled_network) => compiled_network, Ok(compiled_network) => compiled_network,
Err(CompileError::Graph(errors)) => return Err((format!("{errors:?}"), errors)), Err(CompileError::Graph(errors)) => {
Err(CompileError::Message(message)) => return Err((message, Vec::new())), let message = format!("{errors:?}");
self.node_graph_errors = errors;
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
}
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
}; };
self.node_graph_warnings = warnings;
assert_ne!(compiled_network.network.nodes.len(), 0, "No proto nodes exist?"); assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
Ok(compiled_network) let updated = self.executor.update(proto_network).map(|(output, types)| {
self.output = output;
types
});
let result = updated.map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
});
self.async_runtime().update_sources(self.executor.sources());
result
} }
/// The errors of an evaluation of the `output` node, each traced through the nodes it passed. fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
fn resolve_errors(&self, output: NodeId, error: &NodeError) -> EvaluationErrors {
let source_map = self.executor.tree().source_map(); let source_map = self.executor.tree().source_map();
let paths = |node: NodeId| -> NodePaths { let paths = |node: NodeId| -> NodePaths {
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect(); let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
@@ -724,6 +564,7 @@ impl NodeRuntime {
paths.into() paths.into()
}; };
let mut errors = Vec::new(); let mut errors = Vec::new();
let output = self.output.node();
let mut pending = vec![(vec![paths(output)], output, error)]; let mut pending = vec![(vec![paths(output)], output, error)];
while let Some((mut trace, node, error)) = pending.pop() { while let Some((mut trace, node, error)) = pending.pop() {
let passed = self.executor.trace_error(node, error); let passed = self.executor.trace_error(node, error);
@@ -745,7 +586,7 @@ impl NodeRuntime {
} }
impl ExecutionResult { impl ExecutionResult {
pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> { fn render_output(&mut self) -> Option<&mut RenderOutput> {
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else { let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
return None; return None;
}; };
@@ -754,54 +595,6 @@ impl ExecutionResult {
} }
} }
/// The area an export of the copied layers' content shows, unless it's endless, like a lone noise pattern, while a fractal's is the body a thumbnail shows.
fn exported_bounds(content: graphene_std::registry::Any) -> Option<[DVec2; 2]> {
let bounds = match content.downcast_ref::<List<Graphic>>() {
Some(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
None => artboard_clip_bounds(content.downcast_ref::<List<Artboard>>()?),
};
match bounds {
RenderBoundingBox::Rectangle([min, max]) if min.is_finite() && max.is_finite() => Some([min, max]),
_ => None,
}
}
/// The SVG with its frame narrowed from the whole pixels its render `covered` to the content's exact `size`.
fn with_frame_size(svg: String, covered: DVec2, size: DVec2) -> String {
let frame = |size: DVec2| format!(r#"viewBox="0 0 {} {}" width="{}" height="{}""#, size.x, size.y, size.x, size.y);
svg.replacen(&frame(covered), &frame(size), 1)
}
/// The union of the artboards' clipping rectangles, which frames what's visible of them better than their unclipped content does.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
None => bounds,
});
}
match combined {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// The text of an SVG render's output.
fn svg_text(value: TaggedValue) -> Result<Option<String>, String> {
match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Ok(Some(svg)),
_ => Err("The render gave no SVG".to_string()),
}
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> { fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll { match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output), Poll::Final(output) | Poll::Partial(output) => Some(output),
@@ -1240,232 +1033,6 @@ mod tests {
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}"); assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
} }
#[tokio::test]
async fn an_svg_export_of_a_generator_settles_once_its_image_is_read_back() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use graphene_std::raster::Image;
use graphene_std::raster::color::Color;
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead, over a rectangle framing the export
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 64., 64.).await;
editor.create_raster_image(Image::new(1, 1, Color::BLACK), None).await;
let layer = editor.get_selected_layer().await.expect("the pasted image should be selected").to_node();
let mandelbrot = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(mandelbrot),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
xy: None,
add_transaction: true,
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(mandelbrot),
input_connector: InputConnector::node_at_index(layer, 1),
});
editor.eval_graph_until_finished().await.expect("the graph evaluates");
// The evaluation the readback wakes draws the same placeholders again, so the image it read back fills them and the export finishes
send_export(&mut editor, FileType::Svg);
let mut saved = None;
for _ in 0..100 {
editor.runtime.update();
editor.runtime.run().await;
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
_ => None,
});
if saved.is_some() {
break;
}
}
let Some(saved) = saved else { panic!("the export never finished") };
let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text");
assert!(
svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"),
"the fractal's image should fill its placeholder: {svg}"
);
}
/// Lets the runtime handle what's queued until the clipboard is written, giving back the SVG written with the copied layers, if any.
async fn clipboard_svg_once_written(editor: &mut EditorTestUtils, mut messages: Vec<FrontendMessage>) -> Option<String> {
use crate::messages::portfolio::ingest::utility_types::TransferData;
for _ in 0..1000 {
let written = messages.iter().find_map(|message| match message {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
});
if let Some(content) = written {
return content.0.iter().find_map(|item| match &item.data {
TransferData::Svg(svg) => Some(svg.clone()),
_ => None,
});
}
editor.runtime.update();
editor.runtime.run().await;
messages = editor.dispatch(Message::Wake);
}
panic!("the clipboard was never written");
}
#[tokio::test]
async fn a_cut_waits_through_document_updates_for_its_outstanding_tasks_then_writes_once() {
use crate::messages::portfolio::ingest::utility_types::TransferData;
/// Runs each task at once, or holds it while `holding` until the test runs it.
#[derive(Default)]
struct HeldTasks {
holding: AtomicBool,
held: std::sync::Mutex<Vec<Task>>,
}
impl Spawn for HeldTasks {
fn spawn(&self, task: Task) {
match self.holding.load(Ordering::Relaxed) {
true => self.held.lock().unwrap().push(task),
false => futures::executor::block_on(task),
}
}
}
let svgs_written = |messages: &[FrontendMessage]| -> Vec<String> {
let written = messages.iter().filter_map(|message| match message {
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
_ => None,
});
let svgs = written.flat_map(|content| &content.0).filter_map(|item| match &item.data {
TransferData::Svg(svg) => Some(svg.clone()),
_ => None,
});
svgs.collect()
};
let tasks = Arc::new(HeldTasks::default());
let mut editor = EditorTestUtils::create();
editor.runtime.replace_task_executor(tasks.clone(), Arc::new(|| {}));
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
// The traced layer's tasks are held from the start, so it's still unfinished when it's cut
tasks.holding.store(true, Ordering::Relaxed);
add_traced_noise_layer(&mut editor).await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
assert!(!tasks.held.lock().unwrap().is_empty(), "the layer should have tasks out");
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] });
let mut messages = editor.dispatch(ClipboardMessage::CutLayers);
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
// Document updates after the cut leave the copy's network alone, outliving the executor's grace for orphaned nodes
for _ in 0..3 {
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
}
assert!(svgs_written(&messages).is_empty(), "nothing should be written while the tasks are out");
assert!(editor.runtime.pending_clipboard.is_some(), "the copy should hold its network");
// Released, the tasks land and the trace runs to its end
tasks.holding.store(false, Ordering::Relaxed);
let held = std::mem::take(&mut *tasks.held.lock().unwrap());
held.into_iter().for_each(futures::executor::block_on);
for _ in 0..1000 {
editor.runtime.update();
editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
}
let svgs = svgs_written(&messages);
assert_eq!(svgs.len(), 1, "the SVG should be written once");
assert!(svgs[0].contains("<path"), "the SVG should hold the traced shapes: {}", svgs[0]);
assert!(editor.runtime.pending_clipboard.is_none(), "the copy should let its network go");
}
// The copy's network is compiled ahead of the edit sent with it, so the edit's node is compiled before the document's update reaches it
#[tokio::test]
async fn the_types_of_an_edit_sent_with_a_copy_reach_the_editor() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use graphene_std::blending_nodes::effects::drop_shadow;
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let shadow_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
editor.dispatch(NodeGraphMessage::CreateNodeInLayerWithTransaction {
node_type: shadow_type.clone(),
layer,
});
let interface = &editor.active_document().network_interface;
let shadow = interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| interface.reference(node_id, &[]) == Some(shadow_type.clone()));
let shadow = shadow.expect("the shadow should be added");
send_update(&mut editor);
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
clipboard_svg_once_written(&mut editor, messages).await.expect("the layer should render an SVG");
let types = &editor.active_document().network_interface.resolved_types.types;
assert!(types.keys().any(|path| path.first() == Some(&shadow)), "the shadow's types should reach the editor");
}
// The edit, the copy, and the cut taking the edited layer away all reach the runtime in one queue
#[tokio::test]
async fn a_copy_renders_the_document_as_it_was_when_copied() {
use graphene_std::raster::color::Color;
let mut editor = editor().await;
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(GraphOperationMessage::FillColorSet { layer, color: Some(Color::RED) });
send_update(&mut editor);
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
let mut messages = editor.dispatch(ClipboardMessage::CopyLayers);
messages.extend(editor.dispatch(ClipboardMessage::CutLayers));
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the cut layer should render an SVG");
assert!(svg.to_lowercase().contains("#ff0000"), "the SVG should show the edited fill: {svg}");
}
#[tokio::test]
async fn a_copy_renders_while_another_layer_fails_to_compile() {
let mut editor = editor().await;
editor.draw_rect(200., 0., 300., 100.).await;
let copied = editor.active_document().metadata().all_layers().nth(1).expect("the first rectangle drawn").to_node();
// The top layer fails to compile
break_compile(&mut editor);
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
assert!(editor.runtime.compile_failed, "the document should fail to compile");
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![copied] });
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the copied layer should render an SVG");
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
}
#[tokio::test] #[tokio::test]
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() { async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
let mut editor = editor().await; let mut editor = editor().await;
@@ -1,4 +1,4 @@
use super::{artboard_clip_bounds, evaluated_output}; use super::evaluated_output;
use crate::messages::frontend::FrontendMessage; use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout; use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
@@ -12,8 +12,8 @@ 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; use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::transform::Footprint; use graphene_std::transform::{Footprint, RenderQuality};
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;
@@ -276,11 +276,11 @@ impl ThumbnailContent {
} }
} }
/// The area the content covers once rendered. /// 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.
fn content_bounds(&self) -> RenderBoundingBox { fn content_bounds(&self, maps_resolved: bool) -> 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), Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
// 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 +289,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() { let bounds = match self.content_bounds(true) {
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,6 +297,38 @@ 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. /// 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> { fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?; let source = layer_content(layer_path, network)?.source(network)?;
@@ -329,6 +361,25 @@ fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
None None
} }
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
None => bounds,
});
}
match combined {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis /// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
/// so the input's extent is always preserved. /// so the input's extent is always preserved.
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] { fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
@@ -347,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id}; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use glam::UVec2; use glam::UVec2;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
@@ -378,8 +430,20 @@ mod tests {
editor.draw_rect(0., 0., 10., 10.).await; editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node(); let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
// The node adding Merge's content to the stack
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
panic!("Merge should be a network node")
};
let Some((&extend_id, _)) = merge_network
.nodes
.iter()
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
else {
panic!("Merge should extend the stack with its content")
};
compile_and_run(&mut editor).await; compile_and_run(&mut editor).await;
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]); let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
assert!(merge_content.is_some(), "The Merge layer's content should be compiled"); assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
assert_eq!( assert_eq!(
editor.runtime.thumbnails.sources.get(&layer).copied(), editor.runtime.thumbnails.sources.get(&layer).copied(),
@@ -63,6 +63,7 @@ pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout,
let render_params = RenderParams { let render_params = RenderParams {
footprint: Footprint::BOUNDLESS, footprint: Footprint::BOUNDLESS,
render_output_type: RenderOutputType::Vello, render_output_type: RenderOutputType::Vello,
thumbnail: true,
..Default::default() ..Default::default()
}; };
let cell_size = layout.cell_size.as_dvec2(); let cell_size = layout.cell_size.as_dvec2();
+9 -20
View File
@@ -117,17 +117,10 @@ impl EditorTestUtils {
panic!("Failed to evaluate graph: {e}"); panic!("Failed to evaluate graph: {e}");
} }
// The copied layers' SVG waits for the readbacks of the GPU images it holds, each landing before a later run
let mut frontend_messages = self.dispatch(message); let mut frontend_messages = self.dispatch(message);
for _ in 0..100 { self.runtime.update();
self.runtime.update(); self.runtime.run().await;
self.runtime.run().await; frontend_messages.extend(self.dispatch(Message::Wake));
frontend_messages.extend(self.dispatch(Message::Wake));
if frontend_messages.iter().any(|message| matches!(message, FrontendMessage::TriggerClipboardWrite { .. })) {
break;
}
}
frontend_messages frontend_messages
.into_iter() .into_iter()
@@ -527,18 +520,14 @@ fn init_test_logger() {
}); });
} }
/// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow. /// 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.
/// 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.
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());
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).",
)
}
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
fn gpu_application_io() -> PlatformApplicationIo { fn gpu_application_io() -> PlatformApplicationIo {
PlatformApplicationIo::new_with_executor(gpu_executor()) 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(
"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)
} }
/// Runs `operation`, returning its result along with the errors it logged. /// Runs `operation`, returning its result along with the errors it logged.
@@ -2,8 +2,6 @@
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";
@@ -25,15 +23,7 @@
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
@@ -46,8 +36,6 @@
}); });
onDestroy(() => { onDestroy(() => {
destroyDragToggleManager(dragToggleListener);
removeEventListener("pointermove", draggingPointerMove); removeEventListener("pointermove", draggingPointerMove);
removeEventListener("pointerup", draggingPointerUp); removeEventListener("pointerup", draggingPointerUp);
removeEventListener("pointercancel", abortDrag); removeEventListener("pointercancel", abortDrag);
@@ -331,7 +331,6 @@
} }
const dragToggleListener: DragToggleListener = { const dragToggleListener: DragToggleListener = {
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
activeGroupChanged: (group) => { activeGroupChanged: (group) => {
activeDragToggleGroup = group; activeDragToggleGroup = group;
}, },
@@ -343,15 +342,6 @@
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);
} }
@@ -1204,7 +1194,6 @@
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)}
> >
@@ -1354,8 +1343,6 @@
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}
@@ -1372,17 +1359,12 @@
: 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}
@@ -1413,15 +1395,10 @@
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);
@@ -538,6 +538,30 @@
</div> </div>
{/if} {/if}
<!-- Click target debug visualizations -->
{#if $nodeGraph.clickTargets}
<div class="click-targets" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
<svg>
{#each $nodeGraph.clickTargets.nodeClickTargets as pathString}
<path class="node" d={pathString} />
{/each}
{#each $nodeGraph.clickTargets.layerClickTargets as pathString}
<path class="layer" d={pathString} />
{/each}
{#each $nodeGraph.clickTargets.connectorClickTargets as pathString}
<path class="connector" d={pathString} />
{/each}
{#each $nodeGraph.clickTargets.iconClickTargets as pathString}
<path class="visibility" d={pathString} />
{/each}
<path class="all-nodes-bounding-box" d={$nodeGraph.clickTargets.allNodesBoundingBox} />
{#each $nodeGraph.clickTargets.importExportNames as pathString}
<path class="import-export-name" d={pathString} />
{/each}
</svg>
</div>
{/if}
<!-- Thick vertical layer connection wires --> <!-- Thick vertical layer connection wires -->
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}> <div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
<svg> <svg>
@@ -1287,6 +1311,46 @@
} }
} }
.click-targets {
position: absolute;
pointer-events: none;
width: 100%;
height: 100%;
z-index: 10;
svg {
overflow: visible;
width: 100%;
height: 100%;
stroke-width: 1;
fill: none;
.layer {
stroke: yellow;
}
.node {
stroke: blue;
}
.connector {
stroke: green;
}
.visibility {
stroke: red;
}
.all-nodes-bounding-box {
stroke: purple;
}
.import-export-name {
stroke: orange;
}
}
}
.wires { .wires {
pointer-events: none; pointer-events: none;
position: absolute; position: absolute;
@@ -41,12 +41,6 @@
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 -->
@@ -82,16 +76,7 @@
{/if} {/if}
{/each} {/each}
{:else} {:else}
<button <button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
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)"}
@@ -558,10 +543,9 @@
margin-left: 8px; margin-left: 8px;
} }
// A label with no expose button before it lines up with the parameter names that follow one // A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:first-child { > .text-label:only-child {
margin-left: calc(20px + 8px + 8px); margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
} }
> .separator.horizontal.unrelated { > .separator.horizontal.unrelated {
@@ -140,9 +140,7 @@
const reorder = allowReorder && allowSelect; const reorder = allowReorder && allowSelect;
let held = position; let held = position;
if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) { if (!reorder && !allowWrap) {
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));
@@ -158,33 +156,6 @@
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) {
@@ -686,10 +657,7 @@
} }
$: 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);
// 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);
$: 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);
+2
View File
@@ -191,6 +191,7 @@ import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gr
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg"; import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg"; import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg"; import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
import NodeFootprintValue from "/../branding/assets/16x16-nodes/node-footprint-value.svg";
import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg"; import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg";
import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg"; import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg";
import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg"; import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg";
@@ -484,6 +485,7 @@ export const ICON_16X16_NODES = {
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 }, NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 }, NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
NodeFloor: { svg: NodeFloor, size: 16 }, NodeFloor: { svg: NodeFloor, size: 16 },
NodeFootprintValue: { svg: NodeFootprintValue, size: 16 },
NodeFormatJson: { svg: NodeFormatJson, size: 16 }, NodeFormatJson: { svg: NodeFormatJson, size: 16 },
NodeFormatNumber: { svg: NodeFormatNumber, size: 16 }, NodeFormatNumber: { svg: NodeFormatNumber, size: 16 },
NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 }, NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 },
+21 -77
View File
@@ -8,30 +8,21 @@
// 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);
@@ -47,13 +38,12 @@ 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 && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false); if (engaged) 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
@@ -64,120 +54,83 @@ 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 listenersOfGroup(group: string): DragToggleListener[] {
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
}
function notifyActiveGroupChange(group: string | undefined) { function notifyActiveGroupChange(group: string | undefined) {
const previousGroup = activeGroup;
activeGroup = group; activeGroup = group;
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
const notifiedGroup = group || previousGroup;
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
} }
function groupAttribute(middleButton: boolean): string { function findMember(target: EventTarget | undefined): HTMLElement | undefined {
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(`[${groupAttribute(middleButton)}]`); const found = target.closest("[data-drag-toggle-group]");
return found instanceof HTMLElement ? found : undefined; return found instanceof HTMLElement ? found : undefined;
} }
function memberState(member: HTMLElement): string | undefined {
return member.getAttribute("data-drag-toggle-state") || 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) { function onPointerDown(e: PointerEvent) {
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return; if (e.button !== 0) return;
suppressNextClickFromSource = undefined; suppressNextClickFromSource = undefined;
suppressNextAuxClick = false;
const middleButton = e.button === MIDDLE_BUTTON; const found = findMember(e.target || undefined);
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 = memberState(found); startingState = found.getAttribute("data-drag-toggle-state") || undefined;
visited = new WeakSet(); visited = new WeakSet();
engaged = false; engaged = false;
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined); notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || 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, middleButtonGesture); const member = findMember(e.target || undefined);
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return; if (!member || member.getAttribute("data-drag-toggle-group") !== 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) engage(); if (!engaged) {
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 (memberState(member) !== startingState) return; if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
visited.add(member); visited.add(member);
toggle(member); member.click();
} }
function onPointerUp(e: Event) { function onPointerUp(e: Event) {
if (!activeGroup) return; if (!activeGroup) return;
const endedGroup = activeGroup;
// An engaged drag already toggled the source, so its release's click won't toggle it again // An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
if (engaged && source && e.type === "pointerup") { if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
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) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false)); if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
} }
function onClickCapture(e: Event) { function onClickCapture(e: Event) {
@@ -188,15 +141,6 @@ 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);
+11 -1
View File
@@ -3,7 +3,7 @@ import type { Writable } from "svelte/store";
import type { IconName } from "/src/icons"; import type { IconName } from "/src/icons";
import type { SubscriptionsRouter } from "/src/subscriptions-router"; import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageBody } from "/src/subscriptions-router"; import type { MessageBody } from "/src/subscriptions-router";
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper"; import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>; export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
@@ -13,6 +13,7 @@ export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId
type NodeGraphStoreState = { type NodeGraphStoreState = {
box: BoxSelection | undefined; box: BoxSelection | undefined;
clickTargets: FrontendClickTargets | undefined;
contextMenuInformation: ContextMenuInformation | undefined; contextMenuInformation: ContextMenuInformation | undefined;
errors: NodeGraphErrorDiagnostic[]; errors: NodeGraphErrorDiagnostic[];
layerWidths: Map<bigint, number>; layerWidths: Map<bigint, number>;
@@ -35,6 +36,7 @@ type NodeGraphStoreState = {
}; };
const initialState: NodeGraphStoreState = { const initialState: NodeGraphStoreState = {
box: undefined, box: undefined,
clickTargets: undefined,
contextMenuInformation: undefined, contextMenuInformation: undefined,
errors: [], errors: [],
layerWidths: new Map(), layerWidths: new Map(),
@@ -134,6 +136,13 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
}); });
}); });
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
update((state) => {
state.clickTargets = data.clickTargets;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => { subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
update((state) => { update((state) => {
state.contextMenuInformation = data.contextMenuInformation; state.contextMenuInformation = data.contextMenuInformation;
@@ -321,6 +330,7 @@ export function destroyNodeGraphStore() {
subscriptions.unsubscribeFrontendMessage("SendUIMetadata"); subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
subscriptions.unsubscribeFrontendMessage("UpdateBox"); subscriptions.unsubscribeFrontendMessage("UpdateBox");
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation"); subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex"); subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex"); subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
+16 -63
View File
@@ -1,8 +1,8 @@
use super::mover::Mover; use super::mover::Mover;
use crate::graph::LAYER_BOTTOM_GAP;
use crate::per_node::PerNode; use crate::per_node::PerNode;
use crate::{NodeIndex, Placement}; use crate::{NodeIndex, Placement};
use glam::IVec2; use glam::IVec2;
use std::mem;
pub(super) struct Snapshot { pub(super) struct Snapshot {
placements: PerNode<Placement>, placements: PerNode<Placement>,
@@ -16,85 +16,38 @@ impl Mover {
Snapshot { placements, positions } Snapshot { placements, positions }
} }
pub(super) fn restore_followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) { pub(super) fn restore_followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) {
let followers = self.followers(before, kept); let followers = self.followers(before, moved);
let mut pushed = PerNode::filled(&self.graph, None); let mut restored = PerNode::filled(&self.graph, false);
for node in followers.indices().filter(|node| followers[*node]) { followers
self.restore_follower(node, &followers, &before.positions, &mut pushed); .indices()
} .filter(|node| followers[*node])
.for_each(|node| self.restore_follower(node, &followers, &before.positions, &mut restored));
} }
fn followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) -> PerNode<bool> { fn followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) -> PerNode<bool> {
let (graph, layout) = self.graph_and_layout(); let (graph, layout) = self.graph_and_layout();
PerNode::from_fn(graph, |node| { PerNode::from_fn(graph, |node| {
let placement = graph[node].placement; let placement = graph[node].placement;
let unchanged = placement == before.placements[node]; let unchanged = placement == before.placements[node];
let was_relative = matches!(before.placements[node], Placement::Relative(_)); let was_relative = matches!(before.placements[node], Placement::Relative(_));
let is_relative = matches!(placement, Placement::Relative(_)); let is_relative = matches!(placement, Placement::Relative(_));
kept[node] && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node] !moved.contains(&node) && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
}) })
} }
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, pushed: &mut PerNode<Option<IVec2>>) -> IVec2 { fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, restored: &mut PerNode<bool>) {
if let Some(push) = pushed[node] { if mem::replace(&mut restored[node], true) {
return push; return;
} }
pushed[node] = Some(IVec2::ZERO);
let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect(); let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect();
let pushed_by_readers = following_readers for reader in following_readers {
.into_iter() self.restore_follower(reader, followers, positions_before, restored);
.map(|reader| self.restore_follower(reader, followers, positions_before, pushed))
.fold(IVec2::ZERO, IVec2::max);
let shift = positions_before[node] + pushed_by_readers - self.position(node);
let shifted = self.graph[node].placement.shifted(shift);
let clear = self.clear_of_the_layer_above(node, shifted);
self.set_placement(node, clear);
let push = pushed_by_readers + clear.stored_offset() - shifted.stored_offset();
pushed[node] = Some(push);
push
}
pub(super) fn carry_along(&mut self, before: &Snapshot, carried: &PerNode<bool>) {
let mut shifts = PerNode::filled(&self.graph, None);
for node in carried.indices().filter(|node| carried[*node]) {
self.carry(node, carried, &before.positions, &mut shifts);
}
}
fn carry(&mut self, node: NodeIndex, carried: &PerNode<bool>, positions_before: &PerNode<IVec2>, shifts: &mut PerNode<Option<IVec2>>) -> IVec2 {
if let Some(shift) = shifts[node] {
return shift;
}
shifts[node] = Some(IVec2::ZERO);
let readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).collect();
let mut shift = IVec2::ZERO;
for reader in readers {
shift = if carried[reader] {
self.carry(reader, carried, positions_before, shifts)
} else {
self.position(reader) - positions_before[reader]
};
if shift != IVec2::ZERO {
break;
}
} }
let shift = positions_before[node] - self.position(node);
let shifted = self.graph[node].placement.shifted(shift); let shifted = self.graph[node].placement.shifted(shift);
self.set_placement(node, shifted); self.set_placement(node, shifted);
shifts[node] = Some(shift);
shift
}
fn clear_of_the_layer_above(&self, node: NodeIndex, placement: Placement) -> Placement {
let Placement::Relative(offset) = placement else { return placement };
let layer_above = self.readers.of(&self.graph, node).find(|wire| self.graph.feeds_stack(wire)).map(|wire| wire.target);
let Some(layer_above) = layer_above.filter(|_| offset.x == 0) else { return placement };
let lowest_free_row = self.graph[layer_above].size.y + LAYER_BOTTOM_GAP;
Placement::Relative(IVec2::new(0, offset.y.max(lowest_free_row)))
} }
} }
-60
View File
@@ -1,60 +0,0 @@
use crate::connections::WiresByNode;
use crate::per_node::PerNode;
use crate::{Graph, NodeIndex, Placement, Wire};
use glam::IVec2;
use std::mem;
#[derive(Clone, Debug)]
pub(super) struct UpstreamOfDragged {
moving_up_or_down: Upstream,
moving_sideways: Upstream,
}
#[derive(Clone, Debug)]
pub(super) struct Upstream {
pub(super) kept: PerNode<bool>,
pub(super) carried: PerNode<bool>,
}
impl UpstreamOfDragged {
pub(super) fn new(graph: &Graph, dragged: &[NodeIndex]) -> Self {
let inputs = WiresByNode::inputs(graph);
let everything = upstream_through(graph, &inputs, dragged, |_| true);
let into_a_node = |wire: &Wire| !graph[wire.target].is_layer();
let split = |kept: PerNode<bool>| {
let carried = PerNode::from_fn(graph, |node| everything[node] && !kept[node] && matches!(graph[node].placement, Placement::Absolute(_)));
Upstream { kept, carried }
};
Self {
moving_up_or_down: split(upstream_through(graph, &inputs, dragged, |wire| into_a_node(wire) || graph.feeds_stack(wire))),
moving_sideways: split(upstream_through(graph, &inputs, dragged, into_a_node)),
}
}
pub(super) fn moving_by(&self, shift: IVec2) -> &Upstream {
if shift.x == 0 { &self.moving_up_or_down } else { &self.moving_sideways }
}
}
fn upstream_through(graph: &Graph, inputs: &WiresByNode, dragged: &[NodeIndex], followed: impl Fn(&Wire) -> bool) -> PerNode<bool> {
let mut upstream = PerNode::filled(graph, false);
for node in dragged {
upstream[*node] = true;
}
dragged
.iter()
.flat_map(|node| inputs.of(graph, *node))
.filter(|wire| followed(wire))
.for_each(|wire| mark_upstream(graph, inputs, wire.source, &mut upstream));
for node in dragged {
upstream[*node] = false;
}
upstream
}
fn mark_upstream(graph: &Graph, inputs: &WiresByNode, node: NodeIndex, upstream: &mut PerNode<bool>) {
if mem::replace(&mut upstream[node], true) {
return;
}
inputs.of(graph, node).for_each(|wire| mark_upstream(graph, inputs, wire.source, upstream));
}
+4 -9
View File
@@ -1,12 +1,10 @@
mod followers; mod followers;
mod kept;
mod mover; mod mover;
mod shift; mod shift;
mod stack; mod stack;
use crate::{Graph, Layout, NodeIndex, Placement}; use crate::{Graph, Layout, NodeIndex, Placement};
use glam::IVec2; use glam::IVec2;
use kept::UpstreamOfDragged;
use mover::Mover; use mover::Mover;
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone. /// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
@@ -14,7 +12,7 @@ use mover::Mover;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Drag { pub struct Drag {
dragged: Vec<NodeIndex>, dragged: Vec<NodeIndex>,
upstream: Option<UpstreamOfDragged>, keep_upstream: bool,
rows_up: Vec<Graph>, rows_up: Vec<Graph>,
held_in_place: Vec<HeldInPlace>, held_in_place: Vec<HeldInPlace>,
} }
@@ -28,11 +26,8 @@ struct HeldInPlace {
impl Drag { impl Drag {
/// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn. /// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn.
/// Dragged layers still carry their content and chain, and carry the stacks below them when moved sideways.
/// Nodes starting a tree of their own upstream of what moves follow the nodes reading them.
#[must_use] #[must_use]
pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self { pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self {
let upstream = keep_upstream.then(|| UpstreamOfDragged::new(&start, &dragged));
let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect(); let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect();
let mut mover = Mover::new(start, Some(start_layout)); let mut mover = Mover::new(start, Some(start_layout));
mover.hold(&dragged); mover.hold(&dragged);
@@ -50,7 +45,7 @@ impl Drag {
.collect(); .collect();
Self { Self {
dragged, dragged,
upstream, keep_upstream,
rows_up: vec![held], rows_up: vec![held],
held_in_place, held_in_place,
} }
@@ -79,7 +74,7 @@ impl Drag {
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)] [IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
.into_iter() .into_iter()
.filter(|shift| *shift != IVec2::ZERO) .filter(|shift| *shift != IVec2::ZERO)
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.upstream.as_ref().map(|upstream| upstream.moving_by(shift)))); .for_each(|shift| mover.shift_step(&self.dragged, shift, self.keep_upstream));
mover.into_graph_and_layout() mover.into_graph_and_layout()
} }
@@ -94,7 +89,7 @@ impl Drag {
fn one_row_further_up(&self) -> Graph { fn one_row_further_up(&self) -> Graph {
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default(); let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
let mut mover = Mover::new(highest_so_far, None); let mut mover = Mover::new(highest_so_far, None);
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.upstream.as_ref().map(|upstream| upstream.moving_by(IVec2::NEG_Y))); mover.shift_step(&self.dragged, IVec2::NEG_Y, self.keep_upstream);
mover.into_graph() mover.into_graph()
} }
} }
Loaded 100 of 263 files, more files were not shown because too many files have changed in this diff. Show more