Compare commits

..
22 Commits
Author SHA1 Message Date
Keavon Chambers b1db3026a2 Export each artboard as its own page of a PDF from the Export dialog 2026-11-26 02:58:11 -08:00
Keavon Chambers 91c7236e10 Encode one PDF scene into several pages, each showing a region of it 2026-11-26 02:58:11 -08:00
Keavon Chambers fa686d5063 Add PDF as a file type in the Export dialog 2026-11-26 02:58:11 -08:00
Keavon Chambers 7d8f124539 Add a krilla-backed PDF scene builder that the renderer can draw into 2026-11-26 02:58:11 -08:00
Keavon Chambers 78a1be4059 Make the renderer's Vello traversal generic over a scene builder trait 2026-11-26 02:58:10 -08:00
Keavon Chambers a7ed5fcf0f Show length and angle fields for inputs whose node rows call for them 2026-11-26 02:37:51 -08:00
Keavon Chambers 48fe21ebe3 Let the math nodes take lengths and angles and give them where meaningful 2026-11-26 02:37:51 -08:00
Keavon Chambers 0ab2f21e47 Make the Transform node and every pair of lengths or angles typed 2026-11-26 02:37:50 -08:00
Keavon Chambers d73bd34750 Show the units of length and angle parameters' defaults in the node docs 2026-11-26 02:37:14 -08:00
Keavon Chambers 4f999ea73b Show a range slider beside angle parameters bounded at both ends 2026-11-26 02:37:14 -08:00
Keavon Chambers 80f9dbb992 Keep angles typed in degrees exact when tools and fields read and write them 2026-11-26 02:37:14 -08:00
Keavon Chambers 9fd1011e1e Make the 'Blur' and 'Median Filter' nodes' radii typed lengths 2026-11-26 02:37:12 -08:00
Keavon Chambers 3d4d7d1058 Make the 'Brush Strokes' node's diameter a typed length 2026-11-26 02:35:57 -08:00
Keavon Chambers 401cf1419a Make the 'Mirror', 'Repeat', and 'Vary Rotations' nodes' angles and distances typed 2026-11-26 02:35:57 -08:00
Keavon Chambers 369671dc41 Make the 'Text' node's size, letter spacing, and letter tilt typed lengths and angles 2026-11-26 02:35:57 -08:00
Keavon Chambers fe505edeff Make the stroke and path nodes' distances and angles typed lengths and angles 2026-11-26 02:35:57 -08:00
Keavon Chambers 63a8befe4b Make the shape generator nodes' sizes and angles typed lengths and angles 2026-11-26 02:35:56 -08:00
Keavon Chambers 3e380b8cd7 Carry units through the math parser's lone-operator reductions 2026-11-26 02:35:56 -08:00
Keavon Chambers 634c30bebf Give exported SVGs a physical size and let Math f(x) take lengths and angles 2026-11-26 02:35:56 -08:00
Keavon Chambers 1e912de804 Add a resolution and lengths in any unit to the New Document dialog 2026-11-26 02:35:56 -08:00
Keavon Chambers ea9c44e003 Add typed length and angle values with a per-document resolution 2026-11-26 02:35:55 -08:00
Keavon Chambers 6a28b82b91 Add units of measure to the math expression language 2026-11-26 02:34:34 -08:00
280 changed files with 15914 additions and 14105 deletions

No files matched your search

