Compare commits

...
20 Commits
Author SHA1 Message Date
Keavon Chambers f2e2c7abcd Add curvature dials to gradients, rendered as a pencil of circles on Vello GPU 2026-11-17 22:53:49 -08:00
Keavon Chambers f6804d9443 Add a Bevel & Emboss effect lighting the inner, outer, emboss, and pillow slopes 2026-11-17 22:53:49 -08:00
Keavon Chambers 5471774764 Add Inner Glow, Satin, and Outline effects to any graphic 2026-11-17 22:53:49 -08:00
Keavon Chambers f1ca7e7ab2 Replace Color Overlay with a Paint Overlay effect that paints with any graphic 2026-11-17 22:53:49 -08:00
Keavon Chambers 07ddc86fc2 Move rendering of the 'Noise Pattern' and 'Mandelbrot' generators to the GPU 2026-11-17 22:53:49 -08:00
Keavon Chambers 3134753d07 Add a Generator graphic type that renderers draw at the resolution they need 2026-11-17 22:53:49 -08:00
Keavon Chambers cece2e9957 Speed up leading adjustments by folding them into textures and solid paints 2026-11-17 22:53:49 -08:00
Keavon Chambers 620f8d992b Allow adjustments on any graphic, carried out where they're read 2026-11-17 22:53:49 -08:00
Keavon Chambers db2d8625a6 Add Blur, Drop Shadow, Inner Shadow, and Outer Glow effects to any graphic 2026-11-17 22:53:49 -08:00
Keavon Chambers c6686a65c3 Move the adjustment and generator kernels into a raster-kernels crate (#4975)
* Move the adjustment and generator kernels into a raster-kernels crate

* Address review findings on the LUT parse cache
2026-11-17 22:53:38 -08:00
Keavon Chambers 455008de2e Fix false positives in the migration API check and scaffolder (#4974) 2026-11-18 04:19:17 +00:00
Keavon ChambersandDennis Kobert 48cf345355 Make document migrations position the nodes they add beside the node they replace (#4959)
* Let document migrations write attributes of the anchor and the nodes they add

* Fix mismatched timestamps when document migrations restart history

* Fix the Data panel showing internal attributes in single-item tables

* Place the nodes document migrations add beside the node they replace by default

* Address review findings on migration node placement

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-17 20:05:34 -08:00
Timon a102519e39 Leave history-only resources out of saves without history (#4970) 2026-11-17 21:45:39 +00:00
Timon 508d67f5b3 Allow the CI '!build' command to build several targets at once (#4965)
* Fix the !build PR command rejecting combined targets and bare platforms

* Make the Flatpak build optional in the Linux CI build
2026-11-17 17:19:14 +00:00
Dennis Kobert fd9da9d56c Move layer discovery from graphene-cli into the document crates (#4973) 2026-11-17 17:15:33 +00:00
Keavon Chambers 4b62b39c74 Fix CLI exports failing or misframing artwork with 'Merge' and 'Artboard' (#4969)
* Fix CLI exports failing or misframing artwork with 'Merge' and 'Artboard'

* Keep the 'Write Layer Path' node's inputs unchanged
2026-11-17 05:13:47 -08:00
Keavon Chambers b822b64e96 Move layer path writing out of the 'Merge' and 'Artboard' networks and into the editor (#4964)
* Move layer path stamping out of 'Merge' and 'Artboard' to cover any node shown as a layer

* Fix layer path stamping panicking on an 'Extend' node shown as a layer

* Rename layer path stamping to writing
2026-11-16 21:29:48 +00:00
Timon 617ce90276 Add support for loading custom font files from the font dropdown, by button or drag-and-drop (#4963)
* Implement basic custom font support

* Keep custom fonts out of the dropdown

* Take a font file dropped on the Inspector's font dropdown
2026-11-16 16:44:55 +00:00
Keavon Chambers 7b2715146c Remove the obsolete 'Monitor' node and its supporting infrastructure (#4962)
* Remove the obsolete 'Monitor' node and its supporting infrastructure

* Make the 'Merge' and 'Artboard' migration test check the rebuilt network
2026-11-15 23:59:57 +00:00
Keavon ChambersandDennis Kobert cf1f7dec80 Make 'Path' a single node instead of a subgraph holding a 'Monitor' node (#4958)
* Let migrations add reflection inputs

* Make 'Path' a single node instead of a subgraph holding a 'Monitor'

* Restore regression coverage for subgraph input narrowing through 'Memoize'

* Observe the content input of 'Path' nodes instead of special-casing them in the runtime

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-15 22:04:48 +00:00
195 changed files with 16982 additions and 3328 deletions

No files matched your search

+10 -2
View File
@@ -20,6 +20,9 @@ on:
linux:
description: "Linux"
type: boolean
flatpak:
description: "Flatpak (with the Linux build)"
type: boolean
debug:
description: "Debug build"
type: boolean
@@ -33,6 +36,8 @@ on:
type: boolean
linux:
type: boolean
flatpak:
type: boolean
debug:
type: boolean
checkout_repo:
@@ -815,7 +820,7 @@ jobs:
path: target/artifacts
linux:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux || inputs.flatpak
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
permissions:
contents: read
@@ -892,12 +897,14 @@ jobs:
fi
- name: 🔧 Install Flatpak tooling
if: github.event_name == 'push' || inputs.flatpak
run: |
sudo apt-get update
sudo apt-get install -y flatpak flatpak-builder
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
- name: 🏗 Build Flatpak
if: github.event_name == 'push' || inputs.flatpak
run: |
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
@@ -914,6 +921,7 @@ jobs:
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
- name: 📦 Upload Flatpak package
if: github.event_name == 'push' || inputs.flatpak
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
with:
name: graphite-flatpak
@@ -921,7 +929,7 @@ jobs:
compression-level: 0
- name: 💬 Update PR comment with Flatpak artifact link
if: github.event_name != 'push' && steps.linux-comment.outputs.comment_id
if: inputs.flatpak && steps.linux-comment.outputs.comment_id
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
+48 -41
View File
@@ -1,16 +1,22 @@
# USAGE:
# After reviewing the code, core team members may comment on a PR with `!build` followed by optional `<target>` and `<profile>` arguments.
# This matches the syntax of the `cargo run build` CLI command, but allows platforms to be specified.
# This extends the syntax of the `cargo run build` CLI command, allowing several targets and specific platforms to be built at once.
#
# `<target>`: `web` (default), `desktop` (all platforms), or `desktop:<platforms>` (subset of `windows+mac+linux`)
# `<target>`: any of `web`, `desktop` (all platforms), `desktop:<platforms>`, or a bare platform (`windows`, `mac`, `linux`), joined by spaces or `+` (default: `web`)
# `flatpak` additionally packages the Linux build as a Flatpak, which `desktop` and `linux` leave out
# `<profile>`: `release` (default) or `debug`
#
# Only the comment's first line is parsed, so notes may follow on the lines below it.
#
# Examples:
# - !build
# - !build debug
# - !build desktop
# - !build web desktop
# - !build linux
# - !build linux+flatpak
# - !build desktop:windows+mac
# - !build desktop:linux debug
# - !build web+desktop:linux debug
name: "!build PR Command"
on:
@@ -37,6 +43,7 @@ jobs:
windows: ${{ steps.pr_info.outputs.windows }}
mac: ${{ steps.pr_info.outputs.mac }}
linux: ${{ steps.pr_info.outputs.linux }}
flatpak: ${{ steps.pr_info.outputs.flatpak }}
debug: ${{ steps.pr_info.outputs.debug }}
steps:
@@ -46,8 +53,8 @@ jobs:
# Passed through the environment so the comment text can't inject shell syntax
COMMENT: ${{ github.event.comment.body }}
run: |
# Split into space-separated words
read -ra WORDS <<< "$COMMENT"
# Split the first line into space-separated words (comments posted from the web UI have CRLF line endings)
read -ra WORDS <<< "${COMMENT%%$'\r'*}"
# First word must be "!build"
if [[ "${WORDS[0]}" != "!build" ]]; then
@@ -55,49 +62,47 @@ jobs:
exit 1
fi
# Initialize build flags (web defaults to true, matching the CLI default target)
WEB="true"
# Initialize build flags
WEB="false"
WINDOWS="false"
MAC="false"
LINUX="false"
FLATPAK="false"
DEBUG="false"
PROFILE=""
# Parse target (optional, defaults to `web` if omitted)
IDX=1
case "${WORDS[$IDX]:-}" in
# Target: `web` enables just the web build (already the default, but accepted explicitly)
"web")
((IDX++)) ;;
# Target: `desktop` enables all three desktop platforms
"desktop")
WEB="false"; WINDOWS="true"; MAC="true"; LINUX="true"; ((IDX++)) ;;
# Target: `desktop:<platforms>` enables a subset of desktop platforms, split by `+`
desktop:*)
WEB="false"
PLATFORMS="${WORDS[$IDX]#desktop:}"
IFS='+' read -ra PARTS <<< "$PLATFORMS"
for PART in "${PARTS[@]}"; do
case "$PART" in
"windows") WINDOWS="true" ;;
"mac") MAC="true" ;;
"linux") LINUX="true" ;;
*) echo "::error::Unrecognized platform: $PART"; exit 1 ;;
esac
done
((IDX++))
;;
esac
# Every remaining word is either the profile or a `+`-separated list of targets
for WORD in "${WORDS[@]:1}"; do
case "$WORD" in
"debug" | "release")
if [[ -n "$PROFILE" ]]; then
echo "::error::Profile given more than once: $WORD"
exit 1
fi
PROFILE="$WORD"
if [[ "$WORD" == "debug" ]]; then DEBUG="true"; fi
continue
;;
esac
# Parse profile (optional, defaults to `release` if omitted)
case "${WORDS[$IDX]:-}" in
"debug") DEBUG="true"; ((IDX++)) ;;
"release") ((IDX++)) ;;
esac
IFS='+' read -ra PARTS <<< "$WORD"
for PART in "${PARTS[@]}"; do
# In `desktop:<platforms>`, the prefix only matters on the first platform since the others are split off as bare platforms
case "$PART" in
"web") WEB="true" ;;
"desktop") WINDOWS="true"; MAC="true"; LINUX="true" ;;
"windows" | "desktop:windows") WINDOWS="true" ;;
"mac" | "desktop:mac") MAC="true" ;;
"linux" | "desktop:linux") LINUX="true" ;;
"flatpak" | "desktop:flatpak") LINUX="true"; FLATPAK="true" ;;
*) echo "::error::Unrecognized argument: $PART"; exit 1 ;;
esac
done
done
# Reject any unexpected trailing words
if [[ $IDX -lt ${#WORDS[@]} ]]; then
echo "::error::Unexpected argument: ${WORDS[$IDX]}"
exit 1
# Without any target, build for web to match the CLI default target
if [[ "$WEB$WINDOWS$MAC$LINUX" != *true* ]]; then
WEB="true"
fi
# Write parsed build flags to job outputs
@@ -105,6 +110,7 @@ jobs:
echo "windows=$WINDOWS" >> $GITHUB_OUTPUT
echo "mac=$MAC" >> $GITHUB_OUTPUT
echo "linux=$LINUX" >> $GITHUB_OUTPUT
echo "flatpak=$FLATPAK" >> $GITHUB_OUTPUT
echo "debug=$DEBUG" >> $GITHUB_OUTPUT
# Fetch the PR's head branch and repo (needed for forked PRs where the code lives in another repo)
@@ -139,6 +145,7 @@ jobs:
windows: ${{ needs.setup.outputs.windows == 'true' }}
mac: ${{ needs.setup.outputs.mac == 'true' }}
linux: ${{ needs.setup.outputs.linux == 'true' }}
flatpak: ${{ needs.setup.outputs.flatpak == 'true' }}
debug: ${{ needs.setup.outputs.debug == 'true' }}
checkout_repo: ${{ needs.setup.outputs.repo }}
checkout_ref: ${{ needs.setup.outputs.ref }}
Generated
+31 -7
View File
@@ -588,6 +588,7 @@ dependencies = [
"glam",
"graphic-types",
"node-macro",
"raster-kernels",
"serde",
"vector-types",
]
@@ -2664,6 +2665,7 @@ dependencies = [
"math-nodes",
"node-macro",
"path-bool-nodes",
"raster-kernels",
"raster-nodes",
"rendering",
"repeat-nodes",
@@ -2695,6 +2697,7 @@ dependencies = [
"graphic-types",
"node-macro",
"rand",
"raster-kernels",
"raster-types",
"serde",
"thiserror 2.0.21",
@@ -2710,10 +2713,12 @@ dependencies = [
"dyn-any",
"glam",
"graphene-hash",
"graphene-resource",
"node-macro",
"raster-types",
"serde",
"serde_json",
"tsify",
"vector-types",
"wasm-bindgen",
]
@@ -4161,6 +4166,7 @@ dependencies = [
"math-parser",
"node-macro",
"rand",
"raster-kernels",
"thiserror 2.0.21",
"vector-types",
]
@@ -5719,6 +5725,20 @@ dependencies = [
"rustversion",
]
[[package]]
name = "raster-kernels"
version = "0.0.0"
dependencies = [
"core-types",
"fastnoise-lite",
"glam",
"graphene-resource",
"graphic-types",
"raster-types",
"thiserror 2.0.21",
"vector-types",
]
[[package]]
name = "raster-nodes"
version = "0.0.0"
@@ -5727,18 +5747,16 @@ dependencies = [
"color",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam",
"graphene-core",
"graphene-hash",
"graphene-resource",
"graphic-types",
"image",
"ndarray",
"node-macro",
"num_enum",
"rand",
"rand_chacha",
"raster-kernels",
"raster-types",
"serde",
"thiserror 2.0.21",
@@ -5991,12 +6009,14 @@ dependencies = [
"log",
"num-traits",
"parley",
"raster-kernels",
"serde",
"skrifa",
"text-nodes",
"usvg",
"vector-types",
"vello_gpu",
"wgpu",
]
[[package]]
@@ -7974,6 +7994,7 @@ dependencies = [
"node-macro",
"qrcodegen",
"rand",
"raster-kernels",
"repeat-nodes",
"rustc-hash 2.1.3",
"serde",
@@ -8034,7 +8055,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8049,7 +8070,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8063,7 +8084,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"naga",
"wesl",
@@ -8524,8 +8545,11 @@ dependencies = [
"futures",
"glam",
"graphene-application-io",
"graphic-types",
"half",
"log",
"node-macro",
"raster-kernels",
"raster-types",
"rendering",
"thiserror 2.0.21",
+4 -3
View File
@@ -95,6 +95,7 @@ core-types = { path = "node-graph/libraries/core-types" }
raster-types = { path = "node-graph/libraries/raster-types" }
vector-types = { path = "node-graph/libraries/vector-types" }
graphic-types = { path = "node-graph/libraries/graphic-types" }
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
brush-types = { path = "node-graph/libraries/brush-types" }
rendering = { path = "node-graph/libraries/rendering" }
brush-nodes = { path = "node-graph/nodes/brush" }
@@ -310,6 +311,6 @@ debug = true
[patch.crates-io]
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
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
+2 -2
View File
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
ui_texture: Option<wgpu::Texture>,
bind_group: Option<wgpu::BindGroup>,
#[derivative(Debug = "ignore")]
overlays_scene: Option<VelloSceneBuilder>,
overlays_scene: Option<VelloSceneBuilder<'static>>,
#[derivative(Debug = "ignore")]
overlays_canvas: VelloCanvas,
surface_outdated: bool,
@@ -220,7 +220,7 @@ impl RenderState {
self.viewport_offset = offset;
}
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
self.surface_outdated = true;
self.overlays_scene = Some(scene);
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
PersistenceUpdatePreferences {
preferences: Preferences,
},
+5 -2
View File
@@ -252,16 +252,19 @@ impl<L: Layout> Gdd<L> {
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
let directories = self.working.list_dirs("").await?;
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
if has_directory(self.layout.resources_dir()) {
if flat.is_none() && has_directory(self.layout.resources_dir()) {
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
}
for (hash, resource) in embedded_bytes {
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
}
// A copy without history has no older blobs to use as bases, so each blob is written in full
match &flat {
Some(flat) => {
let named = flat.registry().resources.values().filter_map(|entry| entry.hash);
for hash in named.filter(|hash| working_copy_hashes.contains(hash)) {
entries.insert(self.layout.resource_path(&hash), None);
}
for hash in flat.registry().blob_hashes() {
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
+113
View File
@@ -0,0 +1,113 @@
//! Finds the path of every layer in a runtime network, once for each instance of the networks holding it.
use std::collections::HashSet;
use document_graph_storage::NodeMetadataEntry;
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
/// The path of every node its metadata marks as a layer.
pub fn layer_paths(network: &NodeNetwork, node_metadata: &[NodeMetadataEntry]) -> Vec<Vec<NodeId>> {
let layers: HashSet<(NetworkLocation, NodeId)> = node_metadata.iter().filter(|node| node.is_layer).map(|node| (node.network, node.local_id)).collect();
let mut layer_paths = Vec::new();
for_each_network_instance(network, |network_path, nested| {
let Some(location) = network.locate(network_path) else { return };
let nested_layers = nested.nodes.keys().filter(|node_id| layers.contains(&(location, **node_id)));
layer_paths.extend(nested_layers.map(|node_id| [network_path, &[*node_id]].concat()));
});
layer_paths
}
/// Visits every network with its path, once for each instance of it.
/// A definition is not entered again from inside itself.
pub fn for_each_network_instance(network: &NodeNetwork, mut visit: impl FnMut(&[NodeId], &NodeNetwork)) {
let mut stack = vec![(Vec::new(), Vec::new())];
while let Some((network_path, enclosing_definitions)) = stack.pop() {
let Some(nested) = network.nested_network(&network_path) else { continue };
visit(&network_path, nested);
for (node_id, node) in &nested.nodes {
let mut enclosing_definitions = enclosing_definitions.clone();
match node.implementation {
DocumentNodeImplementation::Definition(id) if enclosing_definitions.contains(&id) => continue,
DocumentNodeImplementation::Definition(id) => enclosing_definitions.push(id),
DocumentNodeImplementation::Network(_) => {}
_ => continue,
}
stack.push(([network_path.as_slice(), &[*node_id]].concat(), enclosing_definitions));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::document::{DocumentNode, NetworkId};
const DEFINITION: NetworkId = NetworkId(9);
fn node_metadata(network: NetworkLocation, local_id: u64, is_layer: bool) -> NodeMetadataEntry {
NodeMetadataEntry {
network,
local_id: NodeId(local_id),
position: None,
is_layer,
display_name: None,
locked: false,
pinned: false,
input_metadata: Vec::new(),
output_names: Vec::new(),
output_descriptions: Vec::new(),
}
}
#[test]
fn a_layer_inside_a_definition_is_found_through_each_instance() {
let instance = DocumentNode {
implementation: DocumentNodeImplementation::Definition(DEFINITION),
..Default::default()
};
let definition = NodeNetwork {
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
..Default::default()
};
let network = NodeNetwork {
nodes: [1, 2].map(|id| (NodeId(id), instance.clone())).into_iter().collect(),
definitions: [(DEFINITION, definition)].into_iter().collect(),
..Default::default()
};
let metadata = [(None, 1, true), (None, 2, false), (Some(DEFINITION), 3, true), (Some(DEFINITION), 4, false)];
let metadata: Vec<_> = metadata.into_iter().map(|(location, local_id, is_layer)| node_metadata(location, local_id, is_layer)).collect();
let mut layer_paths = layer_paths(&network, &metadata);
layer_paths.sort();
assert_eq!(layer_paths, vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]]);
}
#[test]
fn a_definition_holding_itself_is_entered_once() {
let recursive = DocumentNode {
implementation: DocumentNodeImplementation::Definition(DEFINITION),
..Default::default()
};
let network = NodeNetwork {
nodes: [(NodeId(1), recursive.clone())].into_iter().collect(),
definitions: [(
DEFINITION,
NodeNetwork {
nodes: [(NodeId(2), recursive)].into_iter().collect(),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let mut network_paths = Vec::new();
for_each_network_instance(&network, |network_path, _| network_paths.push(network_path.to_vec()));
assert_eq!(network_paths, vec![vec![], vec![NodeId(1)]]);
}
}
+2
View File
@@ -29,6 +29,8 @@ pub mod codec;
pub mod error;
pub mod export;
pub mod io;
#[cfg(feature = "conversion")]
pub mod layers;
pub mod layout;
mod load;
pub mod manifest;
+55 -12
View File
@@ -104,7 +104,7 @@ impl<L: Layout> Gdd<L> {
Ok(rewritten) => rewritten,
Err(error) => {
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
(session_with_truncated_history(&self.session, migrated)?, remap_metadata(&self.metadata, |_| None))
}
};
self.keep_blobs_durably(blobs.into_added()).await?;
@@ -189,19 +189,24 @@ impl<L: Layout> Gdd<L> {
session.absorb_retired_marks(previous.retired_marks());
Ok((session, remap_metadata(&self.metadata, remap)))
}
}
/// A session whose history restarts from `migrated`.
fn session_with_truncated_history(&self, migrated: Registry) -> Result<Session, Error> {
let previous = &self.session;
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated.clone())?;
/// A session continuing `previous` whose history restarts from `migrated`.
fn session_with_truncated_history(previous: &Session, migrated: Registry) -> Result<Session, Error> {
let peer_users = migrated.peer_users.clone();
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated)?;
let history: Vec<Delta> = restarted.history().cloned().collect();
let mut session = Session::load(previous.peer(), previous.user(), migrated, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
session.absorb_retired_marks(previous.retired_marks());
Ok(session)
}
// The bootstrap re-stamps every value, so its registry is the one matching its history. Its deltas leave out
// which user each device belongs to, so those registrations carry over directly.
let mut registry = restarted.retired_registry().clone();
registry.peer_users = peer_users;
let history: Vec<Delta> = restarted.history().cloned().collect();
let mut session = Session::load(previous.peer(), previous.user(), registry, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
session.absorb_retired_marks(previous.retired_marks());
Ok(session)
}
/// Resolves declaration resources to the declarations migrations name. A declaration's resource derives from its identifier and version
@@ -269,3 +274,41 @@ impl DeclarationResolver for DocumentDeclarations {
Some(self.encoded.get(self.known.get(&resource)?)?.proto.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
#[test]
fn a_truncated_history_matches_its_registry_and_keeps_device_registrations() {
let other_device = PeerId(2);
let mut previous = Session::with_peer(PeerId(1));
previous
.stage_computed_ops(vec![RegistryDelta::RegisterPeer {
peer: other_device,
user: previous.user(),
}])
.unwrap();
previous.retire_all().unwrap();
// Each edit stamps the value later than a fresh bootstrap would
for edit in 0..10 {
let delta = AttributeDelta {
key: "edit".to_string(),
value: Some(Value::Str(edit.to_string())),
};
previous.stage_computed_ops(vec![RegistryDelta::ChangeDocumentAttribute { delta }]).unwrap();
previous.retire_all().unwrap();
}
let session = session_with_truncated_history(&previous, previous.retired_registry().clone()).unwrap();
assert_eq!(session.user_of(other_device), Some(previous.user()));
// Device registrations carry over apart from the history, so everything else must match its replay
let replayed = Session::replay_from_history(session.peer(), session.user(), session.history().cloned(), session.next_node_counter()).unwrap();
let mut registry = session.retired_registry().clone();
registry.peer_users = replayed.retired_registry().peer_users.clone();
assert_eq!(&registry, replayed.retired_registry());
}
}
+44
View File
@@ -578,6 +578,50 @@ fn export_with_history_carries_history_only_resources() {
});
}
/// An export without history leaves behind the working copy's bytes of a resource only history still names.
#[test]
fn export_without_history_drops_history_only_resources() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::NoMetadata;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let byte_store = empty_byte_store();
let removed_payload = b"bytes of a removed resource";
let removed_hash = ResourceHash::from(&removed_payload[..]);
gdd.add_resource(ResourceId::new(), removed_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
let kept_payload = b"bytes of a kept resource";
let kept_hash = ResourceHash::from(&kept_payload[..]);
let kept_id = ResourceId::new();
gdd.add_resource(kept_id, kept_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
let mut resources = ResourceRegistry::new();
resources.push_source_back(&kept_id, DataSource::Embedded);
resources.resolve(&kept_id, kept_hash);
gdd.commit_from_runtime(&network_referencing_resource(kept_id), &NoMetadata, &resources, &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert!(gdd.has_resource(&removed_hash).await, "the working copy should still hold the removed resource's bytes");
let options = ExportOptions {
include_history: false,
..Default::default()
};
let archive = gdd
.export_to_bytes(ExportFormat::Zip, options, &byte_store, None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
.await
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
assert!(reopened.has_resource(&kept_hash).await, "bytes the registry names should travel with the export");
assert!(!reopened.has_resource(&removed_hash).await, "history-only bytes should stay behind");
});
}
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
+9
View File
@@ -7,6 +7,15 @@ use std::collections::{BTreeMap, btree_map};
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
@@ -1,7 +1,6 @@
pub mod node {
pub const CALL_ARGUMENT: &str = "call_argument";
pub const VISIBLE: &str = "visible";
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
pub const REFLECTION_METADATA: &str = "reflection_metadata";
pub mod input {
@@ -382,9 +382,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
attributes
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
.map_err(map_serialization_error(node::VISIBLE))?;
attributes
.set_if_not_default(node::SKIP_DEDUPLICATION, &doc_node.skip_deduplication, &false, timestamp)
.map_err(map_serialization_error(node::SKIP_DEDUPLICATION))?;
write_ui_attributes(&mut attributes, ctx.metadata, network, runtime_node_id, timestamp)?;
+1 -1
View File
@@ -44,7 +44,7 @@ pub use from_runtime::{
encode_node_ui_attributes, node_value_resource_refs, storage_location_id, storage_node_id, value_resource_ref,
};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
+1 -10
View File
@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap};
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::document::NetworkLocation;
use crate::{NetworkReference, Value};
use crate::{NetworkReference, Position, Value};
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
@@ -124,12 +124,3 @@ pub trait NodeMetadataSource {
pub struct NoMetadata;
impl NodeMetadataSource for NoMetadata {}
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
}
+3
View File
@@ -22,6 +22,9 @@ impl Node {
pub fn inputs_mut(&mut self) -> &mut Vec<InputSlot> {
&mut self.inputs
}
pub fn attributes_mut(&mut self) -> &mut Attributes {
&mut self.attributes
}
/// True if both nodes agree on every value-bearing field, ignoring slot/attribute timestamps.
pub fn value_equal(&self, other: &Self) -> bool {
+1 -10
View File
@@ -260,8 +260,7 @@ fn test_metadata_preservation() {
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
call_argument: concrete!(String),
visible: false, // Non-default value
skip_deduplication: true, // Non-default value
visible: false, // Non-default value
..Default::default()
},
),
@@ -296,9 +295,6 @@ fn test_metadata_preservation() {
// Verify visible is preserved
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
// Verify skip_deduplication is preserved
assert_eq!(orig_node_0.skip_deduplication, conv_node_0.skip_deduplication, "skip_deduplication should be preserved");
// Verify import_type is preserved for Import inputs
match (&orig_node_0.inputs[0], &conv_node_0.inputs[0]) {
(NodeInput::Import { import_type: orig_type, .. }, NodeInput::Import { import_type: conv_type, .. }) => {
@@ -354,11 +350,6 @@ fn test_demo_artwork_round_trip() {
artwork_name, node_id
);
assert_eq!(orig_node.visible, conv_node.visible, "{}: visible should be preserved for node {:?}", artwork_name, node_id);
assert_eq!(
orig_node.skip_deduplication, conv_node.skip_deduplication,
"{}: skip_deduplication should be preserved for node {:?}",
artwork_name, node_id
);
// Check input count
assert_eq!(
-1
View File
@@ -457,7 +457,6 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
call_argument: node.attributes.get_or(node::CALL_ARGUMENT, concrete!(core_types::Context)),
implementation: convert_implementation(context, &node.implementation)?,
visible: node.attributes.get_or(node::VISIBLE, true),
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
// Regenerated during compilation; not stored.
compile_metadata: None,
original_location: Default::default(),
+6 -4
View File
@@ -5,7 +5,7 @@ use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::document::NodeNetwork;
use graph_craft::document::{NodeId, NodeNetwork};
use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
@@ -97,10 +97,12 @@ impl LiveDocument {
&mut self.gdd
}
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
/// The document's runtime network, with the path of every layer in it.
pub async fn network_with_layers(&self) -> Result<(NodeNetwork, Vec<Vec<NodeId>>), LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
Ok(network)
let (network, node_metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
let layers = document_format::layers::layer_paths(&network, &node_metadata);
Ok((network, layers))
}
pub fn leave(&mut self) {
+115 -4
View File
@@ -5,7 +5,8 @@ use document_container::archive::ArchiveFormat;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NetworkMetadataEntry, NodeMetadataEntry};
use graph_craft::document::NodeNetwork;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use std::collections::HashMap;
use std::error::Error;
use std::path::Path;
@@ -17,6 +18,8 @@ use migration_nodes as _;
/// A document's runtime network, with the file it was opened from.
pub struct LoadedDocument {
pub network: NodeNetwork,
/// The path of every layer in `network`, once for each instance of the networks holding it.
pub layers: Vec<Vec<NodeId>>,
pub origin: DocumentOrigin,
}
@@ -58,9 +61,13 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
let named_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
if !named_gdd && ArchiveFormat::detect(&bytes).is_none() {
let document_string = String::from_utf8(bytes).map_err(|error| format!("Document {} is neither a .gdd archive nor text: {error}", path.display()))?;
let network = legacy_network(&document_string).map_err(|error| format!("Failed to parse legacy document {}: {error}", path.display()))?;
let parse_error = |error| format!("Failed to parse legacy document {}: {error}", path.display());
let document: serde_json::Value = serde_json::from_str(&document_string).map_err(parse_error)?;
let network = legacy_network(&document).map_err(parse_error)?;
let layers = legacy_layer_paths(&network, &document);
return Ok(LoadedDocument {
network,
layers,
origin: DocumentOrigin::Legacy(document_string),
});
}
@@ -68,14 +75,118 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
let gdd = open_gdd(&bytes).await?;
let declarations = gdd.declarations(&gdd).await;
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs())?;
let layers = document_format::layers::layer_paths(&network, &nodes);
Ok(LoadedDocument {
network,
layers,
origin: DocumentOrigin::Gdd { gdd: Box::new(gdd), nodes, networks },
})
}
fn legacy_network(document_string: &str) -> Result<NodeNetwork, serde_json::Error> {
let document: serde_json::Value = serde_json::from_str(document_string)?;
fn legacy_network(document: &serde_json::Value) -> Result<NodeNetwork, serde_json::Error> {
let network = document["network_interface"]["network"].to_string();
serde_json::from_str(&network)
}
/// The path of every node a legacy document's metadata marks as a layer.
fn legacy_layer_paths(network: &NodeNetwork, document: &serde_json::Value) -> Vec<Vec<NodeId>> {
let mut layer_paths = Vec::new();
document_format::layers::for_each_network_instance(network, |network_path, _| {
let Some(network_metadata) = legacy_network_metadata(network, document, network_path) else {
return;
};
let is_layer = |node_metadata: &serde_json::Value| node_metadata["node_type_metadata"]["Layer"].is_object();
let layers = legacy_node_metadata(network_metadata).into_iter().filter(|(_, node_metadata)| is_layer(node_metadata));
layer_paths.extend(layers.map(|(node_id, _)| [network_path, &[node_id]].concat()));
});
layer_paths
}
/// The metadata of the network at this path in a legacy document.
/// Older documents keep a held network's metadata inside its node's metadata, newer ones keep a definition's in a table.
fn legacy_network_metadata<'a>(network: &NodeNetwork, document: &'a serde_json::Value, network_path: &[NodeId]) -> Option<&'a serde_json::Value> {
let document_network_metadata = &document["network_interface"]["network_metadata"];
let definitions = &document_network_metadata["persistent_metadata"]["definitions"];
let mut current = network;
let mut network_metadata = document_network_metadata;
for node_id in network_path {
let node = current.nodes.get(node_id)?;
network_metadata = match node.implementation {
DocumentNodeImplementation::Definition(id) => &definitions[id.0.to_string()],
DocumentNodeImplementation::Network(_) => &legacy_node_metadata(network_metadata).remove(node_id)?["network_metadata"],
_ => return None,
};
current = network.implementation_network(&node.implementation)?;
}
Some(network_metadata)
}
/// The metadata of each node in a legacy network, by ID.
fn legacy_node_metadata(network_metadata: &serde_json::Value) -> HashMap<NodeId, &serde_json::Value> {
let entries = network_metadata["persistent_metadata"]["node_metadata"].as_array().into_iter().flatten();
entries.filter_map(|entry| Some((NodeId(entry[0].as_u64()?), &entry[1]["persistent_metadata"]))).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::document::{DocumentNode, NetworkId};
fn node(implementation: DocumentNodeImplementation) -> DocumentNode {
DocumentNode { implementation, ..Default::default() }
}
/// A network holding the nodes 3 and 4.
fn inner_network() -> NodeNetwork {
NodeNetwork {
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
..Default::default()
}
}
fn sorted_legacy_layer_paths(network: &NodeNetwork, document: &str) -> Vec<Vec<NodeId>> {
let document = serde_json::from_str(document).expect("The test document should be valid JSON");
let mut layer_paths = legacy_layer_paths(network, &document);
layer_paths.sort();
layer_paths
}
#[test]
fn a_layer_inside_a_definition_is_found_through_each_instance() {
let definition = NetworkId(9);
let network = NodeNetwork {
nodes: [1, 2].map(|id| (NodeId(id), node(DocumentNodeImplementation::Definition(definition)))).into_iter().collect(),
definitions: [(definition, inner_network())].into_iter().collect(),
..Default::default()
};
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
"node_metadata": [[1, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [2, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]],
"definitions": { "9": { "persistent_metadata": {
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
} } }
} } } }"#;
let expected = vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]];
assert_eq!(sorted_legacy_layer_paths(&network, document), expected);
}
#[test]
fn a_layer_inside_a_held_network_is_found() {
let network = NodeNetwork {
nodes: [(NodeId(1), node(DocumentNodeImplementation::Network(inner_network())))].into_iter().collect(),
..Default::default()
};
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
"node_metadata": [[1, { "persistent_metadata": {
"node_type_metadata": { "Layer": {} },
"network_metadata": { "persistent_metadata": {
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
} }
} }]]
} } } }"#;
assert_eq!(sorted_legacy_layer_paths(&network, document), vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)]]);
}
}
@@ -1,9 +1,10 @@
use document_graph_storage::attr::node::VISIBLE;
use document_graph_storage::attr::node::ui::DISPLAY_NAME;
use graphene_std::Color;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use migration_core::{Attributes, Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
@@ -29,11 +30,23 @@ fn number(input: &NodeInput) -> Option<f64> {
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
pub fn vary_nodes_from_copy_to_points(
node: &Node,
compiler: Option<&dyn Compiler>,
inputs: &mut Inputs,
upstream: &mut Upstream,
target: &mut Target,
attributes: &mut Attributes,
) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
// A stored default name would misname the new node
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Copy to Points") {
attributes.remove(node.id(), DISPLAY_NAME);
}
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
let unset = || literal(Tagged::Bool(false));
@@ -170,6 +183,8 @@ fn bias_keeping_average_scale(bias: f64) -> f64 {
mod tests {
use super::*;
use crate::CompilerHost;
use document_graph_storage::attr::node::ui::POSITION;
use document_graph_storage::{NodeId, Position, TimeStamp, Value, to_value};
use migration_core::Declaration;
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
@@ -184,10 +199,13 @@ mod tests {
}
fn contract() -> SourceContract {
SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
SourceContract {
display_names: &["Copy to Points"],
..SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
}
}
fn star_inputs() -> Vec<NodeInput> {
@@ -262,6 +280,48 @@ mod tests {
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
}
#[test]
fn the_default_name_is_cleared() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
let name = Value::Str("Copy to Points".to_string());
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(DISPLAY_NAME, name, TimeStamp::ORIGIN);
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert!(migrated.node_instances[&copies].attributes().get_typed::<String>(DISPLAY_NAME).is_none());
}
/// Matches the layout the legacy migration gives a star copied at a scale of 2 with random rotations spanning 90°.
#[test]
fn stages_lead_up_to_a_placed_node_in_a_row() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
let position = to_value(&Position::Absolute([20, 10])).unwrap();
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(POSITION, position, TimeStamp::ORIGIN);
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
let position_of = |node: NodeId| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION);
// Walk back from the anchor through each stage's points
let mut stages = Vec::new();
let mut stage = copies;
while let NodeInput::Node { id, .. } = fixture.inputs(&migrated, stage)[0]
&& id != star
{
stages.insert(0, position_of(id));
stage = id;
}
let NodeInput::Node { id: group, .. } = fixture.inputs(&migrated, stage)[1] else {
panic!("the repeat reads the group")
};
assert_eq!(stages, [-1, 6, 13].map(|x| Some(Position::Absolute([x, 10]))));
assert_eq!(position_of(group), Some(Position::Absolute([-8, 13])));
}
#[test]
fn bias_keeps_its_average() {
assert_eq!(bias_keeping_average_scale(0.), 0.5);
+2 -2
View File
@@ -29,7 +29,7 @@ pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
pub use declaration::{Declaration, DeclarationKind, DeclarationResolver};
#[cfg(feature = "typed")]
pub use document_graph_storage::NodeInput;
pub use document_graph_storage::{NodeInput, Position, attr};
pub use error::MigrationError;
pub use format::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
#[cfg(feature = "typed")]
@@ -44,7 +44,7 @@ pub use registry::{register_migration, registered_migrations};
#[cfg(feature = "typed")]
pub use value::{encode, literal, literal_of};
#[cfg(feature = "typed")]
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
pub use view::{AddedNode, AnchorContext, AttributeWrite, Attributes, CHAIN_WIDTH, Downstream, Edits, FEEDER_ROW_HEIGHT, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
+74 -2
View File
@@ -1,7 +1,14 @@
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode};
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp, Value};
use serde::Serialize;
use std::ops::Deref;
/// How many grid cells the editor's layout steps left for each node of a layer's chain.
pub const CHAIN_WIDTH: i32 = 7;
/// How many grid cells apart the rows of nodes feeding a node from below are.
pub const FEEDER_ROW_HEIGHT: i32 = 3;
/// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Region(u8);
@@ -14,6 +21,8 @@ impl Region {
pub const DOWNSTREAM: Self = Self(1 << 3);
/// The anchor's whole network, as read through [`Graph`].
pub const NETWORK: Self = Self(1 << 4);
/// Attributes of the anchor and of the nodes the run adds, such as their positions and display names.
pub const ATTRIBUTES: Self = Self(1 << 5);
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
@@ -223,6 +232,8 @@ pub struct Edits {
pub connections: Vec<(OutputConnector, InputConnector)>,
/// The declaration this anchor switches to, when not the migration's target.
pub target: Option<Declaration>,
/// Attribute writes to the anchor and the nodes this run adds.
pub attributes: Vec<AttributeWrite>,
}
impl Edits {
@@ -234,6 +245,57 @@ impl Edits {
self.removed_nodes.extend(other.removed_nodes);
self.connections.extend(other.connections);
self.target = other.target.or(self.target);
self.attributes.extend(other.attributes);
}
}
/// One attribute of the anchor or of a node the run adds. A run's writes apply in the order it recorded them.
#[derive(Debug)]
pub struct AttributeWrite {
pub node: NodeId,
pub key: String,
/// `None` deletes the key.
pub value: Option<Value>,
}
/// Attributes of the anchor and of the nodes this run adds, such as where they sit and what they're named.
#[derive(Default)]
pub struct Attributes {
writes: Vec<AttributeWrite>,
}
impl Attributes {
/// Write `value` under `key` on the anchor or on a node this run adds.
pub fn set<T: Serialize>(&mut self, node: NodeId, key: &str, value: &T) {
self.writes.push(AttributeWrite {
node,
key: key.to_string(),
value: Some(encode(value)),
});
}
/// Delete `key` from the anchor or from a node this run adds.
pub fn remove(&mut self, node: NodeId, key: &str) {
self.writes.push(AttributeWrite {
node,
key: key.to_string(),
value: None,
});
}
}
impl<'a> View<'a> for Attributes {
const REGION: Region = Region::ATTRIBUTES;
fn extract(_context: &AnchorContext<'a>) -> Self {
Self::default()
}
fn into_edits(self) -> Result<Edits, MigrationError> {
Ok(Edits {
attributes: self.writes,
..Default::default()
})
}
}
@@ -329,6 +391,16 @@ impl Inputs {
self.origins.push(None);
}
/// Add a slot the compiler fills in with what `metadata` names, a frozen mirror value such as the node's path.
pub fn push_reflection<T: Serialize>(&mut self, metadata: T) {
let mut slot = new_slot(NodeInput::Reflection);
slot.attributes.set(REFLECTION_METADATA, encode(&metadata), TimeStamp::ORIGIN);
self.edited = true;
self.slots.push(slot);
self.origins.push(None);
}
pub fn remove(&mut self, index: u32) {
if !self.check(index, self.slots.len()) {
return;
+1 -1
View File
@@ -16,7 +16,7 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// A `network` prefix names a built-in network definition, as in `#[migration(network "Merge"@1 => "module::merge"@2)]`.
///
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`, `Attributes`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
///
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
#[proc_macro_attribute]
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `blending_nodes`.
mod paint_overlay_from_color_overlay;
mod renames;
@@ -0,0 +1,43 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Node, migration};
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
attributes.remove(node.id(), DISPLAY_NAME);
}
}
#[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};
#[test]
fn rewrites_history() {
let contract = SourceContract {
display_names: &["Color Overlay"],
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
};
check_commutation(&PaintOverlayFromColorOverlay, &contract);
check_undo(&PaintOverlayFromColorOverlay, &contract);
}
#[test]
fn only_the_old_default_name_is_cleared() {
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
}
}
}
@@ -0,0 +1,5 @@
//! Nodes that only moved to a new identifier.
use migration_core::rename;
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
@@ -4,3 +4,5 @@ use migration_core::rename;
// Version 2 is where old Upload Texture nodes join the lineage, and stored Passthrough nodes already have its layout
rename!("graphene_core::ops::PassthroughNode"@1 => @2);
// The removed Monitor node passes its one input on, as a Passthrough does
rename!("graphene_core::memo::MonitorNode"@1 => "graphene_core::ops::PassthroughNode"@2);
+2
View File
@@ -1,6 +1,8 @@
//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod blending_nodes;
mod graphene_core;
mod math_nodes;
mod raster_nodes;
mod vector_nodes;
@@ -0,0 +1,99 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Inputs, MigrationError, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
const FORM: u32 = 1;
/// 'Gradient Form' became 'Gradient Curvature', whose start and end curvatures take the presets of the form it set: 0 and 0 for linear, 1 and 0.5 for
/// radial. A wired form becomes linear, 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.],
};
inputs.set(FORM, literal(Tagged::Number(start)));
inputs.push(literal(Tagged::Number(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::{NodeInput, decl};
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());
}
#[test]
fn forms_become_their_curvature_presets() {
let gradient = literal(Tagged::Number(0.));
for (old_form, [start, end]) in [
(form(GradientForm::Linear), [0., 0.]),
(form(GradientForm::Radial), [1., 0.5]),
(NodeInput::Import { index: 0 }, [0., 0.]),
] {
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(), literal(Tagged::Number(start)), literal(Tagged::Number(end))]);
}
}
#[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,4 +1,5 @@
//! Migrations of the nodes in `math_nodes`.
mod gradient_curvature_from_gradient_form;
mod math_formula_from_math_f;
mod renames;
@@ -0,0 +1,104 @@
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
use migration_core::{Attributes, Downstream, Inputs, Node, decl, literal, migration};
/// The pattern fills the plane rather than being cut off at the unit square, so it's read through that square filled with it, and the node gained a
/// primary input.
#[migration("raster_nodes::std_nodes::MandelbrotNode"@1 => @2)]
pub fn mandelbrot_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
inputs.insert(0, literal(Tagged::None));
let nodes = SquareNodes {
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
fill: decl!("graphene_core::vector::FillNode"@1),
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
};
fill_square_with_pattern(node, downstream, attributes, nodes, 1.);
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{ROOT_NETWORK, TimeStamp};
use migration_core::attr::node::ui::{IS_LAYER, POSITION};
use migration_core::{NodeInput, Position};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(0, |_, _| literal(Tagged::None))
}
#[test]
fn rewrites_history() {
check_commutation(&MandelbrotV1, &contract());
check_undo(&MandelbrotV1, &contract());
}
#[test]
fn the_export_reads_a_unit_square_filled_with_the_pattern() {
let mut fixture = Fixture::new(&MandelbrotV1);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
fixture.export(NodeInput::Node { id: mandelbrot, index: 0 });
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
assert_eq!(fixture.inputs(&migrated, mandelbrot), [literal(Tagged::None)]);
let Some(NodeInput::Node { id: placement, .. }) = migrated.networks[&ROOT_NETWORK].exports[0].target else {
panic!("the export should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, placement), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([0.5, 0.5])));
}
/// The positions of the pattern, its paint, the rectangle, the fill, and the placement after migrating a pattern at `position`.
fn placed_square(position: Position, layer: Option<[i32; 2]>) -> [Option<Position>; 5] {
let mut fixture = Fixture::new(&MandelbrotV1);
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
let place = |fixture: &mut Fixture, node, position: Position| {
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
};
place(&mut fixture, mandelbrot, position);
let reader = match layer {
Some(layer_position) => {
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::None), NodeInput::Node { id: mandelbrot, index: 0 }]);
place(&mut fixture, layer, Position::Absolute(layer_position));
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
layer
}
None => fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]),
};
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
NodeInput::Node { id, .. } => id,
_ => panic!("slot {slot} of {node:?} should read a node"),
};
let placement = reads(reader, if layer.is_some() { 1 } else { 0 });
let fill = reads(placement, 0);
let (rectangle, paint) = (reads(fill, 0), reads(fill, 1));
[mandelbrot, paint, rectangle, fill, placement].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
}
#[test]
fn a_chained_pattern_gives_its_place_to_the_filled_rectangle() {
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Chain, Some([30, 10]));
assert_eq!([rectangle, fill, placement], [Some(Position::Chain); 3]);
assert_eq!(pattern, Some(Position::Absolute([0, 0])));
assert_eq!(paint, Some(Position::Absolute([7, 0])));
}
#[test]
fn a_placed_pattern_gets_its_square_to_the_right() {
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Absolute([5, 5]), None);
assert_eq!(pattern, Some(Position::Absolute([5, 5])));
assert_eq!(paint, Some(Position::Absolute([12, 5])));
assert_eq!(rectangle, Some(Position::Absolute([12, 2])));
assert_eq!(fill, Some(Position::Absolute([19, 5])));
assert_eq!(placement, Some(Position::Absolute([26, 5])));
}
}
@@ -1,4 +1,7 @@
//! Migrations of the nodes in `raster_nodes`.
mod mandelbrot_v1;
mod mix_colors_from_mix_node;
mod noise_pattern_v1;
mod pattern_square;
mod renames;
@@ -0,0 +1,97 @@
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
use migration_core::{Attributes, Downstream, Inputs, MigrationError, Node, decl, literal_of, migration};
const CLIP: u32 = 1;
/// The pattern fills the plane, so the Clip toggle that cut it off at a 100-unit square is gone, and a clipped pattern is read through that square
/// filled with it. A wired toggle counts as clipped.
#[migration("raster_nodes::std_nodes::NoisePatternNode"@1 => @2)]
pub fn noise_pattern_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) -> Result<(), MigrationError> {
let Some(clip) = node.inputs().get(CLIP as usize) else {
return Err(MigrationError::invariant("Noise Pattern has a Clip input"));
};
let clipped = !matches!(literal_of::<Tagged>(&clip.input), Some(Tagged::Bool(false)));
inputs.remove(CLIP);
if clipped {
let nodes = SquareNodes {
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
fill: decl!("graphene_core::vector::FillNode"@1),
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
};
fill_square_with_pattern(node, downstream, attributes, nodes, 100.);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{Declaration, NodeInput, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@1);
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
fn contract() -> SourceContract {
SourceContract {
// The toggle a clipped pattern's readers move off of can't be reading that pattern, since its own migration removes it
reads_own_output: |slot| slot != CLIP as usize,
..SourceContract::new(16, |random, slot| match slot {
1 => literal(Tagged::Bool(random.below(2) == 0)),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
}
fn noise_inputs(clip: bool) -> Vec<NodeInput> {
let mut inputs: Vec<NodeInput> = (0..16).map(|slot| literal(Tagged::Number(slot as f64))).collect();
inputs[CLIP as usize] = literal(Tagged::Bool(clip));
inputs
}
#[test]
fn rewrites_history() {
check_commutation(&NoisePatternV1, &contract());
check_undo(&NoisePatternV1, &contract());
}
#[test]
fn a_clipped_pattern_is_read_through_a_square_filled_with_it() {
let mut fixture = Fixture::new(&NoisePatternV1);
let noise = fixture.add(NOISE_PATTERN, noise_inputs(true));
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
// The settings after the removed toggle move down a slot
let inputs = fixture.inputs(&migrated, noise);
assert_eq!(inputs.len(), 15);
assert_eq!(inputs[CLIP as usize], literal(Tagged::Number(2.)));
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
NodeInput::Node { id, .. } => id,
_ => panic!("slot {slot} of {node:?} should read a node"),
};
let placement = reads(consumer, 0);
let fill = reads(placement, 0);
let paint = reads(fill, 1);
assert_eq!(reads(paint, 0), noise);
assert_eq!(fixture.declaration_of(&migrated, reads(fill, 0)), Some(decl!("vector_nodes::generator_nodes::RectangleNode"@1)));
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([50., 50.])));
assert_eq!(fixture.inputs(&migrated, paint)[1], literal(Tagged::DVec2([-50., -50.])));
}
#[test]
fn an_unclipped_pattern_keeps_its_readers() {
let mut fixture = Fixture::new(&NoisePatternV1);
let noise = fixture.add(NOISE_PATTERN, noise_inputs(false));
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
assert_eq!(fixture.inputs(&migrated, noise).len(), 15);
assert_eq!(fixture.inputs(&migrated, consumer), [NodeInput::Node { id: noise, index: 0 }]);
assert_eq!(migrated.node_instances.len(), 2);
}
}
@@ -0,0 +1,152 @@
//! The square that Noise Pattern and Mandelbrot were cut off at before their patterns filled the plane, which their migrations keep.
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, Declaration, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, literal};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants these migrations use.
#[derive(Serialize, Deserialize)]
pub(super) enum Tagged {
None,
Number(f64),
Bool(bool),
BoxCorners(Vec<f64>),
Color(Color),
GradientRamp(GradientRamp),
GradientForm(GradientForm),
DVec2([f64; 2]),
DAffine2([f64; 6]),
}
#[derive(Serialize, Deserialize)]
pub(super) struct Color {
red: f32,
green: f32,
blue: f32,
alpha: f32,
linear: bool,
}
impl Color {
fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
Self {
red,
green,
blue,
alpha,
linear: true,
}
}
}
#[derive(Serialize, Deserialize)]
pub(super) struct GradientRamp {
stops: GradientStops,
gradient_space: GradientSpace,
}
#[derive(Serialize, Deserialize)]
pub(super) struct GradientStops {
color: Vec<Color>,
}
#[derive(Serialize, Deserialize)]
pub(super) enum GradientSpace {
OkLab,
}
#[derive(Serialize, Deserialize)]
pub(super) enum GradientForm {
Linear,
}
/// The declarations the square is built from, which each migration names itself so the runner orders it against them.
pub(super) struct SquareNodes {
pub rectangle: Declaration,
pub fill: Declaration,
pub transform: Declaration,
}
/// Makes everything reading the pattern read a rectangle filled with it instead, covering the square from the origin of the pattern's space out to `size`.
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
pub(super) fn fill_square_with_pattern(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes, nodes: SquareNodes, size: f64) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let number = |number| literal(Tagged::Number(number));
let pair = |value| literal(Tagged::DVec2([value, value]));
let wire = |id| NodeInput::Node { id, index: 0 };
let transform = |content, translation| vec![content, pair(translation), number(0.), pair(1.), pair(0.)];
let rectangle = downstream.add_node(NewNode {
declaration: nodes.rectangle,
inputs: vec![
literal(Tagged::None),
number(size),
number(size),
literal(Tagged::BoxCorners(Vec::new())),
literal(Tagged::Bool(true)),
literal(Tagged::Bool(false)),
],
});
let paint = downstream.add_node_keyed(
NewNode {
declaration: nodes.transform,
inputs: transform(wire(node.id()), -size / 2.),
},
"paint",
);
// Past the rectangle and its paint, the Fill holds the defaults its definition gives a new node
let backup_gradient = GradientRamp {
stops: GradientStops {
color: vec![Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)],
},
gradient_space: GradientSpace::OkLab,
};
let fill = downstream.add_node(NewNode {
declaration: nodes.fill,
inputs: vec![
wire(rectangle),
wire(paint),
literal(Tagged::Color(Color::new(0., 0., 0., 0.))),
literal(Tagged::GradientRamp(backup_gradient)),
literal(Tagged::GradientForm(GradientForm::Linear)),
literal(Tagged::Bool(false)),
literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
],
});
let placement = downstream.add_node_keyed(
NewNode {
declaration: nodes.transform,
inputs: transform(wire(fill), size / 2.),
},
"placement",
);
for consumer in consumers {
downstream.connect(OutputConnector { node: placement, output: 0 }, consumer);
}
// In a layer's chain, the filled rectangle takes the pattern's place. The pattern and its paint leave the chain with no coordinates to go by,
// so they start at the graph's origin. Elsewhere the square sits to the pattern's right.
let stored = node.attributes().get_typed::<Position>(POSITION);
if stored == Some(Position::Chain) {
for id in [placement, fill, rectangle] {
attributes.set(id, POSITION, &Position::Chain);
}
attributes.set(node.id(), POSITION, &Position::Absolute([0, 0]));
attributes.set(paint, POSITION, &Position::Absolute([7, 0]));
} else {
let [x, y] = match stored {
Some(Position::Absolute(coordinates)) => coordinates,
_ => [0, 0],
};
for (id, [x_offset, y_offset]) in [(paint, [7, 0]), (rectangle, [7, -3]), (fill, [14, 0]), (placement, [21, 0])] {
attributes.set(id, POSITION, &Position::Absolute([x + x_offset, y + y_offset]));
}
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `vector_nodes`.
mod path_from_path_network;
mod renames;
@@ -0,0 +1,49 @@
use migration_core::{Inputs, migration};
use serde::Serialize;
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
#[derive(Serialize)]
enum Reflected {
DocumentNodePath,
}
/// The Path subgraph became the node it held, which takes the instance's inputs and is given its own path as that node was.
#[migration(network "Path"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2)]
pub fn path_from_path_network(inputs: &mut Inputs) {
inputs.push_reflection(Reflected::DocumentNodePath);
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::NodeInput;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
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(&PathFromPathNetwork, &contract());
check_undo(&PathFromPathNetwork, &contract());
}
#[test]
fn collapses_into_the_node_and_gives_it_its_path() {
let (content, modification) = (literal(1.), literal(2.));
let mut fixture = Fixture::new(&PathFromPathNetwork);
let (path, network) = fixture.add_network(decl!(network "Path"@1), vec![content.clone(), modification.clone()]);
let migrated = fixture.migrate(&PathFromPathNetwork).unwrap();
assert_eq!(fixture.declaration_of(&migrated, path), Some(decl!("vector_nodes::vector_modification_nodes::PathNode"@2)));
assert!(!migrated.networks.contains_key(&network));
assert_eq!(fixture.inputs(&migrated, path), [content, modification, NodeInput::Reflection]);
let own_path = &migrated.node_instances[&path].inputs()[2];
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
}
}
@@ -0,0 +1,5 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2);
+2
View File
@@ -40,6 +40,8 @@ pub enum RunnerError {
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
#[error("added node {0:?} already exists")]
AddedNodeExists(NodeId),
#[error("node {anchor:?} writes attributes of {node:?}, which is neither it nor a node it adds")]
AttributesOutsideRegion { anchor: NodeId, node: NodeId },
#[error("{0:?} is rewired by one anchor while its own migration replaces or removes it")]
ConflictingSlot(InputConnector),
#[error("{0:?} does not exist in the migrated state")]
+93 -3
View File
@@ -2,10 +2,12 @@
use crate::{MigrationBlobs, RunnerError};
use document_graph_storage::TimeStamp;
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::attributes::attr::node::ui::{IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, implements};
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{
AnchorContext, CHAIN_WIDTH, Compiler, Declaration, DeclarationResolver, Edits, FEEDER_ROW_HEIGHT, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, encode, implements,
};
use std::collections::{HashMap, HashSet};
/// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store.
@@ -173,6 +175,10 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI
}
add_nodes(&mut target, &runs, resolver)?;
for (anchor, edits) in &runs {
place_added_nodes(&mut target, *anchor, edits);
write_attributes(&mut target, *anchor, edits)?;
}
let input_edits: HashMap<NodeId, &InputsEdit> = runs.iter().filter_map(|(anchor, edits)| Some((*anchor, edits.inputs.as_ref()?))).collect();
for (anchor, inputs) in &input_edits {
@@ -328,6 +334,90 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec
Ok(())
}
/// Default positions for the nodes one run adds, read from the anchor's own position only. The nodes leading up to the anchor's
/// chain input form a row, or join the chain of a chained or layer anchor. Each other node sits below the first one reading it,
/// or on the anchor when none does. Without absolute coordinates for the anchor, only the chain is placed.
fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
let Some(anchor_node) = target.node_instances.get(&anchor) else { return };
let stored = anchor_node.attributes().get_typed::<Position>(POSITION);
let is_layer = anchor_node.attributes().get_or(IS_LAYER, false);
let anchor_inputs: Vec<NodeInput> = match &edits.inputs {
Some(inputs) => inputs.slots.iter().map(|slot| slot.input.clone()).collect(),
None => anchor_node.inputs().iter().map(|slot| slot.input.clone()).collect(),
};
let added_inputs: HashMap<NodeId, &[NodeInput]> = edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())).collect();
let reads = |inputs: &[NodeInput], node: NodeId| inputs.iter().any(|input| matches!(input, NodeInput::Node { id, .. } if *id == node));
let chain_input = if is_layer { 1 } else { 0 };
let mut chain = Vec::new();
let mut next = anchor_inputs.get(chain_input);
while let Some(NodeInput::Node { id, .. }) = next
&& let Some(inputs) = added_inputs.get(id)
&& !chain.contains(id)
{
chain.push(*id);
next = inputs.first();
}
let joins_chain = is_layer || stored == Some(Position::Chain);
let coordinates = match stored {
Some(Position::Absolute(coordinates)) => Some(coordinates),
_ => None,
};
let mut positions = Vec::new();
for (step, id) in chain.iter().enumerate() {
match coordinates {
_ if joins_chain => positions.push((*id, Position::Chain)),
Some([x, y]) => positions.push((*id, Position::Absolute([x - CHAIN_WIDTH * (step as i32 + 1), y]))),
None => {}
}
}
if let Some([x, y]) = coordinates {
let readers: Vec<(&[NodeInput], i32)> = std::iter::once((anchor_inputs.as_slice(), x))
.chain(chain.iter().enumerate().map(|(step, id)| (added_inputs[id], x - CHAIN_WIDTH * (step as i32 + 1))))
.collect();
let mut feeders_below = vec![0; readers.len()];
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
let position = match readers.iter().position(|(inputs, _)| reads(inputs, added.id)) {
Some(reader) => {
feeders_below[reader] += 1;
[readers[reader].1 - CHAIN_WIDTH, y + FEEDER_ROW_HEIGHT * feeders_below[reader]]
}
None => [x, y],
};
positions.push((added.id, Position::Absolute(position)));
}
}
for (id, position) in positions {
if let Some(node) = target.node_instances.get_mut(&id) {
node.attributes_mut().set(POSITION, encode(&position), TimeStamp::ORIGIN);
}
}
}
/// Apply one run's attribute writes, which may only name its anchor and the nodes it adds.
fn write_attributes(target: &mut Registry, anchor: NodeId, edits: &Edits) -> Result<(), RunnerError> {
for write in &edits.attributes {
let in_region = write.node == anchor || edits.added_nodes.iter().any(|added| added.id == write.node);
let node = target.node_instances.get_mut(&write.node).filter(|_| in_region);
let node = node.ok_or(RunnerError::AttributesOutsideRegion { anchor, node: write.node })?;
match &write.value {
Some(value) => node.attributes_mut().set(&write.key, value.clone(), TimeStamp::ORIGIN),
None => {
node.attributes_mut().remove(&write.key);
}
}
}
Ok(())
}
/// Make `consumer`, named in the source layout, read `output` in the target layout. Fails when the consumer's own migration replaced or
/// removed that slot, since two runs then disagree on what it should read.
fn connect(target: &mut Registry, output: OutputConnector, consumer: InputConnector, input_edits: &HashMap<NodeId, &InputsEdit>) -> Result<(), RunnerError> {
+37 -3
View File
@@ -3,9 +3,10 @@
use crate::node::{apply_migration, needs_whole_states, rewrite_history};
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::attributes::attr::node::ui::{DISPLAY_NAME, IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::{
Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, apply_retired_op,
AttributeDelta, Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Position, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, Value,
apply_retired_op, to_value,
};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, implements, literal, registered_migrations};
use std::collections::HashSet;
@@ -138,6 +139,8 @@ pub struct SourceContract {
pub literal: fn(&mut Random, usize) -> NodeInput,
/// Whether a slot may read an output of another node of the source declaration.
pub reads_own_output: fn(usize) -> bool,
/// Display names, besides a custom one, that generated histories give nodes, such as a default the migration clears.
pub display_names: &'static [&'static str],
}
impl SourceContract {
@@ -146,6 +149,7 @@ impl SourceContract {
input_count,
literal,
reads_own_output: |_| true,
display_names: &[],
}
}
}
@@ -276,11 +280,36 @@ impl Generator<'_> {
self.commit_interaction(ops);
}
/// A name, position, or layer flag, written or deleted.
fn attribute(&mut self) -> AttributeDelta {
let (key, value) = match self.random.below(3) {
0 => {
let names = self.contract.display_names;
let name = match self.random.below(names.len() + 2) {
index if index < names.len() => Some(names[index]),
index if index == names.len() => Some("Renamed"),
_ => None,
};
(DISPLAY_NAME, name.map(|name| Value::Str(name.to_string())))
}
1 => {
let position = match self.random.below(3) {
0 => Position::Chain,
_ => Position::Absolute([self.random.below(20) as i32, self.random.below(20) as i32]),
};
(POSITION, Some(to_value(&position).expect("positions serialize")))
}
_ => (IS_LAYER, (self.random.below(2) == 0).then_some(Value::Bool(true))),
};
AttributeDelta { key: key.to_string(), value }
}
fn step(&mut self) {
let nodes = self.live_nodes();
let root_nodes = self.live_nodes_in(ROOT_NETWORK);
match self.random.below(11) {
match self.random.below(13) {
0..=3 => {
let (declaration, input_count) = if self.random.below(3) == 0 {
(self.source, self.contract.input_count)
@@ -335,6 +364,11 @@ impl Generator<'_> {
self.session.undo().expect("an interaction is left to undo");
self.undoable -= 1;
}
11 | 12 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let delta = self.attribute();
self.commit(RegistryDelta::ChangeNodeAttribute { id, delta });
}
_ => {}
}
}
@@ -0,0 +1,137 @@
//! Attribute writes on the anchor and the nodes it adds, and the positions added nodes get by default.
use document_graph_storage::attr::node::ui::{DISPLAY_NAME, POSITION};
use document_graph_storage::{NodeId, NodeInput, Position, Value, to_value};
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, FEEDER_ROW_HEIGHT, Inputs, NewNode, Node, Upstream, decl, migration};
use migration_runner::RunnerError;
use migration_runner::testing::Fixture;
/// Clears the anchor's old default name and places a node it adds.
#[migration("attributes::renamed"@1 => @2)]
pub fn renamed(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Old name") {
attributes.remove(node.id(), DISPLAY_NAME);
}
let added = downstream.add_node(NewNode {
declaration: decl!("math_nodes::add"@1),
inputs: vec![],
});
attributes.set(added, POSITION, &Position::Absolute([3, 4]));
}
/// Renames the node its first input reads, which it neither is nor adds.
#[migration("attributes::outside"@1 => @2)]
pub fn outside(node: &Node, attributes: &mut Attributes) {
if let Some(NodeInput::Node { id, .. }) = node.inputs().first().map(|slot| &slot.input) {
attributes.set(*id, DISPLAY_NAME, &"Renamed");
}
}
/// Adds two nodes leading up to the anchor's first input, and one feeding the nearer of them from below.
#[migration("attributes::placed"@1 => @2)]
pub fn placed(node: &Node, inputs: &mut Inputs, upstream: &mut Upstream) {
let add = decl!("math_nodes::add"@1);
let source = node.inputs().first().map_or(NodeInput::Import { index: 0 }, |slot| slot.input.clone());
let far = upstream.add_node_keyed(
NewNode {
declaration: add,
inputs: vec![source],
},
"far",
);
let below = upstream.add_node_keyed(NewNode { declaration: add, inputs: vec![] }, "below");
let near = upstream.add_node_keyed(
NewNode {
declaration: add,
inputs: vec![wire(far), wire(below)],
},
"near",
);
inputs.set(0, wire(near));
}
fn set_name(fixture: &mut Fixture, node: NodeId, name: &str) {
let name = Value::Str(name.to_string());
fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut().set(DISPLAY_NAME, name, Default::default());
}
/// The positions of the far, near, and below nodes `Placed` adds for an anchor stored at `position`.
fn placed_around(position: Position) -> [Option<Position>; 3] {
let migration = &Placed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::placed"@1), vec![NodeInput::Import { index: 0 }]);
let position = to_value(&position).unwrap();
fixture.registry.node_instances.get_mut(&anchor).unwrap().attributes_mut().set(POSITION, position, Default::default());
let migrated = fixture.migrate(migration).unwrap();
let position_of = |id: NodeId| migrated.node_instances[&id].attributes().get_typed::<Position>(POSITION);
let NodeInput::Node { id: near, .. } = fixture.inputs(&migrated, anchor)[0] else {
panic!("the anchor reads the near node")
};
let [NodeInput::Node { id: far, .. }, NodeInput::Node { id: below, .. }] = fixture.inputs(&migrated, near)[..] else {
panic!("the near node reads the far and below nodes")
};
[position_of(far), position_of(near), position_of(below)]
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn a_run_writes_its_anchor_and_the_nodes_it_adds() {
let migration = &Renamed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
set_name(&mut fixture, anchor, "Old name");
fixture.export(wire(anchor));
let migrated = fixture.migrate(migration).unwrap();
assert!(migrated.node_instances[&anchor].attributes().get(DISPLAY_NAME).is_none());
let added = migrated.node_instances.iter().find(|(id, _)| **id != anchor).map(|(_, node)| node).expect("the run adds a node");
assert_eq!(added.attributes().get_typed::<Position>(POSITION), Some(Position::Absolute([3, 4])));
}
#[test]
fn a_name_given_by_the_user_is_kept() {
let migration = &Renamed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
set_name(&mut fixture, anchor, "Mine");
let migrated = fixture.migrate(migration).unwrap();
assert_eq!(migrated.node_instances[&anchor].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), Some("Mine"));
}
#[test]
fn added_nodes_lead_up_to_a_placed_anchor() {
let [far, near, below] = placed_around(Position::Absolute([20, 10]));
assert_eq!(far, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10])));
assert_eq!(near, Some(Position::Absolute([20 - CHAIN_WIDTH, 10])));
assert_eq!(below, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10 + FEEDER_ROW_HEIGHT])));
}
#[test]
fn added_nodes_join_a_chained_anchors_chain() {
let [far, near, below] = placed_around(Position::Chain);
assert_eq!([far, near], [Some(Position::Chain); 2]);
assert_eq!(below, None);
}
#[test]
fn writing_another_nodes_attributes_fails() {
let migration = &Outside;
let mut fixture = Fixture::new(migration);
let other = fixture.add(decl!("math_nodes::add"@1), vec![]);
fixture.add(decl!("attributes::outside"@1), vec![wire(other)]);
let error = fixture.migrate(migration).unwrap_err();
assert!(matches!(error, RunnerError::AttributesOutsideRegion { node, .. } if node == other), "{error}");
}
@@ -33,6 +33,18 @@ pub fn opacity_toggles(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Number(100.)));
}
/// Frozen mirror of the `DocumentNodeMetadata` variant the migration below uses.
#[derive(Serialize)]
pub enum Reflected {
DocumentNodePath,
}
/// Gives the node its own path.
#[migration("vector_nodes::bounding_box"@1 => @2)]
pub fn bounding_box_own_path(inputs: &mut Inputs) {
inputs.push_reflection(Reflected::DocumentNodePath);
}
pub const ROTATION: u32 = 2;
/// Rotation is now stored in degrees.
@@ -1,3 +1,4 @@
mod attributes;
mod blobs;
mod compiler;
mod examples;
@@ -5,8 +6,9 @@ mod networks;
mod registration;
mod rewrite;
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use document_graph_storage::{NodeId, NodeInput, ROOT_NETWORK, Registry};
use examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
use migration_core::{decl, literal, literal_of};
use migration_runner::RunnerError;
use migration_runner::testing::{Fixture, registered};
@@ -57,6 +59,19 @@ fn opacity_toggles_build_the_target_layout() {
assert_eq!(fixture.declaration_of(&migrated, opacity), Some(decl!("blending_nodes::opacity"@2)));
}
#[test]
fn reflection_input_stores_what_it_reflects() {
let mut fixture = Fixture::new(&BoundingBoxOwnPath);
let bounding_box = fixture.add(decl!("vector_nodes::bounding_box"@1), vec![literal(Tagged::Number(1.))]);
let migrated = fixture.migrate(&BoundingBoxOwnPath).unwrap();
let slots = migrated.node_instances[&bounding_box].inputs();
assert_eq!(slots.len(), 2);
assert_eq!(slots[1].input, NodeInput::Reflection);
assert_eq!(slots[1].attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
}
#[test]
fn transform_converts_a_literal_rotation() {
let mut fixture = Fixture::new(&TransformDegrees);
@@ -13,6 +13,9 @@ fn every_migration_registers_once() {
sources.sort();
let mut expected = vec![
decl!("attributes::outside"@1),
decl!("attributes::placed"@1),
decl!("attributes::renamed"@1),
decl!("blending_nodes::opacity"@1),
decl!("blob_nodes::text"@1),
decl!("compiler::anchor"@1),
@@ -30,6 +33,7 @@ fn every_migration_registers_once() {
decl!("order::static_late"@1),
decl!("transform_nodes::transform"@1),
decl!("vector_nodes::angle_between"@1),
decl!("vector_nodes::bounding_box"@1),
decl!("vector_nodes::extract_xy"@1),
decl!("vector_nodes::split_vec2"@2),
];
@@ -1,6 +1,6 @@
//! The history properties of `migration_runner::testing` on the examples.
use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use crate::examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
use migration_core::{decl, literal};
use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered};
@@ -18,6 +18,11 @@ fn opacity_toggles_commute() {
check_commutation(&OpacityToggles, &numbers(2));
}
#[test]
fn bounding_box_own_path_commutes() {
check_commutation(&BoundingBoxOwnPath, &numbers(1));
}
#[test]
fn transform_degrees_commutes() {
check_commutation(&TransformDegrees, &numbers(3));
+25 -2
View File
@@ -12,7 +12,7 @@ pub(crate) struct NodeSource {
pub version: u32,
pub function: String,
pub file: PathBuf,
/// The parameters and output as written, without their attributes. Comparing it tells whether stored inputs still fit.
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
pub signature: String,
}
@@ -131,7 +131,10 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
}
let function_name = function.sig.ident.to_string();
let parameters = function.sig.inputs.iter().map(|parameter| match parameter {
// A `#[data]` field is the node's own state rather than a stored input, so documents don't notice it changing
let is_data_field = |parameter: &&syn::FnArg| matches!(parameter, syn::FnArg::Typed(typed) if typed.attrs.iter().any(|attribute| attribute.path().is_ident("data")));
let parameters = function.sig.inputs.iter().filter(|parameter| !is_data_field(parameter)).map(|parameter| match parameter {
syn::FnArg::Typed(typed) => {
let (pattern, ty) = (&typed.pat, &typed.ty);
quote::quote!(#pattern: #ty).to_string()
@@ -149,3 +152,23 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
signature,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn data_fields_are_left_out_of_the_signature() {
let function: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(category("Raster"))]
fn lookup(_: impl Ctx, image: Item<Color>, #[data] cache: Cache) -> Item<Color> {
image
}
};
let node = node_source(&function, Path::new("lib.rs"), &["raster_nodes".to_string()]).expect("the function is a node");
assert_eq!(node.identifier, "raster_nodes::LookupNode");
assert!(!node.signature.contains("cache"), "{}", node.signature);
assert!(node.signature.contains("image"), "{}", node.signature);
}
}
+21 -4
View File
@@ -1,6 +1,6 @@
//! Scaffolds node migrations into `migration-nodes`, one file per step, in a module per node crate.
use crate::lineage::{MigrationStep, find_migrations};
use crate::lineage::{MigrationStep, find_all_migrations};
use crate::nodes::{NodeSource, find_nodes};
use convert_case::{Case, Casing};
use std::path::{Path, PathBuf};
@@ -18,7 +18,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
match (command, arguments) {
("new", []) => {
let steps = missing_steps(&nodes, &find_migrations(&migrations)?);
let steps = missing_steps(&nodes, &find_all_migrations(workspace, &MIGRATION_CRATES)?);
if steps.is_empty() {
println!("Every node version already has a migration leading to it");
return Ok(());
@@ -35,7 +35,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
));
}
let steps = missing_steps(std::slice::from_ref(node), &find_migrations(&migrations)?);
let steps = missing_steps(std::slice::from_ref(node), &find_all_migrations(workspace, &MIGRATION_CRATES)?);
if steps.is_empty() {
return Err(format!("migrations up to `{}`@{} already exist", node.identifier, node.version));
}
@@ -168,7 +168,7 @@ fn write_step(migrations: &Path, node: &NodeSource, name: &str, step: &str, from
/// Describe what changed from version {from}.\n\
#[migration({step})]\n\
pub fn {name}(inputs: &mut Inputs) {{\n\
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, or `&mut Downstream`\");\n\
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, `&mut Downstream`, or `&mut Attributes`\");\n\
}}\n\n\
#[cfg(test)]\n\
mod tests {{\n\
@@ -242,6 +242,7 @@ fn declare_module(file: &Path, module: &str) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::*;
use crate::lineage::find_migrations;
/// A workspace with one node crate and an empty `migration-nodes`, removed on drop.
struct Workspace(PathBuf);
@@ -329,6 +330,22 @@ mod tests {
assert!(missing_steps(&nodes, &found).is_empty());
}
#[test]
fn a_version_reached_from_a_compiled_migration_needs_no_step() {
let workspace = Workspace::new("compiled");
let compiled = workspace.0.join("document/migrations/compiled/src");
std::fs::create_dir_all(&compiled).unwrap();
std::fs::write(
compiled.join("lib.rs"),
"#[migration(\"old::Node\"@1 => \"blending_nodes::OpacityNode\"@2)]\npub fn opacity_from_node(inputs: &mut Inputs) {}\n",
)
.unwrap();
scaffold(&workspace.0, "new", &[]).unwrap();
assert!(!workspace.0.join(MIGRATIONS).join("blending_nodes/opacity_v1.rs").exists());
assert!(workspace.read("legacy/brighten_v1.rs").contains("\"legacy::adjust::BrightenNode\"@1 => @2"));
}
#[test]
fn a_file_no_module_declares_is_no_migration() {
let workspace = Workspace::new("undeclared");
@@ -1,7 +1,7 @@
use crate::consts::DEFAULT_STROKE_WIDTH;
use crate::messages::portfolio::document::SelectionParts;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
@@ -429,7 +429,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut layers = Vec::new();
for (_, new_vector, transform) in paths {
let Some(node_type) = resolve_network_node_type("Path") else {
let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
error!("Path node does not exist");
continue;
};
@@ -987,17 +987,17 @@ mod test {
.iter()
.find_map(|(id, node)| (node.implementation == graph_craft::document::DocumentNodeImplementation::Definition(entry)).then_some(*id))
.expect("the pasted layer");
let (inner, input_index) = interface.document_network().definitions[&entry]
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
let inner = interface.document_network().definitions[&entry]
.nodes
.iter()
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
.expect("the entry should have a value input");
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
.expect("the entry should have an Extend node");
let before = interface.document_network().definitions[&entry].clone();
let NodeInput::Value { tagged_value, exposed } = &before.nodes[&inner].inputs[input_index] else {
unreachable!("the input was found as a value")
};
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[layer]);
// Leaving out the stack below keeps the entry a working layer
let no_base = NodeInput::type_default(graphene_std::list!(graphene_std::Graphic), false);
interface.set_input(&InputConnector::node_at_index(inner, 0), no_base, &[layer]);
assert_ne!(interface.document_network().definitions[&entry], before, "the edit should change the pasted entry");
editor.paste_from_clipboard(clipboard.clone()).await;
@@ -64,6 +64,9 @@ pub struct DropdownInput {
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (we can replace this with `usize` if we switch to a Rust-based GUI)
#[serde(rename = "selectedIndex")]
pub selected_index: Option<u32>,
// Shown while no entry is selected
#[derivative(Default(value = "\"-\".to_string()"))]
pub placeholder: String,
#[serde(rename = "drawIcon")]
pub draw_icon: bool,
pub disabled: bool,
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::core_types::misc::format_f64;
use graphene_std::generator::Generator;
use graphene_std::gradient::Gradient;
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
@@ -32,7 +33,7 @@ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
use kurbo::BezPath;
use std::any::Any;
use std::ops::Range;
@@ -394,6 +395,7 @@ macro_rules! inspectable_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
List<i64>,
@@ -450,6 +452,7 @@ macro_rules! inspectable_types {
Item<Raster<GPU>>,
Item<Color>,
Item<Gradient>,
Item<Generator>,
Item<String>,
Item<f64>,
Item<i64>,
@@ -618,7 +621,7 @@ impl<T: TableItemLayout> TableItemLayout for Item<T> {
}
}
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
let attribute_keys: Vec<String> = self.attributes().keys().filter(|key| !key.starts_with(INTERNAL_ATTRIBUTE_PREFIX)).map(str::to_string).collect();
// A single element, so no leading ID column, unlike the `List` table
let saved_gradient_settings = data.gradient_settings;
@@ -792,6 +795,45 @@ impl TableItemLayout for Coverage {
}
}
impl TableItemLayout for Effects {
fn type_name() -> &'static str {
"Effects"
}
fn identifier(&self) -> String {
"Effects".to_string()
}
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for Effect {
fn type_name() -> &'static str {
"Effect"
}
fn identifier(&self) -> String {
"Effect".to_string()
}
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"TransferCurve"
@@ -857,6 +899,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPU(item) => item.identifier(),
Self::Color(item) => item.identifier(),
Self::Gradient(item) => item.identifier(),
Self::Generator(item) => item.identifier(),
Self::Text(item) => item.identifier(),
Self::NoneList(list) => list.identifier(),
Self::GraphicList(list) => list.identifier(),
@@ -865,6 +908,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPUList(list) => list.identifier(),
Self::ColorList(list) => list.identifier(),
Self::GradientList(list) => list.identifier(),
Self::GeneratorList(list) => list.identifier(),
Self::TextList(list) => list.identifier(),
Self::StrokeList(list) => list.identifier(),
}
@@ -882,6 +926,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
Self::Color(item) => item.layout_with_breadcrumb(data),
Self::Gradient(item) => item.layout_with_breadcrumb(data),
Self::Generator(item) => item.layout_with_breadcrumb(data),
Self::Text(item) => item.layout_with_breadcrumb(data),
Self::NoneList(list) => list.layout_with_breadcrumb(data),
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
@@ -890,6 +935,7 @@ impl TableItemLayout for Graphic {
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
Self::ColorList(list) => list.layout_with_breadcrumb(data),
Self::GradientList(list) => list.layout_with_breadcrumb(data),
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
Self::TextList(list) => list.layout_with_breadcrumb(data),
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
}
@@ -1213,6 +1259,11 @@ macro_rules! impl_table_item_layout_for_choice_enum {
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
BevelDirection,
BevelStyle,
EffectKind,
Generator,
GlowSource,
GradientForm,
GradientSpread,
GradientSpace,
@@ -1359,9 +1410,11 @@ macro_rules! known_item_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
Gradient,
Generator,
Color,
NodeId,
DAffine2,
@@ -1383,6 +1436,12 @@ macro_rules! known_item_types {
Appearance,
Coverage,
Cover,
Effects,
Effect,
EffectKind,
GlowSource,
BevelStyle,
BevelDirection,
DashPattern,
BoxCorners,
TransferCurve,
@@ -262,9 +262,6 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume
if expected.visible != actual.visible {
let _ = writeln!(out, " visible: expected={} actual={}", expected.visible, actual.visible);
}
if expected.skip_deduplication != actual.skip_deduplication {
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
}
if expected.compile_metadata != actual.compile_metadata {
let _ = writeln!(out, " compile_metadata: expected={:?} actual={:?}", expected.compile_metadata, actual.compile_metadata);
}
@@ -325,6 +325,9 @@ pub enum DocumentMessage {
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
},
UpdateEffectsReach {
effects_reach: HashMap<NodeId, f64>,
},
Undo,
UngroupSelectedLayers,
UngroupLayer {
@@ -1915,6 +1915,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
}
DocumentMessage::UpdateEffectsReach { effects_reach } => {
let layer_effects_reach = effects_reach
.into_iter()
.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))
.collect();
self.network_interface.update_effects_reach(layer_effects_reach);
}
DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
@@ -4894,7 +4902,7 @@ mod document_message_handler_tests {
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
// Inspecting it via the Data panel (which splices in a monitor node) must not leave a dangling reference that crashes compilation.
// Inspecting it via the Data panel must not leave a dangling reference that crashes compilation.
#[tokio::test]
async fn merge_selected_nodes_while_inspecting_does_not_crash() {
let mut editor = EditorTestUtils::create();
@@ -4909,7 +4917,7 @@ mod document_message_handler_tests {
let merged = editor.active_document().network_interface.selected_nodes_in_nested_network(&[]).unwrap().0.clone();
assert_eq!(merged.len(), 1, "merge should leave one encapsulating node selected");
// Simulate the Data panel inspecting the merged node, which compiles the graph with a monitor node spliced in
// Simulate the Data panel inspecting the merged node
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
let document_id = portfolio.active_document_id.unwrap();
let document = portfolio.documents.get_mut(&document_id).unwrap();
@@ -5069,15 +5077,11 @@ mod document_message_handler_tests {
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
let news: Vec<graphene_std::list::Item<graphene_std::Graphic>> = instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<graphene_std::Graphic>>(&editor.runtime)
.collect();
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
let phantom_count = news
.iter()
.flat_map(|new| new.iter_element_values())
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
.count();
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element");
let phantom_count = news.iter().filter(|new| matches!(new.element(), graphene_std::Graphic::None(_))).count();
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
}
@@ -137,7 +137,9 @@ impl<'a> ModifyInputsContext<'a> {
self.network_interface.move_node_to_chain_start(&smooth_anchors_id, layer, &[], self.import);
// Add Path node to chain start (closest to the Merge node)
let path = resolve_network_node_type("Path").expect("Path node does not exist").default_node_template();
let path = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Path node does not exist")
.default_node_template();
let path_id = NodeId::new();
self.network_interface.insert_node(path_id, path, &[]);
self.network_interface.move_node_to_chain_start(&path_id, layer, &[], self.import);
@@ -150,7 +152,7 @@ impl<'a> ModifyInputsContext<'a> {
let (vector, paths) = Vector::from_bezpath(&bezpath);
let modification = Box::new(VectorModification::create_from_vector(&vector, &paths));
let shape = resolve_network_node_type("Path")
let shape = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Path node does not exist")
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]);
let shape_id = NodeId::new();
@@ -410,7 +412,7 @@ impl<'a> ModifyInputsContext<'a> {
// If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`.
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
if node_definition.identifier == "Path" {
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
let layer_input_type = self.network_interface.input_type(&InputConnector::layer_secondary_input(output_layer.to_node()), &[]);
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
@@ -759,20 +761,26 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let Some(output_layer) = self.get_output_layer() else { return };
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 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;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
let [start, end] = match gradient_form {
GradientForm::Linear => LINEAR_DIALS,
GradientForm::Radial => RADIAL_DIALS,
};
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
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.
@@ -994,7 +1002,7 @@ impl<'a> ModifyInputsContext<'a> {
}
pub fn vector_modify(&mut self, modification_type: VectorModificationType) {
let Some(path_node_id) = self.existing_network_node_id("Path", true) else {
let Some(path_node_id) = self.existing_proto_node_id(graphene_std::vector::path::IDENTIFIER, true) else {
return;
};
self.network_interface.vector_modify(&path_node_id, modification_type);
@@ -175,44 +175,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
icon: Some("NodeMerge"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(4), 0)],
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(-14, -2)),
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(-14, -1)),
..Default::default()
},
// Derive the parent layer's NodeId from the document path
NodeTemplate {
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 0)),
..Default::default()
},
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(1), 0),
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(2), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::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(3), 0)],
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()
@@ -244,7 +225,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
icon: Some("NodeArtboard"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(3), 0)],
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
call_argument: generic!(T),
@@ -256,32 +237,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::import(item!(TaggedValue), 4),
NodeInput::import(item!(TaggedValue), 5),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
..Default::default()
},
// Derive the parent layer's NodeId from the document path
NodeTemplate {
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 3)),
..Default::default()
},
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
NodeInput::node(NodeId(1), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
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(2), 0),
NodeInput::node(NodeId(0), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
@@ -769,56 +731,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Path",
version: 1,
category: "Vector: Geometry",
icon: Some("NodePath"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T),
skip_deduplication: true,
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::import(concrete!(graphene_std::vector::VectorModification), 1),
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
],
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(vector::path_modify::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::type_default(item!(Vector), true),
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
],
input_metadata: vec![
("Content", "The original shape that edits made with the Pen and Path tools are applied to.").into(),
("Modification", "The edits made with the Pen and Path tools, stored as changes to points and segments.").into(),
],
output_names: vec!["Modified".to_string()],
output_descriptions: vec!["The shape with the Pen and Path tool edits applied.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Holds the edits made with the Pen and Path tools, applying them to the incoming shape."),
inspector: None,
},
];
document_node_derive::post_process_nodes(custom)
@@ -848,14 +760,11 @@ fn static_node_inspector() -> NodeInspector {
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("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("grid_inspector".to_string(), Box::new(node_inspector::grid_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(
"monitor_inspector".to_string(),
Box::new(|_node_id, _context| node_inspector::string_inspector("Used internally by the editor to read the data passing through it.")),
);
map
}
@@ -23,7 +23,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
// Add the rest of the protonodes from the macro.
// Typed nodes are registered in `core_types::NODE_REGISTRY` via the macro's auto-generated `register_node` codegen.
// `skip_impl` nodes (e.g. Cache, Monitor) bypass that registration but are wired up manually in
// `skip_impl` nodes (e.g. Cache) bypass that registration but are wired up manually in
// `interpreted_executor::node_registry::NODE_REGISTRY` via `async_node!`. We consult that extended registry as a
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
@@ -183,7 +183,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::AddPathNode => {
if let Some(layer) = make_path_editable_is_allowed(network_interface) {
responses.add(NodeGraphMessage::CreateNodeInLayerWithTransaction {
node_type: DefinitionIdentifier::Network("Path".into()),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER),
layer,
});
responses.add(EventMessage::SelectionChanged);
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
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::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
// ============
// STRUCT TYPES
// ============
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().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::<BevelStyle>(x) => enum_choice::<BevelStyle>().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::<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::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -1001,7 +1005,12 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
}
}
let parameter_widgets_info = ParameterWidgetsInfo {
blank_assist: false,
..parameter_widgets_info
};
let ParameterWidgetsInfo {
document_id,
document_node,
node_id,
index,
@@ -1025,8 +1034,27 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
Some(TaggedValue::TypeDefault(_)) => Font::default(),
_ => return (first_widgets, second_widgets),
};
let filters = vec![TypeFilter::font()];
let file_drop_action = IngestAction::resource_input(document_id, node_id, index, &filters);
let load_button = IconButton::new("FileImport", 24)
.tooltip_label("Load Font File")
.tooltip_description("Use a font that isn't in the list by loading its .ttf or .otf file. The font is saved with the document.")
.on_update(move |_| {
IngestMessage::SetResourceInput {
document_id,
node_id,
input_index: index,
filters: filters.clone(),
}
.into()
})
.widget_instance();
{
first_widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
load_button,
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
DropdownInput::new(vec![
fonts
@@ -1050,7 +1078,15 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
.collect::<Vec<_>>(),
])
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
.placeholder(font.font_family.clone())
.virtual_scrolling(true)
.on_file_drop(move |file| {
IngestMessage::Ingest {
content: DataTransferItem::from_file(PathBuf::from(&file.name), Some(file.mime_type.as_str()).filter(|mime| !mime.is_empty()), file.data.clone()).into(),
action: file_drop_action.clone(),
}
.into()
})
.widget_instance(),
]);
@@ -1094,6 +1130,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
})
.map(|i| i as u32),
)
.placeholder(font.font_style.clone())
.widget_instance(),
]);
second_widgets = Some(second_row);
@@ -3013,6 +3050,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
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::*;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
// 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) => {
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
Some(&TaggedValue::Number(value)) => Some(value),
_ => None,
};
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
}
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're exactly those
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, [start, end], tooltip) in [
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
] {
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures == Some([start, end]))
.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 curvatures would get without this panel
let options = ParameterOptions {
soft_min: Some(-1.),
soft_max: Some(1.),
slider: true,
..Default::default()
};
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(curvature(StartCurvatureInput::INDEX));
layout.extend(curvature(EndCurvatureInput::INDEX));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*;
@@ -3143,8 +3253,8 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
} else {
let number_of_inputs = context.network_interface.number_of_inputs(&node_id, context.selection_network_path);
for input_index in 1..number_of_inputs {
// Hide inputs that are connected to a scope
if let Some(NodeInput::Scope(_)) = context
// Hide inputs that are connected to a scope or filled in by the compiler
if let Some(NodeInput::Scope(_) | NodeInput::Reflection(_)) = context
.network_interface
.input_from_connector(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
{
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
_ => Self::General,
}
@@ -270,7 +270,7 @@ impl OverlayContext {
}
}
pub fn take_scene(self) -> VelloSceneBuilder {
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
let empty_scene = overlay_scene(&internal.viewport);
std::mem::replace(&mut internal.scene, empty_scene)
@@ -486,13 +486,13 @@ pub enum DrawHandles {
}
pub(super) struct OverlayContextInternal {
scene: VelloSceneBuilder,
scene: VelloSceneBuilder<'static>,
viewport: ViewportMessageHandler,
visibility_settings: OverlaysVisibilitySettings,
}
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
const MAX_TEXTURE_SIZE: u32 = 2048;
@@ -7,6 +7,7 @@ use std::sync::Arc;
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum ResourceMessage {
StoreEmbedded { resource_id: ResourceId, data: Arc<[u8]> },
StoreFont { resource_id: ResourceId, font: Font, data: Arc<[u8]> },
AddFont { resource_id: ResourceId, font: Font },
ResolveAll,
Resolve { resource_id: ResourceId },
@@ -35,6 +35,20 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
self.registry.resolve(&resource_id, hash);
responses.add(ResourceStorageMessage::Store { data });
}
ResourceMessage::StoreFont { resource_id, font, data } => {
let hash = ResourceHash::from(data.as_ref());
self.registry.push_source_back(&resource_id, DataSource::Embedded);
self.registry.push_source_back(
&resource_id,
DataSource::Font {
family: font.font_family.clone(),
style: Some(font.font_style.clone()),
},
);
self.registry.resolve(&resource_id, hash);
responses.add(ResourceStorageMessage::Store { data });
responses.add(FontsMessage::ResourceResolved { font, hash });
}
ResourceMessage::AddFont { resource_id, font } => {
let style = fonts.font_catalog.find_font_style_in_catalog(&font);
let style_name = style.map(|style| style.to_named_style()).unwrap_or_else(|| font.font_style.clone());
@@ -872,7 +872,7 @@ async fn demo_artwork_vector_modifications_still_apply() {
let document = editor.active_document();
let network = &document.network_interface;
let path_definition = DefinitionIdentifier::Network("Path".into());
let path_definition = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let mut path_layers = 0;
let mut any_curve = false;
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
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.
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
/// Transform from document space to viewport space.
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.
@@ -131,7 +133,7 @@ impl DocumentMetadata {
let mut use_local = true;
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
let identifier = DefinitionIdentifier::Network("Path".into());
let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier)
&& let Some(&source) = self.first_element_source_ids.get(&layer.to_node())
&& !network_interface
@@ -347,9 +349,9 @@ impl DocumentMetadata {
}
/// 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. 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.
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
/// 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.
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 stroke = self
.layer_appearance_attributes
@@ -359,8 +361,10 @@ impl DocumentMetadata {
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())
});
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
Some([min - reach, max + reach])
}
/// Get the bounding box of the click target of the specified layer in viewport space
@@ -732,7 +736,7 @@ mod tests {
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
let [min, max] = metadata.bounding_box_document_with_stroke(layer).unwrap();
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
assert_eq!((min.x, max.x), (0., 110.));
}
@@ -1216,9 +1216,9 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
let path = vec![merge];
editor.enter_editable_network(merge).await;
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Origins to Polyline".into()), 0, 0).await;
let path = vec![subgraph];
editor.enter_editable_network(subgraph).await;
let import_count = editor.active_document().network_interface.number_of_imports(&path);
// With a primary, the only one is past the last import
@@ -1226,20 +1226,20 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
let empty_connectors = network_interface.empty_import_export_connectors(true, &path);
assert_eq!(empty_connectors.iter().map(|(index, _)| *index).collect::<Vec<_>>(), vec![import_count]);
// The attribute name given to Merge's interior Write Attribute node
let write_attribute = network_interface
// The closed setting given to the subgraph's interior Points to Polyline node
let points_to_polyline = network_interface
.nested_network(&path)
.and_then(|network| {
network
.nodes
.iter()
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::graphic::write_attribute::IDENTIFIER))
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::vector::points_to_polyline::IDENTIFIER))
})
.map(|(node_id, _)| *node_id)
.expect("Merge should contain a Write Attribute node");
let value_input = InputConnector::node_at_index(write_attribute, 1);
.expect("Origins to Polyline should contain a Points to Polyline node");
let value_input = InputConnector::node_at_index(points_to_polyline, 1);
let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&value_input, &path) else {
panic!("Merge's Write Attribute node should be given its attribute name as a value");
panic!("The Points to Polyline node should be given its closed setting as a value");
};
let displaced_value = (**tagged_value).clone();
@@ -1257,7 +1257,7 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
"the new import should be wired to the input"
);
let network_interface = &editor.active_document().network_interface;
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(merge, import_count), &[]);
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(subgraph, import_count), &[]);
assert!(
matches!(new_input, Some(NodeInput::Value { tagged_value, exposed: true }) if **tagged_value == displaced_value),
"the new import should take over the value its wire displaced, found {new_input:?}"
@@ -1273,11 +1273,11 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
let network_interface = &editor.active_document().network_interface;
assert!(network_interface.empty_import_export_connectors(true, &path).iter().any(|(index, _)| *index == 0));
// The content given to Merge's interior Write Attribute node by its Into Group node
let wired_input = InputConnector::node_at_index(write_attribute, 0);
// The points given to the subgraph's interior Points to Polyline node by its Combine Paths node
let wired_input = InputConnector::node_at_index(points_to_polyline, 0);
assert!(
matches!(network_interface.input_from_connector(&wired_input, &path), Some(NodeInput::Node { .. })),
"Merge's Write Attribute node should be wired its content from another node"
"The Points to Polyline node should have its points wired from another node"
);
editor
.handle_message(NodeGraphMessage::AddImportAndConnect {
@@ -864,14 +864,15 @@ async fn reconciling_an_input_value_edit_reproduces_the_interface() {
let group = only_group(editor);
editor.active_document_mut().network_interface.make_editable(&[group]);
let interface = &mut editor.active_document_mut().network_interface;
let (inner, index) = interface
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
let inner = interface
.nested_network(&[group])
.expect("the group's network")
.nodes
.iter()
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
.expect("a node with a value input inside the group");
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
.expect("an Extend node inside the group");
interface.set_input(&InputConnector::node_at_index(inner, 0), NodeInput::value(TaggedValue::None, false), &[group]);
})
.await;
}
@@ -1064,13 +1065,14 @@ fn table_layer(editor: &EditorTestUtils) -> (NodeId, graph_craft::document::Netw
.expect("a committed layer should name a table entry")
}
/// A node inside the table entry `definition`, and the index of one of its value inputs.
fn value_input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
/// The Extend node inside the layer's table entry `definition`, and the index of its base input.
fn input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
editor.active_document().network_interface.document_network().definitions[&definition]
.nodes
.iter()
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
.expect("the layer's network should have a node with a value input")
.find_map(|(id, node)| (node.implementation == extend).then_some((*id, 0)))
.expect("the layer's network should have an Extend node")
}
/// The network location `deltas` recorded for a write to an input of `node_id`.
@@ -1119,7 +1121,7 @@ async fn an_edit_inside_a_table_entry_constructs_the_diff() {
let (layer, _) = table_layer(&editor);
editor.active_document_mut().network_interface.make_editable(&[layer]);
let (layer, definition) = table_layer(&editor);
let (inner, input_index) = value_input_inside(&editor, definition);
let (inner, input_index) = input_inside(&editor, definition);
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
@@ -1174,7 +1176,7 @@ async fn a_write_keeps_its_network_when_the_instance_changes_implementation() {
let (layer, _) = table_layer(&editor);
editor.active_document_mut().network_interface.make_editable(&[layer]);
let (layer, definition) = table_layer(&editor);
let (inner, input_index) = value_input_inside(&editor, definition);
let (inner, input_index) = input_inside(&editor, definition);
let interface = &mut editor.active_document_mut().network_interface;
interface.discard_deltas();
@@ -1387,14 +1389,10 @@ async fn making_an_instance_unique_forks_its_network() {
assert_ne!(forked, definition);
assert!(!interface.is_shared(&copy, &[]) && !interface.is_shared(&layer, &[]));
let (inner, input_index) = value_input_inside(&editor, forked);
let (inner, input_index) = input_inside(&editor, forked);
let original = editor.active_document().network_interface.document_network().definitions[&definition].clone();
let interface = &mut editor.active_document_mut().network_interface;
let NodeInput::Value { tagged_value, exposed } = &interface.document_network().definitions[&forked].nodes[&inner].inputs[input_index] else {
unreachable!("the input was found as a value")
};
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[copy]);
interface.set_input(&InputConnector::node_at_index(inner, input_index), NodeInput::value(TaggedValue::None, false), &[copy]);
assert_ne!(interface.document_network().definitions[&forked], original, "the edit should change the copy's network");
assert_eq!(interface.document_network().definitions[&definition], original, "the original's network should be untouched");
@@ -62,6 +62,19 @@ impl NodeNetworkInterface {
layer_paths
}
/// The path of every node in the document's networks made from the definition.
pub fn node_paths_with_reference(&self, reference: &DefinitionIdentifier) -> Vec<Vec<NodeId>> {
let mut node_paths = Vec::new();
self.for_each_network(&mut |network_path, network_metadata| {
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
if self.reference(node_id, network_path).as_ref() == Some(reference) {
node_paths.push([network_path, &[*node_id]].concat());
}
}
});
node_paths
}
fn for_each_layer(&self, visit: &mut impl FnMut(&[NodeId], NodeId)) {
self.for_each_network(&mut |network_path, network_metadata| {
for (node_id, node_metadata) in &network_metadata.persistent_metadata.node_metadata {
@@ -1050,11 +1063,11 @@ impl NodeNetworkInterface {
Some(transformed.bounding_box())
}
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
self.document_metadata.document_bounds(include_artboards, true, || {
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
})
}
@@ -1071,17 +1084,17 @@ impl NodeNetworkInterface {
.reduce(Quad::combine_bounds)
}
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
return None;
};
selected_nodes
.selected_layers(&self.document_metadata)
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
.reduce(Quad::combine_bounds)
}
@@ -1209,7 +1222,6 @@ impl NodeNetworkInterface {
node.inputs = old_node.inputs;
node.call_argument = old_node.manual_composition.unwrap_or_default();
node.visible = old_node.visible;
node.skip_deduplication = old_node.skip_deduplication;
node.original_location = old_node.original_location;
node_metadata.persistent_metadata.display_name = old_node.alias;
node_metadata.persistent_metadata.locked = old_node.locked;
@@ -221,7 +221,7 @@ impl NodeNetworkInterface {
return;
};
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
let deltas = if current.implementation == target.implementation {
field_deltas(location, local_id, (current, current_metadata), (&target, &target_metadata))
} else {
vec![
@@ -61,7 +61,7 @@ static INPUT_CONVERSIONS: Lazy<HashMap<ProtoNodeIdentifier, Vec<Option<&'static
.collect()
});
/// Proto nodes whose every implementation returns its one input's type unchanged (like Monitor and Memoize), so a wire through one is constrained by what it feeds.
/// Proto nodes whose every implementation returns its one input's type unchanged (like Memoize), so a wire through one is constrained by what it feeds.
static TYPE_PRESERVING_NODES: Lazy<HashSet<ProtoNodeIdentifier>> = Lazy::new(|| {
NODE_REGISTRY
.iter()
@@ -420,7 +420,7 @@ impl NodeNetworkInterface {
}
/// A check of which wire types an input accepts, built once so testing many types searches the node's matching implementations only once.
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Monitor) also needs the inputs it feeds to accept the type.
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Memoize) also needs the inputs it feeds to accept the type.
fn type_acceptor(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Box<dyn Fn(&Type) -> bool> {
let accepts_here: Box<dyn Fn(&Type) -> bool> = match input_connector {
InputConnector::Export(export_index) => match network_path.split_last() {
@@ -768,25 +768,48 @@ mod tests {
#[tokio::test]
async fn subgraph_inputs_look_through_type_preserving_nodes() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let path_node_id = editor.create_node_by_name(DefinitionIdentifier::Network("Path".into())).await;
let merge = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 0, 0).await;
// The Path subgraph's content goes through a Monitor node, which accepts most types, before the node that needs a vector
let content_types = editor
.active_document()
.network_interface
.potential_valid_input_types(&InputConnector::node_at_index(path_node_id, 0), &[])
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>();
assert!(content_types.iter().any(|ty| ty == "Vector"), "Path's content should accept a vector, found {content_types:?}");
// A new import feeding a Memoize, which accepts most types, before a Path that needs a vector
editor.enter_editable_network(merge).await;
let memoize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::memo::memoize::IDENTIFIER), -20, 10).await;
let path = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), -10, 10).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::node(memoize, 0),
input_connector: InputConnector::node_at_index(path, 0),
})
.await;
let import_index = editor.active_document().network_interface.number_of_imports(&[merge]);
editor
.handle_message(NodeGraphMessage::AddImportAndConnect {
import_index,
input_connector: InputConnector::node_at_index(memoize, 0),
})
.await;
let network_interface = &editor.active_document().network_interface;
let type_names = |input_connector: &InputConnector, network_path: &[super::NodeId]| {
network_interface
.potential_valid_input_types(input_connector, network_path)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
};
let memoize_types = type_names(&InputConnector::node_at_index(memoize, 0), &[merge]);
assert!(memoize_types.iter().any(|ty| ty == "Color"), "Memoize itself should accept a color, found {memoize_types:?}");
let content_types = type_names(&InputConnector::node_at_index(merge, import_index), &[]);
assert!(content_types.iter().any(|ty| ty == "Vector"), "the input should accept a vector, found {content_types:?}");
assert!(
!content_types.iter().any(|ty| ty == "Color"),
"Path's content should not accept a color just because its Monitor does, found {content_types:?}"
"the input should not accept a color just because its Memoize does, found {content_types:?}"
);
}
@@ -6,7 +6,7 @@ impl NodeNetworkInterface {
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))
&& let Some(geometry) = self.document_metadata.vector_modify.get(&path_node)
{
let mut modified = geometry.clone();
@@ -28,7 +28,7 @@ impl NodeNetworkInterface {
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing.
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
self.compute_modified_vector(layer)
}
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
}
/// 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>) {
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
}
}
@@ -21,8 +21,6 @@ pub struct NodeTemplate {
pub implementation: NodeTemplateImplementation,
/// Represents the eye icon for hiding/showing the node in the graph UI.
pub visible: bool,
/// Prevents identical proto nodes from being deduplicated during compilation, e.g. for monitor nodes.
pub skip_deduplication: bool,
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed in italics.
pub display_name: String,
/// Metadata to override the Inspector widgets for each input. Kept the same length as `inputs`.
@@ -57,7 +55,6 @@ impl Default for NodeTemplate {
call_argument: concrete!(Context),
implementation: NodeTemplateImplementation::default(),
visible: true,
skip_deduplication: false,
display_name: String::new(),
input_metadata: Vec::new(),
output_names: Vec::new(),
@@ -110,7 +107,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
compile_metadata: _,
original_location: _,
} = document_node;
@@ -161,7 +157,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
display_name,
input_metadata,
output_names,
@@ -179,7 +174,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
display_name,
mut input_metadata,
mut output_names,
@@ -211,7 +205,6 @@ impl NodeTemplate {
call_argument,
implementation,
visible,
skip_deduplication,
compile_metadata: None,
original_location: Default::default(),
};
@@ -20,7 +20,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -117,10 +117,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"raster_nodes::std_nodes::SampleImageNode",
],
},
NodeReplacement {
node: graphene_std::memo::monitor::IDENTIFIER,
aliases: &["graphene_core::memo::MonitorNode"],
},
NodeReplacement {
node: graphene_std::memo::memoize::IDENTIFIER,
aliases: &["graphene_core::memo::MemoNode", "graphene_core::memo::ImpureMemoNode"],
@@ -299,10 +295,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
aliases: &["math_nodes::GradientTypeNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
aliases: &["math_nodes::SpreadMethodNode"],
@@ -516,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
node: graphene_std::blending_nodes::effects::blur::IDENTIFIER,
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
@@ -537,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::ChannelMixerNode",
],
},
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -546,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
"raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
@@ -944,8 +938,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_core::vector::PathLengthNode"],
},
NodeReplacement {
node: graphene_std::vector::path_modify::IDENTIFIER,
node: graphene_std::vector::path::IDENTIFIER,
aliases: &[
"vector_nodes::vector_modification_nodes::PathModifyNode",
"graphene_core::vector::vector_modification_nodes::PathModifyNode",
"graphene_core::vector::vector_data::modification::PathModifyNode",
"graphene_core::vector::vector_modification::PathModifyNode",
@@ -1162,6 +1157,14 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
(out, hash_to_id)
}
/// The removed Monitor node, which old documents still hold.
const MONITOR_IDENTIFIER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode");
/// Whether the implementation is the removed Monitor node, with or without the type arguments it was once stored with.
fn is_monitor(implementation: &DocumentNodeImplementation) -> bool {
matches!(implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().split('<').next() == Some(MONITOR_IDENTIFIER.as_str()))
}
/// Whether the node is a subgraph that feeds its first input through a Monitor into a Transform proto node and forwards the other four inputs unchanged, making it equivalent to a bare Transform node.
fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph_craft::document::NodeNetwork) -> bool {
let Some(network) = document_network.implementation_network(&node.implementation) else {
@@ -1177,7 +1180,7 @@ fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph
_ => false,
})
};
let Some((monitor_id, monitor)) = find_proto_node(&graphene_std::memo::monitor::IDENTIFIER) else {
let Some((monitor_id, monitor)) = find_proto_node(&MONITOR_IDENTIFIER) else {
return false;
};
let Some((transform_id, transform)) = find_proto_node(&graphene_std::transform_nodes::transform::IDENTIFIER) else {
@@ -1274,6 +1277,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
}
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
@@ -1370,9 +1377,31 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The Merge and Artboard networks no longer pass their content through a Monitor node, since thumbnails are found from the layers themselves.
// The "Path" wrapper network was replaced with the `path` proto node directly. Convert old `Network("Path")` instances to the proto node, forwarding the Content and Modification inputs.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer Path's network impl orphans its child paths.
let path_wrappers: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Path".into()))).then_some((*node_id, path)))
.collect();
for (node_id, network_path) in &path_wrappers {
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let Some(definition) = resolve_document_node_type(&new_reference) else { continue };
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
for (index, input) in old_inputs.into_iter().take(2).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// The Merge and Artboard networks no longer hold a Monitor node or write the layer's path onto their content, since the editor finds thumbnails and writes the paths itself.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: rebuilding the network orphans its child paths.
let monitored_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
let outdated_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
.network_interface
.document_network()
.recursive_nodes()
@@ -1381,17 +1410,37 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
let reference = document.network_interface.reference(node_id, &path)?;
let is_merge_or_artboard = [DefinitionIdentifier::Network("Merge".into()), DefinitionIdentifier::Network("Artboard".into())].contains(&reference);
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
let has_monitor = network.nodes.values().any(|inner_node| inner_node.implementation == monitor);
let path_of_subgraph = DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER);
let has_removed_node = network
.nodes
.values()
.any(|inner_node| is_monitor(&inner_node.implementation) || inner_node.implementation == path_of_subgraph);
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
(is_merge_or_artboard && has_removed_node).then_some((*node_id, path, reference))
})
.collect();
for (node_id, network_path, reference) in &monitored_layers {
for (node_id, network_path, reference) in &outdated_layers {
let Some(definition) = resolve_document_node_type(reference) else { continue };
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
}
// Any Monitor still left becomes a Passthrough of its content, once the passes above have used it to recognize old networks
let monitors: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| is_monitor(&node.implementation))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in &monitors {
let mut passthrough = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
..Default::default()
};
document.network_interface.replace_implementation(node_id, network_path, &mut passthrough);
document.network_interface.set_call_argument(node_id, network_path, passthrough.call_argument);
}
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math Function"
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math Formula", which reads the pair as `a` and `b`.
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
@@ -1637,6 +1686,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
})
.collect();
for (node_id, network_path) in &gradient_form_nodes {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
reset_default_display_name(document, node_id, network_path, "Gradient Form");
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
_ => {
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
graphene_std::renderer::dial_gradient::LINEAR_DIALS
}
};
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
}
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
@@ -1815,6 +1907,52 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
let old_pattern_nodes = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let reference = document.network_interface.reference(node_id, &path)?;
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
let clip_index = match node.inputs.len() {
16 => 1,
15 if starts_with_clip => 0,
_ => return None,
};
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && node.inputs.is_empty() {
return Some((*node_id, path, reference, None, Some(1.)));
}
None
})
.collect::<Vec<_>>();
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
let Some(definition) = resolve_document_node_type(reference) else { continue };
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
if let Some(clip_index) = clip_index {
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
}
}
if let Some(size) = clipped_size {
fill_square_with_pattern(document, node_id, network_path, *size);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
@@ -1874,6 +2012,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.require_whole_document_stage();
}
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
.cloned()
.unwrap_or_default();
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
document.network_interface.insert_node(fill_id, fill_template, network_path);
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
};
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
};
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
wire(document, paint_transform_id, 0, *pattern_node_id);
wire(document, fill_id, 0, rectangle_id);
wire(document, fill_id, 1, paint_transform_id);
wire(document, placement_transform_id, 0, fill_id);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
}
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
if was_in_chain {
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
}
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
let offsets = [
(paint_transform_id, IVec2::new(7, 0)),
(rectangle_id, IVec2::new(7, -3)),
(fill_id, IVec2::new(14, 0)),
(placement_transform_id, IVec2::new(21, 0)),
];
for (node_id, offset) in offsets {
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
}
}
Some(())
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -2405,7 +2613,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
];
for (parameter, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -2726,20 +2933,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
for (i, input) in old_inputs.iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
}
}
// The Threshold node's luminance calculation input was retired
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -3463,7 +3656,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// SVG-import legacy Path nodes baked their geometry at non-exposed input 0; move it to input 1 (the modern slot for VectorModification).
// For exposed input 0, any baked value is unused at runtime, so just reset it.
if reference == DefinitionIdentifier::Network("Path".into()) {
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
let input_0 = node.inputs.first()?;
if let NodeInput::Value { tagged_value, exposed } = input_0
&& let TaggedValue::VectorModification(modification) = &**tagged_value
@@ -4918,7 +5111,7 @@ mod tests {
let content = std::mem::replace(&mut extend.inputs[1], NodeInput::node(monitor_id, 0));
let monitor_template = NodeTemplate {
inputs: vec![content],
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(MONITOR_IDENTIFIER),
..Default::default()
};
network_template.nodes.insert(monitor_id, monitor_template);
@@ -4933,14 +5126,34 @@ mod tests {
else {
panic!("{name} should stay a network node")
};
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
assert!(
network.nodes.values().all(|inner_node| inner_node.implementation != monitor),
"{name} should no longer have a Monitor node"
);
// A Monitor left in place would become a Passthrough, so only the rebuilt network has the definition's node count
let NodeTemplateImplementation::Network(shipped) = resolve_network_node_type(name).expect("The definition should exist").default_node_template().implementation else {
panic!("{name} should be a network node")
};
assert_eq!(network.nodes.len(), shipped.nodes.len(), "{name} should be rebuilt from its definition, without the Monitor node");
}
}
// The removed Monitor node keeps passing on its content wherever it's left
#[test]
fn a_monitor_node_becomes_a_passthrough() {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let content = NodeInput::value(TaggedValue::Number(42.), false);
let monitor_template = NodeTemplate {
inputs: vec![content.clone()],
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode<_, _, _>")),
..Default::default()
};
document.network_interface.insert_node(node_id, monitor_template, &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
assert_eq!(node.inputs, [content]);
}
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
// that fed the decimal index to its two item-at-index nodes
#[test]
@@ -5038,6 +5251,54 @@ mod tests {
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn gradient_form_nodes_become_gradient_curvature_presets() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let (source_id, form_id) = (NodeId(1), NodeId(2));
for (identifier, form, dials) in [
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
] {
let mut document = DocumentMessageHandler::default();
let placeholder = || NodeInput::value(TaggedValue::None, false);
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![placeholder()],
..Default::default()
},
&[],
);
document.network_interface.insert_node(
form_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![placeholder(); 2],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&form_id];
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(
[curvature(1), curvature(2)],
dials.map(|dial| Some(TaggedValue::Number(dial))),
"{form:?} should become its curvature presets"
);
}
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -5987,4 +6248,79 @@ mod tests {
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
}
}
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
#[tokio::test]
async fn clipped_patterns_become_rectangles_filled_with_them() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
let document = editor.active_document_mut();
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
}
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
let mut legacy = NodeTemplate { inputs, ..Default::default() };
legacy.normalize_input_metadata();
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
}
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
assert_eq!(upstream(paint, 0), Some(pattern));
}
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
#[tokio::test]
async fn marbled_mandelbrot_renders_after_migration() {
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction};
use crate::messages::prelude::IngestMessage;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
let data = std::fs::read("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
editor.dispatch(IngestMessage::Ingest {
content: DataTransferItem::from_file("marbled-mandelbrot.graphite".into(), None, data).into(),
action: IngestAction::Open,
});
if let Err(error) = editor.eval_graph_until_finished().await {
panic!("The migrated demo failed to render: {error}");
}
}
}
@@ -6,6 +6,7 @@ use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graphene_std::raster::Image;
use graphene_std::raster_nodes::color_lookup_table::{Lut, LutParseError};
use graphene_std::text::Font;
#[derive(ExtractField)]
pub struct IngestMessageContext {
@@ -66,7 +67,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
let preferred = items.into_iter().min_by_key(|item| match item.data {
TransferData::Svg(_) => 0,
TransferData::Raster { .. } => 1,
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => 2,
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => 2,
TransferData::Text(_) => 3,
TransferData::ApplicationData(_) => 4,
});
@@ -103,11 +104,17 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
return;
}
// The file goes to the document that asked for it, which may no longer be active or open once the dialog closes
let resource_id = ResourceId::new();
let font = if data_type == DataType::Font { Font::from_data(&data) } else { None };
let resource_store_message = match font {
Some(font) => ResourceMessage::StoreFont { resource_id, font, data: data.into() },
None => ResourceMessage::StoreEmbedded { resource_id, data: data.into() },
};
let messages = [
DocumentMessage::AddTransaction,
DocumentMessage::Resource(ResourceMessage::StoreEmbedded { resource_id, data: data.into() }),
resource_store_message.into(),
DocumentMessage::NodeGraph(NodeGraphMessage::SetInputValue {
node_id,
input_index: input_index as usize,
@@ -172,7 +179,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
};
(insert, None)
}
TransferData::Lut(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
};
if !place_at_origin {
@@ -209,7 +216,7 @@ fn unsupported(responses: &mut VecDeque<Message>) {
});
}
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image or LUT only if it fully parses.
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image, LUT, or font only if it parses.
fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> Option<&'static str> {
const WRONG_TYPE: &str = "This input does not accept the format of the chosen file.";
@@ -233,6 +240,7 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
}
LutParseError::Unreadable => "This file could not be read as a LUT. It may be corrupted or an unsupported format variant.",
}),
DataType::Font => Font::from_data(data).is_none().then_some("This file could not be read as a font."),
_ => None,
}
}
@@ -442,6 +450,27 @@ mod tests {
assert!(!stores(IDENTITY_CUBE, TypeFilter::raster()));
}
#[test]
fn resource_input_stores_a_font_file_under_the_name_it_carries() {
let font_file: &[u8] = crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE.as_ref();
let stored_font = |data: &[u8]| {
let responses = ingest_named(data, Some("custom.ttf"), resource_input(TypeFilter::font().types), true);
responses.into_iter().find_map(|message| match message {
Message::Portfolio(PortfolioMessage::DocumentPassMessage {
document_id: REQUESTING_DOCUMENT,
message: DocumentMessage::Resource(ResourceMessage::StoreFont { font, .. }),
}) => Some(font),
_ => None,
})
};
assert_eq!(stored_font(font_file), Some(Font::new("Source Sans Pro".to_string(), "Regular (400)".to_string())));
// A file cut off after its intact signature, and an image named as a font
assert_eq!(stored_font(&font_file[..40]), None);
assert_eq!(stored_font(&Image::new(8, 8, Color::WHITE).to_png()), None);
}
#[test]
fn lookup_table_outside_a_node_input_only_shows_a_dialog() {
let responses = ingest_named(IDENTITY_CUBE, Some("grade.cube"), IngestAction::Import, true);
@@ -23,6 +23,9 @@ const TEXT_MIME: &str = "text/plain";
const GRAPHITE_PREFIX: &str = "graphite: ";
const SNIFFED_TEXT_LENGTH: usize = 4096;
const FONT_FILE_EXTENSIONS: &[&str] = &["ttf", "otf"];
const FONT_FILE_SIGNATURES: [&[u8]; 3] = [&[0, 1, 0, 0], b"OTTO", b"true"];
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
pub enum IngestAction {
@@ -65,6 +68,7 @@ pub enum DataType {
Gdd,
Svg,
Raster(ImageFormat),
Font,
Lut,
Text,
#[default]
@@ -98,6 +102,7 @@ impl DataType {
GDD_FILE_EXTENSION => Self::Gdd,
"svg" => Self::Svg,
extension if LUT_FILE_EXTENSIONS.contains(&extension) => Self::Lut,
extension if FONT_FILE_EXTENSIONS.contains(&extension) => Self::Font,
extension => ImageFormat::from_extension(extension).map_or(Self::Unknown, Self::Raster),
}
}
@@ -113,6 +118,9 @@ impl DataType {
if let Ok(format) = image::guess_format(data) {
return Self::Raster(format);
}
if FONT_FILE_SIGNATURES.iter().any(|signature| data.starts_with(signature)) {
return Self::Font;
}
// Only the head is read as text, where a character split by the cut is the one invalid sequence tolerated
let head = &data[..data.len().min(SNIFFED_TEXT_LENGTH)];
@@ -139,8 +147,7 @@ impl DataType {
Self::Svg => SVG_MIME,
Self::Raster(format) => format.to_mime_type(),
Self::Text => TEXT_MIME,
// The LUT formats share no MIME type
Self::Lut | Self::Unknown => return None,
Self::Lut | Self::Font | Self::Unknown => return None,
})
}
@@ -151,6 +158,7 @@ impl DataType {
Self::Svg => &["svg"],
Self::Raster(format) => format.extensions_str(),
Self::Lut => LUT_FILE_EXTENSIONS,
Self::Font => FONT_FILE_EXTENSIONS,
Self::Text | Self::Unknown => &[],
}
}
@@ -189,6 +197,13 @@ impl TypeFilter {
types: vec![DataType::Lut],
}
}
pub fn font() -> Self {
Self {
name: "Font".into(),
types: vec![DataType::Font],
}
}
}
impl From<TypeFilter> for FileFilter {
@@ -221,6 +236,7 @@ pub enum TransferData {
Document(Vec<u8>),
LegacyDocument(String),
Lut(Vec<u8>),
Font(Vec<u8>),
Other(Vec<u8>),
}
@@ -232,6 +248,7 @@ impl TransferData {
Self::Document(_) => DataType::Gdd,
Self::LegacyDocument(_) => DataType::GraphiteLegacy,
Self::Lut(_) => DataType::Lut,
Self::Font(_) => DataType::Font,
Self::Text(_) | Self::ApplicationData(_) => DataType::Text,
Self::Other(_) => DataType::Unknown,
}
@@ -240,7 +257,7 @@ impl TransferData {
pub fn into_bytes(self) -> Vec<u8> {
match self {
Self::Text(text) | Self::Svg(text) | Self::LegacyDocument(text) => text.into_bytes(),
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Other(data) => data,
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Font(data) | Self::Other(data) => data,
Self::ApplicationData(_) => DataTransferItem::from(self).into_raw().map(|(_, data)| data.into_bytes()).unwrap_or_default(),
}
}
@@ -295,6 +312,7 @@ impl DataTransferItem {
DataType::Svg => text(data, TransferData::Svg),
DataType::Raster(format) => TransferData::Raster { format, data },
DataType::Lut => TransferData::Lut(data),
DataType::Font => TransferData::Font(data),
DataType::Text | DataType::Unknown => TransferData::Other(data),
};
Self { data, path: Some(path) }
@@ -312,7 +330,7 @@ impl DataTransferItem {
},
TransferData::Svg(svg) => Some((DataType::Svg, RawData::Text(svg))),
TransferData::Raster { format, data } => Some((DataType::Raster(format), RawData::Bytes(data))),
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => None,
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => None,
}
}
}
@@ -404,6 +422,7 @@ mod tests {
DataType::from_content("\u{feff}<?xml version=\"1.0\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"/>".as_bytes()),
DataType::Svg
);
assert_eq!(DataType::from_content(b"OTTO\0\x0c"), DataType::Font);
assert_eq!(DataType::from_content(b"just text"), DataType::Unknown);
assert_eq!(DataType::from_content(&[0xff, 0xfe, 0x00]), DataType::Unknown);
}
@@ -426,6 +445,7 @@ mod tests {
assert_eq!(detect(Some("application/graphite+json"), ""), DataType::GraphiteLegacy);
assert_eq!(detect(Some("image/png"), "document.gdd"), DataType::Raster(ImageFormat::Png));
assert_eq!(detect(None, "grade.CUBE"), DataType::Lut);
assert_eq!(detect(None, "Custom.TTF"), DataType::Font);
assert_eq!(detect(Some("application/vnd.iccprofile"), "profile.icm"), DataType::Lut);
assert_eq!(detect(Some("text/csv"), "table.csv"), DataType::Unknown);
assert_eq!(DataType::detect(&[], None, None), DataType::Unknown);
@@ -78,7 +78,7 @@ impl EditTarget {
/// The Path node, which vector edits insert beside a layer with vector content when it's missing.
pub fn path() -> Self {
Self::network_node("Path", Insertion::BesideVectorLayer)
Self::proto_node(graphene_std::vector::path::IDENTIFIER, Insertion::BesideVectorLayer)
}
/// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing.
@@ -23,7 +23,11 @@ pub fn find_spline(document: &DocumentMessageHandler, layer: LayerNodeIdentifier
.network_interface
.upstream_flow_back_from_nodes([layer.to_node()].to_vec(), &[], FlowType::HorizontalFlow)
.map(|node_id| (document.network_interface.reference(&node_id, &[]), node_id))
.take_while(|(reference, _)| reference.as_ref().is_some_and(|node_ref| node_ref != &DefinitionIdentifier::Network("Path".into())))
.take_while(|(reference, _)| {
reference
.as_ref()
.is_some_and(|node_ref| node_ref != &DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))
})
.find(|(reference, _)| {
reference
.as_ref()
@@ -115,7 +119,7 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
// Add a path node after the combine paths node
let path_node_id = NodeId::new();
let path_node = document_node_definitions::resolve_network_node_type("Path")
let path_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
.expect("Failed to create path node")
.default_node_template();
responses.add(NodeGraphMessage::InsertNode {
@@ -342,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
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -76,8 +76,8 @@ mod test_ellipse {
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
Some(ResolvedEllipse {
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
transform: document.metadata().transform_to_document(layer),
})
})
@@ -635,7 +635,8 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
// Must not already have an existing Path node, in the right-most part of the layer chain, which has an empty set of modifications
// (otherwise users could repeatedly keep running this command and stacking up empty Path nodes)
if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1)
if let Some(TaggedValue::VectorModification(modifications)) =
NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), 1)
&& modifications.is_empty()
{
return None;
@@ -698,8 +698,7 @@ mod test_artboard {
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime)
.flatten()
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<Artboard>>(&editor.runtime)
.collect()
}
@@ -280,18 +280,25 @@ fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHand
#[cfg(test)]
mod test_fill {
pub use crate::test_utils::test_prelude::*;
use graphene_std::Graphic;
use graphene_std::color::SRGBA8;
use graphene_std::list::Item;
use graphene_std::vector::fill;
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
// The Fill tool writes solid colors, which reach the paint input embedded as `Graphic` items
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
let instrumented = match editor.eval_graph_until_finished().await {
Ok(instrumented) => instrumented,
Err(e) => panic!("Failed to evaluate graph: {e}"),
};
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).collect()
instrumented
.grab_all_input::<fill::PaintInput, Item<Graphic>>(&editor.runtime)
.filter_map(|paint| match paint.into_element() {
Graphic::Color(color) => Some(color),
_ => None,
})
.collect()
}
#[tokio::test]
@@ -1,6 +1,6 @@
use super::tool_prelude::*;
use crate::consts::SNAP_POINT_TOLERANCE;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -312,7 +312,7 @@ impl Fsm for FreehandToolFsmState {
let parent = document.new_layer_bounding_artboard(input, viewport);
let node_type = resolve_network_node_type("Path").expect("Path node does not exist");
let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let node = node_type.default_node_template();
let nodes = vec![(NodeId(0), node)];
@@ -454,7 +454,7 @@ mod test_freehand {
.filter_map(|layer| {
let graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
// Only get layers with path nodes
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
let vector = document.network_interface.compute_modified_vector(layer)?;
let transform = document.metadata().transform_to_viewport(layer);
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
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 gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_form_reference
&& gradient_form.is_none()
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
{
gradient_form = Some(*value);
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
// Curvatures other than the radial form's are drawn with the linear form's controls
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
Some(&TaggedValue::Number(value)) => value,
_ => 0.,
};
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
}
}
@@ -3366,7 +3369,7 @@ mod test_gradient {
.await;
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 Form' node onto the Fill's fill input wire.
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
@@ -3375,7 +3378,7 @@ mod test_gradient {
})
.await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let form_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
@@ -3384,10 +3387,10 @@ mod test_gradient {
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Form node should have been inserted")
.expect("Gradient Curvature node should have been inserted")
};
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
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");
@@ -6,7 +6,7 @@ use crate::consts::{
};
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::{path_overlays, selected_segments};
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
@@ -2859,7 +2859,7 @@ impl Fsm for PathToolFsmState {
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
layer
} else {
let Some(node_type) = resolve_network_node_type("Path") else {
let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
error!("Could not resolve node type for Path");
continue;
};
@@ -1,7 +1,7 @@
use super::tool_prelude::*;
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, SEGMENT_OVERLAY_SIZE};
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -1434,7 +1434,7 @@ impl PenToolData {
}
// New path layer
let node_type = resolve_network_node_type("Path").expect("Path node does not exist");
let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let nodes = vec![(NodeId(0), node_type.default_node_template())];
let parent = document.new_layer_bounding_artboard(input, viewport);
@@ -2526,7 +2526,7 @@ mod test_pen_tool {
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> {
let document = editor.active_document();
let path_identifier = DefinitionIdentifier::Network("Path".into());
let path_identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
let mut path_layers = document
.metadata()
.all_layers()
@@ -1,7 +1,7 @@
use super::tool_prelude::*;
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -442,7 +442,7 @@ impl Fsm for SplineToolFsmState {
let parent = document.new_layer_bounding_artboard(input, viewport);
let path_node_type = resolve_network_node_type("Path").expect("Path node does not exist");
let path_node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
let path_node = path_node_type.default_node_template();
let spline_node_type = resolve_proto_node_type(graphene_std::vector::spline::IDENTIFIER).expect("Spline node does not exist");
let spline_node = spline_node_type.node_template_input_override([Some(NodeInput::node(NodeId(1), 0))]);
+88 -99
View File
@@ -1,7 +1,8 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -10,12 +11,12 @@ use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::list::{Item, List};
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -38,7 +39,6 @@ pub struct ExecutionResponse {
responses: VecDeque<FrontendMessage>,
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
dropped_thumbnails: Vec<NodeId>,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>,
}
@@ -48,6 +48,8 @@ pub struct ExecutionResponse {
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
PathContent(NodeId),
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
@@ -241,14 +243,14 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view");
}
/// Updates the network to monitor all inputs. Useful for the testing.
/// 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(&mut network);
let instrumented = Instrumented::new(&network);
let resources = document.resources.registry.clone();
@@ -258,7 +260,7 @@ impl NodeGraphExecutor {
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::new(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -288,7 +290,7 @@ impl NodeGraphExecutor {
resources,
previewed,
layers,
observations: self.observations(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
} else if inspected_node_changed {
@@ -314,8 +316,9 @@ impl NodeGraphExecutor {
}
/// Every observation a graph update of the document starts with.
fn observations(&self) -> HashMap<ObservationKey, Observation> {
self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)).into_iter().collect()
fn observations(&self, network_interface: &NodeNetworkInterface) -> HashMap<ObservationKey, Observation> {
let data_panel = self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation));
data_panel.into_iter().chain(path_content_observations(network_interface)).collect()
}
/// Adds an evaluate request for whatever current network is cached.
@@ -445,11 +448,11 @@ impl NodeGraphExecutor {
};
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
let bounds = match export_config.bounds {
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
@@ -483,7 +486,7 @@ impl NodeGraphExecutor {
resources,
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -518,7 +521,6 @@ impl NodeGraphExecutor {
result,
responses: existing_responses,
dropped_thumbnails,
vector_modify,
mut observations,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -645,7 +647,7 @@ impl NodeGraphExecutor {
None => responses.add(response),
}
}
document.network_interface.update_vector_modify(vector_modify);
document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
@@ -1032,6 +1034,7 @@ impl NodeGraphExecutor {
clip_targets,
vector_data,
appearance_attributes,
effects_reach,
backgrounds: _,
} = render_output.metadata;
@@ -1048,6 +1051,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw);
@@ -1179,125 +1183,110 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
path_nodes.into_iter().filter_map(|node_path| {
let key = ObservationKey::PathContent(*node_path.last()?);
let observation = Observation {
node_path,
connector: ObservedConnector::Input(path::ContentInput::INDEX),
overrides: ContextOverrides::default(),
};
Some((key, observation))
})
}
/// The incoming geometry of each 'Path' node, read from its observed content.
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
observations
.iter()
.filter_map(|(key, result)| {
let ObservationKey::PathContent(path_node) = *key else { return None };
let value = result.data.as_ref()?;
let geometry = match value.downcast_ref::<List<Vector>>() {
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
};
Some((path_node, geometry))
})
.collect()
}
// Re-export for usage by tests in other modules
#[cfg(test)]
pub use test::Instrumented;
#[cfg(test)]
mod test {
use std::sync::Arc;
use super::*;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNode, NodeNetwork};
use graphene_std::Context;
use graph_craft::document::NodeNetwork;
use graphene_std::NodeParameter;
use graphene_std::list::Item;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
#[derive(Default)]
pub struct Instrumented {
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<Vec<NodeId>>>>,
protonodes_by_path: HashMap<Vec<NodeId>, Vec<Vec<NodeId>>>,
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<NodeId>>>,
}
impl Instrumented {
/// Adds montior nodes to the network
fn add(&mut self, network: &mut NodeNetwork, path: &mut Vec<NodeId>) {
// Required to do seperately to satiate the borrow checker.
let mut monitor_nodes = Vec::new();
for (id, node) in network.nodes.iter_mut() {
// Recursively instrument
if let DocumentNodeImplementation::Network(nested) = &mut node.implementation {
path.push(*id);
self.add(nested, path);
path.pop();
/// Records the path of each proto node in the network and the networks nested in it.
fn add(&mut self, network: &NodeNetwork, path: &mut Vec<NodeId>) {
for (id, node) in &network.nodes {
path.push(*id);
match &node.implementation {
DocumentNodeImplementation::Network(nested) => self.add(nested, path),
DocumentNodeImplementation::ProtoNode(identifier) => self.protonodes_by_name.entry(identifier.clone()).or_default().push(path.clone()),
_ => {}
}
let mut monitor_node_ids = Vec::with_capacity(node.inputs.len());
for input in &mut node.inputs {
let node_id = NodeId::new();
path.push(node_id);
monitor_node_ids.push(path.clone());
path.pop();
// A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent
if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) {
continue;
}
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
monitor_nodes.push((old_input, node_id));
}
if let DocumentNodeImplementation::ProtoNode(identifier) = &mut node.implementation {
path.push(*id);
self.protonodes_by_name.entry(identifier.clone()).or_default().push(monitor_node_ids.clone());
self.protonodes_by_path.insert(path.clone(), monitor_node_ids);
path.pop();
}
}
for (input, monitor_id) in monitor_nodes {
let monitor_node = DocumentNode {
inputs: vec![input],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
call_argument: graph_craft::generic!(T),
skip_deduplication: true,
..Default::default()
};
network.nodes.insert(monitor_id, monitor_node);
path.pop();
}
}
/// Instrument a graph and return a new [Instrumented] state.
pub fn new(network: &mut NodeNetwork) -> Self {
pub fn new(network: &NodeNetwork) -> Self {
let mut instrumented = Self::default();
instrumented.add(network, &mut Vec::new());
instrumented
}
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
Some(x.output.clone())
} else {
dynamic.downcast_ref::<IORecord<Context, Output>>().map(|x| x.output.clone())
}
/// Reads the value an input of the proto node at this path received, if it has the `Output` type.
/// Only the value types the Data panel can show come through.
fn grab_input<Output: Clone + 'static>(path: &[NodeId], input_index: usize, runtime: &NodeRuntime) -> Option<Output> {
let observation = Observation {
node_path: path.to_vec(),
connector: ObservedConnector::Input(input_index),
overrides: ContextOverrides::default(),
};
runtime.observe(observation)?.downcast_ref::<Output>().cloned()
}
/// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type.
/// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
/// Grab all of the values of the input every time it occurs in the graph, downcast to the received `Output` type.
/// A value whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
self.protonodes_by_name
.get(&Input::NODE_IDENTIFIER)
.map_or([].as_slice(), |x| x.as_slice())
.map_or([].as_slice(), |paths| paths.as_slice())
.iter()
.filter_map(|inputs| inputs.get(Input::INDEX))
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
.filter_map(Instrumented::downcast_record::<Output>)
.filter_map(|path| Self::grab_input::<Output>(path, Input::INDEX, runtime))
}
pub fn grab_protonode_input<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Output> {
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Output>(dynamic)
pub fn grab_protonode_input<Input: NodeParameter, Output: Clone + 'static>(&self, path: &[NodeId], runtime: &NodeRuntime) -> Option<Output> {
Self::grab_input::<Output>(path, Input::INDEX, runtime)
}
/// Grabs a ranked input's recorded value as its bare element `Element`.
/// A stored value materializes as an `Item<Element>` wire, so the monitor records the whole cell and this unwraps its element.
pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> {
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
Self::downcast_record::<Item<Element>>(dynamic).map(|item| item.into_element())
/// Grabs a ranked input's received value as its bare element `Element`.
/// A stored value materializes as an `Item<Element>` wire, so the input receives the whole cell and this unwraps its element.
pub fn grab_ranked_input<Input: NodeParameter, Element: Clone + 'static>(&self, path: &[NodeId], runtime: &NodeRuntime) -> Option<Element> {
Self::grab_input::<Item<Element>>(path, Input::INDEX, runtime).map(Item::into_element)
}
pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(
pub fn grab_input_from_layer<Input: NodeParameter, Output: Clone + 'static>(
&self,
layer: LayerNodeIdentifier,
network_interface: &NodeNetworkInterface,
@@ -1305,7 +1294,7 @@ mod test {
) -> Option<Output> {
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
let node = node_graph_layer.upstream_node_id_from_protonode(Input::NODE_IDENTIFIER)?;
self.grab_protonode_input::<Input, Output>(&vec![node], runtime)
self.grab_protonode_input::<Input, Output>(&[node], runtime)
}
}
}
@@ -19,7 +19,7 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
}
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
/// for one more update, so a first update clears those of the test harness's instrumented graph.
/// for one more update, so a first update clears those of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await;
compile_and_run(editor).await;
+49 -83
View File
@@ -11,17 +11,15 @@ use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::list::{Item, List};
use graphene_std::memo::IORecord;
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
@@ -30,6 +28,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use thumbnails::Thumbnails;
#[cfg(test)]
mod layer_path_tests;
mod observer;
mod thumbnails;
@@ -57,7 +57,6 @@ pub struct NodeRuntime {
resources: ResourceRegistry,
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
@@ -65,9 +64,6 @@ pub struct NodeRuntime {
preprocessor: preprocessor::Preprocessor,
vector_modify: HashMap<NodeId, VectorGeometry>,
vector_evaluations: HashMap<NodeId, (NodeId, u64)>,
/// Cached surface for Wasm viewport rendering (reused across frames)
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
wasm_canvas_cache: CanvasSurfaceHandle,
@@ -155,15 +151,12 @@ impl NodeRuntime {
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
monitor_nodes: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
preprocessor: preprocessor::Preprocessor::new(),
vector_modify: Default::default(),
vector_evaluations: Default::default(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
@@ -222,6 +215,7 @@ impl NodeRuntime {
};
apply_previews(&mut network, &previewed);
write_layer_paths(&mut network, &layers);
self.observer.replace_all(observations);
self.resources = resources;
@@ -376,7 +370,6 @@ impl NodeRuntime {
result: ExecutionResult::Panic(payload),
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
observations: HashMap::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
@@ -388,7 +381,7 @@ impl NodeRuntime {
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let dropped_thumbnails = self.update_thumbnails(&mut responses).await;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let response = ExecutionResponse {
@@ -396,12 +389,19 @@ impl NodeRuntime {
result,
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
observations,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
/// Reads one observation from the last evaluation, apart from the observations the runtime keeps.
#[cfg(test)]
pub(crate) fn observe(&self, observation: Observation) -> Option<ObservedValue> {
let mut observer = Observer::default();
observer.set((), Some(observation));
observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data
}
async fn read_back(&self, texture: Texture) -> Raster<CPU> {
let application_io = self.editor_api.application_io.as_ref().unwrap();
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
@@ -429,12 +429,6 @@ impl NodeRuntime {
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings = warnings;
self.monitor_nodes = proto_network
.nodes
.iter()
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
.map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id))
.collect();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -465,41 +459,9 @@ impl NodeRuntime {
EvaluationErrors(errors.into())
}
/// Updates state data, giving back the layers whose thumbnails were dropped because they no longer have content to show.
async fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
/// Renders the stale thumbnails, giving back the layers whose thumbnails were dropped because they no longer have content to show.
async fn update_thumbnails(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
let dropped_thumbnails = self.thumbnails.drop_sourceless();
for (monitor_node_path, _) in &self.monitor_nodes {
let Some(parent_network_node_id) = monitor_parent_node(monitor_node_path) else {
warn!("Monitor node has invalid node id");
continue;
};
if !records_vector(&self.executor, monitor_node_path) {
continue;
}
let tree = self.executor.tree();
let Ok(content_node) = tree.input_node(monitor_node_path, 0) else { continue };
let Ok(Some(context)) = tree.last_context(content_node) else { continue };
let context_hash = context_hash(&context);
if self.vector_evaluations.get(&parent_network_node_id) == Some(&(content_node, context_hash)) {
continue;
}
let Some(output) = tree.evaluate(content_node, &context).ok().and_then(evaluated_output) else {
continue;
};
let geometry = if let Some(list) = output.downcast_ref::<List<Vector>>() {
VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default())
} else if let Some(item) = output.downcast_ref::<Item<Vector>>() {
VectorGeometry::from_item(item)
} else {
continue;
};
self.vector_modify.insert(parent_network_node_id, geometry);
self.vector_evaluations.insert(parent_network_node_id, (content_node, context_hash));
}
self.thumbnails.render_stale(&self.executor, &self.editor_api, responses).await;
dropped_thumbnails
@@ -514,18 +476,6 @@ impl ExecutionResult {
}
}
/// The layer a monitor node belongs to, since monitor nodes sit within the network of the document node they monitor.
fn monitor_parent_node(monitor_node_path: &[NodeId]) -> Option<NodeId> {
monitor_node_path.len().checked_sub(2).and_then(|index| monitor_node_path.get(index)).copied()
}
fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> bool {
// TODO: Tell this from the monitor node's type once the types the borrow tree records can be compared with concrete ones
executor
.introspect(monitor_node_path)
.is_ok_and(|data| data.is::<IORecord<Context, List<Vector>>>() || data.is::<IORecord<Context, Item<Vector>>>())
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
@@ -638,31 +588,48 @@ mod tests {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
}
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
fn vectorize_layer(editor: &mut EditorTestUtils) {
/// Adds a layer tracing an image of noise, which an export has to wait on over several evaluations.
async fn add_traced_noise_layer(editor: &mut EditorTestUtils) {
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;
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
let mut noise = Image::new(64, 64, Color::BLACK);
let mut state = 0x2545_f491_u32;
for pixel in &mut noise.data {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
let gray = (state % 256) as f32 / 255.;
*pixel = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
}
editor.create_raster_image(noise, None).await;
// Trace the image between the layer and the nodes feeding it
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let mut create = |node_type| {
let node_id = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(node_id),
node_type,
xy: None,
add_transaction: true,
});
node_id
};
let noise = create(DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER));
let vectorize = create(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER));
let content = InputConnector::node_at_index(layer.to_node(), 1);
let image = editor
.active_document()
.network_interface
.upstream_output_connector(&content, &[])
.expect("the image layer has content");
let vectorize = NodeId::new();
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
node_id: Some(vectorize),
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER),
xy: None,
add_transaction: true,
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(noise),
output_connector: image,
input_connector: InputConnector::node_at_index(vectorize, 0),
});
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(vectorize),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
input_connector: content,
});
}
@@ -709,8 +676,7 @@ mod tests {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 512., 512.).await;
vectorize_layer(&mut editor);
add_traced_noise_layer(&mut editor).await;
send_export(&mut editor);
editor.runtime.update();
@@ -0,0 +1,67 @@
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
use graphene_std::graphic::extend;
fn rectangle() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
// A layer without an Extend node gets its path written onto its whole output
#[tokio::test]
async fn a_layer_gets_click_targets() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let rectangle = editor.create_node_by_name_at(rectangle(), 0, 0).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::node(rectangle, 0),
input_connector: InputConnector::Export(0),
})
.await;
assert!(editor.active_document().metadata().click_targets.is_empty(), "A node not shown as a layer should have no click targets");
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: rectangle, is_layer: true }).await;
let document = editor.active_document();
let layer = LayerNodeIdentifier::new(rectangle, &document.network_interface);
let click_targets = document.metadata().click_targets(layer);
assert!(
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
"A node shown as a layer should have click targets"
);
}
// A layer that is an Extend node gets its path written onto what it adds
#[tokio::test]
async fn an_extend_node_layer_gets_click_targets() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let extend = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(extend::IDENTIFIER), 0, 0).await;
let (below, added) = (editor.create_node_by_name_at(rectangle(), -10, 0).await, editor.create_node_by_name_at(rectangle(), -10, 4).await);
for (rectangle, input) in [(below, InputConnector::node(extend, extend::BaseInput)), (added, InputConnector::node(extend, extend::NewInput))] {
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::node(rectangle, 0),
input_connector: input,
})
.await;
}
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::node(extend, 0),
input_connector: InputConnector::Export(0),
})
.await;
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: extend, is_layer: true }).await;
let document = editor.active_document();
let layer = LayerNodeIdentifier::new(extend, &document.network_interface);
let click_targets = document.metadata().click_targets(layer);
assert!(
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
"An Extend node shown as a layer should have click targets for what it adds"
);
}
@@ -4,12 +4,11 @@ use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
use graph_craft::document::{NodeId, NodeNetwork};
#[cfg(feature = "gpu")]
use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::gradient::Gradient;
use graphene_std::graphic::extend;
use graphene_std::list::{Item, List};
#[cfg(feature = "gpu")]
use graphene_std::ops::ConvertAsync;
@@ -19,8 +18,9 @@ use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::transform::{Footprint, RenderQuality};
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic, NodeParameter};
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::layer_content;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
@@ -399,20 +399,7 @@ pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicEx
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let output = network.output_source(layer_path, 0)?;
// A hidden layer, or one passing through what's below it, has nothing of its own to show
if !output.starts_with(layer_path) {
return None;
}
let (node_id, network_path) = output.split_last()?;
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
let source = if node.implementation == DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
network.input_source(network_path, node.inputs.get(extend::NewInput::INDEX)?)?
} else {
output
};
let source = layer_content(layer_path, network)?.source(network)?;
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
@@ -484,6 +471,7 @@ mod tests {
use glam::UVec2;
use graph_craft::document::NodeId;
use graphene_std::application_io::TimingInformation;
use interpreted_executor::layer_paths::layer_path_writer_id;
async fn compile_and_run(editor: &mut EditorTestUtils) {
let portfolio = editor.portfolio_message_handler_mut();
@@ -510,7 +498,7 @@ mod tests {
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
compile_and_run(&mut editor).await;
let merge_content = compiled_id(&editor, &[layer, shipped_node_id("Merge", NodeId(3))]);
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
assert_eq!(
editor.runtime.thumbnails.sources.get(&layer).copied(),
@@ -540,9 +540,10 @@
margin-left: 8px;
}
// A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:only-child {
// A label with no expose button before it lines up with the parameter names that follow one
> .text-label:first-child {
margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
}
> .separator.horizontal.unrelated {
@@ -8,27 +8,13 @@
import { widgetSizingStyles } from "/src/utility-functions/widgets";
import type { MenuListEntry, ActionShortcut, WidgetSizing } from "/wrapper/pkg/graphite_wasm_wrapper";
const DASH_ENTRY: MenuListEntry = {
value: "",
label: "-",
icon: undefined,
annotation: "",
disabled: false,
children: [],
childrenHash: 0n,
font: undefined,
tooltipLabel: "",
tooltipDescription: "",
tooltipShortcut: undefined,
tooltipCode: "",
};
const dispatch = createEventDispatcher<{ selectedIndex: number; previewIndex: number; fileDrop: File }>();
let self: LayoutRow | undefined;
// Content
export let selectedIndex: number | undefined = undefined; // When not provided, a dash is displayed
export let selectedIndex: number | undefined = undefined; // When not provided, the placeholder is displayed
export let placeholder = "-";
export let drawIcon = false;
export let disabled = false;
// Children
@@ -132,13 +118,13 @@
return undefined;
}
function makeActiveEntry(): MenuListEntry {
function makeActiveEntry(): MenuListEntry | undefined {
const allEntries = entries.flat();
if (selectedIndex !== undefined && selectedIndex >= 0 && selectedIndex < allEntries.length) {
return allEntries[selectedIndex];
}
return DASH_ENTRY;
return undefined;
}
function takesDraggedFile(e: DragEvent): boolean {
@@ -187,10 +173,10 @@
data-dropdown-input
>
<LayoutRow class="dropdown-box" classes={{ disabled, open }} {tooltipLabel} {tooltipDescription} {tooltipShortcut} on:click={() => !disabled && (open = true)} data-floating-menu-spawner>
{#if activeEntry.icon}
{#if activeEntry?.icon}
<IconLabel class="dropdown-icon" icon={activeEntry.icon} />
{/if}
<TextLabel class="dropdown-label">{activeEntry.label}</TextLabel>
<TextLabel class="dropdown-label">{activeEntry?.label ?? placeholder}</TextLabel>
<IconLabel class="dropdown-arrow" icon="DropdownArrow" />
</LayoutRow>
<MenuList
@@ -200,7 +186,7 @@
on:activeEntry={({ detail }) => commitEntry(detail)}
on:open={({ detail }) => (open = detail)}
{open}
activeEntry={activeEntry === DASH_ENTRY ? undefined : activeEntry}
{activeEntry}
{entries}
entriesHash={entriesHash || 0n}
{drawIcon}
+1 -2
View File
@@ -14,7 +14,6 @@ pub struct DocumentNode {
pub call_argument: Type,
pub implementation: DocumentNodeImplementation,
pub visible: bool,
pub skip_deduplication: bool,
pub compile_metadata: Option<NodeCompileMetadata>,
pub original_location: OriginalLocation,
}
@@ -139,7 +138,7 @@ When the document graph is executed, the following steps occur:
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize and monitor nodes.
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize nodes.
## Debugging
@@ -29,7 +29,7 @@ impl DocumentNode {
}
impl NodeNetwork {
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and finding monitor nodes.
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and observing node values.
///
/// Table entries are not visited, since each instance gets its paths when [`Self::flatten`] copies the entry.
pub fn generate_node_paths(&mut self, prefix: &[NodeId]) {
@@ -28,7 +28,6 @@ impl DocumentNode {
call_argument: self.call_argument,
construction_args,
original_location: self.original_location,
skip_deduplication: self.skip_deduplication,
compile_metadata: self.compile_metadata.unwrap_or_default(),
upstream_context_features: Default::default(),
}
-7
View File
@@ -44,11 +44,6 @@ pub struct DocumentNode {
/// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step.
#[serde(default = "return_true")]
pub visible: bool,
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
#[serde(default)]
pub skip_deduplication: bool,
#[serde(skip)]
pub compile_metadata: Option<NodeCompileMetadata>,
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
@@ -82,7 +77,6 @@ impl Default for DocumentNode {
call_argument: concrete!(Context),
implementation: Default::default(),
visible: true,
skip_deduplication: Default::default(),
original_location: OriginalLocation::default(),
compile_metadata: Default::default(),
}
@@ -817,7 +811,6 @@ impl core_types::graphene_hash::CacheHash for DocumentNode {
self.call_argument.cache_hash(state);
self.implementation.cache_hash(state);
self.visible.cache_hash(state);
self.skip_deduplication.cache_hash(state);
self.compile_metadata.cache_hash(state);
}
}
@@ -88,11 +88,6 @@ pub struct OldDocumentNode {
pub locked: bool,
/// Metadata about the node including its position in the graph UI. Ensure the click target in the encapsulating network is updated when the node moves by using network.update_click_target(node_id).
pub metadata: OldDocumentNodeMetadata,
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
#[serde(default)]
pub skip_deduplication: bool,
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
#[serde(skip)]
pub original_location: OriginalLocation,
@@ -577,6 +577,9 @@ tagged_value! {
TonalRange(raster_nodes::adjustments::TonalRange),
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
GlowSource(graphic_types::GlowSource),
BevelStyle(graphic_types::BevelStyle),
BevelDirection(graphic_types::BevelDirection),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
@@ -711,6 +714,25 @@ impl TaggedValue {
None
}
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
let mut choices = input.split("::");
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
if first == "StrokeAlign" {
return Some(match second {
"Center" => vector::style::StrokeAlign::Center,
"Inside" => vector::style::StrokeAlign::Inside,
"Outside" => vector::style::StrokeAlign::Outside,
_ => {
log::error!("Invalid StrokeAlign default type variant: {input}");
return None;
}
});
}
log::error!("Invalid StrokeAlign default type: {input}");
None
}
match ty {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
@@ -729,6 +751,7 @@ impl TaggedValue {
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
_ => return None,
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more