Compare commits

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

* Refuse to save transient nodes

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

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

* Draw no viewport overlays while the node graph is open

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

* Allow wrapping a network in scope without the render node

* Implement CacheHash for BTreeMap

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

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

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

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

* Follow the wire's route with its center line

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

No files matched your search

+1 -7
View File
@@ -150,20 +150,14 @@ jobs:
run: cargo run build web${{ inputs.debug && ' debug' || '' }} run: cargo run build web${{ inputs.debug && ' debug' || '' }}
- name: 📤 Publish to Cloudflare Pages - name: 📤 Publish to Cloudflare Pages
if: inputs.merge_queue == false if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
id: cloudflare id: cloudflare
continue-on-error: ${{ github.event_name != 'push' }}
env: env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }} CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
# Passed through the environment so a branch name can't inject shell syntax # Passed through the environment so a branch name can't inject shell syntax
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }} HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
run: | run: |
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
echo "No Cloudflare API token available (fork PR), skipping deploy."
exit 0
fi
if [ "${{ github.event_name }}" = "push" ]; then if [ "${{ github.event_name }}" = "push" ]; then
DEPLOY_BRANCH="master" DEPLOY_BRANCH="master"
else else
+7 -2
View File
@@ -7,6 +7,8 @@ on:
push: push:
branches: branches:
- master - master
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
workflow_dispatch: {}
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other) # Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
concurrency: concurrency:
@@ -245,7 +247,8 @@ jobs:
permissions: permissions:
contents: read contents: read
env: env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} # A manual run has no base commit of its own, so it compares against master
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
steps: steps:
- name: 📥 Clone repository - name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -259,7 +262,9 @@ jobs:
rustflags: "" rustflags: ""
- name: 📥 Fetch the base commit - name: 📥 Fetch the base commit
run: git fetch --depth=1 origin "$BASE_SHA" run: |
git fetch --depth=1 origin "$BASE_REF"
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
- name: 🔬 Check migrations against the base commit - name: 🔬 Check migrations against the base commit
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA" run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
@@ -51,6 +51,8 @@ jobs:
with: with:
# Cache on Cargo.lock file # Cache on Cargo.lock file
cache-on-failure: true cache-on-failure: true
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
save-if: ${{ github.event_name == 'push' }}
- name: Install gungraun-runner and valgrind - name: Install gungraun-runner and valgrind
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3 uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
Generated
+53 -161
View File
@@ -590,6 +590,7 @@ dependencies = [
"node-macro", "node-macro",
"raster-kernels", "raster-kernels",
"serde", "serde",
"text-nodes",
"vector-types", "vector-types",
] ]
@@ -1226,7 +1227,6 @@ dependencies = [
"kurbo", "kurbo",
"log", "log",
"lyon_geom", "lyon_geom",
"math-parser",
"node-macro", "node-macro",
"num-derive", "num-derive",
"num-traits", "num-traits",
@@ -1239,7 +1239,7 @@ dependencies = [
"rustc-hash 2.1.3", "rustc-hash 2.1.3",
"serde", "serde",
"serde_json", "serde_json",
"skrifa 0.44.0", "skrifa",
"tinyvec", "tinyvec",
"tsify", "tsify",
"wasm-bindgen", "wasm-bindgen",
@@ -2136,9 +2136,6 @@ name = "float-cmp"
version = "0.9.0" version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
dependencies = [
"num-traits",
]
[[package]] [[package]]
name = "fnv" name = "fnv"
@@ -2158,15 +2155,6 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "font-types"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
dependencies = [
"bytemuck",
]
[[package]] [[package]]
name = "font-types" name = "font-types"
version = "0.12.7" version = "0.12.7"
@@ -2208,7 +2196,7 @@ dependencies = [
"linebender_resource_handle", "linebender_resource_handle",
"memmap2", "memmap2",
"parlance", "parlance",
"read-fonts 0.41.0", "read-fonts",
"smallvec", "smallvec",
] ]
@@ -2510,6 +2498,7 @@ dependencies = [
"futures", "futures",
"glam", "glam",
"graph-craft", "graph-craft",
"graph-ui-types",
"graphene-animation", "graphene-animation",
"graphene-application-io", "graphene-application-io",
"graphene-canvas-utils", "graphene-canvas-utils",
@@ -2547,6 +2536,44 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "graph-ui"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graph-craft",
"graph-ui-icons",
"graph-ui-types",
"graphene-std",
"graphic-types",
"node-macro",
"rendering",
"svg-convert",
"text-nodes",
"vector-types",
"vello_gpu",
]
[[package]]
name = "graph-ui-icons"
version = "0.0.0"
[[package]]
name = "graph-ui-types"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"graph-layout",
"graphene-hash",
"graphic-types",
"serde",
"tsify",
"wasm-bindgen",
]
[[package]] [[package]]
name = "graphene-animation" name = "graphene-animation"
version = "0.0.0" version = "0.0.0"
@@ -2885,6 +2912,7 @@ dependencies = [
"glam", "glam",
"graph-craft", "graph-craft",
"graph-layout", "graph-layout",
"graph-ui",
"graphene-hash", "graphene-hash",
"graphene-std", "graphene-std",
"graphite-proc-macros", "graphite-proc-macros",
@@ -3052,7 +3080,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [ dependencies = [
"bitflags 2.13.2", "bitflags 2.13.2",
"bytemuck", "bytemuck",
"read-fonts 0.41.0", "read-fonts",
"smallvec", "smallvec",
] ]
@@ -3087,40 +3115,6 @@ dependencies = [
"foldhash 0.2.0", "foldhash 0.2.0",
] ]
[[package]]
name = "hayro-ccitt"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adbed896e99325bc312778bb9c9c289d795d51c12775c44dd5e4352f679c7e46"
[[package]]
name = "hayro-jbig2"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb5c7f3a4eb551c2bb7fa16e268f728d4bc2a5c9b090554b8dc0ee2503fb5840"
dependencies = [
"hayro-ccitt",
]
[[package]]
name = "hayro-jpeg2000"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e5e5f2b3de970707fc22fd956d8f44211602939d5e4588603afa919cb7b3740"
[[package]]
name = "hayro-syntax"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ced8279487b029813f6cc05399099fa34df6fa23d8f7b0d41d972c49d5b30d"
dependencies = [
"hayro-jbig2",
"hayro-jpeg2000",
"rustc-hash 2.1.3",
"smallvec",
"zune-jpeg",
]
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
@@ -3474,12 +3468,6 @@ dependencies = [
"quick-error", "quick-error",
] ]
[[package]]
name = "imagesize"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
[[package]] [[package]]
name = "imagesize" name = "imagesize"
version = "0.15.0" version = "0.15.0"
@@ -3852,33 +3840,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "krilla"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
dependencies = [
"base64 0.22.1",
"bumpalo",
"flate2",
"float-cmp",
"gif",
"image-webp",
"imagesize 0.14.0",
"indexmap",
"pdf-writer",
"png 0.18.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.42.1",
"smallvec",
"subsetter",
"tiny-skia-path",
"xmp-writer",
"yoke",
"zune-jpeg",
]
[[package]] [[package]]
name = "kurbo" name = "kurbo"
version = "0.13.1" version = "0.13.1"
@@ -5112,7 +5073,7 @@ dependencies = [
"parlance", "parlance",
"parley_data", "parley_data",
"parley_emoji", "parley_emoji",
"skrifa 0.44.0", "skrifa",
] ]
[[package]] [[package]]
@@ -5143,18 +5104,6 @@ dependencies = [
"vector-types", "vector-types",
] ]
[[package]]
name = "pdf-writer"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
dependencies = [
"bitflags 2.13.2",
"itoa",
"memchr",
"ryu",
]
[[package]] [[package]]
name = "peer-transport" name = "peer-transport"
version = "0.0.0" version = "0.0.0"
@@ -5837,6 +5786,7 @@ dependencies = [
"glam", "glam",
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"half",
"log", "log",
"raster-types", "raster-types",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -5957,16 +5907,6 @@ dependencies = [
"yasna", "yasna",
] ]
[[package]]
name = "read-fonts"
version = "0.39.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
dependencies = [
"bytemuck",
"font-types 0.11.3",
]
[[package]] [[package]]
name = "read-fonts" name = "read-fonts"
version = "0.41.0" version = "0.41.0"
@@ -5974,7 +5914,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"font-types 0.12.7", "font-types",
"once_cell", "once_cell",
] ]
@@ -6120,15 +6060,14 @@ dependencies = [
"graphene-hash", "graphene-hash",
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"hayro-syntax",
"krilla",
"kurbo", "kurbo",
"linesweeper",
"log", "log",
"num-traits", "num-traits",
"parley", "parley",
"raster-kernels", "raster-kernels",
"serde", "serde",
"skrifa 0.44.0", "skrifa",
"text-nodes", "text-nodes",
"usvg", "usvg",
"vector-types", "vector-types",
@@ -6706,12 +6645,6 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]] [[package]]
name = "same-file" name = "same-file"
version = "1.0.6" version = "1.0.6"
@@ -7073,16 +7006,6 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "skrifa"
version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
dependencies = [
"bytemuck",
"read-fonts 0.39.2",
]
[[package]] [[package]]
name = "skrifa" name = "skrifa"
version = "0.44.0" version = "0.44.0"
@@ -7090,7 +7013,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"read-fonts 0.41.0", "read-fonts",
] ]
[[package]] [[package]]
@@ -7269,18 +7192,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "subsetter"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
dependencies = [
"kurbo",
"rustc-hash 2.1.3",
"skrifa 0.42.1",
"write-fonts",
]
[[package]] [[package]]
name = "substring" name = "substring"
version = "1.4.5" version = "1.4.5"
@@ -7463,7 +7374,7 @@ dependencies = [
"rand", "rand",
"serde", "serde",
"serde_json", "serde_json",
"skrifa 0.44.0", "skrifa",
"thiserror 2.0.21", "thiserror 2.0.21",
"titlecase", "titlecase",
"tsify", "tsify",
@@ -8063,14 +7974,14 @@ dependencies = [
"flate2", "flate2",
"fontdb", "fontdb",
"harfrust", "harfrust",
"imagesize 0.15.0", "imagesize",
"kurbo", "kurbo",
"log", "log",
"pico-args", "pico-args",
"roxmltree 0.21.2", "roxmltree 0.21.2",
"simplecss", "simplecss",
"siphasher", "siphasher",
"skrifa 0.44.0", "skrifa",
"strict-num", "strict-num",
"svgtypes", "svgtypes",
"tiny-skia-path", "tiny-skia-path",
@@ -9413,19 +9324,6 @@ dependencies = [
"toml 0.5.11", "toml 0.5.11",
] ]
[[package]]
name = "write-fonts"
version = "0.48.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
dependencies = [
"font-types 0.11.3",
"indexmap",
"kurbo",
"log",
"read-fonts 0.39.2",
]
[[package]] [[package]]
name = "writeable" name = "writeable"
version = "0.6.4" version = "0.6.4"
@@ -9566,12 +9464,6 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xmp-writer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]] [[package]]
name = "yansi" name = "yansi"
version = "1.0.1" version = "1.0.1"
+6 -2
View File
@@ -34,6 +34,9 @@ members = [
"node-graph/libraries/*", "node-graph/libraries/*",
"node-graph/nodes/*", "node-graph/nodes/*",
"node-graph/graph-craft", "node-graph/graph-craft",
"node-graph/graph-ui",
"node-graph/graph-ui/icons",
"node-graph/graph-ui/types",
"node-graph/graphene-cli", "node-graph/graphene-cli",
"node-graph/nodes/gstd", "node-graph/nodes/gstd",
"node-graph/interpreted-executor", "node-graph/interpreted-executor",
@@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
math-nodes = { path = "node-graph/nodes/math" } math-nodes = { path = "node-graph/nodes/math" }
path-bool-nodes = { path = "node-graph/nodes/path-bool" } path-bool-nodes = { path = "node-graph/nodes/path-bool" }
graph-craft = { path = "node-graph/graph-craft" } graph-craft = { path = "node-graph/graph-craft" }
graph-ui = { path = "node-graph/graph-ui" }
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
graph-ui-types = { path = "node-graph/graph-ui/types" }
document-format = { path = "document/format" } document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false } document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" } document-container = { path = "document/container" }
@@ -223,8 +229,6 @@ skrifa = "0.44"
polycool = "0.4" polycool = "0.4"
color = "0.3" color = "0.3"
# Linebender ecosystem (END) # Linebender ecosystem (END)
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
hayro-syntax = { version = "0.9", default-features = false, features = ["std"] }
rand = { version = "0.10", default-features = false, features = ["std_rng"] } rand = { version = "0.10", default-features = false, features = ["std_rng"] }
rand_chacha = "0.10" rand_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [ glam = { version = "0.34", default-features = false, features = [
+5 -2
View File
@@ -234,7 +234,11 @@ impl RenderState {
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true), WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
WgpuCurrentSurfaceTexture::Occluded => return Ok(()), WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost), WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated), WgpuCurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.executor.context().device, &self.config);
window.request_redraw();
return Ok(());
}
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout), WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation), WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
}; };
@@ -327,7 +331,6 @@ impl RenderState {
pub(crate) enum RenderError { pub(crate) enum RenderError {
OutdatedUITextureError, OutdatedUITextureError,
SurfaceLost, SurfaceLost,
SurfaceOutdated,
SurfaceTimeout, SurfaceTimeout,
SurfaceValidation, SurfaceValidation,
} }
@@ -57,10 +57,6 @@ pub mod network {
pub const IMPORT_METADATA: &str = "ui::import_metadata"; pub const IMPORT_METADATA: &str = "ui::import_metadata";
pub const EXPORT_NAMES: &str = "ui::export_names"; pub const EXPORT_NAMES: &str = "ui::export_names";
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions"; pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
/// is the default, CSS's 96. Only the root network's applies.
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
} }
pub mod delta { pub mod delta {
+7 -7
View File
@@ -44,6 +44,8 @@ pub enum ConversionError {
IndexOverflow(usize), IndexOverflow(usize),
#[error("Node ID {0} is used by more than one node in the document")] #[error("Node ID {0} is used by more than one node in the document")]
DuplicateNodeId(u64), DuplicateNodeId(u64),
#[error("The transient node {0} cannot be saved")]
TransientNode(String),
} }
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for /// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
@@ -473,12 +475,6 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
.map_err(map_serialization_error(network::PINNED_ORDER))?; .map_err(map_serialization_error(network::PINNED_ORDER))?;
} }
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
attributes
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
}
Ok(()) Ok(())
} }
@@ -565,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
} }
// Nodes the binary doesn't register, such as in tests, are at their first version // Nodes the binary doesn't register, such as in tests, are at their first version
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1); let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
let (version, flags) = registered.unwrap_or((1, Default::default()));
if flags.transient {
return Err(ConversionError::TransientNode(identifier_str));
}
let EncodedDeclaration { id, hash, bytes, proto } = let EncodedDeclaration { id, hash, bytes, proto } =
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?; EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
@@ -38,8 +38,6 @@ pub struct NetworkMetadataEntry {
pub import_metadata: Vec<InputMetadataEntry>, pub import_metadata: Vec<InputMetadataEntry>,
pub export_names: Vec<String>, pub export_names: Vec<String>,
pub export_descriptions: Vec<String>, pub export_descriptions: Vec<String>,
/// The document's pixels per inch, where it differs from the default.
pub pixels_per_inch: Option<f64>,
} }
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so /// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -80,11 +78,6 @@ pub trait NodeMetadataSource {
Vec::new() Vec::new()
} }
/// The network's pixels per inch, where it differs from the default.
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
None
}
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> { fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
Vec::new() Vec::new()
} }
+5 -3
View File
@@ -406,9 +406,11 @@ fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input:
match slot { match slot {
Slot::Input(id, index) => { Slot::Input(id, index) => {
let Some(input) = input else { return }; let Some(input) = input else { return };
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) { // A chain the line no longer holds the slot for, as shrinking a node's inputs leaves, is not written back
slot.input = input.clone(); let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) else {
} return;
};
slot.input = input.clone();
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input }); ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
} }
Slot::Export(id, index) => { Slot::Export(id, index) => {
@@ -2,7 +2,7 @@
//! operation mixed in. After every operation nothing may name a node the document no longer has. //! operation mixed in. After every operation nothing may name a node the document no longer has.
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value}; use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session}; use crate::{Implementation, InputSlot, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp};
/// A slot that can name a node. /// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
@@ -94,14 +94,16 @@ impl Scenario for Branching {
node.inputs[1].input = second; node.inputs[1].input = second;
node node
}; };
// Nodes that still have an input past the primary one, the only ones an edit may write there
let wide: Vec<NodeId> = nodes.iter().copied().filter(|id| registry.node_instances[id].inputs.len() > 1).collect();
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind // Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
let plain: Vec<NodeId> = nodes let plain: Vec<NodeId> = wide
.iter() .iter()
.copied() .copied()
.filter(|id| !matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. }))) .filter(|id| !matches!(place_value(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect(); .collect();
match random.below(12) { match random.below(14) {
// Draw a node on top of the chain off the export // Draw a node on top of the chain off the export
0..=2 => { 0..=2 => {
let id = session.next_node_id(); let id = session.next_node_id();
@@ -122,7 +124,7 @@ impl Scenario for Branching {
} }
// Hang a node on an input past the primary one, over whatever is there already // Hang a node on an input past the primary one, over whatever is there already
3..=5 => { 3..=5 => {
let Some(host) = random.pick(&nodes) else { return Vec::new() }; let Some(host) = random.pick(&wide) else { return Vec::new() };
let id = session.next_node_id(); let id = session.next_node_id();
let first = match place_value(&registry, Place::Input(host, 1)) { let first = match place_value(&registry, Place::Input(host, 1)) {
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index }, Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
@@ -179,6 +181,25 @@ impl Scenario for Branching {
new_input: value(random.below(100)), new_input: value(random.below(100)),
}] }]
} }
// Rewrite a node's whole input list, which an index-addressed write cannot express
11..=12 => {
let Some(node) = random.pick(&nodes) else { return Vec::new() };
let mut inputs = registry.node_instances[&node].inputs.clone();
match random.below(3) {
// Swap the first two, so what the node rested on moves past its primary input
0 if inputs.len() > 1 => inputs.swap(0, 1),
// One input more, holding a value
1 if inputs.len() < 4 => inputs.push(InputSlot {
input: value(random.below(100)),
timestamp: TimeStamp::ORIGIN,
attributes: Default::default(),
}),
// One input fewer, as removing a subgraph's import slot leaves the nodes wrapping it
_ if inputs.len() > 1 => _ = inputs.pop(),
_ => return Vec::new(),
}
vec![RegistryDelta::SetNodeInputs { id: node, inputs }]
}
// Cut the chain off an input past the primary one, taking its nodes with it // Cut the chain off an input past the primary one, taking its nodes with it
_ => { _ => {
let hosts: Vec<NodeId> = nodes let hosts: Vec<NodeId> = nodes
+35 -16
View File
@@ -12,25 +12,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
/// Note: This only works for complete networks with all inputs resolved. /// Note: This only works for complete networks with all inputs resolved.
/// Test networks with Import inputs will fail compilation (which is expected). /// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> { fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
use graph_craft::document::value::TaggedValue;
let mut network = network.clone(); let mut network = network.clone();
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?; network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
let resolution_node = NodeId(u64::MAX);
network.nodes.insert(
resolution_node,
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
..Default::default()
},
);
network
.scope_injections
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
let compiler = Compiler {}; let compiler = Compiler {};
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?; compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(()) Ok(())
@@ -673,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored"); assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
} }
#[test]
fn a_transient_node_is_rejected() {
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
let metadata = NodeMetadata {
display_name: "Transient",
category: "",
icon: None,
fields: Vec::new(),
description: "",
inspector: None,
context_features: Vec::new(),
flags: NodeFlags {
transient: true,
..Default::default()
},
version: 1,
output_fields: None,
};
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
let mut network = create_simple_network();
network.nodes.insert(
NodeId(100),
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
},
);
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
}
/// A node input referencing a node in a different network can't be remapped to a valid local runtime /// A node input referencing a node in a different network can't be remapped to a valid local runtime
/// ID, so conversion must reject it rather than emit a dangling reference. /// ID, so conversion must reject it rather than emit a dangling reference.
#[test] #[test]
-1
View File
@@ -417,7 +417,6 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA), import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES), export_names: attributes.get_or_default(network::EXPORT_NAMES),
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS), export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
} }
} }
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV2, &contract());
check_undo(&BevelAndEmbossV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV2);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -1,50 +1,49 @@
use migration_core::{Inputs, Node, literal, literal_of, migration}; use migration_core::{Inputs, NodeInput, encode, migration};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
const RADIUS: usize = 1; /// Frozen mirror of the `TaggedValue` variant this migration writes.
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
enum Tagged { enum Tagged {
None, TypeDefault(Type),
Number(f64), }
Length(TypedLength),
/// Frozen mirror of the `Type` an empty list of graphics stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
List(Box<Type>),
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct TypedLength { struct TypeDescriptor {
value: f64, name: String,
unit: LengthUnit,
} }
#[derive(Serialize, Deserialize)] /// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("blending_nodes::effects::BlurNode"@2 => @3)] #[migration("blending_nodes::effects::BlurNode"@2 => @3)]
pub fn blur_v2(node: &Node, inputs: &mut Inputs) { pub fn blur_v2(inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return }; inputs.insert(2, empty_radius_mask());
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return }; }
inputs.set( /// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
RADIUS as u32, fn empty_radius_mask() -> NodeInput {
literal(Tagged::Length(TypedLength { let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
value: pixels, name: "graphic_types::graphic::Graphic".to_string(),
unit: LengthUnit::Pixel, }))));
})), NodeInput::Value {
); value: encode(&no_graphics),
exposed: false,
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use migration_core::decl; use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract { fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) }) SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
} }
#[test] #[test]
@@ -54,13 +53,17 @@ mod tests {
} }
#[test] #[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() { fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BlurV2); let mut fixture = Fixture::new(&BlurV2);
let number = |number: f64| literal(Tagged::Number(number)); let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), vec![literal(Tagged::None), number(10.), number(0.), number(0.)]);
let migrated = fixture.migrate(&BlurV2).unwrap(); let migrated = fixture.migrate(&BlurV2).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel })); let mut expected = inputs;
assert_eq!(fixture.inputs(&migrated, blur), [literal(Tagged::None), radius, number(0.), number(0.)]); expected.insert(2, empty_radius_mask());
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
assert_eq!(fixture.inputs(&migrated, blur), expected);
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
} }
} }
@@ -0,0 +1,43 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ConvolutionKernelV1, &contract());
check_undo(&ConvolutionKernelV1, &contract());
}
#[test]
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&ConvolutionKernelV1);
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
}
}
@@ -0,0 +1,48 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Integer(i64),
}
/// 'Inner Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
#[migration("blending_nodes::effects::InnerGlowNode"@2 => @3)]
pub fn inner_glow_v2(inputs: &mut Inputs) {
inputs.insert(8, literal(Tagged::Number(0.)));
inputs.insert(9, literal(Tagged::Number(0.)));
inputs.insert(10, literal(Tagged::Integer(0)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerGlowV2, &contract());
check_undo(&InnerGlowV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerGlowV2);
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@2), inputs.clone());
let migrated = fixture.migrate(&InnerGlowV2).unwrap();
let mut expected = inputs;
expected.splice(8..8, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@3)));
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
}
}
@@ -1,14 +1,21 @@
//! Migrations of the nodes in `blending_nodes`. //! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1; mod bevel_and_emboss_v1;
mod bevel_and_emboss_v2;
mod blur_v2; mod blur_v2;
mod convolution_kernel_v1;
mod drop_shadow_v1; mod drop_shadow_v1;
mod inner_glow_v1; mod inner_glow_v1;
mod inner_glow_v2;
mod inner_shadow_v1; mod inner_shadow_v1;
mod mask_by_any_graphic; mod mask_by_any_graphic;
mod outer_glow_v1; mod outer_glow_v1;
mod outer_glow_v2;
mod outline_v1; mod outline_v1;
mod outline_v2; mod outline_v2;
mod outline_v3;
mod paint_overlay_from_color_overlay; mod paint_overlay_from_color_overlay;
mod paint_overlay_v2;
mod radial_blur_v1;
mod renames; mod renames;
mod satin_v1; mod satin_v1;
@@ -0,0 +1,48 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Integer(i64),
}
/// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
#[migration("blending_nodes::effects::OuterGlowNode"@2 => @3)]
pub fn outer_glow_v2(inputs: &mut Inputs) {
inputs.insert(7, literal(Tagged::Number(0.)));
inputs.insert(8, literal(Tagged::Number(0.)));
inputs.insert(9, literal(Tagged::Integer(0)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OuterGlowV2, &contract());
check_undo(&OuterGlowV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OuterGlowV2);
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@2), inputs.clone());
let migrated = fixture.migrate(&OuterGlowV2).unwrap();
let mut expected = inputs;
expected.splice(7..7, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@3)));
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
}
}
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Outline' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
pub fn outline_v3(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV3, &contract());
check_undo(&OutlineV3, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV3);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
let migrated = fixture.migrate(&OutlineV3).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
pub fn paint_overlay_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PaintOverlayV2, &contract());
check_undo(&PaintOverlayV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&PaintOverlayV2);
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
assert_eq!(fixture.inputs(&migrated, overlay), expected);
}
}
@@ -0,0 +1,92 @@
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
const CENTER: u32 = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
DVec2([f64; 2]),
DAffine2([f64; 6]),
}
/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps.
/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin.
#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)]
pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
let Some(center) = node.inputs().get(CENTER as usize) else {
return Err(MigrationError::invariant("Radial Blur has a Center input"));
};
inputs.set(CENTER, transform_input(&center.input));
Ok(())
}
/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired.
fn transform_input(center: &NodeInput) -> NodeInput {
let ([x, y], exposed) = match center {
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(center) {
Some(Tagged::DVec2(center)) => (center, *exposed),
_ => ([0., 0.], *exposed),
},
_ => ([0., 0.], true),
};
NodeInput::Value {
value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])),
exposed,
}
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const CENTER_SLOT: usize = CENTER as usize;
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])),
_ => literal(random.below(10) as f64),
})
}
fn radial_blur_inputs(center: NodeInput) -> Vec<NodeInput> {
let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
inputs[CENTER_SLOT] = center;
inputs
}
#[test]
fn rewrites_history() {
check_commutation(&RadialBlurV1, &contract());
check_undo(&RadialBlurV1, &contract());
}
#[test]
fn the_center_becomes_the_translation_of_the_transform_in_its_place() {
let mut fixture = Fixture::new(&RadialBlurV1);
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.]))));
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.])));
assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2)));
assert_eq!(fixture.inputs(&migrated, radial_blur), expected);
}
#[test]
fn a_wired_center_becomes_the_identity_shown_in_the_graph() {
let mut fixture = Fixture::new(&RadialBlurV1);
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 }));
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
let identity = NodeInput::Value {
value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
exposed: true,
};
assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity));
}
}
@@ -3,3 +3,4 @@
use migration_core::rename; use migration_core::rename;
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2); rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DIAMETER: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The diameter is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("brush_nodes::BrushStrokesNode"@1 => @2)]
pub fn brush_strokes_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DIAMETER) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DIAMETER as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&BrushStrokesV1, &contract());
check_undo(&BrushStrokesV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&BrushStrokesV1);
let number = |number: f64| literal(Tagged::Number(number));
let brush_strokes = fixture.add(decl!("brush_nodes::BrushStrokesNode"@1), vec![literal(Tagged::None), number(0.), number(40.), number(0.), number(100.)]);
let migrated = fixture.migrate(&BrushStrokesV1).unwrap();
let diameter = literal(Tagged::Length(TypedLength { value: 40., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, brush_strokes), [literal(Tagged::None), number(0.), diameter, number(0.), number(100.)]);
}
}
@@ -1,3 +0,0 @@
//! Migrations of the nodes in `brush_nodes`.
mod brush_strokes_v1;
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::BevelNode"@1 => @2)]
pub fn bevel_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&BevelV1, &contract());
check_undo(&BevelV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&BevelV1);
let number = |number: f64| literal(Tagged::Number(number));
let bevel = fixture.add(decl!("core_types::vector::BevelNode"@1), vec![literal(Tagged::None), number(10.)]);
let migrated = fixture.migrate(&BevelV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, bevel), [literal(Tagged::None), distance]);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TOLERANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::DecimateNode"@1 => @2)]
pub fn decimate_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
TOLERANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&DecimateV1, &contract());
check_undo(&DecimateV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&DecimateV1);
let number = |number: f64| literal(Tagged::Number(number));
let decimate = fixture.add(decl!("core_types::vector::DecimateNode"@1), vec![literal(Tagged::None), number(5.)]);
let migrated = fixture.migrate(&DecimateV1).unwrap();
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, decimate), [literal(Tagged::None), tolerance]);
}
}
@@ -1,71 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DIRECTION: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The direction is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
#[migration("core_types::vector::ExtrudeNode"@1 => @2)]
pub fn extrude_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DIRECTION) else { return };
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(DIRECTION as u32, lengths(pixels));
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&ExtrudeV1, &contract());
check_undo(&ExtrudeV1, &contract());
}
#[test]
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
let mut fixture = Fixture::new(&ExtrudeV1);
let node = fixture.add(
decl!("core_types::vector::ExtrudeNode"@1),
vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.])), literal(Tagged::None)],
);
let migrated = fixture.migrate(&ExtrudeV1).unwrap();
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.]), literal(Tagged::None)]);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const MAX_DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The max distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::JitterPointsNode"@1 => @2)]
pub fn jitter_points_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(MAX_DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
MAX_DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&JitterPointsV1, &contract());
check_undo(&JitterPointsV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&JitterPointsV1);
let number = |number: f64| literal(Tagged::Number(number));
let jitter_points = fixture.add(decl!("core_types::vector::JitterPointsNode"@1), vec![literal(Tagged::None), number(5.), number(0.), number(1.)]);
let migrated = fixture.migrate(&JitterPointsV1).unwrap();
let max_distance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, jitter_points), [literal(Tagged::None), max_distance, number(0.), number(1.)]);
}
}
@@ -1,14 +0,0 @@
//! Migrations of the nodes in `core_types`.
mod bevel_v1;
mod decimate_v1;
mod extrude_v1;
mod jitter_points_v1;
mod offset_path_v1;
mod offset_points_v1;
mod point_inside_v1;
mod round_corners_v1;
mod sample_polyline_v1;
mod scatter_points_v2;
mod simplify_v1;
mod weld_v1;
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::OffsetPathNode"@1 => @2)]
pub fn offset_path_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&OffsetPathV1, &contract());
check_undo(&OffsetPathV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&OffsetPathV1);
let number = |number: f64| literal(Tagged::Number(number));
let offset_path = fixture.add(decl!("core_types::vector::OffsetPathNode"@1), vec![literal(Tagged::None), number(10.), number(0.), number(4.)]);
let migrated = fixture.migrate(&OffsetPathV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, offset_path), [literal(Tagged::None), distance, number(0.), number(4.)]);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::OffsetPointsNode"@1 => @2)]
pub fn offset_points_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&OffsetPointsV1, &contract());
check_undo(&OffsetPointsV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&OffsetPointsV1);
let number = |number: f64| literal(Tagged::Number(number));
let offset_points = fixture.add(decl!("core_types::vector::OffsetPointsNode"@1), vec![literal(Tagged::None), number(10.)]);
let migrated = fixture.migrate(&OffsetPointsV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, offset_points), [literal(Tagged::None), distance]);
}
}
@@ -1,68 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const POINT: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
#[migration("core_types::vector::PointInsideNode"@1 => @2)]
pub fn point_inside_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(POINT) else { return };
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(POINT as u32, lengths(pixels));
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| match slot {
POINT => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&PointInsideV1, &contract());
check_undo(&PointInsideV1, &contract());
}
#[test]
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
let mut fixture = Fixture::new(&PointInsideV1);
let node = fixture.add(decl!("core_types::vector::PointInsideNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
let migrated = fixture.migrate(&PointInsideV1).unwrap();
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
}
}
@@ -1,96 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
const MIN_ANGLE_THRESHOLD: usize = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The radius is a length and the minimum angle threshold is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("core_types::vector::RoundCornersNode"@1 => @2)]
pub fn round_corners_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(RADIUS) {
inputs.set(RADIUS as u32, length(pixels));
}
if let Some(degrees) = number_at(MIN_ANGLE_THRESHOLD) {
inputs.set(MIN_ANGLE_THRESHOLD as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RoundCornersV1, &contract());
check_undo(&RoundCornersV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
let mut fixture = Fixture::new(&RoundCornersV1);
let number = |number: f64| literal(Tagged::Number(number));
let round_corners = fixture.add(
decl!("core_types::vector::RoundCornersNode"@1),
vec![literal(Tagged::None), number(10.), number(0.5), number(100.), number(5.)],
);
let migrated = fixture.migrate(&RoundCornersV1).unwrap();
assert_eq!(fixture.inputs(&migrated, round_corners), [literal(Tagged::None), length(10.), number(0.5), number(100.), angle(5.)]);
}
}
@@ -1,80 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SEPARATION: usize = 2;
const START_OFFSET: usize = 4;
const STOP_OFFSET: usize = 5;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The separation and start and stop offsets are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("core_types::vector::SamplePolylineNode"@1 => @2)]
pub fn sample_polyline_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [SEPARATION, START_OFFSET, STOP_OFFSET] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&SamplePolylineV1, &contract());
check_undo(&SamplePolylineV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&SamplePolylineV1);
let number = |number: f64| literal(Tagged::Number(number));
let sample_polyline = fixture.add(
decl!("core_types::vector::SamplePolylineNode"@1),
vec![literal(Tagged::None), number(0.), number(100.), number(100.), number(10.), number(20.), number(0.)],
);
let migrated = fixture.migrate(&SamplePolylineV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, sample_polyline),
[literal(Tagged::None), number(0.), length(100.), number(100.), length(10.), length(20.), number(0.)]
);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SEPARATION: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The separation is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::ScatterPointsNode"@2 => @3)]
pub fn scatter_points_v2(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(SEPARATION) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
SEPARATION as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&ScatterPointsV2, &contract());
check_undo(&ScatterPointsV2, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&ScatterPointsV2);
let number = |number: f64| literal(Tagged::Number(number));
let scatter_points = fixture.add(decl!("core_types::vector::ScatterPointsNode"@2), vec![literal(Tagged::None), number(10.), number(0.)]);
let migrated = fixture.migrate(&ScatterPointsV2).unwrap();
let separation = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, scatter_points), [literal(Tagged::None), separation, number(0.)]);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TOLERANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::SimplifyNode"@1 => @2)]
pub fn simplify_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
TOLERANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&SimplifyV1, &contract());
check_undo(&SimplifyV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&SimplifyV1);
let number = |number: f64| literal(Tagged::Number(number));
let simplify = fixture.add(decl!("core_types::vector::SimplifyNode"@1), vec![literal(Tagged::None), number(5.)]);
let migrated = fixture.migrate(&SimplifyV1).unwrap();
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, simplify), [literal(Tagged::None), tolerance]);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DISTANCE: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("core_types::vector::WeldNode"@1 => @2)]
pub fn weld_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(DISTANCE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
DISTANCE as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&WeldV1, &contract());
check_undo(&WeldV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&WeldV1);
let number = |number: f64| literal(Tagged::Number(number));
let weld = fixture.add(decl!("core_types::vector::WeldNode"@1), vec![literal(Tagged::None), number(0.1), number(0.)]);
let migrated = fixture.migrate(&WeldV1).unwrap();
let distance = literal(Tagged::Length(TypedLength { value: 0.1, unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, weld), [literal(Tagged::None), distance, number(0.)]);
}
}
@@ -1,7 +1,5 @@
//! Migrations of the nodes in `graphene_core`. //! Migrations of the nodes in `graphene_core`.
mod pack_strips_v1;
mod passthrough_from_upload_texture_node; mod passthrough_from_upload_texture_node;
mod renames; mod renames;
mod stroke_v1;
mod vary_colors_from_assign_colors; mod vary_colors_from_assign_colors;
@@ -1,73 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SEPARATION: usize = 1;
const STRIP_MAX_LENGTH: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The separation and strip max length are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("graphene_core::vector::PackStripsNode"@1 => @2)]
pub fn pack_strips_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [SEPARATION, STRIP_MAX_LENGTH] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&PackStripsV1, &contract());
check_undo(&PackStripsV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&PackStripsV1);
let number = |number: f64| literal(Tagged::Number(number));
let pack_strips = fixture.add(decl!("graphene_core::vector::PackStripsNode"@1), vec![literal(Tagged::None), number(10.), number(1000.), number(0.)]);
let migrated = fixture.migrate(&PackStripsV1).unwrap();
assert_eq!(fixture.inputs(&migrated, pack_strips), [literal(Tagged::None), length(10.), length(1000.), number(0.)]);
}
}
@@ -1,79 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const WEIGHT: usize = 2;
const DASH_OFFSET: usize = 8;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The weight and dash offset are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
pub fn stroke_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [WEIGHT, DASH_OFFSET] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&StrokeV1, &contract());
check_undo(&StrokeV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&StrokeV1);
let number = |number: f64| literal(Tagged::Number(number));
let stroke = fixture.add(
decl!("graphene_core::vector::StrokeNode"@1),
vec![literal(Tagged::None), number(0.), number(2.), number(0.), number(0.), number(0.), number(4.), number(0.), number(5.)],
);
let migrated = fixture.migrate(&StrokeV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, stroke),
[literal(Tagged::None), number(0.), length(2.), number(0.), number(0.), number(0.), number(4.), number(0.), length(5.)]
);
}
}
@@ -1,4 +1 @@
//! Migrations of the nodes in `graphene_std`. //! Migrations of the nodes in `graphene_std`.
mod renames;
mod text_v1;
@@ -1,13 +0,0 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
rename!("graphene_std::render_node::RenderNode"@1 => @2);
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
rename!("graphene_std::render_node::RenderNode"@2 => @3);
@@ -1,130 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SIZE: usize = 3;
const LETTER_SPACING: usize = 5;
const LETTER_TILT: usize = 6;
const MAX_WIDTH: usize = 8;
const MAX_HEIGHT: usize = 10;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The size, letter spacing, and max sizes are lengths and the letter tilt is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("graphene_std::text::TextNode"@1 => @2)]
pub fn text_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [SIZE, LETTER_SPACING, MAX_WIDTH, MAX_HEIGHT] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
if let Some(degrees) = number_at(LETTER_TILT) {
inputs.set(LETTER_TILT as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(12, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&TextV1, &contract());
check_undo(&TextV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_lengths_and_an_angle() {
let mut fixture = Fixture::new(&TextV1);
let number = |number: f64| literal(Tagged::Number(number));
let text = fixture.add(
decl!("graphene_std::text::TextNode"@1),
vec![
literal(Tagged::None),
number(0.),
number(0.),
number(24.),
number(1.2),
number(2.),
number(10.),
number(0.),
number(100.),
number(0.),
number(100.),
number(0.),
],
);
let migrated = fixture.migrate(&TextV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, text),
[
literal(Tagged::None),
number(0.),
number(0.),
length(24.),
number(1.2),
length(2.),
angle(10.),
number(0.),
length(100.),
number(0.),
length(100.),
number(0.)
]
);
}
}
@@ -1,74 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const LOCATION: usize = 1;
const DIMENSIONS: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The location and dimensions are pairs of lengths, which keep the pixels they held. Wired Vec2s still feed them, read as pixels.
#[migration("graphic_nodes::artboard::CreateArtboardNode"@1 => @2)]
pub fn create_artboard_v1(node: &Node, inputs: &mut Inputs) {
for slot in [LOCATION, DIMENSIONS] {
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
inputs.set(slot as u32, lengths(pixels));
}
}
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
LOCATION | DIMENSIONS => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&CreateArtboardV1, &contract());
check_undo(&CreateArtboardV1, &contract());
}
#[test]
fn vec2s_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&CreateArtboardV1);
let none = || literal(Tagged::None);
let artboard = fixture.add(
decl!("graphic_nodes::artboard::CreateArtboardNode"@1),
vec![none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([1920., 1080.])), none(), none()],
);
let migrated = fixture.migrate(&CreateArtboardV1).unwrap();
assert_eq!(fixture.inputs(&migrated, artboard), [none(), lengths([10., 20.]), lengths([1920., 1080.]), none(), none()]);
}
}
@@ -1,96 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const OFFSET: usize = 2;
const ANGLE: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The offset is a length and the angle is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("graphic_nodes::graphic::MirrorNode"@1 => @2)]
pub fn mirror_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(OFFSET) {
inputs.set(OFFSET as u32, length(pixels));
}
if let Some(degrees) = number_at(ANGLE) {
inputs.set(ANGLE as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&MirrorV1, &contract());
check_undo(&MirrorV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
let mut fixture = Fixture::new(&MirrorV1);
let number = |number: f64| literal(Tagged::Number(number));
let mirror = fixture.add(
decl!("graphic_nodes::graphic::MirrorNode"@1),
vec![literal(Tagged::None), number(0.), number(20.), number(45.), number(1.)],
);
let migrated = fixture.migrate(&MirrorV1).unwrap();
assert_eq!(fixture.inputs(&migrated, mirror), [literal(Tagged::None), number(0.), length(20.), angle(45.), number(1.)]);
}
}
@@ -1,4 +0,0 @@
//! Migrations of the nodes in `graphic_nodes`.
mod create_artboard_v1;
mod mirror_v1;
-5
View File
@@ -2,13 +2,8 @@
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`. //! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod blending_nodes; mod blending_nodes;
mod brush_nodes;
mod core_types;
mod graphene_core; mod graphene_core;
mod graphene_std; mod graphene_std;
mod graphic_nodes;
mod math_nodes; mod math_nodes;
mod raster_nodes; mod raster_nodes;
mod repeat_nodes;
mod transform_nodes;
mod vector_nodes; mod vector_nodes;
@@ -1,47 +0,0 @@
use migration_core::{Inputs, NodeInput, migration};
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
#[migration("math_nodes::MathFormulaNode"@2 => @3)]
pub fn math_formula_v2(inputs: &mut Inputs) {
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
String(String),
}
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::String("a + b".to_string())),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&MathFormulaV2, &contract());
check_undo(&MathFormulaV2, &contract());
}
#[test]
fn the_resolution_is_read_from_the_scope() {
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("a * 2".to_string())), literal(Tagged::Number(0.))];
let mut fixture = Fixture::new(&MathFormulaV2);
let formula = fixture.add(decl!("math_nodes::MathFormulaNode"@2), inputs.clone());
let migrated = fixture.migrate(&MathFormulaV2).unwrap();
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
assert_eq!(fixture.inputs(&migrated, formula), expected);
}
}
@@ -1,47 +0,0 @@
use migration_core::{Inputs, NodeInput, migration};
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
pub fn math_function_v2(inputs: &mut Inputs) {
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
String(String),
}
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::String("x".to_string())),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&MathFunctionV2, &contract());
check_undo(&MathFunctionV2, &contract());
}
#[test]
fn the_resolution_is_read_from_the_scope() {
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
let mut fixture = Fixture::new(&MathFunctionV2);
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
assert_eq!(fixture.inputs(&migrated, function), expected);
}
}
@@ -1,6 +1,4 @@
//! Migrations of the nodes in `math_nodes`. //! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f; mod math_formula_from_math_f;
mod math_formula_v2;
mod math_function_v2;
mod renames; mod renames;
@@ -3,21 +3,3 @@
use migration_core::rename; use migration_core::rename;
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2); rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
// Version 2 takes lengths and angles too, with its output type following them, and stored nodes already have its layout
rename!("math_nodes::SineNode"@1 => @2);
rename!("math_nodes::CosineNode"@1 => @2);
rename!("math_nodes::TangentNode"@1 => @2);
rename!("math_nodes::SignNode"@1 => @2);
rename!("math_nodes::SumNode"@1 => @2);
rename!("math_nodes::AverageNode"@1 => @2);
rename!("math_nodes::MinimumNode"@1 => @2);
rename!("math_nodes::MaximumNode"@1 => @2);
// Version 2 reads a number beside a length or angle in pixels or degrees, and stored nodes already have its layout
rename!("math_nodes::LerpNode"@1 => @2);
rename!("math_nodes::ClampNode"@1 => @2);
rename!("math_nodes::LessThanNode"@1 => @2);
rename!("math_nodes::GreaterThanNode"@1 => @2);
rename!("math_nodes::EqualsNode"@1 => @2);
rename!("math_nodes::NotEqualsNode"@1 => @2);
@@ -0,0 +1,43 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
}
/// 'Make Opaque' gained a Strength percentage, set to 100% to keep making the content fully opaque.
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
pub fn make_opaque_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Number(100.)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MakeOpaqueV1, &contract());
check_undo(&MakeOpaqueV1, &contract());
}
#[test]
fn keeps_the_content_and_adds_full_strength() {
let content = literal(1.);
let mut fixture = Fixture::new(&MakeOpaqueV1);
let make_opaque = fixture.add(decl!("raster_nodes::adjustments::MakeOpaqueNode"@1), vec![content.clone()]);
let migrated = fixture.migrate(&MakeOpaqueV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, make_opaque), Some(decl!("raster_nodes::adjustments::MakeOpaqueNode"@2)));
assert_eq!(fixture.inputs(&migrated, make_opaque), [content, literal(Tagged::Number(100.))]);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
pub fn median_filter_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&MedianFilterV1, &contract());
check_undo(&MedianFilterV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&MedianFilterV1);
let number = |number: f64| literal(Tagged::Number(number));
let median_filter = fixture.add(decl!("raster_nodes::filter::MedianFilterNode"@1), vec![literal(Tagged::None), number(5.)]);
let migrated = fixture.migrate(&MedianFilterV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, median_filter), [literal(Tagged::None), radius]);
}
}
@@ -1,9 +1,10 @@
//! Migrations of the nodes in `raster_nodes`. //! Migrations of the nodes in `raster_nodes`.
mod make_opaque_v1;
mod mandelbrot_v1; mod mandelbrot_v1;
mod mandelbrot_v2; mod mandelbrot_v2;
mod median_filter_v1;
mod mix_colors_from_mix_node; mod mix_colors_from_mix_node;
mod noise_pattern_v1; mod noise_pattern_v1;
mod noise_pattern_v2;
mod pattern_square; mod pattern_square;
mod renames; mod renames;
@@ -0,0 +1,185 @@
use migration_core::attr::node::VISIBLE;
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
}
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let gamma_correction = downstream.add_node(NewNode {
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
});
for consumer in consumers {
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !node.attributes().get_or(VISIBLE, true) {
attributes.set(gamma_correction, VISIBLE, &false);
}
// The Gamma Correction takes the pattern's place, with the pattern before it
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(gamma_correction, POSITION, &stored);
}
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
use migration_core::Declaration;
use migration_core::attr::node::ui::IS_LAYER;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
fn contract() -> SourceContract {
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
}
fn noise_inputs() -> Vec<NodeInput> {
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn rewrites_history() {
check_commutation(&NoisePatternV2, &contract());
check_undo(&NoisePatternV2, &contract());
}
#[test]
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
fixture.export(wire(noise));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
panic!("the consumer should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
assert_eq!(migrated.node_instances.len(), 4);
}
#[test]
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
let visibility_of_gamma_correction = |visible: bool| {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
if !visible {
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
}
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
panic!("the consumer should read a node")
};
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
};
// Visible is the default, so only a disabled pattern writes it
assert_eq!(visibility_of_gamma_correction(false), Some(false));
assert_eq!(visibility_of_gamma_correction(true), None);
}
#[test]
fn an_unread_pattern_gains_no_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(migrated.node_instances.len(), 1);
}
#[test]
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
let mut fixture = Fixture::new(&NoisePatternV2);
// A custom subgraph exporting the pattern, read by the root network's export
let (subgraph, instance) = (NetworkId(100), NodeId(100));
fixture.registry.networks.insert(subgraph, Network::default());
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
fixture.registry.node_instances.insert(instance, instance_node);
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
fixture.export_from(subgraph, wire(noise));
fixture.export(wire(instance));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
panic!("the subgraph's export should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
}
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
let (reader, slot) = if read_by_layer {
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
(layer, 1)
} else {
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
};
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
panic!("slot {slot} of the reader should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
}
#[test]
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
}
}
}
@@ -1,4 +0,0 @@
//! Migrations of the nodes in `repeat_nodes`.
mod repeat_array_v1;
mod repeat_radial_v1;
@@ -1,98 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const DIRECTION: usize = 1;
const ANGLE: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
Angle(TypedAngle),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The direction is a pair of lengths and the angle is an angle, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
#[migration("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2)]
pub fn repeat_array_v1(node: &Node, inputs: &mut Inputs) {
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
if let Some(Tagged::DVec2(pixels)) = literal_at(DIRECTION) {
inputs.set(DIRECTION as u32, direction(pixels));
}
if let Some(Tagged::Number(degrees)) = literal_at(ANGLE) {
inputs.set(ANGLE as u32, angle(degrees));
}
}
fn direction(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| match slot {
0 => literal(Tagged::None),
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::Number(random.below(100) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&RepeatArrayV1, &contract());
check_undo(&RepeatArrayV1, &contract());
}
#[test]
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
let mut fixture = Fixture::new(&RepeatArrayV1);
let number = |number: f64| literal(Tagged::Number(number));
let repeat_array = fixture.add(
decl!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1),
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 50.])), number(90.), number(5.)],
);
let migrated = fixture.migrate(&RepeatArrayV1).unwrap();
assert_eq!(fixture.inputs(&migrated, repeat_array), [literal(Tagged::None), direction([100., 50.]), angle(90.), number(5.)]);
}
}
@@ -1,96 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const START_ANGLE: usize = 1;
const RADIUS: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The start angle is an angle and the radius is a length, which keep the numbers of degrees and pixels they held. Wired numbers still feed them, read as degrees and pixels.
#[migration("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2)]
pub fn repeat_radial_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(RADIUS) {
inputs.set(RADIUS as u32, length(pixels));
}
if let Some(degrees) = number_at(START_ANGLE) {
inputs.set(START_ANGLE as u32, angle(degrees));
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RepeatRadialV1, &contract());
check_undo(&RepeatRadialV1, &contract());
}
#[test]
fn numbers_of_degrees_and_pixels_become_an_angle_and_a_length() {
let mut fixture = Fixture::new(&RepeatRadialV1);
let number = |number: f64| literal(Tagged::Number(number));
let repeat_radial = fixture.add(
decl!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1),
vec![literal(Tagged::None), number(45.), number(5.), number(5.)],
);
let migrated = fixture.migrate(&RepeatRadialV1).unwrap();
assert_eq!(fixture.inputs(&migrated, repeat_radial), [literal(Tagged::None), angle(45.), length(5.), number(5.)]);
}
}
@@ -1,4 +0,0 @@
//! Migrations of the nodes in `transform_nodes`.
mod transform_v1;
mod vary_rotations_v2;
@@ -1,125 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TRANSLATION: usize = 1;
const ROTATION: usize = 2;
const SKEW: usize = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
Angle(TypedAngle),
LengthVec2(TypedLengthVec2),
AngleVec2(TypedAngleVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedAngleVec2 {
value: [f64; 2],
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The translation is a pair of lengths and the rotation and skew are angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
#[migration("transform_nodes::transform_nodes::TransformNode"@1 => @2)]
pub fn transform_v1(node: &Node, inputs: &mut Inputs) {
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
if let Some(Tagged::DVec2(pixels)) = literal_at(TRANSLATION) {
inputs.set(TRANSLATION as u32, translation(pixels));
}
if let Some(Tagged::Number(degrees)) = literal_at(ROTATION) {
inputs.set(ROTATION as u32, rotation(degrees));
}
if let Some(Tagged::DVec2(degrees)) = literal_at(SKEW) {
inputs.set(SKEW as u32, skew(degrees));
}
}
/// The whole-list counterpart of the Transform node, with parameters that migrate the same way.
#[migration("transform_nodes::transform_nodes::TransformListNode"@1 => @2)]
pub fn transform_list_v1(node: &Node, inputs: &mut Inputs) {
transform_v1(node, inputs);
}
fn translation(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn rotation(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
fn skew(degrees: [f64; 2]) -> NodeInput {
literal(Tagged::AngleVec2(TypedAngleVec2 {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
0 => literal(Tagged::None),
ROTATION => literal(Tagged::Number(random.below(360) as f64)),
_ => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
})
}
#[test]
fn rewrites_history() {
check_commutation(&TransformV1, &contract());
check_undo(&TransformV1, &contract());
}
#[test]
fn pixels_and_degrees_become_typed_lengths_and_angles() {
let mut fixture = Fixture::new(&TransformV1);
let vec2 = |x: f64, y: f64| literal(Tagged::DVec2([x, y]));
let transform = fixture.add(
decl!("transform_nodes::transform_nodes::TransformNode"@1),
vec![literal(Tagged::None), vec2(10., 20.), literal(Tagged::Number(45.)), vec2(2., 3.), vec2(15., 0.)],
);
let migrated = fixture.migrate(&TransformV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, transform),
[literal(Tagged::None), translation([10., 20.]), rotation(45.), vec2(2., 3.), skew([15., 0.])]
);
}
}
@@ -1,79 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const MIN: usize = 1;
const MAX: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The ends of the range are angles, which keep the numbers of degrees they held. Wired numbers still feed them, read as degrees.
#[migration("transform_nodes::transform_nodes::VaryRotationsNode"@2 => @3)]
pub fn vary_rotations_v2(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [MIN, MAX] {
if let Some(degrees) = number_at(slot) {
inputs.set(slot as u32, angle(degrees));
}
}
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&VaryRotationsV2, &contract());
check_undo(&VaryRotationsV2, &contract());
}
#[test]
fn numbers_of_degrees_become_angles_in_degrees() {
let mut fixture = Fixture::new(&VaryRotationsV2);
let number = |number: f64| literal(Tagged::Number(number));
let vary_rotations = fixture.add(
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
vec![literal(Tagged::None), number(-180.), number(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)],
);
let migrated = fixture.migrate(&VaryRotationsV2).unwrap();
assert_eq!(
fixture.inputs(&migrated, vary_rotations),
[literal(Tagged::None), angle(-180.), angle(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)]
);
}
}
@@ -1,99 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
const START_ANGLE: usize = 2;
const SWEEP_ANGLE: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The radius is a length and the start and sweep angles are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("vector_nodes::generator_nodes::ArcNode"@1 => @2)]
pub fn arc_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(pixels) = number_at(RADIUS) {
inputs.set(RADIUS as u32, length(pixels));
}
for slot in [START_ANGLE, SWEEP_ANGLE] {
if let Some(degrees) = number_at(slot) {
inputs.set(slot as u32, angle(degrees));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&ArcV1, &contract());
check_undo(&ArcV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_a_length_and_angles() {
let mut fixture = Fixture::new(&ArcV1);
let number = |number: f64| literal(Tagged::Number(number));
let arc = fixture.add(
decl!("vector_nodes::generator_nodes::ArcNode"@1),
vec![literal(Tagged::None), number(50.), number(0.), number(270.), number(1.)],
);
let migrated = fixture.migrate(&ArcV1).unwrap();
assert_eq!(fixture.inputs(&migrated, arc), [literal(Tagged::None), length(50.), angle(0.), angle(270.), number(1.)]);
}
}
@@ -1,100 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const ARROW_TO: usize = 1;
const SHAFT_WIDTH: usize = 2;
const HEAD_WIDTH: usize = 3;
const HEAD_LENGTH: usize = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
Length(TypedLength),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The end point is a pair of lengths and the shaft and head sizes are lengths, which keep the pixels they held. Wired values still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::ArrowNode"@1 => @2)]
pub fn arrow_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(ARROW_TO).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
inputs.set(ARROW_TO as u32, lengths(pixels));
}
for slot in [SHAFT_WIDTH, HEAD_WIDTH, HEAD_LENGTH] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, slot| match slot {
0 => literal(Tagged::None),
ARROW_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::Number(random.below(100) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&ArrowV1, &contract());
check_undo(&ArrowV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&ArrowV1);
let number = |number: f64| literal(Tagged::Number(number));
let arrow = fixture.add(
decl!("vector_nodes::generator_nodes::ArrowNode"@1),
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 0.])), number(10.), number(30.), number(20.)],
);
let migrated = fixture.migrate(&ArrowV1).unwrap();
assert_eq!(fixture.inputs(&migrated, arrow), [literal(Tagged::None), lengths([100., 0.]), length(10.), length(30.), length(20.)]);
}
}
@@ -1,65 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&CircleV1, &contract());
check_undo(&CircleV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&CircleV1);
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
let migrated = fixture.migrate(&CircleV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
}
}
@@ -1,73 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS_X: usize = 1;
const RADIUS_Y: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::EllipseNode"@1 => @2)]
pub fn ellipse_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [RADIUS_X, RADIUS_Y] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&EllipseV1, &contract());
check_undo(&EllipseV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&EllipseV1);
let number = |number: f64| literal(Tagged::Number(number));
let ellipse = fixture.add(decl!("vector_nodes::generator_nodes::EllipseNode"@1), vec![literal(Tagged::None), number(50.), number(25.)]);
let migrated = fixture.migrate(&EllipseV1).unwrap();
assert_eq!(fixture.inputs(&migrated, ellipse), [literal(Tagged::None), length(50.), length(25.)]);
}
}
@@ -1,111 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SPACING: usize = 6;
const ANGLES: usize = 7;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
AngleVec2(TypedAngleVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
struct TypedAngleVec2 {
value: [f64; 2],
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The spacing is a pair of lengths, filled from one number in both axes, and the isometric angles are a pair of angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
#[migration("vector_nodes::generator_nodes::GridNode"@1 => @2)]
pub fn grid_v1(node: &Node, inputs: &mut Inputs) {
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
match literal_at(SPACING) {
Some(Tagged::Number(pixels)) => inputs.set(SPACING as u32, lengths([pixels, pixels])),
Some(Tagged::DVec2(pixels)) => inputs.set(SPACING as u32, lengths(pixels)),
_ => {}
}
if let Some(Tagged::DVec2(degrees)) = literal_at(ANGLES) {
inputs.set(ANGLES as u32, angles(degrees));
}
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angles(degrees: [f64; 2]) -> NodeInput {
literal(Tagged::AngleVec2(TypedAngleVec2 {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, slot| match slot {
SPACING if random.below(2) == 0 => literal(Tagged::Number(random.below(100) as f64)),
SPACING | ANGLES => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&GridV1, &contract());
check_undo(&GridV1, &contract());
}
#[test]
fn pixels_and_degrees_become_typed_lengths_and_angles() {
let mut fixture = Fixture::new(&GridV1);
let none = || literal(Tagged::None);
let square = fixture.add(
decl!("vector_nodes::generator_nodes::GridNode"@1),
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::Number(10.)), literal(Tagged::DVec2([30., 30.]))],
);
let rectangular = fixture.add(
decl!("vector_nodes::generator_nodes::GridNode"@1),
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([30., 60.]))],
);
let migrated = fixture.migrate(&GridV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, square),
[none(), none(), none(), none(), none(), none(), lengths([10., 10.]), angles([30., 30.])]
);
assert_eq!(
fixture.inputs(&migrated, rectangular),
[none(), none(), none(), none(), none(), none(), lengths([10., 20.]), angles([30., 60.])]
);
}
}
@@ -1,72 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const TIP_ANGLE: usize = 6;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The tip angle is an angle, which keeps the number of degrees it held. A wired number still feeds it, read as degrees.
#[migration("vector_nodes::generator_nodes::HeartNode"@1 => @2)]
pub fn heart_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(TIP_ANGLE) else { return };
let Some(Tagged::Number(degrees)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
TIP_ANGLE as u32,
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&HeartV1, &contract());
check_undo(&HeartV1, &contract());
}
#[test]
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
let mut fixture = Fixture::new(&HeartV1);
let number = |number: f64| literal(Tagged::Number(number));
let heart = fixture.add(
decl!("vector_nodes::generator_nodes::HeartNode"@1),
vec![literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), number(75.)],
);
let migrated = fixture.migrate(&HeartV1).unwrap();
let tip_angle = literal(Tagged::Angle(TypedAngle { value: 75., unit: AngleUnit::Degree }));
assert_eq!(
fixture.inputs(&migrated, heart),
[literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), tip_angle]
);
}
}
@@ -1,68 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const LINE_TO: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
DVec2([f64; 2]),
LengthVec2(TypedLengthVec2),
}
#[derive(Serialize, Deserialize)]
struct TypedLengthVec2 {
value: [f64; 2],
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The end point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::LineNode"@1 => @2)]
pub fn line_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(LINE_TO) else { return };
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(LINE_TO as u32, lengths(pixels));
}
fn lengths(pixels: [f64; 2]) -> NodeInput {
literal(Tagged::LengthVec2(TypedLengthVec2 {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| match slot {
LINE_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
_ => literal(Tagged::None),
})
}
#[test]
fn rewrites_history() {
check_commutation(&LineV1, &contract());
check_undo(&LineV1, &contract());
}
#[test]
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
let mut fixture = Fixture::new(&LineV1);
let node = fixture.add(decl!("vector_nodes::generator_nodes::LineNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
let migrated = fixture.migrate(&LineV1).unwrap();
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
}
}
@@ -1,16 +1,4 @@
//! Migrations of the nodes in `vector_nodes`. //! Migrations of the nodes in `vector_nodes`.
mod arc_v1;
mod arrow_v1;
mod circle_v1;
mod ellipse_v1;
mod grid_v1;
mod heart_v1;
mod line_v1;
mod path_from_path_network; mod path_from_path_network;
mod qr_code_v1;
mod rectangle_v1;
mod regular_polygon_v1;
mod renames; mod renames;
mod spiral_v1;
mod star_v1;
@@ -1,69 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const SIZE: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The size is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::QrCodeNode"@1 => @2)]
pub fn qr_code_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(SIZE) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(SIZE as u32, length(pixels));
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, slot| if slot == SIZE { literal(Tagged::Number(random.below(100) as f64)) } else { literal(Tagged::None) })
}
#[test]
fn rewrites_history() {
check_commutation(&QrCodeV1, &contract());
check_undo(&QrCodeV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&QrCodeV1);
let none = || literal(Tagged::None);
let qr_code = fixture.add(
decl!("vector_nodes::generator_nodes::QrCodeNode"@1),
vec![none(), none(), none(), literal(Tagged::Number(200.)), none(), none()],
);
let migrated = fixture.migrate(&QrCodeV1).unwrap();
assert_eq!(fixture.inputs(&migrated, qr_code), [none(), none(), none(), length(200.), none(), none()]);
}
}
@@ -1,79 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const WIDTH: usize = 1;
const HEIGHT: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The width and height are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::RectangleNode"@1 => @2)]
pub fn rectangle_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [WIDTH, HEIGHT] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RectangleV1, &contract());
check_undo(&RectangleV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&RectangleV1);
let number = |number: f64| literal(Tagged::Number(number));
let rectangle = fixture.add(
decl!("vector_nodes::generator_nodes::RectangleNode"@1),
vec![literal(Tagged::None), number(100.), number(80.), number(0.), number(1.), number(0.)],
);
let migrated = fixture.migrate(&RectangleV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, rectangle),
[literal(Tagged::None), length(100.), length(80.), number(0.), number(1.), number(0.)]
);
}
}
@@ -1,66 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 2;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::RegularPolygonNode"@1 => @2)]
pub fn regular_polygon_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&RegularPolygonV1, &contract());
check_undo(&RegularPolygonV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&RegularPolygonV1);
let number = |number: f64| literal(Tagged::Number(number));
let polygon = fixture.add(decl!("vector_nodes::generator_nodes::RegularPolygonNode"@1), vec![literal(Tagged::None), number(6.), number(50.)]);
let migrated = fixture.migrate(&RegularPolygonV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, polygon), [literal(Tagged::None), number(6.), radius]);
}
}
@@ -1,105 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const START_ANGLE: usize = 3;
const INNER_RADIUS: usize = 4;
const OUTER_RADIUS: usize = 5;
const ANGULAR_RESOLUTION: usize = 6;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
Angle(TypedAngle),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
#[derive(Serialize, Deserialize)]
struct TypedAngle {
value: f64,
unit: AngleUnit,
}
#[derive(Serialize, Deserialize)]
enum AngleUnit {
Degree,
}
/// The radii are lengths and the start angle and angular resolution are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
#[migration("vector_nodes::generator_nodes::SpiralNode"@1 => @2)]
pub fn spiral_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [INNER_RADIUS, OUTER_RADIUS] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
for slot in [START_ANGLE, ANGULAR_RESOLUTION] {
if let Some(degrees) = number_at(slot) {
inputs.set(slot as u32, angle(degrees));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
fn angle(degrees: f64) -> NodeInput {
literal(Tagged::Angle(TypedAngle {
value: degrees,
unit: AngleUnit::Degree,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&SpiralV1, &contract());
check_undo(&SpiralV1, &contract());
}
#[test]
fn numbers_of_pixels_and_degrees_become_lengths_and_angles() {
let mut fixture = Fixture::new(&SpiralV1);
let number = |number: f64| literal(Tagged::Number(number));
let spiral = fixture.add(
decl!("vector_nodes::generator_nodes::SpiralNode"@1),
vec![literal(Tagged::None), number(0.), number(5.), number(0.), number(0.), number(25.), number(90.)],
);
let migrated = fixture.migrate(&SpiralV1).unwrap();
assert_eq!(
fixture.inputs(&migrated, spiral),
[literal(Tagged::None), number(0.), number(5.), angle(0.), length(0.), length(25.), angle(90.)]
);
}
}
@@ -1,73 +0,0 @@
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS_1: usize = 2;
const RADIUS_2: usize = 3;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
#[migration("vector_nodes::generator_nodes::StarNode"@1 => @2)]
pub fn star_v1(node: &Node, inputs: &mut Inputs) {
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
Some(Tagged::Number(number)) => Some(number),
_ => None,
};
for slot in [RADIUS_1, RADIUS_2] {
if let Some(pixels) = number_at(slot) {
inputs.set(slot as u32, length(pixels));
}
}
}
fn length(pixels: f64) -> NodeInput {
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
}))
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&StarV1, &contract());
check_undo(&StarV1, &contract());
}
#[test]
fn numbers_of_pixels_become_lengths_in_pixels() {
let mut fixture = Fixture::new(&StarV1);
let number = |number: f64| literal(Tagged::Number(number));
let star = fixture.add(decl!("vector_nodes::generator_nodes::StarNode"@1), vec![literal(Tagged::None), number(5.), number(50.), number(25.)]);
let migrated = fixture.migrate(&StarV1).unwrap();
assert_eq!(fixture.inputs(&migrated, star), [literal(Tagged::None), number(5.), length(50.), length(25.)]);
}
}
+15 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES))); let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
// Removal failing only leaves a temporary directory behind // Removal failing only leaves a temporary directory behind
let _ = std::fs::remove_dir_all(&directory); let _ = std::fs::remove_dir_all(&directory);
let baseline_nodes = baseline_nodes?; let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
let problems = api_problems(&baseline_nodes, &current, &migrations); let problems = api_problems(&baseline_nodes, &current, &migrations);
if !problems.is_empty() { if !problems.is_empty() {
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
// Moving a module keeps the function and its API, which is what a rename looks like // Moving a module keeps the function and its API, which is what a rename looks like
let moved = current let moved = current
.iter() .iter()
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature); .find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
problems.push(match moved { problems.push(match moved {
Some(new) => format!( Some(new) => format!(
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`", "`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
}); });
continue; continue;
}; };
if new.transient {
continue;
}
if new.version < version { if new.version < version {
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version)); problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
@@ -123,6 +126,7 @@ mod tests {
NodeSource { NodeSource {
identifier: identifier.to_string(), identifier: identifier.to_string(),
version, version,
transient: false,
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(), function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
file: PathBuf::from("lib.rs"), file: PathBuf::from("lib.rs"),
signature: signature.to_string(), signature: signature.to_string(),
@@ -168,6 +172,15 @@ mod tests {
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]); assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
} }
#[test]
fn a_node_turned_transient_needs_no_migration() {
let transient = NodeSource {
transient: true,
..node("a::b", 1, "(x: f64, y: f64)")
};
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
}
#[test] #[test]
fn a_bump_needs_a_migration_from_the_baseline_version() { fn a_bump_needs_a_migration_from_the_baseline_version() {
let bumped = [node("a::b", 3, "(x: f64)")]; let bumped = [node("a::b", 3, "(x: f64)")];
+1
View File
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))? let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
.into_iter() .into_iter()
.filter(|node| !node.transient)
.map(|node| (node.identifier, node.version)) .map(|node| (node.identifier, node.version))
.collect(); .collect();
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?; let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
+24
View File
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
/// function name with a `Node` suffix. /// function name with a `Node` suffix.
pub identifier: String, pub identifier: String,
pub version: u32, pub version: u32,
pub transient: bool,
pub function: String, pub function: String,
pub file: PathBuf, pub file: PathBuf,
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit. /// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
let mut path = module_path.join("::"); let mut path = module_path.join("::");
let mut version = 1; let mut version = 1;
let mut transient = false;
for argument in arguments { for argument in arguments {
transient |= argument.path().is_ident("transient");
let syn::Meta::List(list) = argument else { continue }; let syn::Meta::List(list) = argument else { continue };
if list.path.is_ident("path") { if list.path.is_ident("path") {
path = list.tokens.to_string().replace(' ', ""); path = list.tokens.to_string().replace(' ', "");
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
Some(NodeSource { Some(NodeSource {
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)), identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
version, version,
transient,
function: function_name, function: function_name,
file: file.to_path_buf(), file: file.to_path_buf(),
signature, signature,
@@ -171,4 +175,24 @@ mod tests {
assert!(!node.signature.contains("cache"), "{}", node.signature); assert!(!node.signature.contains("cache"), "{}", node.signature);
assert!(node.signature.contains("image"), "{}", node.signature); assert!(node.signature.contains("image"), "{}", node.signature);
} }
#[test]
fn the_transient_attribute_is_read() {
let transient: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(transient, memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let saved: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(category(""), memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
assert!(node(&transient).transient);
assert!(!node(&saved).transient);
}
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node, /// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename. /// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> { pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
let nodes = find_nodes(&workspace.join(NODE_CRATES))?; let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
let migrations = workspace.join(MIGRATIONS); let migrations = workspace.join(MIGRATIONS);
match (command, arguments) { match (command, arguments) {
+2 -1
View File
@@ -14,7 +14,7 @@ publish.workspace = true
workspace = true workspace = true
[features] [features]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"] wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "graph-ui/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
[dependencies] [dependencies]
# Local dependencies # Local dependencies
@@ -35,6 +35,7 @@ preprocessor = { workspace = true }
math-parser = { workspace = true } math-parser = { workspace = true }
snapping = { workspace = true } snapping = { workspace = true }
wgpu-executor = { workspace = true } wgpu-executor = { workspace = true }
graph-ui = { workspace = true, features = ["serde"] }
# Workspace dependencies # Workspace dependencies
js-sys = { workspace = true } js-sys = { workspace = true }
+1 -3
View File
@@ -1,5 +1,5 @@
// GRAPH // GRAPH
pub const GRID_SIZE: u32 = 24; pub const GRID_SIZE: u32 = graph_ui::metrics::GRID_SIZE as u32;
pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2; pub const HALF_GRID_SIZE: u32 = GRID_SIZE / 2;
pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72; pub const EXPORTS_TO_TOP_EDGE_PIXEL_GAP: u32 = 72;
pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120; pub const EXPORTS_TO_RIGHT_EDGE_PIXEL_GAP: u32 = 120;
@@ -11,8 +11,6 @@ pub const STACK_VERTICAL_GAP: i32 = 3;
pub const LAYER_INDENT_OFFSET: i32 = 8; pub const LAYER_INDENT_OFFSET: i32 = 8;
/// Horizontal grid width of a non-layer node in a chain. /// Horizontal grid width of a non-layer node in a chain.
pub const NODE_CHAIN_WIDTH: i32 = 7; pub const NODE_CHAIN_WIDTH: i32 = 7;
/// How quickly a dragged node glides into the grid cell it moves to, as the time it takes to cover all but 1/e (about 37%) of the remaining distance.
pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
// VIEWPORT // VIEWPORT
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.; pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
+1 -3
View File
@@ -80,10 +80,8 @@ const SIDE_EFFECT_FREE_MESSAGES: &[MessageDiscriminant] = &[
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateLayerPanel, NodeGraphMessageDiscriminant::UpdateLayerPanel,
))), ))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendWires))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(NodeGraphMessageDiscriminant::SendGlide))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::UpdateVisibleNodes, NodeGraphMessageDiscriminant::UpdateLayersInView,
))), ))),
MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph( MessageDiscriminant::Portfolio(PortfolioMessageDiscriminant::Document(DocumentMessageDiscriminant::NodeGraph(
NodeGraphMessageDiscriminant::SendSelectedNodes, NodeGraphMessageDiscriminant::SendSelectedNodes,
@@ -665,6 +665,18 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}"); assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
} }
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
let mut editor = create_editor_with_three_layers().await;
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
}
/// - paste /// - paste
/// - assert that ellipse was copied /// - assert that ellipse was copied
#[tokio::test] #[tokio::test]
@@ -6,8 +6,6 @@ use crate::messages::prelude::*;
pub enum DialogMessage { pub enum DialogMessage {
// Sub-messages // Sub-messages
#[child] #[child]
DocumentSetupDialog(DocumentSetupDialogMessage),
#[child]
ExportDialog(ExportDialogMessage), ExportDialog(ExportDialogMessage),
#[child] #[child]
NewDocumentDialog(NewDocumentDialogMessage), NewDocumentDialog(NewDocumentDialogMessage),
@@ -36,7 +34,6 @@ pub enum DialogMessage {
localized_commit_year: String, localized_commit_year: String,
}, },
RequestDemoArtworkDialog, RequestDemoArtworkDialog,
RequestDocumentSetupDialog,
RequestExportDialog, RequestExportDialog,
RequestLicensesDialogWithLocalizedCommitDate { RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: String, localized_commit_year: String,
@@ -4,7 +4,6 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
use crate::messages::frontend::utility_types::ExportBounds; use crate::messages::frontend::utility_types::ExportBounds;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
#[derive(ExtractField)] #[derive(ExtractField)]
pub struct DialogMessageContext<'a> { pub struct DialogMessageContext<'a> {
@@ -17,7 +16,6 @@ pub struct DialogMessageContext<'a> {
pub struct DialogMessageHandler { pub struct DialogMessageHandler {
on_dismiss: Option<Message>, on_dismiss: Option<Message>,
redisplay: Option<Message>, redisplay: Option<Message>,
document_setup_dialog: DocumentSetupDialogMessageHandler,
export_dialog: ExportDialogMessageHandler, export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler, new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler, preferences_dialog: PreferencesDialogMessageHandler,
@@ -29,7 +27,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let DialogMessageContext { portfolio, preferences } = context; let DialogMessageContext { portfolio, preferences } = context;
match message { match message {
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }), DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()), DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }), DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
@@ -103,25 +100,30 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let dialog = DemoArtworkDialog; let dialog = DemoArtworkDialog;
dialog.send_dialog_to_frontend(responses); dialog.send_dialog_to_frontend(responses);
} }
DialogMessage::RequestDocumentSetupDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
pixels_per_inch: document.network_interface.pixels_per_inch(),
};
self.document_setup_dialog.send_dialog_to_frontend(responses);
}
}
DialogMessage::RequestExportDialog => { DialogMessage::RequestExportDialog => {
self.on_dismiss = Some(DialogMessage::Close.into()); self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() { if let Some(document) = portfolio.active_document() {
self.export_dialog.artboards = document.artboard_names(); let artboards = document
.metadata()
.all_layers()
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
.map(|layer| {
let name = document
.network_interface
.node_metadata(&layer.to_node(), &[])
.map(|node| node.persistent_metadata.display_name.clone())
.filter(|name| !name.is_empty())
.unwrap_or_else(|| "Artboard".to_string());
(layer, name)
})
.collect();
self.export_dialog.artboards = artboards;
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
&& !self.export_dialog.artboards.iter().any(|(artboard, _)| *artboard == layer) && !self.export_dialog.artboards.contains_key(&layer)
{ {
self.export_dialog.bounds = self.export_dialog.default_bounds(); self.export_dialog.bounds = ExportBounds::AllArtwork;
self.export_dialog.bounds_chosen = false;
} }
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some(); self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
@@ -143,9 +145,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
self.new_document_dialog = NewDocumentDialogMessageHandler { self.new_document_dialog = NewDocumentDialogMessageHandler {
name: portfolio.generate_new_document_name(None), name: portfolio.generate_new_document_name(None),
infinite: false, infinite: false,
width: TypedLength::pixels(1920.), dimensions: glam::UVec2::new(1920, 1080),
height: TypedLength::pixels(1080.),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}; };
self.new_document_dialog.send_dialog_to_frontend(responses); self.new_document_dialog.send_dialog_to_frontend(responses);
} }
@@ -1,9 +0,0 @@
use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DocumentSetupDialogMessage {
Resolution { pixels_per_inch: f64 },
Submit,
}
@@ -1,158 +0,0 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
/// A dialog to allow users to change the settings of the active document.
#[derive(Debug, Clone, ExtractField)]
pub struct DocumentSetupDialogMessageHandler {
pub pixels_per_inch: f64,
}
impl Default for DocumentSetupDialogMessageHandler {
fn default() -> Self {
Self {
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
}
#[message_handler_data]
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
DocumentSetupDialogMessage::Submit => {
// The settings apply as one undo step, which ending the transaction drops if nothing changed
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
responses.add(DocumentMessage::EndTransaction);
}
}
self.send_dialog_to_frontend(responses);
}
advertise_actions!(DocumentSetupDialogUpdate;
);
}
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "Document Setup";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("OK")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for DocumentSetupDialogMessageHandler {
fn layout(&self) -> Layout {
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
Layout(vec![LayoutGroup::row(resolution)])
}
}
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
vec![
TextLabel::new("Resolution")
.table_align(true)
.sizing(WidgetSizing::fixed(90))
.tooltip_label("Resolution")
.tooltip_description(description)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(pixels_per_inch))
.unit(" PPI")
.min(1.)
.max(100_000.)
.tooltip_label("Resolution")
.tooltip_description(description)
// Matches the width of the New Document dialog's Name field
.sizing(WidgetSizing::default().min_width(204))
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
.widget_instance(),
]
}
#[cfg(test)]
mod tests {
use crate::test_utils::test_prelude::*;
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
editor.active_document().network_interface.pixels_per_inch()
}
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
}
async fn confirm(editor: &mut EditorTestUtils) {
editor
.handle_message(DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
})
.await;
}
#[tokio::test]
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer_count = editor.active_document().metadata().all_layers().count();
open_and_set_resolution(&mut editor, 300.).await;
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
// Undoing reverts only the resolution, leaving the rectangle drawn before it
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96.);
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(pixels_per_inch(&editor), 300.);
}
#[tokio::test]
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
open_and_set_resolution(&mut editor, 300.).await;
confirm(&mut editor).await;
open_and_set_resolution(&mut editor, 150.).await;
editor.handle_message(DialogMessage::Close).await;
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
}
}
@@ -1,7 +0,0 @@
mod document_setup_dialog_message;
mod document_setup_dialog_message_handler;
#[doc(inline)]
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
#[doc(inline)]
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
@@ -14,10 +14,7 @@ pub struct ExportDialogMessageHandler {
pub file_type: FileType, pub file_type: FileType,
pub scale_factor: f64, pub scale_factor: f64,
pub bounds: ExportBounds, pub bounds: ExportBounds,
/// Whether the bounds were picked in the dialog, rather than left at the default of the file type, which a change of file type replaces. pub artboards: HashMap<LayerNodeIdentifier, String>,
pub bounds_chosen: bool,
/// Each artboard with its name, from the top of the Layers panel down.
pub artboards: Vec<(LayerNodeIdentifier, String)>,
pub has_selection: bool, pub has_selection: bool,
} }
@@ -27,7 +24,6 @@ impl Default for ExportDialogMessageHandler {
file_type: Default::default(), file_type: Default::default(),
scale_factor: 1., scale_factor: 1.,
bounds: Default::default(), bounds: Default::default(),
bounds_chosen: false,
artboards: Default::default(), artboards: Default::default(),
has_selection: false, has_selection: false,
} }
@@ -40,23 +36,20 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
let ExportDialogMessageContext { portfolio } = context; let ExportDialogMessageContext { portfolio } = context;
match message { match message {
ExportDialogMessage::FileType { file_type } => { ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
self.file_type = file_type;
if !self.bounds_chosen {
self.bounds = self.default_bounds();
}
}
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor, ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
ExportDialogMessage::ExportBounds { bounds } => { ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
self.bounds = bounds;
self.bounds_chosen = true;
}
ExportDialogMessage::Submit => { ExportDialogMessage::Submit => {
let bounds = self.current_bounds(); // Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
let bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
ExportBounds::AllArtwork
} else {
self.bounds
};
let artboard_name = match bounds { let artboard_name = match bounds {
ExportBounds::Artboard(layer) => self.artboards.iter().find(|(artboard, _)| *artboard == layer).map(|(_, name)| name.clone()), ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
_ => None, _ => None,
}; };
responses.add_front(PortfolioMessage::SubmitDocumentExport { responses.add_front(PortfolioMessage::SubmitDocumentExport {
@@ -77,23 +70,6 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
); );
} }
impl ExportDialogMessageHandler {
/// The bounds a file type starts with: each artboard as its own page for a PDF, or otherwise all the artwork.
pub fn default_bounds(&self) -> ExportBounds {
if self.file_type == FileType::Pdf { ExportBounds::AllArtboards } else { ExportBounds::AllArtwork }
}
/// The chosen bounds, falling back to the default and then "All Artwork" in place of a choice that isn't currently available.
fn current_bounds(&self) -> ExportBounds {
let available = |bounds: &ExportBounds| match bounds {
ExportBounds::Selection => self.has_selection,
ExportBounds::AllArtboards => self.file_type == FileType::Pdf && !self.artboards.is_empty(),
ExportBounds::AllArtwork | ExportBounds::Artboard(_) => true,
};
[self.bounds, self.default_bounds()].into_iter().find(available).unwrap_or(ExportBounds::AllArtwork)
}
}
impl DialogLayoutHolder for ExportDialogMessageHandler { impl DialogLayoutHolder for ExportDialogMessageHandler {
const ICON: &'static str = "File"; const ICON: &'static str = "File";
const TITLE: &'static str = "Export"; const TITLE: &'static str = "Export";
@@ -118,9 +94,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
impl LayoutHolder for ExportDialogMessageHandler { impl LayoutHolder for ExportDialogMessageHandler {
fn layout(&self) -> Layout { fn layout(&self) -> Layout {
// The vector types, then the raster ones // The vector type, then the raster ones
let file_types = [ let file_types = [
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")], vec![(FileType::Svg, "SVG")],
vec![ vec![
(FileType::Png, "PNG"), (FileType::Png, "PNG"),
(FileType::Jpg, "JPG"), (FileType::Jpg, "JPG"),
@@ -163,7 +139,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
.min(0.) .min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.increment_step(0.5) .increment_step(0.5)
.disabled(matches!(self.file_type, FileType::Svg | FileType::Pdf)) .disabled(self.file_type == FileType::Svg)
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into()) .on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
.sizing(WidgetSizing::default().min_width(200)) .sizing(WidgetSizing::default().min_width(200))
.widget_instance(), .widget_instance(),
@@ -173,12 +149,15 @@ impl LayoutHolder for ExportDialogMessageHandler {
(ExportBounds::AllArtwork, "All Artwork".to_string(), false), (ExportBounds::AllArtwork, "All Artwork".to_string(), false),
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection), (ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
]; ];
// Only a PDF can hold every artboard, each as its own page let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
let all_artboards = (!self.artboards.is_empty()).then(|| (ExportBounds::AllArtboards, "All Artboards".to_string(), self.file_type != FileType::Pdf)); let choices = [standard_bounds, artboards];
let artboards = self.artboards.iter().map(|(layer, name)| (ExportBounds::Artboard(*layer), name.to_string(), false));
let choices = [standard_bounds, all_artboards.into_iter().chain(artboards).collect()];
let current_bounds = self.current_bounds(); // Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
ExportBounds::AllArtwork
} else {
self.bounds
};
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0); let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0);
let mut entries = choices let mut entries = choices
@@ -209,44 +188,3 @@ impl LayoutHolder for ExportDialogMessageHandler {
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)]) Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EditorTestUtils;
use graphene_std::uuid::NodeId;
#[test]
fn a_pdf_defaults_to_every_artboard_as_a_page() {
let editor = EditorTestUtils::create();
let portfolio = editor.portfolio_message_handler();
let mut dialog = ExportDialogMessageHandler {
artboards: vec![(LayerNodeIdentifier::new_unchecked(NodeId(1)), "Artboard".to_string())],
has_selection: true,
..Default::default()
};
let send = |dialog: &mut ExportDialogMessageHandler, message: ExportDialogMessage| dialog.process_message(message, &mut VecDeque::new(), ExportDialogMessageContext { portfolio });
// Bounds left at the default follow the file type between PDF and a single image
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtboards);
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Png });
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
// A choice of other bounds stays through a change of file type
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::Selection });
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
assert_eq!(dialog.current_bounds(), ExportBounds::Selection);
// Even a choice of the bounds another file type defaults to
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::AllArtwork });
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Png });
send(&mut dialog, ExportDialogMessage::FileType { file_type: FileType::Pdf });
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
// Without artboards, a PDF falls back to one page of all the artwork
send(&mut dialog, ExportDialogMessage::ExportBounds { bounds: ExportBounds::AllArtboards });
dialog.artboards.clear();
assert_eq!(dialog.current_bounds(), ExportBounds::AllArtwork);
}
}
-1
View File
@@ -8,7 +8,6 @@
mod dialog_message; mod dialog_message;
mod dialog_message_handler; mod dialog_message_handler;
pub mod document_setup_dialog;
pub mod export_dialog; pub mod export_dialog;
pub mod new_document_dialog; pub mod new_document_dialog;
pub mod preferences_dialog; pub mod preferences_dialog;
@@ -1,14 +1,12 @@
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graphene_std::units::TypedLength;
#[impl_message(Message, DialogMessage, NewDocumentDialog)] #[impl_message(Message, DialogMessage, NewDocumentDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum NewDocumentDialogMessage { pub enum NewDocumentDialogMessage {
Name { name: String }, Name { name: String },
Infinite { infinite: bool }, Infinite { infinite: bool },
DimensionsX { width: TypedLength }, DimensionsX { width: f64 },
DimensionsY { height: TypedLength }, DimensionsY { height: f64 },
Resolution { pixels_per_inch: f64 },
Submit, Submit,
} }
@@ -1,34 +1,16 @@
use crate::messages::dialog::document_setup_dialog::resolution_row;
use crate::messages::layout::layout_message_handler::unit_suffix;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::node_inspector::length_decimal_places;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::DVec2; use glam::UVec2;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::Color; use graphene_std::Color;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength, TypedLengthVec2};
/// A dialog to allow users to set some initial options about a new document. /// A dialog to allow users to set some initial options about a new document.
#[derive(Debug, Clone, ExtractField)] #[derive(Debug, Clone, Default, ExtractField)]
pub struct NewDocumentDialogMessageHandler { pub struct NewDocumentDialogMessageHandler {
pub name: String, pub name: String,
pub infinite: bool, pub infinite: bool,
pub width: TypedLength, pub dimensions: UVec2,
pub height: TypedLength,
pub pixels_per_inch: f64,
}
impl Default for NewDocumentDialogMessageHandler {
fn default() -> Self {
Self {
name: String::new(),
infinite: false,
width: TypedLength::default(),
height: TypedLength::default(),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
} }
#[message_handler_data] #[message_handler_data]
@@ -37,38 +19,24 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
match message { match message {
NewDocumentDialogMessage::Name { name } => self.name = name, NewDocumentDialogMessage::Name { name } => self.name = name,
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite, NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
NewDocumentDialogMessage::DimensionsX { width } => { NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
self.width = whole_pixels(width); NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
self.height = self.in_unit(self.height, self.width.unit);
}
NewDocumentDialogMessage::DimensionsY { height } => {
self.height = whole_pixels(height);
self.width = self.in_unit(self.width, self.height.unit);
}
NewDocumentDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
NewDocumentDialogMessage::Submit => { NewDocumentDialogMessage::Submit => {
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() }); responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
// Like the artboard, the resolution is part of the document's starting state rather than an undo step
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
let dimensions = self.artboard_dimensions();
let pixels = dimensions.to_length_vec2(self.pixels_per_inch).pixels();
if self.infinite { if self.infinite {
// Infinite canvas: add a locked white background layer // Infinite canvas: add a locked white background layer
graph_modification_utils::new_background_layer(0, responses); graph_modification_utils::new_background_layer(0, responses);
} else if pixels.x > 0. && pixels.y > 0. { } else if self.dimensions.x > 0 && self.dimensions.y > 0 {
// Finite canvas: create an artboard with the specified dimensions // Finite canvas: create an artboard with the specified dimensions
responses.add(GraphOperationMessage::NewArtboard { responses.add(GraphOperationMessage::NewArtboard {
id: NodeId::new(), id: NodeId::new(),
location: DVec2::ZERO, location: glam::DVec2::ZERO,
dimensions, dimensions: self.dimensions.as_dvec2(),
background: Color::WHITE, background: Color::WHITE,
clip: true, clip: true,
}); });
responses.add(NavigationMessage::CanvasPan { delta: pixels }); responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
} }
responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -139,191 +107,32 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
.widget_instance(), .widget_instance(),
]; ];
// Each dimension shows the unit it was typed in and keeps any length unit typed into it let scale = vec![
let dimension_field = |length: TypedLength, label: &str| {
NumberInput::new(Some(length.value))
.label(label)
.unit(unit_suffix(length.unit.symbol()))
.display_decimal_places(length_decimal_places(length.unit, self.pixels_per_inch))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(self.pixels_per_inch)
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
};
let dimensions = vec![
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(), TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance(),
dimension_field(self.width, "W") NumberInput::new(Some(self.dimensions.x as f64))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into()) .label("W")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
.widget_instance(), .widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(), Separator::new(SeparatorStyle::Related).widget_instance(),
dimension_field(self.height, "H") NumberInput::new(Some(self.dimensions.y as f64))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into()) .label("H")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
.widget_instance(), .widget_instance(),
]; ];
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into()); Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(dimensions), LayoutGroup::row(resolution)])
}
}
impl NewDocumentDialogMessageHandler {
/// A dimension converted into `unit` at the chosen resolution, keeping its size.
fn in_unit(&self, length: TypedLength, unit: LengthUnit) -> TypedLength {
whole_pixels(TypedLength {
value: length.unit.convert(length.value, unit, self.pixels_per_inch),
unit,
})
}
/// The artboard's size in the unit both dimensions share, like an A4 page in millimeters.
pub fn artboard_dimensions(&self) -> TypedLengthVec2 {
TypedLengthVec2 {
value: DVec2::new(self.width.value, self.height.value),
unit: self.width.unit,
}
}
}
/// The length a dimension field holds, in the unit it shows.
fn typed_length(number_input: &NumberInput) -> TypedLength {
let unit = math_parser::units::Unit::named(number_input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
TypedLength {
value: number_input.value.unwrap_or_default(),
unit,
}
}
/// Rounds a dimension typed in pixels to a whole number of them, leaving one in a physical unit as typed.
fn whole_pixels(length: TypedLength) -> TypedLength {
if length.unit == LengthUnit::Pixel { TypedLength::pixels(length.value.round()) } else { length }
}
#[cfg(test)]
mod tests {
use super::NewDocumentDialogMessageHandler;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_DIMENSIONS_INPUT_INDEX;
use crate::test_utils::test_prelude::*;
use graph_craft::document::value::TaggedValue;
use graphene_std::units::{LengthUnit, TypedLengthVec2};
use std::collections::HashMap;
/// Commits text into the dialog's number field with this label or tooltip label, as the frontend sends a typed entry.
fn type_into_field(editor: &mut EditorTestUtils, label: &str, text: &str) {
// A widget's ID follows from its place in the layout, which the dialog's state doesn't change
let mut layout = NewDocumentDialogMessageHandler::default().layout();
layout.replace_widget_ids(LayoutTarget::DialogColumn1, &mut Vec::new(), &HashMap::new());
let widget_id = layout.iter().find_map(|instance| match &*instance.widget {
Widget::NumberInput(number_input) if number_input.label == label || number_input.tooltip_label == label => Some(instance.widget_id),
_ => None,
});
let Some(widget_id) = widget_id else {
panic!("the dialog has no number field labeled \"{label}\"")
};
editor.dispatch(LayoutMessage::WidgetValueUpdate {
layout_target: LayoutTarget::DialogColumn1,
widget_id,
value: serde_json::Value::String(text.into()),
});
}
async fn create_document(editor: &mut EditorTestUtils) {
editor
.handle_message(DialogMessage::CloseAndThen {
followups: vec![NewDocumentDialogMessage::Submit.into()],
})
.await;
}
fn artboard_dimensions(editor: &EditorTestUtils) -> Option<TaggedValue> {
let network_interface = &editor.active_document().network_interface;
let artboard = network_interface.all_artboards().into_iter().next()?;
let node = network_interface.document_network().nodes.get(&artboard.to_node())?;
node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value().cloned()
}
fn artboard_pixels(editor: &EditorTestUtils) -> Option<DVec2> {
let pixels_per_inch = editor.active_document().network_interface.pixels_per_inch();
artboard_dimensions(editor)?.as_length_vec2_pixels(pixels_per_inch).map(DVec2::round)
}
#[tokio::test]
async fn a_new_document_starts_at_the_chosen_resolution_without_an_undo_step() {
let mut editor = EditorTestUtils::create();
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
type_into_field(&mut editor, "Resolution", "300");
create_document(&mut editor).await;
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(1920., 1080.)));
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(1920., 1080.)));
}
#[tokio::test]
async fn typing_a_unit_into_one_dimension_converts_the_other_into_it() {
let mut editor = EditorTestUtils::create();
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
type_into_field(&mut editor, "W", "210mm");
// The height of 1080 px at 96 PPI became 285.75 mm, so it grows with the resolution like the width
type_into_field(&mut editor, "Resolution", "300");
create_document(&mut editor).await;
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(2480., 3375.)));
}
#[tokio::test]
async fn dimensions_typed_in_millimeters_convert_to_pixels_at_the_chosen_resolution() {
let mut editor = EditorTestUtils::create();
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
type_into_field(&mut editor, "W", "210mm");
type_into_field(&mut editor, "H", "297mm");
// The lengths stay in millimeters, so their size in pixels follows a resolution chosen after them
type_into_field(&mut editor, "Resolution", "300");
create_document(&mut editor).await;
assert_eq!(artboard_pixels(&editor), Some(DVec2::new(2480., 3508.)));
// The artboard keeps the millimeters, so changing the resolution later keeps the page's physical size
let a4 = TaggedValue::LengthVec2(TypedLengthVec2 {
value: DVec2::new(210., 297.),
unit: LengthUnit::Millimeter,
});
assert_eq!(artboard_dimensions(&editor), Some(a4));
}
#[tokio::test]
async fn moving_an_artboard_sized_in_millimeters_keeps_its_millimeters() {
let mut editor = EditorTestUtils::create();
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
type_into_field(&mut editor, "W", "210mm");
type_into_field(&mut editor, "H", "297mm");
create_document(&mut editor).await;
let a4 = artboard_dimensions(&editor);
// Tools move and nudge an artboard by resizing it to its own size in whole pixels, which 793.7 x 1122.5 px rounds to
let layer = editor
.active_document()
.network_interface
.all_artboards()
.into_iter()
.next()
.expect("the document should have an artboard");
let dimensions = artboard_pixels(&editor).expect("the artboard should have dimensions");
editor
.handle_message(GraphOperationMessage::ResizeArtboard {
layer,
location: DVec2::new(10., 0.),
dimensions,
})
.await;
assert_eq!(artboard_dimensions(&editor), a4);
} }
} }
@@ -1,8 +1,8 @@
use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE}; use crate::consts::{VIEWPORT_ZOOM_WHEEL_RATE, VIEWPORT_ZOOM_WHEEL_RATE_CHANGE};
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode; use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graph_ui::wire::WireStyle;
#[derive(ExtractField)] #[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> { pub struct PreferencesDialogMessageContext<'a> {
@@ -254,16 +254,16 @@ impl PreferencesDialogMessageHandler {
.widget_instance(), .widget_instance(),
]; ];
let graph_wire_style = RadioInput::new(vec![ let graph_wire_style = RadioInput::new(vec![
RadioEntryData::new(GraphWireStyle::Direct.to_string()) RadioEntryData::new("Direct")
.label(GraphWireStyle::Direct.to_string()) .label("Direct")
.tooltip_label(GraphWireStyle::Direct.to_string()) .tooltip_label("Direct")
.tooltip_description(GraphWireStyle::Direct.tooltip_description()) .tooltip_description("Wires bend to run at an angle directly between nodes.")
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::Direct }.into()), .on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::Direct }.into()),
RadioEntryData::new(GraphWireStyle::GridAligned.to_string()) RadioEntryData::new("Grid-Aligned")
.label(GraphWireStyle::GridAligned.to_string()) .label("Grid-Aligned")
.tooltip_label(GraphWireStyle::GridAligned.to_string()) .tooltip_label("Grid-Aligned")
.tooltip_description(GraphWireStyle::GridAligned.tooltip_description()) .tooltip_description("Wires follow the grid, running in straight lines between nodes.")
.on_update(move |_| PreferencesMessage::GraphWireStyle { style: GraphWireStyle::GridAligned }.into()), .on_update(move |_| PreferencesMessage::GraphWireStyle { style: WireStyle::GridAligned }.into()),
]) ])
.selected_index(Some(preferences.graph_wire_style as u32)) .selected_index(Some(preferences.graph_wire_style as u32))
.sizing(WidgetSizing::default().shrink(false)) .sizing(WidgetSizing::default().shrink(false))
@@ -5,11 +5,9 @@ use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewIm
use crate::messages::input_mapper::utility_types::misc::ActionShortcut; use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions; use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::node_graph::graph_ui::GraphNameField;
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic, use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuInformation, FrontendNodeType, FrontendRemoteCursor};
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry}; use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction}; use crate::messages::portfolio::ingest::utility_types::{DataTransfer, IngestAction};
use crate::messages::portfolio::utility_types::WorkspacePanelLayout; use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
use crate::messages::prelude::*; use crate::messages::prelude::*;
@@ -65,8 +63,6 @@ pub enum FrontendMessage {
SendUIMetadata { SendUIMetadata {
#[serde(rename = "nodeDescriptions")] #[serde(rename = "nodeDescriptions")]
node_descriptions: Vec<(String, String)>, node_descriptions: Vec<(String, String)>,
#[serde(rename = "nodeIcons")]
node_icons: Vec<(String, IconName)>,
#[serde(rename = "nodeTypes")] #[serde(rename = "nodeTypes")]
node_types: Vec<FrontendNodeType>, node_types: Vec<FrontendNodeType>,
}, },
@@ -121,11 +117,6 @@ pub enum FrontendMessage {
preferences: PreferencesMessageHandler, preferences: PreferencesMessageHandler,
}, },
TriggerTextCommit, TriggerTextCommit,
/// Asks the frontend to enter inline-rename mode for a layer in the graph view.
TriggerEditLayerNameInGraph {
#[serde(rename = "nodeId")]
node_id: NodeId,
},
TriggerVisitLink { TriggerVisitLink {
url: String, url: String,
}, },
@@ -158,34 +149,11 @@ pub enum FrontendMessage {
ColorPickerStartHistoryTransaction, ColorPickerStartHistoryTransaction,
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event. /// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
ColorPickerCommitHistoryTransaction, ColorPickerCommitHistoryTransaction,
UpdateImportsExports {
/// If the primary import is not visible, then it is None.
imports: Vec<Option<FrontendGraphOutput>>,
/// If the primary export is not visible, then it is None.
exports: Vec<Option<FrontendGraphInput>>,
/// The primary import location.
#[serde(rename = "importPosition")]
import_position: (i32, i32),
/// The primary export location.
#[serde(rename = "exportPosition")]
export_position: (i32, i32),
/// The document network does not have an add import or export button.
#[serde(rename = "addImportExport")]
add_import_export: bool,
},
UpdateInSelectedNetwork {
#[serde(rename = "inSelectedNetwork")]
in_selected_network: bool,
},
/// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable. /// Whether the network shown in the graph lies inside a built-in node, whose contents are read-only until made editable.
UpdateNetworkReadOnly { UpdateNetworkReadOnly {
#[serde(rename = "readOnly")] #[serde(rename = "readOnly")]
read_only: bool, read_only: bool,
}, },
UpdateBox {
#[serde(rename = "box")]
box_selection: Option<BoxSelection>,
},
UpdateRemoteCursors { UpdateRemoteCursors {
cursors: Vec<FrontendRemoteCursor>, cursors: Vec<FrontendRemoteCursor>,
}, },
@@ -196,13 +164,17 @@ pub enum FrontendMessage {
#[serde(rename = "contextMenuInformation")] #[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>, context_menu_information: Option<ContextMenuInformation>,
}, },
UpdateClickTargets {
#[serde(rename = "clickTargets")]
click_targets: Option<FrontendClickTargets>,
},
UpdateGraphViewOverlay { UpdateGraphViewOverlay {
open: bool, open: bool,
}, },
UpdateGraphTooltip {
label: String,
description: String,
},
UpdateGraphNameField {
field: Option<GraphNameField>,
opens: bool,
},
UpdateWorkspacePanelLayout { UpdateWorkspacePanelLayout {
#[serde(rename = "panelLayout")] #[serde(rename = "panelLayout")]
panel_layout: WorkspacePanelLayout, panel_layout: WorkspacePanelLayout,
@@ -229,36 +201,6 @@ pub enum FrontendMessage {
source: String, source: String,
result: Option<String>, result: Option<String>,
}, },
UpdateImportReorderIndex {
#[serde(rename = "importIndex")]
index: Option<usize>,
},
UpdateExportReorderIndex {
#[serde(rename = "exportIndex")]
index: Option<usize>,
},
/// The wire a dragged node would be inserted onto if dropped now, keyed by the node and index of the input it feeds (the max node ID for an export).
UpdateWireInsertionPreview {
wire: Option<(NodeId, usize)>,
},
/// How far each node, and the imports and exports, gliding into the place it moved to is drawn from that place, in node graph space.
UpdateGlideOffsets {
nodes: Vec<(NodeId, (f64, f64))>,
imports: (f64, f64),
exports: (f64, f64),
},
/// The connector a press at the pointer would grab, by its center in node graph space.
UpdateHoveredConnector {
center: Option<(f64, f64)>,
},
UpdateLayerWidths {
#[serde(rename = "layerWidths")]
layer_widths: HashMap<NodeId, u32>,
#[serde(rename = "chainWidths")]
chain_widths: HashMap<NodeId, u32>,
#[serde(rename = "hasLeftInputWire")]
has_left_input_wire: HashMap<NodeId, bool>,
},
UpdateDocumentArtwork { UpdateDocumentArtwork {
svg: String, svg: String,
}, },
@@ -304,25 +246,9 @@ pub enum FrontendMessage {
#[serde(rename = "setColorChoice")] #[serde(rename = "setColorChoice")]
set_color_choice: Option<PrimarySecondary>, set_color_choice: Option<PrimarySecondary>,
}, },
UpdateGraphFadeArtwork {
percentage: f64,
},
UpdateMouseCursor { UpdateMouseCursor {
cursor: MouseCursorIcon, cursor: MouseCursorIcon,
}, },
UpdateNodeGraphNodes {
nodes: Vec<FrontendNode>,
},
UpdateNodeGraphErrorDiagnostics {
errors: Vec<NodeGraphErrorDiagnostic>,
},
UpdateVisibleNodes {
nodes: Vec<NodeId>,
},
UpdateNodeGraphWires {
wires: Vec<WirePathUpdate>,
},
ClearAllNodeGraphWires,
UpdateNodeGraphSelection { UpdateNodeGraphSelection {
selected: Vec<NodeId>, selected: Vec<NodeId>,
}, },
@@ -339,27 +265,15 @@ pub enum FrontendMessage {
height: u32, height: u32,
pixels: serde_bytes::ByteBuf, pixels: serde_bytes::ByteBuf,
}, },
UpdateNodeThumbnailCanvases { UpdateNodeThumbnailCanvas {
id: NodeId, id: NodeId,
#[serde(rename = "layersPanelCanvasId")] #[serde(rename = "canvasId")]
layers_panel_canvas_id: u64, canvas_id: u64,
#[serde(rename = "nodeGraphCanvasId")]
node_graph_canvas_id: u64,
}, },
UpdateOpenDocumentsList { UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")] #[serde(rename = "openDocuments")]
open_documents: Vec<DocumentInfo>, open_documents: Vec<DocumentInfo>,
}, },
UpdateWirePathInProgress {
#[serde(rename = "wirePath")]
wire_path: Option<WirePath>,
/// Where the wire meets the connector it's dragged from, in node graph space.
#[serde(rename = "draggedFrom")]
dragged_from: Option<(f64, f64)>,
/// Where the wire's loose end meets a connector it has snapped onto, in node graph space.
#[serde(rename = "snappedTo")]
snapped_to: Option<(f64, f64)>,
},
UpdatePlatform { UpdatePlatform {
platform: AppWindowPlatform, platform: AppWindowPlatform,
}, },
@@ -78,7 +78,6 @@ pub enum FileType {
Tga, Tga,
Ico, Ico,
Svg, Svg,
Pdf,
} }
impl FileType { impl FileType {
@@ -92,7 +91,6 @@ impl FileType {
FileType::Tga => "tga", FileType::Tga => "tga",
FileType::Ico => "ico", FileType::Ico => "ico",
FileType::Svg => "svg", FileType::Svg => "svg",
FileType::Pdf => "pdf",
} }
} }
@@ -106,7 +104,6 @@ impl FileType {
FileType::Tga => "TGA Image", FileType::Tga => "TGA Image",
FileType::Ico => "ICO Image", FileType::Ico => "ICO Image",
FileType::Svg => "SVG Image", FileType::Svg => "SVG Image",
FileType::Pdf => "PDF Document",
}; };
FileFilter { FileFilter {
name: name.into(), name: name.into(),
@@ -133,7 +130,6 @@ impl FileType {
FileType::Tga => ImageFormat::Tga, FileType::Tga => ImageFormat::Tga,
FileType::Ico => ImageFormat::Ico, FileType::Ico => ImageFormat::Ico,
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()), FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
FileType::Pdf => return Err("PDF cannot be exported from an image buffer".to_string()),
}; };
if self == FileType::Ico && (width > 256 || height > 256) { if self == FileType::Ico && (width > 256 || height > 256) {
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string()); return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
@@ -168,8 +164,6 @@ pub enum ExportBounds {
#[default] #[default]
AllArtwork, AllArtwork,
Selection, Selection,
/// Each artboard as its own page, for a file type that holds pages.
AllArtboards,
Artboard(LayerNodeIdentifier), Artboard(LayerNodeIdentifier),
} }
@@ -234,7 +228,6 @@ mod tests {
#[test] #[test]
fn file_types_that_cannot_hold_the_image_say_so() { fn file_types_that_cannot_hold_the_image_say_so() {
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err()); assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err()); assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err(); let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
@@ -87,9 +87,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility), entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked), entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes), entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes), entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }), entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }), entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }), entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
@@ -417,20 +417,16 @@ impl LayoutMessageHandler {
} }
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate. // A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
Value::String(expression) => { Value::String(expression) => {
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else { let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
return;
};
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway. // Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
if number_input.value == Some(evaluated) && number_input.unit == unit { if number_input.value == Some(evaluated) {
return; return;
} }
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`. // Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
responses.add((number_input.on_commit.callback)(&())); responses.add((number_input.on_commit.callback)(&()));
number_input.value = Some(evaluated); number_input.value = Some(evaluated);
number_input.unit = unit;
responses.add((number_input.on_update.callback)(number_input)); responses.add((number_input.on_update.callback)(number_input));
} }
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback. // The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
@@ -708,41 +704,21 @@ fn populate_computed_display_fields(layout: &mut Layout) {
} }
} }
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`. /// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
pub fn unit_suffix(symbol: &str) -> String { /// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() } fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
} let value = math_parser::evaluate(expression)
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
let value = math_parser::ast::Node::try_parse_from_str(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}")) .inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()? .ok()?
.eval(&context)
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}")) .inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?; .ok()?;
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it let real = value.as_real()?;
let field_unit = math_parser::units::Unit::named(number_input.unit.trim()); if real.is_nan() {
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
(Some(quantity), Some(unit)) => {
let read = quantity
.read_in(unit, number_input.pixels_per_inch)
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
.ok()?
.as_real()?;
(read, Some(*quantity))
}
_ => (value.as_real()?, None),
};
if in_field_unit.is_nan() {
return None; return None;
} }
let mut validated = in_field_unit; let mut validated = real;
if let Some(min) = number_input.min { if let Some(min) = number_input.min {
validated = validated.max(min); validated = validated.max(min);
} }
@@ -753,17 +729,5 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
validated = validated.round(); validated = validated.round();
} }
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it Some(validated)
let kept_unit = quantity.and_then(|quantity| {
let symbol = quantity.unit.single()?.definition().symbol;
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
});
if let Some((quantity, symbol)) = kept_unit
&& validated == in_field_unit
&& let Some(kept_value) = quantity.value.as_real()
{
return Some((kept_value, Some(symbol.to_string())));
}
Some((validated, None))
} }
@@ -247,14 +247,6 @@ pub struct NumberInput {
#[serde(rename = "unitIsHiddenWhenEditing")] #[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))] #[derivative(Default(value = "true"))]
pub unit_is_hidden_when_editing: bool, pub unit_is_hidden_when_editing: bool,
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
#[serde(skip)]
pub kept_units: Vec<String>,
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
#[serde(skip)]
#[derivative(Default(value = "96."))]
pub pixels_per_inch: f64,
// Tooltips // Tooltips
#[serde(rename = "tooltipLabel")] #[serde(rename = "tooltipLabel")]
@@ -615,7 +607,6 @@ pub enum MathExpressionRole {
Function, Function,
Keyword, Keyword,
Operator, Operator,
Unit,
Bracket, Bracket,
MatrixLiteral, MatrixLiteral,
Error, Error,
@@ -632,7 +623,6 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
Role::Function => Self::Function, Role::Function => Self::Function,
Role::Keyword => Self::Keyword, Role::Keyword => Self::Keyword,
Role::Operator => Self::Operator, Role::Operator => Self::Operator,
Role::Unit => Self::Unit,
Role::Bracket => Self::Bracket, Role::Bracket => Self::Bracket,
Role::MatrixLiteral => Self::MatrixLiteral, Role::MatrixLiteral => Self::MatrixLiteral,
Role::Error => Self::Error, Role::Error => Self::Error,
@@ -888,6 +878,22 @@ pub struct SliderMarker {
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position. /// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
#[serde(rename = "betweenNeighbors")] #[serde(rename = "betweenNeighbors")]
between_neighbors: bool, between_neighbors: bool,
/// How this marker and the next may pass each other.
#[serde(rename = "overlapNext")]
overlap_next: MarkerOverlap,
}
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum MarkerOverlap {
/// Neither may pass the other.
#[default]
Never,
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
NextOnly,
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
Freely,
} }
impl SliderMarker { impl SliderMarker {
@@ -900,6 +906,7 @@ impl SliderMarker {
paired_with_next: false, paired_with_next: false,
dashed_to_next: false, dashed_to_next: false,
between_neighbors: false, between_neighbors: false,
overlap_next: MarkerOverlap::Never,
} }
} }
@@ -917,6 +924,11 @@ impl SliderMarker {
self.dashed_to_next = true; self.dashed_to_next = true;
self self
} }
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
self.overlap_next = overlap;
self
}
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -181,13 +181,6 @@ impl LayoutHolder for MenuBarMessageHandler {
.on_commit(|_| DialogMessage::RequestExportDialog.into()) .on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document), .disabled(no_active_document),
], ],
vec![
MenuListEntry::new("Document Setup…")
.label("Document Setup…")
.icon("Settings")
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
vec![preferences], vec![preferences],
]) ])
@@ -0,0 +1,262 @@
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::application_io::Texture;
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List};
use graphene_std::math_nodes::{color_value, gradient_value};
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::style::RenderMode;
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
#[derive(Clone, Copy, Debug)]
enum Base {
VectorLayer,
ImageLayer,
/// A group holding a vector layer, with the effect on the group.
Group,
}
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
if effect == blur::IDENTIFIER {
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
.upstream_node_id_from_protonode(effect)
.expect("the layer has its blur");
let value = Box::new(TaggedValue::Number(10.));
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id,
input_index: blur::RadiusInput::INDEX,
value,
})
.await;
}
}
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
match base {
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
Base::VectorLayer | Base::Group => {
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
}
}
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
if !matches!(base, Base::Group) {
add_effect(&mut editor, base_layer, effect.clone()).await;
}
editor.select_tool(ToolType::Select).await;
editor.select_primary_color(red).await;
editor.select_secondary_color(red).await;
editor.draw_rect(20., 20., 200., 200.).await;
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
editor
.handle_message(GraphOperationMessage::FillColorSet {
layer: clipped_layer,
color: Some(red),
})
.await;
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
// Grouped once the red is clipped, the group takes the base's place beneath it
if let Base::Group = base {
let nodes = vec![base_layer.to_node()];
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
let group_folder_type = GroupFolderType::Layer;
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
let group = editor.get_selected_layer().await.expect("the group is selected");
add_effect(&mut editor, group, effect).await;
}
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
stack.push(clipped);
stack
}
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
// The clip's def in SVG carries out the blur but not the shadow
let mut render = SvgRender::new();
graphic.render_svg(
&mut render,
&RenderParams {
for_export: true,
..Default::default()
},
);
let body = render.svg.to_svg_string();
let reference = body.rfind("url(#mask-").expect("the red is clipped");
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
let defs = &render.svg_defs;
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
let def_end = ["</mask>", "</clipPath>"]
.iter()
.filter_map(|closing| defs[def_start..].find(closing))
.min()
.expect("the clip's def is closed");
let clip = &defs[def_start..def_start + def_end];
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
let size = UVec2::new(256, 256);
let executor = gpu_executor();
let texture = executor
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
.expect("the clip renders");
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
let pixel = |x: u32, y: u32| -> [u8; 4] {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
let within = pixel(90, 90);
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
}
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
#[derive(Clone, Copy, Debug)]
enum Endless {
Color,
Gradient,
NoisePattern,
}
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
editor
}
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
let node = match endless {
Endless::Color => color_value::IDENTIFIER,
Endless::Gradient => gradient_value::IDENTIFIER,
Endless::NoisePattern => noise_pattern::IDENTIFIER,
};
let node_type = DefinitionIdentifier::ProtoNode(node);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
}
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.expect("a document is open");
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).expect("the active document exists");
let submitted = executor
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO, None)
.expect("the evaluation is submitted");
let mut messages = editor.dispatch(submitted);
editor.runtime.update();
let frame = editor.runtime.run().await;
messages.extend(editor.dispatch(Message::Wake));
(messages, frame)
}
#[tokio::test]
async fn endless_layers_clip_to_the_shape_beneath_them() {
let size = UVec2::new(256, 256);
let frame_pixels = async |editor: &mut EditorTestUtils| {
let (_, frame) = evaluate_viewport(editor, size).await;
let frame = frame.expect("the viewport presents a frame");
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
};
let pixel = |pixels: &[u8], x: u32, y: u32| {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
let rectangle_alone = frame_pixels(&mut editor).await;
add_clipped_endless_layer(&mut editor, endless).await;
let clipped = frame_pixels(&mut editor).await;
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
assert_eq!(
pixel(&clipped, x, y),
pixel(&rectangle_alone, x, y),
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
);
}
// In SVG Preview, the endless content is drawn only within the rectangle's mask
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
add_clipped_endless_layer(&mut editor, endless).await;
let (messages, _) = evaluate_viewport(&mut editor, size).await;
let svg = messages
.into_iter()
.find_map(|message| match message {
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
_ => None,
})
.expect("the viewport's artwork is sent as SVG");
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
assert!(
!draws_endless_content(unmasked) && draws_endless_content(masked),
"{endless:?}: the content is drawn within the mask: {svg}"
);
}
}
#[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
let stack = clipped_stack(base, effect.clone()).await;
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
// Flattened into one list of vectors, the base clips its sibling by the same rule
if let Base::VectorLayer = base {
let flattened: List<Vector> = stack.into_flattened_list();
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
}
}
}
}
Loaded 100 of 400 files, more files were not shown because too many files have changed in this diff. Show more