+2 -7
View File
@@ -7,8 +7,6 @@ on:
push:
branches:
- 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)
concurrency:
@@ -247,8 +245,7 @@ jobs:
permissions:
contents: read
env:
# 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' }}
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -262,9 +259,7 @@ jobs:
rustflags: ""
- name: 📥 Fetch the base commit
run: |
git fetch --depth=1 origin "$BASE_REF"
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
run: git fetch --depth=1 origin "$BASE_SHA"
- name: 🔬 Check migrations against the base commit
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
Generated
+161 -12
View File
@@ -590,7 +590,6 @@ dependencies = [
"node-macro",
"raster-kernels",
"serde",
"text-nodes",
"vector-types",
]
@@ -1227,6 +1226,7 @@ dependencies = [
"kurbo",
"log",
"lyon_geom",
"math-parser",
"node-macro",
"num-derive",
"num-traits",
@@ -1239,7 +1239,7 @@ dependencies = [
"rustc-hash 2.1.3",
"serde",
"serde_json",
"skrifa",
"skrifa 0.44.0",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -2136,6 +2136,9 @@ name = "float-cmp"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
dependencies = [
"num-traits",
]
[[package]]
name = "fnv"
@@ -2155,6 +2158,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "font-types"
version = "0.12.7"
@@ -2196,7 +2208,7 @@ dependencies = [
"linebender_resource_handle",
"memmap2",
"parlance",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -3040,7 +3052,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
"smallvec",
]
@@ -3075,6 +3087,40 @@ dependencies = [
"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]]
name = "heck"
version = "0.5.0"
@@ -3428,6 +3474,12 @@ dependencies = [
"quick-error",
]
[[package]]
name = "imagesize"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
[[package]]
name = "imagesize"
version = "0.15.0"
@@ -3800,6 +3852,33 @@ dependencies = [
"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]]
name = "kurbo"
version = "0.13.1"
@@ -5033,7 +5112,7 @@ dependencies = [
"parlance",
"parley_data",
"parley_emoji",
"skrifa",
"skrifa 0.44.0",
]
[[package]]
@@ -5064,6 +5143,18 @@ dependencies = [
"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]]
name = "peer-transport"
version = "0.0.0"
@@ -5746,7 +5837,6 @@ dependencies = [
"glam",
"graphene-resource",
"graphic-types",
"half",
"log",
"raster-types",
"thiserror 2.0.21",
@@ -5867,6 +5957,16 @@ dependencies = [
"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]]
name = "read-fonts"
version = "0.41.0"
@@ -5874,7 +5974,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types",
"font-types 0.12.7",
"once_cell",
]
@@ -6020,13 +6120,15 @@ dependencies = [
"graphene-hash",
"graphene-resource",
"graphic-types",
"hayro-syntax",
"krilla",
"kurbo",
"log",
"num-traits",
"parley",
"raster-kernels",
"serde",
"skrifa",
"skrifa 0.44.0",
"text-nodes",
"usvg",
"vector-types",
@@ -6604,6 +6706,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "same-file"
version = "1.0.6"
@@ -6965,6 +7073,16 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "skrifa"
version = "0.44.0"
@@ -6972,7 +7090,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts",
"read-fonts 0.41.0",
]
[[package]]
@@ -7151,6 +7269,18 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
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]]
name = "substring"
version = "1.4.5"
@@ -7333,7 +7463,7 @@ dependencies = [
"rand",
"serde",
"serde_json",
"skrifa",
"skrifa 0.44.0",
"thiserror 2.0.21",
"titlecase",
"tsify",
@@ -7933,14 +8063,14 @@ dependencies = [
"flate2",
"fontdb",
"harfrust",
"imagesize",
"imagesize 0.15.0",
"kurbo",
"log",
"pico-args",
"roxmltree 0.21.2",
"simplecss",
"siphasher",
"skrifa",
"skrifa 0.44.0",
"strict-num",
"svgtypes",
"tiny-skia-path",
@@ -9283,6 +9413,19 @@ dependencies = [
"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]]
name = "writeable"
version = "0.6.4"
@@ -9423,6 +9566,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
[[package]]
name = "xmp-writer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
[[package]]
name = "yansi"
version = "1.0.1"
+2
View File
@@ -223,6 +223,8 @@ skrifa = "0.44"
polycool = "0.4"
color = "0.3"
# 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_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [
@@ -57,6 +57,10 @@ pub mod network {
pub const IMPORT_METADATA: &str = "ui::import_metadata";
pub const EXPORT_NAMES: &str = "ui::export_names";
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 {
@@ -473,6 +473,12 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
.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(())
}
@@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry {
pub import_metadata: Vec<InputMetadataEntry>,
pub export_names: 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
@@ -78,6 +80,11 @@ pub trait NodeMetadataSource {
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> {
Vec::new()
}
@@ -12,9 +12,25 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
/// Note: This only works for complete networks with all inputs resolved.
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
use graph_craft::document::value::TaggedValue;
let mut network = network.clone();
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 {};
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
+1
View File
@@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES),
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
}
}
@@ -1,53 +0,0 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV2, &contract());
check_undo(&BevelAndEmbossV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV2);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -1,49 +1,50 @@
use migration_core::{Inputs, NodeInput, encode, migration};
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
TypeDefault(Type),
}
/// Frozen mirror of the `Type` an empty list of graphics stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
List(Box<Type>),
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypeDescriptor {
name: String,
struct TypedLength {
value: f64,
unit: LengthUnit,
}
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
#[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("blending_nodes::effects::BlurNode"@2 => @3)]
pub fn blur_v2(inputs: &mut Inputs) {
inputs.insert(2, empty_radius_mask());
}
pub fn blur_v2(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 };
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
fn empty_radius_mask() -> NodeInput {
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
name: "graphic_types::graphic::Graphic".to_string(),
}))));
NodeInput::Value {
value: encode(&no_graphics),
exposed: false,
}
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
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))
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
@@ -53,17 +54,13 @@ mod tests {
}
#[test]
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&BlurV2);
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
let number = |number: f64| literal(Tagged::Number(number));
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 mut expected = inputs;
expected.insert(2, empty_radius_mask());
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
assert_eq!(fixture.inputs(&migrated, blur), expected);
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
let radius = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, blur), [literal(Tagged::None), radius, number(0.), number(0.)]);
}
}
@@ -1,43 +0,0 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ConvolutionKernelV1, &contract());
check_undo(&ConvolutionKernelV1, &contract());
}
#[test]
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&ConvolutionKernelV1);
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
}
}
@@ -1,9 +1,7 @@
//! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1;
mod bevel_and_emboss_v2;
mod blur_v2;
mod convolution_kernel_v1;
mod drop_shadow_v1;
mod inner_glow_v1;
mod inner_shadow_v1;
@@ -11,8 +9,6 @@ mod mask_by_any_graphic;
mod outer_glow_v1;
mod outline_v1;
mod outline_v2;
mod outline_v3;
mod paint_overlay_from_color_overlay;
mod paint_overlay_v2;
mod renames;
mod satin_v1;
@@ -1,53 +0,0 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Outline' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
pub fn outline_v3(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV3, &contract());
check_undo(&OutlineV3, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV3);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
let migrated = fixture.migrate(&OutlineV3).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -1,53 +0,0 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
pub fn paint_overlay_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PaintOverlayV2, &contract());
check_undo(&PaintOverlayV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&PaintOverlayV2);
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
assert_eq!(fixture.inputs(&migrated, overlay), expected);
}
}
@@ -0,0 +1,66 @@
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.)]);
}
}
@@ -0,0 +1,3 @@
//! Migrations of the nodes in `brush_nodes`.
mod brush_strokes_v1;
@@ -0,0 +1,66 @@
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]);
}
}
@@ -0,0 +1,66 @@
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]);
}
}
@@ -0,0 +1,71 @@
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)]);
}
}
@@ -0,0 +1,66 @@
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.)]);
}
}
@@ -0,0 +1,14 @@
//! 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;
@@ -0,0 +1,66 @@
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.)]);
}
}
@@ -0,0 +1,66 @@
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]);
}
}
@@ -0,0 +1,68 @@
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.])]);
}
}
@@ -0,0 +1,96 @@
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.)]);
}
}
@@ -0,0 +1,80 @@
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.)]
);
}
}
@@ -0,0 +1,66 @@
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.)]);
}
}
@@ -0,0 +1,66 @@
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]);
}
}
@@ -0,0 +1,66 @@
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,5 +1,7 @@
//! Migrations of the nodes in `graphene_core`.
mod pack_strips_v1;
mod passthrough_from_upload_texture_node;
mod renames;
mod stroke_v1;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,73 @@
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.)]);
}
}
@@ -0,0 +1,79 @@
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,3 +1,4 @@
//! Migrations of the nodes in `graphene_std`.
mod renames;
mod text_v1;
@@ -0,0 +1,130 @@
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.)
]
);
}
}
@@ -0,0 +1,74 @@
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()]);
}
}
@@ -0,0 +1,96 @@
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.)]);
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `graphic_nodes`.
mod create_artboard_v1;
mod mirror_v1;
+5
View File
@@ -2,8 +2,13 @@
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod blending_nodes;
mod brush_nodes;
mod core_types;
mod graphene_core;
mod graphene_std;
mod graphic_nodes;
mod math_nodes;
mod raster_nodes;
mod repeat_nodes;
mod transform_nodes;
mod vector_nodes;
@@ -0,0 +1,47 @@
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);
}
}
@@ -0,0 +1,47 @@
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,4 +1,6 @@
//! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f;
mod math_formula_v2;
mod math_function_v2;
mod renames;
@@ -3,3 +3,21 @@
use migration_core::rename;
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,66 @@
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]);
}
}
@@ -2,6 +2,7 @@
mod mandelbrot_v1;
mod mandelbrot_v2;
mod median_filter_v1;
mod mix_colors_from_mix_node;
mod noise_pattern_v1;
mod pattern_square;
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `repeat_nodes`.
mod repeat_array_v1;
mod repeat_radial_v1;
@@ -0,0 +1,98 @@
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.)]);
}
}
@@ -0,0 +1,96 @@
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.)]);
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `transform_nodes`.
mod transform_v1;
mod vary_rotations_v2;
@@ -0,0 +1,125 @@
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.])]
);
}
}
@@ -0,0 +1,79 @@
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.)]
);
}
}
@@ -0,0 +1,99 @@
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.)]);
}
}
@@ -0,0 +1,100 @@
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.)]);
}
}
@@ -0,0 +1,65 @@
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]);
}
}
@@ -0,0 +1,73 @@
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.)]);
}
}
@@ -0,0 +1,111 @@
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.])]
);
}
}
@@ -0,0 +1,72 @@
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]
);
}
}
@@ -0,0 +1,68 @@
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,4 +1,16 @@
//! 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 qr_code_v1;
mod rectangle_v1;
mod regular_polygon_v1;
mod renames;
mod spiral_v1;
mod star_v1;
@@ -0,0 +1,69 @@
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()]);
}
}
@@ -0,0 +1,79 @@
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.)]
);
}
}
@@ -0,0 +1,66 @@
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]);
}
}
@@ -0,0 +1,105 @@
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.)]
);
}
}
@@ -0,0 +1,73 @@
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.)]);
}
}
@@ -6,6 +6,8 @@ use crate::messages::prelude::*;
pub enum DialogMessage {
// Sub-messages
#[child]
DocumentSetupDialog(DocumentSetupDialogMessage),
#[child]
ExportDialog(ExportDialogMessage),
#[child]
NewDocumentDialog(NewDocumentDialogMessage),
@@ -34,6 +36,7 @@ pub enum DialogMessage {
localized_commit_year: String,
},
RequestDemoArtworkDialog,
RequestDocumentSetupDialog,
RequestExportDialog,
RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: String,
@@ -4,6 +4,7 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
use crate::messages::frontend::utility_types::ExportBounds;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
#[derive(ExtractField)]
pub struct DialogMessageContext<'a> {
@@ -16,6 +17,7 @@ pub struct DialogMessageContext<'a> {
pub struct DialogMessageHandler {
on_dismiss: Option<Message>,
redisplay: Option<Message>,
document_setup_dialog: DocumentSetupDialogMessageHandler,
export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler,
@@ -27,6 +29,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let DialogMessageContext { portfolio, preferences } = context;
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::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
@@ -100,30 +103,25 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let dialog = DemoArtworkDialog;
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 => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
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;
self.export_dialog.artboards = document.artboard_names();
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
&& !self.export_dialog.artboards.contains_key(&layer)
&& !self.export_dialog.artboards.iter().any(|(artboard, _)| *artboard == layer)
{
self.export_dialog.bounds = ExportBounds::AllArtwork;
self.export_dialog.bounds = self.export_dialog.default_bounds();
self.export_dialog.bounds_chosen = false;
}
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
@@ -145,7 +143,9 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
self.new_document_dialog = NewDocumentDialogMessageHandler {
name: portfolio.generate_new_document_name(None),
infinite: false,
dimensions: glam::UVec2::new(1920, 1080),
width: TypedLength::pixels(1920.),
height: TypedLength::pixels(1080.),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
};
self.new_document_dialog.send_dialog_to_frontend(responses);
}
@@ -0,0 +1,9 @@
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,
}
@@ -0,0 +1,158 @@
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");
}
}
@@ -0,0 +1,7 @@
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,7 +14,10 @@ pub struct ExportDialogMessageHandler {
pub file_type: FileType,
pub scale_factor: f64,
pub bounds: ExportBounds,
pub artboards: HashMap<LayerNodeIdentifier, String>,
/// 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 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,
}
@@ -24,6 +27,7 @@ impl Default for ExportDialogMessageHandler {
file_type: Default::default(),
scale_factor: 1.,
bounds: Default::default(),
bounds_chosen: false,
artboards: Default::default(),
has_selection: false,
}
@@ -36,20 +40,23 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
let ExportDialogMessageContext { portfolio } = context;
match message {
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
ExportDialogMessage::FileType { file_type } => {
self.file_type = file_type;
if !self.bounds_chosen {
self.bounds = self.default_bounds();
}
}
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
ExportDialogMessage::ExportBounds { bounds } => {
self.bounds = bounds;
self.bounds_chosen = true;
}
ExportDialogMessage::Submit => {
// 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 bounds = self.current_bounds();
let artboard_name = match bounds {
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
ExportBounds::Artboard(layer) => self.artboards.iter().find(|(artboard, _)| *artboard == layer).map(|(_, name)| name.clone()),
_ => None,
};
responses.add_front(PortfolioMessage::SubmitDocumentExport {
@@ -70,6 +77,23 @@ 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 {
const ICON: &'static str = "File";
const TITLE: &'static str = "Export";
@@ -94,9 +118,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
impl LayoutHolder for ExportDialogMessageHandler {
fn layout(&self) -> Layout {
// The vector type, then the raster ones
// The vector types, then the raster ones
let file_types = [
vec![(FileType::Svg, "SVG")],
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
vec![
(FileType::Png, "PNG"),
(FileType::Jpg, "JPG"),
@@ -139,7 +163,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.increment_step(0.5)
.disabled(self.file_type == FileType::Svg)
.disabled(matches!(self.file_type, FileType::Svg | FileType::Pdf))
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
.sizing(WidgetSizing::default().min_width(200))
.widget_instance(),
@@ -149,15 +173,12 @@ impl LayoutHolder for ExportDialogMessageHandler {
(ExportBounds::AllArtwork, "All Artwork".to_string(), false),
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
];
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
let choices = [standard_bounds, artboards];
// Only a PDF can hold every artboard, each as its own page
let all_artboards = (!self.artboards.is_empty()).then(|| (ExportBounds::AllArtboards, "All Artboards".to_string(), self.file_type != FileType::Pdf));
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()];
// 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 current_bounds = self.current_bounds();
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0);
let mut entries = choices
@@ -188,3 +209,44 @@ impl LayoutHolder for ExportDialogMessageHandler {
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,6 +8,7 @@
mod dialog_message;
mod dialog_message_handler;
pub mod document_setup_dialog;
pub mod export_dialog;
pub mod new_document_dialog;
pub mod preferences_dialog;
@@ -1,12 +1,14 @@
use crate::messages::prelude::*;
use graphene_std::units::TypedLength;
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum NewDocumentDialogMessage {
Name { name: String },
Infinite { infinite: bool },
DimensionsX { width: f64 },
DimensionsY { height: f64 },
DimensionsX { width: TypedLength },
DimensionsY { height: TypedLength },
Resolution { pixels_per_inch: f64 },
Submit,
}
@@ -1,16 +1,34 @@
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::portfolio::document::node_graph::node_inspector::length_decimal_places;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::UVec2;
use glam::DVec2;
use graph_craft::document::NodeId;
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.
#[derive(Debug, Clone, Default, ExtractField)]
#[derive(Debug, Clone, ExtractField)]
pub struct NewDocumentDialogMessageHandler {
pub name: String,
pub infinite: bool,
pub dimensions: UVec2,
pub width: TypedLength,
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]
@@ -19,24 +37,38 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
match message {
NewDocumentDialogMessage::Name { name } => self.name = name,
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
NewDocumentDialogMessage::DimensionsX { width } => {
self.width = whole_pixels(width);
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 => {
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 {
// Infinite canvas: add a locked white background layer
graph_modification_utils::new_background_layer(0, responses);
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
} else if pixels.x > 0. && pixels.y > 0. {
// Finite canvas: create an artboard with the specified dimensions
responses.add(GraphOperationMessage::NewArtboard {
id: NodeId::new(),
location: glam::DVec2::ZERO,
dimensions: self.dimensions.as_dvec2(),
location: DVec2::ZERO,
dimensions,
background: Color::WHITE,
clip: true,
});
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
responses.add(NavigationMessage::CanvasPan { delta: pixels });
}
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -107,32 +139,191 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
.widget_instance(),
];
let scale = vec![
// Each dimension shows the unit it was typed in and keeps any length unit typed into it
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(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.dimensions.x as f64))
.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())
dimension_field(self.width, "W")
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into())
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(self.dimensions.y as f64))
.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())
dimension_field(self.height, "H")
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into())
.widget_instance(),
];
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
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(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);
}
}
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -196,6 +196,10 @@ pub enum FrontendMessage {
#[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>,
},
UpdateClickTargets {
#[serde(rename = "clickTargets")]
click_targets: Option<FrontendClickTargets>,
},
UpdateGraphViewOverlay {
open: bool,
},
@@ -78,6 +78,7 @@ pub enum FileType {
Tga,
Ico,
Svg,
Pdf,
}
impl FileType {
@@ -91,6 +92,7 @@ impl FileType {
FileType::Tga => "tga",
FileType::Ico => "ico",
FileType::Svg => "svg",
FileType::Pdf => "pdf",
}
}
@@ -104,6 +106,7 @@ impl FileType {
FileType::Tga => "TGA Image",
FileType::Ico => "ICO Image",
FileType::Svg => "SVG Image",
FileType::Pdf => "PDF Document",
};
FileFilter {
name: name.into(),
@@ -130,6 +133,7 @@ impl FileType {
FileType::Tga => ImageFormat::Tga,
FileType::Ico => ImageFormat::Ico,
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) {
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());
@@ -164,6 +168,8 @@ pub enum ExportBounds {
#[default]
AllArtwork,
Selection,
/// Each artboard as its own page, for a file type that holds pages.
AllArtboards,
Artboard(LayerNodeIdentifier),
}
@@ -228,6 +234,7 @@ mod tests {
#[test]
fn file_types_that_cannot_hold_the_image_say_so() {
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());
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
@@ -87,7 +87,9 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
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!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
@@ -417,16 +417,20 @@ impl LayoutMessageHandler {
}
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
Value::String(expression) => {
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else {
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.
if number_input.value == Some(evaluated) {
if number_input.value == Some(evaluated) && number_input.unit == unit {
return;
}
// 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)(&()));
number_input.value = Some(evaluated);
number_input.unit = unit;
responses.add((number_input.on_update.callback)(number_input));
}
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
@@ -704,21 +708,41 @@ fn populate_computed_display_fields(layout: &mut Layout) {
}
}
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
let value = math_parser::evaluate(expression)
/// 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 `%`.
pub fn unit_suffix(symbol: &str) -> String {
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() }
}
/// 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}"))
.ok()?
.eval(&context)
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?;
let real = value.as_real()?;
if real.is_nan() {
// 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 field_unit = math_parser::units::Unit::named(number_input.unit.trim());
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;
}
let mut validated = real;
let mut validated = in_field_unit;
if let Some(min) = number_input.min {
validated = validated.max(min);
}
@@ -729,5 +753,17 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
validated = validated.round();
}
Some(validated)
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it
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,6 +247,14 @@ pub struct NumberInput {
#[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))]
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
#[serde(rename = "tooltipLabel")]
@@ -607,6 +615,7 @@ pub enum MathExpressionRole {
Function,
Keyword,
Operator,
Unit,
Bracket,
MatrixLiteral,
Error,
@@ -623,6 +632,7 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
Role::Function => Self::Function,
Role::Keyword => Self::Keyword,
Role::Operator => Self::Operator,
Role::Unit => Self::Unit,
Role::Bracket => Self::Bracket,
Role::MatrixLiteral => Self::MatrixLiteral,
Role::Error => Self::Error,
@@ -181,6 +181,13 @@ impl LayoutHolder for MenuBarMessageHandler {
.on_commit(|_| DialogMessage::RequestExportDialog.into())
.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"))]
vec![preferences],
])
@@ -1,153 +0,0 @@
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
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");
}
#[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
let stack = clipped_stack(base, effect.clone()).await;
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
// Flattened into one list of vectors, the base clips its sibling by the same rule
if let Base::VectorLayer = base {
let flattened: List<Vector> = stack.into_flattened_list();
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
}
}
}
}
@@ -7,7 +7,6 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use crate::node_graph_executor::InspectedContext;
use glam::{Affine2, DAffine2, Vec2};
use graph_craft::document::NodeId;
use graphene_std::RadialBlurMethod;
use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
@@ -26,6 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::Footprint;
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::units::{Angle, AngleVec2, Length, LengthVec2};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
@@ -36,7 +36,7 @@ use graphene_std::vector::style::{
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
MaskMode, MinimumMaximumMode, NoiseDistribution,
MaskMode,
};
use kurbo::BezPath;
use std::any::Any;
@@ -402,6 +402,10 @@ macro_rules! inspectable_types {
List<Generator>,
List<String>,
List<f64>,
List<Length>,
List<Angle>,
List<LengthVec2>,
List<AngleVec2>,
List<i64>,
List<bool>,
List<DVec2>,
@@ -462,6 +466,10 @@ macro_rules! inspectable_types {
Item<Generator>,
Item<String>,
Item<f64>,
Item<Length>,
Item<Angle>,
Item<LengthVec2>,
Item<AngleVec2>,
Item<i64>,
Item<bool>,
Item<DVec2>,
@@ -1101,6 +1109,55 @@ impl TableItemLayout for f64 {
}
}
impl TableItemLayout for Length {
fn type_name() -> &'static str {
"Length"
}
fn identifier(&self) -> String {
format!("{} px", format_f64(round_away_float_noise(self.pixels())))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for Angle {
fn type_name() -> &'static str {
"Angle"
}
fn identifier(&self) -> String {
format!("{}°", format_f64(round_away_float_noise(self.degrees())))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for LengthVec2 {
fn type_name() -> &'static str {
"Length Vec2"
}
fn identifier(&self) -> String {
format_dvec2(self.pixels())
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for AngleVec2 {
fn type_name() -> &'static str {
"Angle Vec2"
}
fn identifier(&self) -> String {
let degrees = self.degrees();
format!("({}°, {}°)", format_rounded(degrees.x, 3), format_rounded(degrees.y, 3))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for u8 {
fn type_name() -> &'static str {
"Byte"
@@ -1272,19 +1329,16 @@ impl_table_item_layout_for_choice_enum!(
BevelDirection,
BevelTechnique,
BevelStyle,
RadialBlurMethod,
EffectKind,
Generator,
GlowSource,
MaskMode,
MinimumMaximumMode,
GradientForm,
GradientSpread,
GradientSpace,
GradientHueDirection,
GradientInterpolation,
GlowTechnique,
NoiseDistribution,
StrokeJoin,
StrokeAlign,
StrokeCap,
@@ -1460,11 +1514,9 @@ macro_rules! known_item_types {
EffectKind,
GlowSource,
MaskMode,
MinimumMaximumMode,
BevelStyle,
BevelDirection,
BevelTechnique,
RadialBlurMethod,
DashPattern,
BoxCorners,
TransferCurve,
@@ -1475,7 +1527,6 @@ macro_rules! known_item_types {
GradientHueDirection,
GradientInterpolation,
GlowTechnique,
NoiseDistribution,
StrokeJoin,
StrokeAlign,
StrokeCap,
@@ -266,6 +266,11 @@ pub enum DocumentMessage {
SetRenderMode {
render_mode: RenderMode,
},
/// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports.
/// The caller wraps it in a transaction to make it one undo step.
SetPixelsPerInch {
pixels_per_inch: f64,
},
ShowNodeInGraph {
node_id: NodeId,
},
@@ -53,6 +53,7 @@ use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::{GradientStops, RenderMode};
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
@@ -304,15 +305,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let visibility_settings = self.overlays_visibility_settings;
// Send the overlays message to the overlays message handler
self.overlays_message_handler.process_message(
message,
responses,
OverlaysMessageContext {
visibility_settings,
viewport,
graph_open: self.graph_view_overlay_open,
},
);
self.overlays_message_handler
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
}
DocumentMessage::Inspector(message) => {
let context = InspectorMessageContext {
@@ -1701,6 +1695,16 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.render_mode = render_mode;
responses.add_front(NodeGraphMessage::RunDocumentGraph);
}
DocumentMessage::SetPixelsPerInch { pixels_per_inch } => {
if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() {
return;
}
self.network_interface.set_pixels_per_inch(pixels_per_inch);
// Lengths typed in a physical unit change their size in pixels, so the graph runs again
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(InspectorMessage::Refresh);
}
DocumentMessage::ShowNodeInGraph { node_id } => {
// The node is in the document network, so the graph first leaves any nested network it's showing
if !self.breadcrumb_network_path.is_empty() {
@@ -2452,6 +2456,23 @@ impl DocumentMessageHandler {
self.network_interface.document_metadata()
}
/// Each artboard with its name, from the top of the Layers panel down.
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
self.metadata()
.all_layers()
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
.map(|layer| {
let name = self
.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()
}
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
&self.breadcrumb_network_path
}
@@ -2687,6 +2708,7 @@ impl DocumentMessageHandler {
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
for path in self.network_interface.paths_reaching(&reconciled.networks) {
self.network_interface.unload_import_export_ports(&path);
self.network_interface.unload_all_nodes_bounding_box(&path);
self.network_interface.unload_outward_wires(&path);
}
self.network_interface.load_structure();
@@ -3236,7 +3258,10 @@ impl DocumentMessageHandler {
}
pub fn current_hash(&self) -> u64 {
self.network_interface.document_network().current_hash()
// The resolution lives in the network's metadata rather than the network, but changing it changes the document
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher);
hasher.finish()
}
pub fn is_auto_saved(&self) -> bool {
@@ -5291,7 +5316,7 @@ mod document_message_handler_tests {
.handle_message(GraphOperationMessage::NewArtboard {
id: NodeId::new(),
location: DVec2::ZERO,
dimensions: DVec2::splat(200.),
dimensions: graphene_std::units::TypedLengthVec2::pixels(DVec2::splat(200.)),
background: Color::WHITE,
clip: true,
})
@@ -7,6 +7,7 @@ use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::units::TypedLengthVec2;
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, VectorModificationType};
use std::sync::Arc;
@@ -136,7 +137,7 @@ pub enum GraphOperationMessage {
NewArtboard {
id: NodeId,
location: DVec2,
dimensions: DVec2,
dimensions: TypedLengthVec2,
background: Color,
clip: bool,
},
@@ -14,6 +14,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graph_craft::list;
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::units::TypedLength;
use graphene_std::vector::style::{Gradient, GradientForm, GradientSettings, GradientSpace, GradientSpread, GradientStop, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::{Artboard, Color};
@@ -807,6 +808,9 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
// Set positions for all imported descendants in a single O(n) pass
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
// Invalidate caches once after all positions are set
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
}
usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
@@ -883,7 +887,7 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
let strokes_node = strokes_node_type.node_template_input_override([
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
Some(NodeInput::value(TaggedValue::Color(color), false)),
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(diameter)), false)),
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
Some(NodeInput::value(TaggedValue::Number(flow), false)),
]);
@@ -4,34 +4,40 @@ use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::transform::Transform;
/// Update the inputs of the transform node to match a new transform
/// Update the inputs of the transform node to match a new transform, keeping each in the unit it was typed in.
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
use graphene_std::transform_nodes::transform::*;
let (rotation, scale, skew) = transform.decompose_rotation_scale_skew();
let translation = transform.translation;
let rotation = rotation.to_degrees();
let skew = DVec2::new(skew.atan().to_degrees(), 0.);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::TranslationInput),
NodeInput::value(TaggedValue::DVec2(translation), false),
&[],
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
NodeInput::value(TaggedValue::Number(rotation), false),
&[],
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::ScaleInput),
NodeInput::value(TaggedValue::DVec2(scale), false),
&[],
);
network_interface.set_input(
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::SkewInput),
NodeInput::value(TaggedValue::DVec2(skew), false),
&[],
);
let pixels_per_inch = network_interface.pixels_per_inch();
let [translation_input, rotation_input, scale_input, skew_input] = [
InputConnector::node(*node_id, TranslationInput),
InputConnector::node(*node_id, RotationInput),
InputConnector::node(*node_id, ScaleInput),
InputConnector::node(*node_id, SkewInput),
];
let existing = |input: &InputConnector| network_interface.input_from_connector(input, &[]).and_then(NodeInput::as_value).cloned().unwrap_or(TaggedValue::None);
let (existing_translation, existing_rotation, existing_skew) = (existing(&translation_input), existing(&rotation_input), existing(&skew_input));
// An input already holding the value is left as typed, so rotating a layer doesn't rewrite a translation typed in millimeters with float noise
let unchanged = |existing: Option<DVec2>, value: DVec2| existing.is_some_and(|existing| existing.abs_diff_eq(value, 1e-9));
if !unchanged(existing_translation.as_length_vec2_pixels(pixels_per_inch), translation) {
let translation = existing_translation.length_vec2_in_same_unit(translation, pixels_per_inch);
network_interface.set_input(&translation_input, NodeInput::value(translation, false), &[]);
}
if !unchanged(existing_rotation.as_angle_degrees().map(DVec2::splat), DVec2::splat(rotation)) {
network_interface.set_input(&rotation_input, NodeInput::value(existing_rotation.angle_in_same_unit(rotation), false), &[]);
}
network_interface.set_input(&scale_input, NodeInput::value(TaggedValue::DVec2(scale), false), &[]);
if !unchanged(existing_skew.as_angle_vec2_degrees(), skew) {
network_interface.set_input(&skew_input, NodeInput::value(existing_skew.angle_vec2_in_same_unit(skew), false), &[]);
}
}
// TODO: This should be extracted from the graph at the location of the transform node.
@@ -63,16 +69,14 @@ impl LayerBounds {
}
}
/// Get the current affine transform from the transform node's inputs
pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
let translation = if let Some(&TaggedValue::DVec2(translation)) = inputs[1].as_value() {
translation
} else {
DVec2::ZERO
};
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
/// Get the current affine transform from the transform node's inputs, sizing a translation in a physical unit by the document's resolution.
pub fn get_current_transform(inputs: &[NodeInput], pixels_per_inch: f64) -> DAffine2 {
let value = |index: usize| inputs.get(index).and_then(NodeInput::as_value);
let translation = value(1).and_then(|value| value.as_length_vec2_pixels(pixels_per_inch)).unwrap_or(DVec2::ZERO);
let rotation = value(2).and_then(TaggedValue::as_angle_degrees).unwrap_or(0.);
let scale = if let Some(&TaggedValue::DVec2(scale)) = value(3) { scale } else { DVec2::ONE };
let skew = value(4).and_then(TaggedValue::as_angle_vec2_degrees).unwrap_or(DVec2::ZERO);
let rotation = rotation.to_radians();
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
@@ -15,6 +15,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, list};
use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::units::{TypedAngle, TypedLength, TypedLengthVec2};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic};
@@ -68,12 +69,12 @@ impl<'a> ModifyInputsContext<'a> {
}
/// Creates an artboard as the primary export for the document network.
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: TypedLengthVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
let artboard_node_template = resolve_network_node_type("Artboard").expect("Node").node_template_input_override([
Some(NodeInput::type_default(list!(Artboard), true)),
Some(NodeInput::type_default(list!(Graphic), true)),
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
Some(NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(location)), false)),
Some(NodeInput::value(TaggedValue::LengthVec2(dimensions), false)),
Some(NodeInput::value(TaggedValue::Color(background), false)),
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
]);
@@ -196,14 +197,14 @@ impl<'a> ModifyInputsContext<'a> {
Some(NodeInput::value(TaggedValue::None, false)),
Some(NodeInput::value(TaggedValue::String(text), false)),
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.font_size)), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.letter_spacing)), false)),
Some(NodeInput::value(TaggedValue::Angle(TypedAngle::degrees(typesetting.letter_tilt)), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_width.unwrap_or(100.))), false)),
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_height.unwrap_or(100.))), false)),
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
]);
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
@@ -729,13 +730,14 @@ impl<'a> ModifyInputsContext<'a> {
};
// `composed_old` = T_n * T_{n-1} * ... * T_1, `prior_combined` = same product without T_n
let pixels_per_inch = self.network_interface.pixels_per_inch();
let compose = |ids: &[_]| {
ids.iter().fold(DAffine2::IDENTITY, |acc, transform_id| {
self.network_interface
.document_network()
.nodes
.get(transform_id)
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs))
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs, pixels_per_inch))
})
};
let prior_combined = compose(prior_transforms);
@@ -871,7 +873,7 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Length(TypedLength::pixels(stroke.weight)), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
@@ -883,7 +885,7 @@ impl<'a> ModifyInputsContext<'a> {
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Length(TypedLength::pixels(stroke.dash_offset)), false), true);
}
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
@@ -894,7 +896,10 @@ impl<'a> ModifyInputsContext<'a> {
.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false)
.and_then(|transform_node_id| {
let document_node = self.network_interface.document_network().nodes.get(&transform_node_id)?;
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
Some((
transform_utils::get_current_transform(&document_node.inputs, self.network_interface.pixels_per_inch()),
transform_node_id,
))
})
.unzip();
let layer_transform = layer_transform.unwrap_or_default();
@@ -932,7 +937,7 @@ impl<'a> ModifyInputsContext<'a> {
let local_transform = metadata.local_transforms.get(&layer.to_node()).copied().unwrap_or(DAffine2::IDENTITY);
let current_transform_node_value = transform_node_id
.and_then(|id| self.network_interface.document_network().nodes.get(&id))
.map(|node| transform_utils::get_current_transform(&node.inputs))
.map(|node| transform_utils::get_current_transform(&node.inputs, self.network_interface.pixels_per_inch()))
.unwrap_or(DAffine2::IDENTITY);
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
} else {
@@ -1020,16 +1025,37 @@ impl<'a> ModifyInputsContext<'a> {
dimensions.y = -dimensions.y;
location.y -= dimensions.y;
}
self.set_input_with_refresh(
InputConnector::node_at_index(artboard_node_id, ARTBOARD_LOCATION_INPUT_INDEX),
NodeInput::value(TaggedValue::DVec2(location), false),
false,
);
self.set_input_with_refresh(
InputConnector::node_at_index(artboard_node_id, ARTBOARD_DIMENSIONS_INPUT_INDEX),
NodeInput::value(TaggedValue::DVec2(dimensions), false),
false,
);
// Each stays in the unit it was typed in, and a component that already rounds to the requested whole pixels stays as typed, so moving an artboard sized in millimeters keeps them
let pixels_per_inch = self.network_interface.pixels_per_inch();
for (index, pixels) in [(ARTBOARD_LOCATION_INPUT_INDEX, location), (ARTBOARD_DIMENSIONS_INPUT_INDEX, dimensions)] {
let input_connector = InputConnector::node_at_index(artboard_node_id, index);
let existing = self
.network_interface
.input_from_connector(&input_connector, &[])
.and_then(NodeInput::as_value)
.cloned()
.unwrap_or(TaggedValue::None);
let existing_lengths = match existing {
TaggedValue::LengthVec2(lengths) => Some(lengths),
TaggedValue::DVec2(pixels) => Some(TypedLengthVec2::pixels(pixels)),
_ => None,
};
let mut value = existing.length_vec2_in_same_unit(pixels, pixels_per_inch);
if let (Some(existing_lengths), TaggedValue::LengthVec2(lengths)) = (existing_lengths, &mut value) {
let existing_pixels = existing_lengths.to_length_vec2(pixels_per_inch).pixels();
for axis in 0..2 {
if existing_pixels[axis].round() == pixels[axis] {
lengths.value[axis] = existing_lengths.value[axis];
}
}
}
if value != existing {
self.set_input_with_refresh(input_connector, NodeInput::value(value, false), false);
}
}
}
/// Set the input, refresh the Inspector, and run the document graph if skip_rerender is false
@@ -1,6 +1,4 @@
#[cfg(test)]
mod clipping_tests;
#[cfg(test)]
pub(crate) mod document_diff;
mod document_history;
mod document_message;
@@ -17,6 +17,7 @@ use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::{concrete, list};
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
use graphene_std::units::TypedLengthVec2;
use graphene_std::vector::Vector;
use graphene_std::*;
use std::collections::{HashMap, VecDeque};
@@ -139,6 +140,18 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
},
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
@@ -230,8 +243,8 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
inputs: vec![
NodeInput::type_default(list!(Artboard), true),
NodeInput::type_default(list!(Graphic), true),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::ZERO)), false),
NodeInput::value(TaggedValue::LengthVec2(TypedLengthVec2::pixels(DVec2::new(1920., 1080.))), false),
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
NodeInput::value(TaggedValue::Bool(true), false),
],
@@ -689,7 +702,6 @@ fn static_node_inspector() -> NodeInspector {
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
map
}
@@ -698,6 +710,41 @@ type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspect
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
/// A number field set up from the proto node parameter's metadata, which only proto nodes have.
fn proto_parameter_number_input(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> NumberInput {
let mut number_input = NumberInput::default();
// The field is cloned so the lock is released before the caller builds the row, which locks the node metadata again
if let Some(field) = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
{
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
if let Some(hard_min) = field.number_hard_min {
number_input = number_input.min(hard_min);
}
if let Some(hard_max) = field.number_hard_max {
number_input = number_input.max(hard_max);
}
if field.number_mode_range {
number_input = number_input
.mode_range()
.range_min(field.number_soft_min.or(field.number_hard_min))
.range_max(field.number_soft_max.or(field.number_hard_max));
}
number_input = number_input.is_integer(false);
if let Some(number_step) = field.number_step {
number_input = number_input.step(number_step);
}
};
number_input
}
/// Defines the logic for inputs to display a custom Inspector widget.
fn static_input_inspector() -> InputInspector {
let mut map: InputInspector = HashMap::new();
@@ -801,50 +848,21 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
// The custom number input settings are only available on proto nodes
"optional_f64".to_string(),
// A length row gated by the bool input before it. Its field keeps any length unit typed into it and gives its bounds in pixels.
"optional_length".to_string(),
Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default();
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
if let Some(field) = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
{
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
// Typing is clamped only by the hard bounds; the slider extent prefers the soft bounds (see `inspector_row_from_type`)
if let Some(hard_min) = field.number_hard_min {
number_input = number_input.min(hard_min);
}
if let Some(hard_max) = field.number_hard_max {
number_input = number_input.max(hard_max);
}
if field.number_mode_range {
number_input = number_input
.mode_range()
.range_min(field.number_soft_min.or(field.number_hard_min))
.range_max(field.number_soft_max.or(field.number_hard_max));
}
number_input = number_input.is_integer(false);
if let Some(number_step) = field.number_step {
number_input = number_input.step(number_step);
}
};
// NOTE: The bool input MUST be at the input index directly before the f64 input!
Ok(vec![LayoutGroup::row(node_inspector::optional_f64_widget(
let number_input = proto_parameter_number_input(node_id, index, context);
// NOTE: The bool input MUST be at the input index directly before the length input!
Ok(vec![LayoutGroup::row(node_inspector::optional_length_widget(
ParameterWidgetsInfo::at_index(node_id, index, false, context),
index - 1,
number_input,
None,
))])
}),
);
map.insert(
// Like `optional_f64`, but with a 0-100% range slider beside the number input, double-click restoring the full 100%.
// As with `optional_f64`, the bool input must be at the input index directly before the f64 input.
// A number row gated by the bool input before it, with a 0-100% range slider beside the number input, double-click restoring the full 100%.
// The bool input must be at the input index directly before the f64 input.
"optional_percentage".to_string(),
Box::new(|node_id, index, context| {
let number_input = NumberInput::default().mode_increment().unit("%").min(0.).max(100.);
@@ -946,15 +964,15 @@ fn static_input_inspector() -> InputInspector {
.and_then(|value| value.as_bool())
.unwrap_or_default();
Ok(vec![node_inspector::vec2_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
&x,
&y,
&unit,
min,
is_integer,
false,
)])
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
// A pair measured in pixels is a pair of lengths, which keeps any length unit typed into it
if unit.trim() == "px" {
let number_props = NumberInput::default().min(min.unwrap_or(f64::NEG_INFINITY)).is_integer(is_integer);
return Ok(vec![node_inspector::length_vec2_widget(info, &x, &y, number_props)]);
}
Ok(vec![node_inspector::vec2_widget(info, &x, &y, &unit, min, is_integer, false)])
}),
);
map.insert(
@@ -1214,46 +1232,16 @@ fn static_input_inspector() -> InputInspector {
map.insert(
"transform_rotation".to_string(),
Box::new(|node_id, index, context| {
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
let document_node = node_inspector::get_document_node(node_id, context)?;
let Some(input) = document_node.inputs.get(index) else {
return Err("Input not found in transform rotation input override".to_string());
};
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val))
.unit("°")
.mode(NumberInputMode::Range)
.range_min(Some(-180.))
.range_max(Some(180.))
.on_update(node_inspector::update_value_at_index(
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
node_id,
index,
))
.on_commit(node_inspector::commit_value)
.widget_instance(),
]);
}
Ok(vec![LayoutGroup::row(widgets)])
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
let number_props = NumberInput::default().mode(NumberInputMode::Range).range_min(Some(-180.)).range_max(Some(180.));
Ok(vec![LayoutGroup::row(node_inspector::angle_widget(info, number_props))])
}),
);
// Translation uses a Vec2 widget with X/Y labels and a "px" unit suffix
map.insert(
"transform_translation".to_string(),
Box::new(|node_id, index, context| {
Ok(vec![node_inspector::vec2_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
"X",
"Y",
" px",
None,
false,
false,
)])
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::length_vec2_widget(info, "X", "Y", NumberInput::default())])
}),
);
// Scale uses a Vec2 widget with W/H labels and an "x" unit suffix
@@ -1271,48 +1259,11 @@ fn static_input_inspector() -> InputInspector {
)])
}),
);
// Skew has a custom override that maps to degrees
map.insert(
"transform_skew".to_string(),
Box::new(|node_id, index, context| {
let mut widgets = node_inspector::start_widgets(&ParameterWidgetsInfo::at_index(node_id, index, true, context));
let document_node = node_inspector::get_document_node(node_id, context)?;
let Some(input) = document_node.inputs.get(index) else {
return Err("Input not found in transform skew input override".to_string());
};
if let Some(&TaggedValue::DVec2(val)) = input.as_non_exposed_value() {
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(val.x))
.label("X")
.unit("°")
.min(-89.9)
.max(89.9)
.on_update(node_inspector::update_value_at_index(
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), val.y)),
node_id,
index,
))
.on_commit(node_inspector::commit_value)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(val.y))
.label("Y")
.unit("°")
.min(-89.9)
.max(89.9)
.on_update(node_inspector::update_value_at_index(
move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(val.x, input.value.unwrap())),
node_id,
index,
))
.on_commit(node_inspector::commit_value)
.widget_instance(),
]);
}
Ok(vec![LayoutGroup::row(widgets)])
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::angle_vec2_widget(info, "X", "Y", NumberInput::default().min(-89.9).max(89.9))])
}),
);
map.insert(
@@ -1706,9 +1657,9 @@ mod test {
editor.handle_message(NodeGraphMessage::MoveNodeToChainStart { node_id, parent: layer }).await;
}
// Guards the `optional_f64` widget override against holding the node metadata lock while building rows that lock it again
// Guards the `optional_length` widget override against holding the node metadata lock while building rows that lock it again
#[tokio::test]
async fn optional_f64_inspector_row_builds() {
async fn optional_length_inspector_row_builds() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -45,11 +45,6 @@ pub enum NodeGraphMessage {
xy: Option<(i32, i32)>,
add_transaction: bool,
},
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
CreateEmptySubgraph {
node_id: Option<NodeId>,
xy: Option<(i32, i32)>,
},
CreateWire {
output_connector: OutputConnector,
input_connector: InputConnector,
@@ -207,6 +202,8 @@ pub enum NodeGraphMessage {
SelectedNodesSet {
nodes: Vec<NodeId>,
},
SendClickTargets,
EndSendClickTargets,
UnloadWires,
SendWires,
UpdateVisibleNodes,
@@ -386,7 +383,6 @@ impl NodeGraphMessage {
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
Self::AddNodes { .. }
| Self::CreateNodeFromContextMenu { .. }
| Self::CreateEmptySubgraph { .. }
| Self::CreateWire { .. }
| Self::CreateWires { .. }
| Self::ConnectUpstreamOutputToInput { .. }
@@ -446,6 +442,8 @@ impl NodeGraphMessage {
| Self::SelectedNodesAdd { .. }
| Self::SelectedNodesRemove { .. }
| Self::SelectedNodesSet { .. }
| Self::SendClickTargets
| Self::EndSendClickTargets
| Self::UnloadWires
| Self::SendWires
| Self::UpdateVisibleNodes
@@ -5,14 +5,13 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
TransactionStatus,
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
};
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
@@ -24,12 +23,14 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position;
use glam::{DVec2, IVec2};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
use graphene_std::*;
use kurbo::{DEFAULT_ACCURACY, Shape};
use renderer::Quad;
#[derive(Debug, ExtractField)]
pub struct NodeGraphMessageContext<'a> {
@@ -421,23 +422,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
});
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
let node_id = node_id.unwrap_or_else(NodeId::new);
let (x, y) = xy.unwrap_or_else(|| {
network_interface
.node_graph_ptz(breadcrumb_network_path)
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
});
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id,
node_template: Box::new(NodeTemplate::empty_subgraph()),
});
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
log::error!("Failed to find upstream node for downstream_input");
@@ -785,19 +769,24 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
let encapsulating_node_id = NodeId::new();
let mut subgraph_template = NodeTemplate::empty_subgraph();
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
log::error!("Could not get center of selected_nodes");
return;
};
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id: encapsulating_node_id,
node_template: Box::new(subgraph_template),
node_template: Box::new(default_node_template),
});
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: encapsulating_node_id,
network_path: selection_network_path.to_vec(),
alias: "Untitled Node".to_string(),
});
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
@@ -2023,6 +2012,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
selected_nodes.set_selected_nodes(nodes);
responses.add(EventMessage::SelectionChanged);
}
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
}),
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
NodeGraphMessage::UnloadWires => {
self.frontend_wires.clear();
responses.add(FrontendMessage::ClearAllNodeGraphWires);
@@ -2537,13 +2530,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
HashSet::new()
};
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
for node_id in all_nodes {
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
log::error!("Could not get the body of node {node_id}");
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
log::error!("Could not get transient metadata for node {node_id}");
continue;
};
if body.overlaps(selection_min, selection_max) {
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
if alt {
nodes.remove(&node_id);
} else {
@@ -3205,6 +3198,11 @@ impl NodeGraphMessageHandler {
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
// Only development builds draw the click targets, so users don't come across the overlay by accident
if cfg!(debug_assertions) {
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
}
if self.has_selection {
common.extend(actions!(NodeGraphMessageDiscriminant;
Copy,
@@ -3428,13 +3426,6 @@ impl NodeGraphMessageHandler {
})
.disabled(read_only)
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("New Custom Node")
.tooltip_label("New Custom Node")
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
.disabled(read_only)
.widget_instance(),
//
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
//
@@ -2,13 +2,14 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::layout_message_handler::unit_suffix;
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::data_panel::node_reference_button;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, LAYER_SECONDARY_INPUT_INDEX, NodeNetworkInterface, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, LAYER_SECONDARY_INPUT_INDEX, NodeNetworkInterface, OutputConnector, wire_feeds_proto_input};
use crate::messages::portfolio::fonts::utility_types::FontCatalogStyle;
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction, TypeFilter};
use crate::messages::prelude::*;
@@ -20,7 +21,6 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete, item};
use graphene_std::RadialBlurMethod;
use graphene_std::animation::RealTimeMode;
use graphene_std::color::SRGBA8;
use graphene_std::raster::{
@@ -32,6 +32,7 @@ use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::units::{Angle, AngleUnit, AngleVec2, Length, LengthUnit, LengthVec2, TypedAngle, TypedAngleVec2, TypedLength, TypedLengthVec2};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
@@ -41,7 +42,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -279,6 +280,11 @@ impl SliderRange {
}
}
/// Builds a parameter's number field.
type FieldWidget = fn(ParameterWidgetsInfo<'_>, NumberInput) -> Vec<WidgetInstance>;
/// Builds a parameter's range slider beside its number field.
type SliderWidget = fn(ParameterWidgetsInfo<'_>, NumberInput, SliderRange) -> Vec<WidgetInstance>;
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
let identifier = parameter_widgets_info
@@ -288,6 +294,7 @@ pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidget
match input.as_value()? {
TaggedValue::Number(value) => Some(*value),
TaggedValue::Angle(angle) => Some(angle.to_degrees()),
_ => None,
}
}
@@ -306,7 +313,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
step,
} = options;
let mut number_input = NumberInput::default();
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch());
if slider {
number_input = number_input.mode_range();
}
@@ -338,16 +345,17 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
let field_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, field: FieldWidget, slider: SliderWidget| -> LayoutGroup {
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
match (number_input.min, number_input.max) {
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
let default = definition_default_number(&default_info);
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
slider(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
}
_ => number_widget(default_info, number_input).into(),
_ => field(default_info, number_input).into(),
}
};
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| field_or_slider(default_info, number_input, number_widget, range_slider_widget);
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
@@ -388,12 +396,16 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<Angle>(x) => field_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), angle_widget, angle_slider_widget),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
Some(x) if id_is::<LengthVec2>(x) => length_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
Some(x) if id_is::<AngleVec2>(x) => angle_vec2_widget(default_info, "X", "Y", bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
@@ -454,12 +466,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -900,6 +909,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
@@ -916,6 +926,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
.on_commit(commit_value)
.widget_instance(),
@@ -927,6 +938,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -942,6 +954,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
.on_commit(commit_value)
.widget_instance(),
@@ -953,6 +966,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -1205,6 +1219,24 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
/// A number row gated by the bool input at `bool_input_index`, drawn as a checkbox in the assist slot after the label like the
/// Opacity node's toggles, so the caller passes `blank_assist = false`. Given a `slider`, a range slider spanning it sits between them.
pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput, slider: Option<SliderRange>) -> Vec<WidgetInstance> {
optional_number_widget(parameter_widgets_info, bool_input_index, number_props, |parameter_widgets_info, number_props| match slider {
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
None => number_widget(parameter_widgets_info, number_props),
})
}
/// Like [`optional_f64_widget`], for a length parameter. Its field keeps any length unit typed into it.
pub fn optional_length_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_input_index: usize, number_props: NumberInput) -> Vec<WidgetInstance> {
optional_number_widget(parameter_widgets_info, bool_input_index, number_props, length_widget)
}
/// The row of an optional parameter, with its `field` built by the caller.
fn optional_number_widget(
parameter_widgets_info: ParameterWidgetsInfo,
bool_input_index: usize,
number_props: NumberInput,
field: impl FnOnce(ParameterWidgetsInfo, NumberInput) -> Vec<WidgetInstance>,
) -> Vec<WidgetInstance> {
let node_id = parameter_widgets_info.node_id;
let enabled = parameter_widgets_info
.document_node
@@ -1215,10 +1247,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
let exposed = parameter_widgets_info.is_exposed();
let number_props = number_props.disabled(enabled == Some(false));
let mut widgets = match slider {
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
None => number_widget(parameter_widgets_info, number_props),
};
let mut widgets = field(parameter_widgets_info, number_props);
if !exposed {
widgets.splice(label_count..label_count, optional_parameter_assist(enabled, node_id, bool_input_index));
@@ -1315,12 +1344,302 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
.on_commit(commit_value)
.widget_instance(),
]),
// A length or angle left over from rows that took one reads as the number its field showed, pixels or degrees
Some(TaggedValue::Length(_) | TaggedValue::Angle(_)) => {
let number = input
.as_non_exposed_value()
.and_then(|value| value.as_length_pixels(parameter_widgets_info.network_interface.pixels_per_inch()).or_else(|| value.as_angle_degrees()));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(number)
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
.on_commit(commit_value)
.widget_instance(),
]);
}
_ => {}
}
widgets
}
/// Converts a field's bounds from the unit they're given in into the unit its value is shown in.
fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput {
let convert = |bound: Option<f64>| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound });
NumberInput {
min: convert(number_input.min),
max: convert(number_input.max),
range_min: convert(number_input.range_min),
range_max: convert(number_input.range_max),
..number_input
}
}
/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the
/// field's bounds given in pixels.
pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let length = match input.as_non_exposed_value() {
Some(&TaggedValue::Length(length)) => length,
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
// A pair shows its `y`, which the "Grid" node's isometric spacing keeps from its rectangular height
Some(&TaggedValue::LengthVec2(lengths)) => TypedLength {
value: lengths.value.y,
unit: lengths.unit,
},
Some(&TaggedValue::DVec2(pixels)) => TypedLength::pixels(pixels.y),
_ => return widgets,
};
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(length.value))
.unit(unit_suffix(length.unit.symbol()))
.display_decimal_places(length_decimal_places(length.unit, pixels_per_inch))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
TaggedValue::Length(TypedLength {
value: input.value.unwrap_or_default(),
unit,
})
}))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the
/// field's bounds given in degrees.
pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let angle = match input.as_non_exposed_value() {
Some(&TaggedValue::Angle(angle)) => angle,
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
_ => return widgets,
};
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_degrees(degrees));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
angle_field(number_props, angle).on_update(parameter_widgets_info.update_value(typed_angle)).widget_instance(),
]);
widgets
}
/// An angle's range slider beside its number field, which keeps the unit the angle was typed in, with the slider's bounds given in degrees.
pub fn angle_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let angle = match input.as_non_exposed_value() {
Some(&TaggedValue::Angle(angle)) => angle,
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
_ => return widgets,
};
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
let unit = angle.unit;
let slid_to = move |position| {
let value = unit.from_degrees(slider.value(position));
TaggedValue::Angle(TypedAngle { value, unit })
};
let default_position = slider.default.map(|default| slider.position(default));
let number_props = bounds_in_unit(number_props, |degrees| unit.from_degrees(degrees));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
value_slider(node_id, index, GradientStops::default(), Color::WHITE, slider.position(angle.to_degrees()), default_position, slid_to)
.range_slider(true)
.disabled(number_props.disabled)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
// A unit spelled out, like `0.25 turn`, needs more room than a degree sign
angle_field(number_props, angle)
.sizing(WidgetSizing::fixed(if unit == AngleUnit::Degree { 60 } else { 90 }))
.on_update(update_value_at_index(typed_angle, node_id, index))
.widget_instance(),
]);
widgets
}
/// The decimal places a field shows a length in, resolving about a hundredth of a pixel in any unit, so `0.125 in` doesn't display as `0.13 in`.
pub(crate) fn length_decimal_places(unit: LengthUnit, pixels_per_inch: f64) -> u32 {
decimal_places_for_size(unit.convert(1., LengthUnit::Pixel, pixels_per_inch))
}
/// The decimal places a field shows an angle in, resolving about a hundredth of a degree in any unit.
fn angle_decimal_places(unit: AngleUnit) -> u32 {
decimal_places_for_size(unit.to_angle(1.).degrees())
}
/// Two decimal places for a unit the size of the field's base unit (a pixel or a degree), and one more for each power of ten larger it is.
fn decimal_places_for_size(base_units_per_unit: f64) -> u32 {
let extra = base_units_per_unit.log10().ceil();
if extra.is_finite() { (2. + extra.clamp(0., 7.)) as u32 } else { 2 }
}
/// The number field showing an angle in the unit it was typed in, which keeps any angle unit typed into it.
fn angle_field(number_props: NumberInput, angle: TypedAngle) -> NumberInput {
number_props
.value(Some(angle.value))
.unit(unit_suffix(angle.unit.symbol()))
.display_decimal_places(angle_decimal_places(angle.unit))
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.on_commit(commit_value)
}
/// The angle in an angle field, in the unit typed into it.
fn typed_angle(input: &NumberInput) -> TaggedValue {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
TaggedValue::Angle(TypedAngle {
value: input.value.unwrap_or_default(),
unit,
})
}
/// A pair of lengths' X and Y number fields, which share the unit the pair was typed in, with the fields' bounds given in pixels.
/// Typing another length unit into either field moves both into it, converting the other component so its length stays the same.
pub fn length_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, number_props: NumberInput) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return LayoutGroup::row(vec![]);
};
let lengths = match input.as_non_exposed_value() {
Some(&TaggedValue::LengthVec2(lengths)) => lengths,
Some(&TaggedValue::DVec2(pixels)) => TypedLengthVec2::pixels(pixels),
// One length stands for both components, like the "Grid" node's isometric spacing
Some(&TaggedValue::Length(length)) => TypedLengthVec2 {
value: DVec2::splat(length.value),
unit: length.unit,
},
Some(&TaggedValue::Number(pixels)) => TypedLengthVec2::pixels(DVec2::splat(pixels)),
_ => return LayoutGroup::row(widgets),
};
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
// A field limited to integers would convert a typed physical length into its pixels, so whole pixels are enforced only on a pair in pixels
let whole_pixels = number_props.is_integer;
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, lengths.unit, pixels_per_inch));
let field = |component: f64, label: &str| {
number_props
.clone()
.is_integer(false)
.label(label)
.value(Some(component))
.unit(unit_suffix(lengths.unit.symbol()))
.display_decimal_places(length_decimal_places(lengths.unit, pixels_per_inch))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(pixels_per_inch)
.on_commit(commit_value)
};
// The edited component takes the typed unit, and the other converts into it
let typed = move |input: &NumberInput, edited_axis: usize| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
let mut value = DVec2::new(
lengths.unit.convert(lengths.value.x, unit, pixels_per_inch),
lengths.unit.convert(lengths.value.y, unit, pixels_per_inch),
);
value[edited_axis] = input.value.unwrap_or_default();
if whole_pixels && unit == LengthUnit::Pixel {
value = value.round();
}
TaggedValue::LengthVec2(TypedLengthVec2 { value, unit })
};
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
field(lengths.value.x, x)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 0)))
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
field(lengths.value.y, y)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 1)))
.widget_instance(),
]);
LayoutGroup::row(widgets)
}
/// A pair of angles' X and Y number fields, which share the unit the pair was typed in, with the fields' bounds given in degrees.
/// Typing another angle unit into either field moves both into it, converting the other component so its angle stays the same.
pub fn angle_vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, number_props: NumberInput) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return LayoutGroup::row(vec![]);
};
let angles = match input.as_non_exposed_value() {
Some(&TaggedValue::AngleVec2(angles)) => angles,
Some(&TaggedValue::DVec2(degrees)) => TypedAngleVec2::degrees(degrees),
_ => return LayoutGroup::row(widgets),
};
let number_props = bounds_in_unit(number_props, |degrees| angles.unit.from_degrees(degrees));
let field = |component: f64, label: &str| {
number_props
.clone()
.label(label)
.value(Some(component))
.unit(unit_suffix(angles.unit.symbol()))
.display_decimal_places(angle_decimal_places(angles.unit))
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.on_commit(commit_value)
};
// The edited component takes the typed unit, and the other converts into it
let typed = move |input: &NumberInput, edited_axis: usize| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
let degrees = angles.to_degrees();
let mut value = if unit == angles.unit {
angles.value
} else {
DVec2::new(unit.from_degrees(degrees.x), unit.from_degrees(degrees.y))
};
value[edited_axis] = input.value.unwrap_or_default();
TaggedValue::AngleVec2(TypedAngleVec2 { value, unit })
};
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
field(angles.value.x, x)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 0)))
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
field(angles.value.y, y)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| typed(input, 1)))
.widget_instance(),
]);
LayoutGroup::row(widgets)
}
// TODO: Auto-generate this enum dropdown menu widget
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1416,11 +1735,80 @@ fn wire_element(ty: &Type) -> Type {
}
}
/// The length or angle type of the field an unwired input shows, where the node's rows take one there among other types.
/// The rows fitting the node's other known inputs decide it when they all need one type there. Otherwise a length or angle the input holds keeps its field.
fn measurement_input_type(node_id: NodeId, input_index: usize, identifier: &graph_craft::ProtoNodeIdentifier, network_interface: &NodeNetworkInterface, network_path: &[NodeId]) -> Option<Type> {
let rows = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)?;
let measurements = [concrete!(Length), concrete!(Angle)];
let element_at = |inputs: &[Type], index: usize| inputs.get(index).map(wire_element);
let offered: Vec<Type> = rows.keys().filter_map(|row| element_at(&row.inputs, input_index)).collect();
if !offered.iter().any(|element| measurements.contains(element)) {
return None;
}
// Only an unwired input shows a field
let held_measurement = |index: usize| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, index), network_path) {
Some(NodeInput::Value { tagged_value, .. }) => Some(wire_element(&tagged_value.ty())).filter(|element| measurements.contains(element)),
_ => None,
};
let Some(NodeInput::Value { .. }) = network_interface.input_from_connector(&InputConnector::node_at_index(node_id, input_index), network_path) else {
return None;
};
let held = held_measurement(input_index).filter(|held| offered.contains(held));
// Wired inputs, through the conversions ahead of them, and inputs holding a length or angle decide which rows fit, unlike a plain number, which may be the one to change
enum Known {
Wired(Type),
Held(Type),
}
let known_inputs: Vec<(usize, Known)> = (0..network_interface.number_of_inputs(&node_id, network_path))
.filter(|&index| index != input_index)
.filter_map(|index| match network_interface.input_from_connector(&InputConnector::node_at_index(node_id, index), network_path)? {
NodeInput::Node { .. } | NodeInput::Import { .. } => {
let wired = network_interface.input_type_not_invalid(&InputConnector::node_at_index(node_id, index), network_path);
Some((index, Known::Wired(wired.compiled_nested_type()?.clone())))
}
NodeInput::Value { .. } => Some((index, Known::Held(held_measurement(index)?))),
_ => None,
})
.collect();
if known_inputs.is_empty() {
return held;
}
let fits = |row: &graphene_std::NodeIOTypes, exactly: bool| {
known_inputs.iter().all(|(index, known)| match known {
Known::Wired(source) if exactly => element_at(&row.inputs, *index) == Some(wire_element(source)),
Known::Wired(source) => row.inputs.get(*index).is_some_and(|connector| wire_feeds_proto_input(identifier, *index, source, connector)),
Known::Held(element) => element_at(&row.inputs, *index).as_ref() == Some(element),
})
};
// The compiler takes a row the wires feed as they are over one they would be converted into
let exact: Vec<&graphene_std::NodeIOTypes> = rows.keys().filter(|row| fits(row, true)).collect();
let fitting = if exact.is_empty() { rows.keys().filter(|row| fits(row, false)).collect() } else { exact };
let needed: Vec<(Type, Type)> = fitting
.iter()
.filter_map(|row| Some((element_at(&row.inputs, input_index)?, wire_element(&row.return_value))))
.collect();
let Some((first, _)) = needed.first() else { return held };
// A number reads in pixels or degrees where it gives what a length or angle would, so rows taking either call for the length or angle
let plain = concrete!(f64);
match needed.iter().find(|(element, _)| measurements.contains(element)) {
Some((measurement, output)) if needed.iter().all(|(element, result)| element == measurement || (*element == plain && result == output)) => Some(measurement.clone()),
None if needed.iter().all(|(element, _)| element == first) => None,
_ => held,
}
}
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(Length), concrete!(Angle)],
vec![concrete!(DVec2)],
vec![concrete!(DAffine2)],
vec![concrete!(Artboard)],
@@ -2788,14 +3176,14 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
if let Some(grid_type) = grid_type {
if grid_type.is_isometric() {
let spacing = LayoutGroup::row(number_widget(
let spacing = LayoutGroup::row(length_widget(
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
NumberInput::default().label("H").min(0.).unit(" px"),
NumberInput::default().label("H").min(0.),
));
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
let angles = angle_vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", NumberInput::default());
widgets.extend([spacing, angles]);
} else {
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
let spacing = length_vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", NumberInput::default().min(0.));
widgets.push(spacing);
}
}
@@ -2810,7 +3198,7 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
.for_socket(ParameterWidgetsInfo::new(node_id, SpiralTypeInput, true, context))
.inspector_row();
let turns = number_widget(ParameterWidgetsInfo::new(node_id, TurnsInput, true, context), NumberInput::default().min(0.1));
let start_angle = number_widget(ParameterWidgetsInfo::new(node_id, StartAngleInput, true, context), NumberInput::default().unit("°"));
let start_angle = angle_widget(ParameterWidgetsInfo::new(node_id, StartAngleInput, true, context), NumberInput::default());
let mut widgets = vec![spiral_type, LayoutGroup::row(turns), LayoutGroup::row(start_angle)];
@@ -2829,35 +3217,23 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
if let Some(&TaggedValue::SpiralType(spiral_type)) = spiral_type_input.as_non_exposed_value() {
match spiral_type {
SpiralType::Archimedean => {
let inner_radius = LayoutGroup::row(number_widget(
ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context),
NumberInput::default().min(0.).unit(" px"),
));
let inner_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context), NumberInput::default().min(0.)));
let outer_radius = LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default().unit(" px")));
let outer_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default()));
widgets.extend([inner_radius, outer_radius]);
}
SpiralType::Logarithmic => {
let inner_radius = LayoutGroup::row(number_widget(
ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context),
NumberInput::default().min(0.).unit(" px"),
));
let inner_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, InnerRadiusInput, true, context), NumberInput::default().min(0.)));
let outer_radius = LayoutGroup::row(number_widget(
ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context),
NumberInput::default().min(0.1).unit(" px"),
));
let outer_radius = LayoutGroup::row(length_widget(ParameterWidgetsInfo::new(node_id, OuterRadiusInput, true, context), NumberInput::default().min(0.1)));
widgets.extend([inner_radius, outer_radius]);
}
}
}
let angular_resolution = number_widget(
ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context),
NumberInput::default().min(1.).max(180.).unit("°"),
);
let angular_resolution = angle_widget(ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context), NumberInput::default().min(1.).max(180.));
widgets.push(LayoutGroup::row(angular_resolution));
@@ -2888,10 +3264,10 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
let spacing = enum_choice::<PointSpacingType>()
.for_socket(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context))
.inspector_row();
let separation = number_widget(ParameterWidgetsInfo::new(node_id, SeparationInput, true, context), NumberInput::default().min(0.).unit(" px"));
let separation = length_widget(ParameterWidgetsInfo::new(node_id, SeparationInput, true, context), NumberInput::default().min(0.));
let quantity = number_widget(ParameterWidgetsInfo::new(node_id, QuantityInput, true, context), NumberInput::default().min(2.).int());
let start_offset = number_widget(ParameterWidgetsInfo::new(node_id, StartOffsetInput, true, context), NumberInput::default().min(0.).unit(" px"));
let stop_offset = number_widget(ParameterWidgetsInfo::new(node_id, StopOffsetInput, true, context), NumberInput::default().min(0.).unit(" px"));
let start_offset = length_widget(ParameterWidgetsInfo::new(node_id, StartOffsetInput, true, context), NumberInput::default().min(0.));
let stop_offset = length_widget(ParameterWidgetsInfo::new(node_id, StopOffsetInput, true, context), NumberInput::default().min(0.));
let adaptive_spacing = bool_widget(ParameterWidgetsInfo::new(node_id, AdaptiveSpacingInput, true, context), CheckboxInput::default().disabled(is_quantity));
vec![
@@ -3217,10 +3593,10 @@ pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorCo
}
// Size X
let size_x = number_widget(ParameterWidgetsInfo::new(node_id, WidthInput, true, context), NumberInput::default());
let size_x = length_widget(ParameterWidgetsInfo::new(node_id, WidthInput, true, context), NumberInput::default());
// Size Y
let size_y = number_widget(ParameterWidgetsInfo::new(node_id, HeightInput, true, context), NumberInput::default());
let size_y = length_widget(ParameterWidgetsInfo::new(node_id, HeightInput, true, context), NumberInput::default());
// Clamped
let clamped = bool_widget(ParameterWidgetsInfo::new(node_id, ClampedInput, true, context), CheckboxInput::default());
@@ -3291,6 +3667,10 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
default_type = field.default_type.clone();
}
if let Some(measurement) = measurement_input_type(node_id, input_index, &proto_node_identifier, context.network_interface, context.selection_network_path) {
break 'early_return measurement;
}
if let Some(default) = default_type {
break 'early_return default;
}
@@ -3719,7 +4099,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
ParameterWidgetsInfo::new(node_id, PaintInput, true, context),
crate::messages::layout::utility_types::widgets::button_widgets::ColorInput::default(),
);
let weight = number_widget(ParameterWidgetsInfo::new(node_id, WeightInput, true, context), NumberInput::default().unit(" px").min(0.));
let weight = length_widget(ParameterWidgetsInfo::new(node_id, WeightInput, true, context), NumberInput::default().min(0.));
let align = enum_choice::<StrokeAlign>().for_socket(ParameterWidgetsInfo::new(node_id, AlignInput, true, context)).inspector_row();
let cap = enum_choice::<StrokeCap>().for_socket(ParameterWidgetsInfo::new(node_id, CapInput, true, context)).inspector_row();
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
@@ -3728,10 +4108,10 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
ParameterWidgetsInfo::new(node_id, MiterLimitInput, true, context),
NumberInput::default().min(0.).disabled(miter_limit_disabled),
);
let disabled_number_input = NumberInput::default().unit(" px").disabled(has_dash_lengths);
let disabled_number_input = NumberInput::default().disabled(has_dash_lengths);
let dash_lengths = dash_pattern_widget(ParameterWidgetsInfo::new(node_id, DashPatternInput, true, context), TextInput::default().centered(true));
let number_input = disabled_number_input;
let dash_offset = number_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
let dash_offset = length_widget(ParameterWidgetsInfo::new(node_id, DashOffsetInput, true, context), number_input);
vec![
color,
@@ -3748,8 +4128,7 @@ pub fn stroke_inspector(node_id: NodeId, context: &mut NodeInspectorContext) ->
pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::offset_path::*;
let number_input = NumberInput::default().unit(" px");
let distance = number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input);
let distance = length_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), NumberInput::default());
let join = enum_choice::<StrokeJoin>().for_socket(ParameterWidgetsInfo::new(node_id, JoinInput, true, context)).inspector_row();
@@ -3772,29 +4151,6 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
}
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::blending_nodes::filters::sharpen::*;
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
let edges_only = get_document_node(node_id, context)
.ok()
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
}
pub struct ParameterWidgetsInfo<'a> {
document_id: DocumentId,
network_interface: &'a NodeNetworkInterface,
@@ -4058,6 +4414,46 @@ mod tests {
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
}
/// The field the second input of a node shows with a length wired into its first, which feeds a circle's radius so it compiles.
async fn second_input_field_beside_a_wired_length(target: graph_craft::ProtoNodeIdentifier) -> Option<Type> {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
let mut editor = crate::test_utils::EditorTestUtils::create();
editor.new_document().await;
// The length comes from an Add of two lengths
let add = graphene_std::math_nodes::add::IDENTIFIER;
let source = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(add), 0, 0).await;
for input_index in 0..2 {
let value = Box::new(TaggedValue::Length(graphene_std::units::TypedLength::pixels(1.)));
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: source, input_index, value }).await;
}
// Only the nodes feeding the document's output are compiled, which resolves the types of their wires
let node = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(target.clone()), 10, 0).await;
let circle = editor
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER), 20, 0)
.await;
for (output_connector, input_connector) in [
(OutputConnector::node(source, 0), InputConnector::primary_input(node)),
(OutputConnector::node(node, 0), InputConnector::node_at_index(circle, 1)),
(OutputConnector::node(circle, 0), InputConnector::Export(0)),
] {
editor.handle_message(NodeGraphMessage::CreateWire { output_connector, input_connector }).await;
}
measurement_input_type(node, 1, &target, &editor.active_document().network_interface, &[])
}
#[tokio::test]
async fn a_number_beside_a_wired_length_shows_as_a_length_where_it_reads_in_pixels() {
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::add::IDENTIFIER).await, Some(concrete!(Length)));
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::clamp::IDENTIFIER).await, Some(concrete!(Length)));
// A divisor of a length is a plain number, which a length would turn into a ratio
assert_eq!(second_input_field_beside_a_wired_length(graphene_std::math_nodes::divide::IDENTIFIER).await, None);
}
fn description(expression: &str) -> Option<String> {
math_expression_error(expression, false).map(|error| math_expression_error_description(&error))
}
@@ -4083,7 +4479,10 @@ mod tests {
fn math_expression_errors_quote_the_expression_safely() {
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
assert_eq!(
description("7 % 3").as_deref(),
Some("`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`")
);
// A quoted token like `*` is a code span, so it can't pair with another into italics
let error = description("2 * * 3").unwrap();
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" | "LengthVec2" | "AngleVec2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
@@ -212,6 +212,23 @@ pub struct NodeEvaluationError {
pub message: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct FrontendClickTargets {
#[serde(rename = "nodeClickTargets")]
pub node_click_targets: Vec<String>,
#[serde(rename = "layerClickTargets")]
pub layer_click_targets: Vec<String>,
#[serde(rename = "connectorClickTargets")]
pub connector_click_targets: Vec<String>,
#[serde(rename = "iconClickTargets")]
pub icon_click_targets: Vec<String>,
#[serde(rename = "allNodesBoundingBox")]
pub all_nodes_bounding_box: String,
#[serde(rename = "importExportNames")]
pub import_export_names: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Direction {
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
pub struct OverlaysMessageContext<'a> {
pub visibility_settings: OverlaysVisibilitySettings,
pub viewport: &'a ViewportMessageHandler,
pub graph_open: bool,
}
#[derive(Debug, Clone, Default, ExtractField)]
@@ -26,7 +25,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
if visibility_settings.all() && !context.graph_open {
if visibility_settings.all() {
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
@@ -19,6 +19,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
use graphene_std::list::{Item, List};
use graphene_std::math::quad::Quad;
use graphene_std::renderer::RenderMetadata;
use graphene_std::renderer::scene_builder::SceneBuilder;
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
@@ -1,7 +1,7 @@
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
use super::test_support::open_demo;
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use glam::DVec2;
use graphene_std::uuid::NodeId;
@@ -20,32 +20,20 @@ const DEMOS: [&str; 8] = [
const REPETITIONS: u32 = 200;
#[test]
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
fn wire_anchors_match_the_ports_of_every_demo_node() {
for demo in DEMOS {
let document = open_demo(demo);
let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() {
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
let on_port = |wanted: Part, anchor: Option<DVec2>| {
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
match (port, anchor) {
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
(Some(port), Some(anchor)) => port.contains(anchor),
(None, None) => true,
_ => false,
}
};
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
for index in 0..interface.number_of_inputs(node_id, &[]) {
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
let input = InputConnector::node_at_index(*node_id, index);
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
}
for index in 0..interface.number_of_outputs(node_id, &[]) {
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
let output = OutputConnector::node(*node_id, index);
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
}
}
}
@@ -72,7 +60,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now();
for _ in 0..REPETITIONS {
for node_id in &node_ids {
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
std::hint::black_box(interface.node_click_targets(node_id, &[]));
}
}
let all_click_targets = start.elapsed() / REPETITIONS;
@@ -296,6 +296,29 @@ fn pinned_order_round_trips_through_the_registry() {
);
}
/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence.
#[test]
fn pixels_per_inch_round_trips_through_the_registry() {
let round_trip = |pixels_per_inch: f64| {
let mut document = open_demo("changing-seasons.graphite");
document.network_interface.set_pixels_per_inch(pixels_per_inch);
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries);
(
rebuilt.pixels_per_inch(),
rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch,
)
};
assert_eq!(round_trip(300.), (300., Some(300.)));
assert_eq!(round_trip(96.), (96., None));
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
@@ -35,6 +35,7 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_absolute_position(*position);
}
interface.invalidate_positions(network_path);
}
}
@@ -171,14 +172,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
interface.finish_drag(&[]);
let kept = interface.positions(node_ids.iter().copied(), &[]);
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
panic!("the root network is laid out")
};
let fresh = graph_layout::Layout::new(&graph);
for (other, position) in kept {
assert_eq!(
Some(position),
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
indices.get(&other).map(|index| fresh.node(*index).position),
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
);
}
@@ -190,7 +190,9 @@ impl DocumentMetadata {
let transform = local_transform.unwrap_or_else(|| {
let transform_node_id = ModifyInputsContext::locate_node_in_layer_chain(&DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER), layer, network_interface);
let transform_node = transform_node_id.and_then(|id| network_interface.document_node(&id, &[]));
transform_node.map(|node| transform_utils::get_current_transform(node.inputs.as_slice())).unwrap_or_default()
transform_node
.map(|node| transform_utils::get_current_transform(node.inputs.as_slice(), network_interface.pixels_per_inch()))
.unwrap_or_default()
});
footprint * transform
@@ -22,7 +22,6 @@ mod layout;
mod layout_pass;
mod memo_network;
mod mutations;
mod node_parts;
mod queries;
mod reconcile;
mod resolved_types;
@@ -37,8 +36,8 @@ mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use layout_pass::NetworkLayout;
pub use node_parts::{Part, PartTarget};
pub use reconcile::{ReconcileError, Reconciled};
pub(crate) use resolved_types::wire_feeds_proto_input;
use store::Guarded;
pub use store::NodeLocator;
pub use structure::vector_outline_targets;
@@ -54,7 +53,7 @@ use crate::consts::{
STACK_VERTICAL_GAP,
};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
EditorDelta::NodeMetadata { network, node_id, change } => {
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
match change {
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
@@ -105,6 +105,7 @@ impl NodeNetworkInterface {
match change {
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch),
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff. Show more