mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1db3026a2 | ||
|
|
91c7236e10 | ||
|
|
fa686d5063 | ||
|
|
7d8f124539 | ||
|
|
78a1be4059 | ||
|
|
a7ed5fcf0f | ||
|
|
48fe21ebe3 | ||
|
|
0ab2f21e47 | ||
|
|
d73bd34750 | ||
|
|
4f999ea73b | ||
|
|
80f9dbb992 | ||
|
|
9fd1011e1e | ||
|
|
3d4d7d1058 | ||
|
|
401cf1419a | ||
|
|
369671dc41 | ||
|
|
fe505edeff | ||
|
|
63a8befe4b | ||
|
|
3e380b8cd7 | ||
|
|
634c30bebf | ||
|
|
1e912de804 | ||
|
|
ea9c44e003 | ||
|
|
6a28b82b91 | ||
|
|
30164b921e | ||
|
|
b10aa51efb | ||
|
|
5d00e45354 | ||
|
|
69c0dd140d | ||
|
|
9a8269c953 | ||
|
|
76361baaa1 | ||
|
|
f569120bf6 | ||
|
|
0df1e16233 | ||
|
|
65bb0ff838 | ||
|
|
d5a7504e3a | ||
|
|
fa65c1f8dc |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
|
||||
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
|
||||
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
|
||||
Generated
+36
-20
@@ -1226,6 +1226,7 @@ dependencies = [
|
||||
"kurbo",
|
||||
"log",
|
||||
"lyon_geom",
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
@@ -2444,21 +2445,6 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glifo"
|
||||
version = "0.4.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"foldhash 0.2.0",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"peniko",
|
||||
"skrifa 0.44.0",
|
||||
"smallvec",
|
||||
"vello_common",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.4"
|
||||
@@ -3101,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"
|
||||
@@ -6097,11 +6117,10 @@ dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"glifo",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"hayro-syntax",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
@@ -8136,7 +8155,6 @@ dependencies = [
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
@@ -8213,7 +8231,6 @@ version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"glifo",
|
||||
"hashbrown 0.17.1",
|
||||
"log",
|
||||
"thiserror 2.0.21",
|
||||
@@ -8696,7 +8713,6 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"web-sys",
|
||||
|
||||
+3
-4
@@ -215,9 +215,7 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support", "text"] }
|
||||
glifo = { version = "0.4", default-features = false, features = ["std"] }
|
||||
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
|
||||
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
|
||||
usvg = "0.49"
|
||||
simplecss = "0.2"
|
||||
parley = { version = "0.12", default-features = false, features = ["std"] }
|
||||
@@ -225,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 = [
|
||||
@@ -320,4 +320,3 @@ fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "2
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
glifo = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -52,9 +52,11 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
mod bookkeeping;
|
||||
mod branch_simulation;
|
||||
mod crdt;
|
||||
mod history_simulation;
|
||||
mod projection;
|
||||
mod round_trip;
|
||||
mod sessions;
|
||||
mod simulation;
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -382,7 +382,8 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
|
||||
if !visited.insert(current) {
|
||||
return None;
|
||||
}
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t) {
|
||||
// A placeholder knows nothing of the node's network or primary input, so what history kept decides instead
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t).filter(|tombstone| !tombstone.placeholder) {
|
||||
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
|
||||
None => known.primary.get(¤t).cloned()?,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Deterministic simulation of a document whose chains branch off inputs past the primary one, with every history
|
||||
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
||||
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||
|
||||
/// A slot that can name a node.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
enum Place {
|
||||
Export(u32),
|
||||
Input(NodeId, u32),
|
||||
}
|
||||
|
||||
fn place_value(registry: &Registry, place: Place) -> Option<NodeInput> {
|
||||
match place {
|
||||
Place::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
|
||||
Place::Export(index) => registry.networks.get(&ROOT_NETWORK)?.exports.get(index as usize)?.target.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_place(place: Place, input: NodeInput) -> RegistryDelta {
|
||||
match place {
|
||||
Place::Input(id, index) => RegistryDelta::ChangeNodeInput { id, index, new_input: input },
|
||||
Place::Export(index) => RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index,
|
||||
export: Some(input),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Every slot naming a node, and the node it names, in a fixed order.
|
||||
fn naming_places(registry: &Registry) -> Vec<(Place, NodeId)> {
|
||||
let mut places = Vec::new();
|
||||
for (&id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = slot.input {
|
||||
places.push((Place::Input(id, index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(network) = registry.networks.get(&ROOT_NETWORK) {
|
||||
for (index, slot) in network.exports.iter().enumerate() {
|
||||
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
|
||||
places.push((Place::Export(index as u32), named));
|
||||
}
|
||||
}
|
||||
}
|
||||
places.sort();
|
||||
places
|
||||
}
|
||||
|
||||
/// The slot naming `node`, of which a document built this way has one.
|
||||
fn consumer_place(registry: &Registry, node: NodeId) -> Option<Place> {
|
||||
naming_places(registry).into_iter().find(|(_, named)| *named == node).map(|(place, _)| place)
|
||||
}
|
||||
|
||||
/// Every node under `place`, through any input.
|
||||
fn under(registry: &Registry, place: Place) -> Vec<NodeId> {
|
||||
let mut seen: Vec<NodeId> = Vec::new();
|
||||
let mut queue: Vec<NodeId> = Vec::new();
|
||||
if let Some(NodeInput::Node { id, .. }) = place_value(registry, place) {
|
||||
queue.push(id);
|
||||
}
|
||||
while let Some(id) = queue.pop() {
|
||||
if seen.contains(&id) || !registry.node_instances.contains_key(&id) {
|
||||
continue;
|
||||
}
|
||||
seen.push(id);
|
||||
for slot in ®istry.node_instances[&id].inputs {
|
||||
if let NodeInput::Node { id: next, .. } = slot.input {
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
/// Nodes chained off the export and off inputs past the primary one.
|
||||
struct Branching;
|
||||
|
||||
impl Scenario for Branching {
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
let nodes = under(®istry, Place::Export(0));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let make = |first: NodeInput, second: NodeInput| {
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = first;
|
||||
node.inputs[1].input = second;
|
||||
node
|
||||
};
|
||||
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
||||
let plain: Vec<NodeId> = nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||
.collect();
|
||||
|
||||
match random.below(12) {
|
||||
// Draw a node on top of the chain off the export
|
||||
0..=2 => {
|
||||
let id = session.next_node_id();
|
||||
let node = make(layers.first().map_or_else(|| value(0), |&top| on(top)), value(random.below(100)));
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
if let Some(&under) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(under, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
}
|
||||
// Hang a node on an input past the primary one, over whatever is there already
|
||||
3..=5 => {
|
||||
let Some(host) = random.pick(&nodes) else { return Vec::new() };
|
||||
let id = session.next_node_id();
|
||||
let first = match place_value(®istry, Place::Input(host, 1)) {
|
||||
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
||||
_ => value(0),
|
||||
};
|
||||
let node = make(first, value(random.below(100)));
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: host,
|
||||
index: 1,
|
||||
new_input: on(id),
|
||||
},
|
||||
]);
|
||||
ops
|
||||
}
|
||||
// Delete a node, reconnecting everything that named it to what it rested on
|
||||
6..=7 => {
|
||||
let Some(node) = random.pick(&plain) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&node].clone();
|
||||
let mut ops: Vec<RegistryDelta> = naming_places(®istry)
|
||||
.into_iter()
|
||||
.filter(|(_, named)| *named == node)
|
||||
.map(|(place, _)| set_place(place, below(®istry, node)))
|
||||
.collect();
|
||||
ops.push(RegistryDelta::RemoveNode { id: node, snapshot });
|
||||
ops
|
||||
}
|
||||
// Move a node to the top of the chain off the export
|
||||
8 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
let Some(place) = consumer_place(®istry, layer) else { return Vec::new() };
|
||||
vec![
|
||||
set_place(place, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a node's value
|
||||
9..=10 => {
|
||||
let Some(node) = random.pick(&plain) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: node,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
// Cut the chain off an input past the primary one, taking its nodes with it
|
||||
_ => {
|
||||
let hosts: Vec<NodeId> = nodes
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||
.collect();
|
||||
let Some(host) = random.pick(&hosts) else { return Vec::new() };
|
||||
let mut gone = under(®istry, Place::Input(host, 1));
|
||||
// Nothing outside the cut may name a node inside it, or taking them would leave that naming nothing
|
||||
let held = naming_places(®istry)
|
||||
.into_iter()
|
||||
.any(|(place, named)| gone.contains(&named) && place != Place::Input(host, 1) && !matches!(place, Place::Input(owner, _) if gone.contains(&owner)));
|
||||
if held {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ops = vec![RegistryDelta::ChangeNodeInput {
|
||||
id: host,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}];
|
||||
gone.sort();
|
||||
for id in gone {
|
||||
ops.push(RegistryDelta::RemoveNode {
|
||||
id,
|
||||
snapshot: registry.node_instances[&id].clone(),
|
||||
});
|
||||
}
|
||||
ops
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Nothing names a node the document no longer has, every node is built from a network it still has, and no node
|
||||
/// input holds the empty export's value. A node may feed nothing or more than one input.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
for (place, named) in naming_places(registry) {
|
||||
assert!(registry.node_instances.contains_key(&named), "{context}: {place:?} names {named:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
assert_ne!(slot.input, empty_export(), "{context}: input {index} of {id:?} holds the empty export's value");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_a_branching_document_whole() {
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
for seed in 0..seeds {
|
||||
simulate::<Branching>(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
@@ -1,64 +1,12 @@
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
|
||||
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
|
||||
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
|
||||
//! head moves must hold the same document.
|
||||
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation mixed in.
|
||||
//! After every operation the document must still be a well-formed stack.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
|
||||
/// as the editor's first layer brings the subgraph every later one is built from.
|
||||
const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
|
||||
fn empty_export() -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("empty")),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// The layers from the top of the stack down, following each layer's first input.
|
||||
fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut layers = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
|
||||
break;
|
||||
}
|
||||
layers.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
layers
|
||||
}
|
||||
|
||||
/// What feeds into `layer` from below.
|
||||
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
|
||||
registry.node_instances[&layer].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
/// Points what sits directly above `layer`, a layer or the export, at `input`.
|
||||
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
|
||||
let layers = stack(registry);
|
||||
@@ -76,365 +24,124 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
|
||||
}
|
||||
}
|
||||
|
||||
fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
/// A single stack of layers off the export.
|
||||
struct Stack;
|
||||
|
||||
fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
ops
|
||||
}
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = std::collections::HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The layers live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
if let Some(bottom) = layers.last() {
|
||||
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
|
||||
}
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
}
|
||||
|
||||
fn assert_consistent(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let document = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(empty_export()),
|
||||
},
|
||||
];
|
||||
host.stage_ops(document).expect("stage the document");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
impl Scenario for Stack {
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
|
||||
let registry = session.registry().clone();
|
||||
let layers = stack(®istry);
|
||||
match random.below(10) {
|
||||
// Draw a layer on top
|
||||
0..=3 => {
|
||||
let id = session.next_node_id();
|
||||
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
|
||||
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
|
||||
node.inputs[1].input = value(random.below(100));
|
||||
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
|
||||
id: LEAF,
|
||||
network: Network::default(),
|
||||
});
|
||||
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
|
||||
ops.extend([
|
||||
RegistryDelta::AddNode { id, node },
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(id)),
|
||||
},
|
||||
]);
|
||||
// The layer below moves into the stack under the new one, as the editor records with its position
|
||||
if let Some(&below) = layers.first() {
|
||||
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
ops
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
// Delete a layer, reconnecting what was above it to what was below
|
||||
4..=5 => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
let snapshot = registry.node_instances[&layer].clone();
|
||||
vec![rewire_above(®istry, layer, below(®istry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
// Move a layer to the top
|
||||
6 => {
|
||||
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
|
||||
vec![
|
||||
rewire_above(®istry, layer, below(®istry, layer)),
|
||||
RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 0,
|
||||
new_input: on(layers[0]),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(on(layer)),
|
||||
},
|
||||
]
|
||||
}
|
||||
8 => {
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
|
||||
continue;
|
||||
};
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
// Change a layer's value
|
||||
_ => {
|
||||
let Some(layer) = random.pick(&layers) else { return Vec::new() };
|
||||
vec![RegistryDelta::ChangeNodeInput {
|
||||
id: layer,
|
||||
index: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step makes the document, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A layer the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A layer the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
|
||||
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
|
||||
/// left drawn by nothing.
|
||||
fn assert_well_formed(context: &str, registry: &Registry) {
|
||||
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
|
||||
let export = exports.first().and_then(|slot| slot.target.clone());
|
||||
if let Some(NodeInput::Node { id, .. }) = &export {
|
||||
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
for (index, slot) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Node { id: named, .. } = &slot.input {
|
||||
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut stacked_on = HashSet::new();
|
||||
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
|
||||
for input in primary_inputs.chain(export.iter()) {
|
||||
if let NodeInput::Node { id, .. } = input {
|
||||
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
|
||||
}
|
||||
}
|
||||
for (id, node) in ®istry.node_instances {
|
||||
if let Implementation::Network(network) = &node.implementation {
|
||||
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
|
||||
}
|
||||
}
|
||||
let layers = stack(registry);
|
||||
if let Some(bottom) = layers.last() {
|
||||
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
|
||||
}
|
||||
let unique: HashSet<NodeId> = layers.iter().copied().collect();
|
||||
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
|
||||
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
|
||||
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_the_stack_whole_and_peers_converged() {
|
||||
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
for seed in 0..seeds {
|
||||
simulate(seed, steps, &mut Vec::new());
|
||||
simulate::<Stack>(seed, steps, &mut Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// A seed fixes the run, so one that fails can be replayed.
|
||||
#[test]
|
||||
fn a_seed_fixes_the_history_run() {
|
||||
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
let histories = |seed| simulate::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
for seed in 0..5 {
|
||||
assert_eq!(histories(seed), histories(seed), "seed {seed}");
|
||||
}
|
||||
@@ -443,9 +150,7 @@ fn a_seed_fixes_the_history_run() {
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn inspect_seed() {
|
||||
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
|
||||
let mut log = Vec::new();
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let host = simulate(seed, steps, &mut log);
|
||||
let host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
|
||||
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
|
||||
}
|
||||
@@ -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(())
|
||||
|
||||
@@ -1033,6 +1033,33 @@ fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
|
||||
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
|
||||
}
|
||||
|
||||
/// Bringing back a step that writes to a node the line never had reconnects an input naming that node to what history
|
||||
/// holds as its primary input, though the write leaves only a placeholder of it.
|
||||
#[test]
|
||||
fn bringing_back_a_step_reconnects_past_a_node_the_line_never_had() {
|
||||
let (source, consumer) = (NodeId(1), NodeId(2));
|
||||
let source_value = NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("under the source")),
|
||||
exposed: false,
|
||||
};
|
||||
let mut source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
|
||||
source_node.inputs[0].input = source_value.clone();
|
||||
let mut consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
|
||||
consumer_node.inputs[0].input = NodeInput::Node { id: source, index: 0 };
|
||||
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let base = step(&mut session, add_network(5));
|
||||
step(&mut session, RegistryDelta::AddNode { id: source, node: source_node });
|
||||
session.commit_op_for_test(RegistryDelta::AddNode { id: consumer, node: consumer_node }).expect("commit");
|
||||
let consumed = step(&mut session, change_node_attribute(source, "position", serde_json::json!(1)));
|
||||
session.move_head_to(base).expect("go back to before the source");
|
||||
|
||||
session.restore_interaction(consumed).expect("bring the consumer back");
|
||||
let registry = session.retired_registry();
|
||||
assert!(registry.removed_nodes.get(&source).is_some_and(|tombstone| tombstone.placeholder));
|
||||
assert_eq!(registry.node_instances[&consumer].inputs()[0].input, source_value);
|
||||
}
|
||||
|
||||
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
|
||||
/// peer id still undoes what its user did from the old one, and nobody else's.
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Shared harness of the deterministic history simulations: a seeded generator, every history operation the History
|
||||
//! panel offers, and the checks each run makes after every operation.
|
||||
|
||||
use crate::{Network, NetworkId, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
/// What every node's implementation names, so nodes need no proto-node declarations. The first node drawn brings it,
|
||||
/// as the editor's first layer brings the subgraph every later one is built from.
|
||||
pub(super) const LEAF: NetworkId = NetworkId(1);
|
||||
|
||||
/// What the export holds while the document is empty, of another type than what a chain's bottom rests on.
|
||||
pub(super) fn empty_export() -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!("empty")),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// A small xorshift generator, so a seed fixes the run.
|
||||
pub(super) struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn new(seed: u64) -> Self {
|
||||
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
|
||||
}
|
||||
|
||||
pub(super) fn below(&mut self, bound: usize) -> usize {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
(self.0 % bound as u64) as usize
|
||||
}
|
||||
|
||||
pub(super) fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
|
||||
(!options.is_empty()).then(|| options[self.below(options.len())])
|
||||
}
|
||||
}
|
||||
|
||||
/// A kind of document the simulation edits.
|
||||
pub(super) trait Scenario {
|
||||
/// One interaction's ops for a random edit, as the editor would stage them.
|
||||
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta>;
|
||||
|
||||
/// Panics with `context` when `registry` is not a document this scenario allows.
|
||||
fn assert_well_formed(context: &str, registry: &Registry);
|
||||
}
|
||||
|
||||
/// The nodes down the chain off the export, following each one's primary input.
|
||||
pub(super) fn stack(registry: &Registry) -> Vec<NodeId> {
|
||||
let mut nodes = Vec::new();
|
||||
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
|
||||
while let Some(NodeInput::Node { id, .. }) = below {
|
||||
if nodes.contains(&id) {
|
||||
break;
|
||||
}
|
||||
nodes.push(id);
|
||||
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
|
||||
}
|
||||
nodes
|
||||
}
|
||||
|
||||
/// What feeds into `node` from below.
|
||||
pub(super) fn below(registry: &Registry, node: NodeId) -> NodeInput {
|
||||
registry.node_instances[&node].inputs[0].input.clone()
|
||||
}
|
||||
|
||||
pub(super) fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
pub(super) fn value(number: usize) -> NodeInput {
|
||||
NodeInput::Value {
|
||||
value: Value::from(serde_json::json!(number)),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads a number from the environment variable `name`, so a run can be widened or replayed.
|
||||
pub(super) fn from_env<T: std::str::FromStr>(name: &str, default: T) -> T {
|
||||
std::env::var(name).ok().and_then(|text| text.parse().ok()).unwrap_or(default)
|
||||
}
|
||||
|
||||
/// The ops of an edit, short enough to read in a failing run's log.
|
||||
fn summarize(ops: &[RegistryDelta]) -> String {
|
||||
let short = |id: &NodeId| id.0 % 1000;
|
||||
let input = |input: &NodeInput| match input {
|
||||
NodeInput::Node { id, .. } => format!("{}", short(id)),
|
||||
_ => "value".to_string(),
|
||||
};
|
||||
ops.iter()
|
||||
.map(|op| match op {
|
||||
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
|
||||
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
|
||||
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
|
||||
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
|
||||
other => format!("{other:?}"),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
}
|
||||
|
||||
/// The revs closing each interaction on the head's line, newest first.
|
||||
fn line_steps(session: &Session) -> Vec<Rev> {
|
||||
let mut steps = Vec::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
if delta.is_interaction_end() {
|
||||
steps.push(delta.id);
|
||||
}
|
||||
current = delta.parent;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// The revs closing interactions left behind on branches.
|
||||
fn branch_steps(session: &Session) -> Vec<Rev> {
|
||||
let line: HashSet<Rev> = {
|
||||
let mut line = HashSet::new();
|
||||
let mut current = session.head_rev();
|
||||
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
|
||||
line.insert(delta.id);
|
||||
current = delta.parent;
|
||||
}
|
||||
line
|
||||
};
|
||||
let mut steps: Vec<Rev> = session
|
||||
.history()
|
||||
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
|
||||
.map(|delta| delta.id)
|
||||
.collect();
|
||||
steps.sort();
|
||||
steps
|
||||
}
|
||||
|
||||
/// The nodes the interaction ending at `end` added and deleted, by what it did in all.
|
||||
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
|
||||
let (mut added, mut removed) = (Vec::new(), Vec::new());
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
match &delta.kind {
|
||||
RegistryDelta::AddNode { id, .. } => added.push(*id),
|
||||
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
|
||||
_ => {}
|
||||
}
|
||||
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
|
||||
}
|
||||
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
|
||||
(net(&added, &removed), net(&removed, &added))
|
||||
}
|
||||
|
||||
/// The nodes the step ending at `end` added that a newer deletion on its own line had taken again.
|
||||
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
|
||||
let mut lost = HashSet::new();
|
||||
let mut added_at = HashMap::new();
|
||||
let mut line = Vec::new();
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current {
|
||||
line.push(delta);
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
|
||||
added_at.entry(*id).or_insert(delta.timestamp);
|
||||
}
|
||||
}
|
||||
for delta in &line {
|
||||
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
|
||||
&& added.contains(id)
|
||||
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
|
||||
{
|
||||
lost.insert(*id);
|
||||
}
|
||||
}
|
||||
lost
|
||||
}
|
||||
|
||||
/// The nodes live on the line just before the interaction ending at `end`.
|
||||
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
|
||||
let mut current = session.delta(end);
|
||||
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
let mut line = Vec::new();
|
||||
while let Some(delta) = current {
|
||||
line.push(delta.clone());
|
||||
current = delta.parent.and_then(|parent| session.delta(parent));
|
||||
}
|
||||
line.reverse();
|
||||
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
|
||||
replayed.retired_registry().node_instances.keys().copied().collect()
|
||||
}
|
||||
|
||||
fn assert_consistent<S: Scenario>(context: &str, session: &Session) {
|
||||
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
|
||||
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
|
||||
let folded = session.snapshot_from_history().expect("history folds");
|
||||
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
|
||||
S::assert_well_formed(context, session.retired_registry());
|
||||
}
|
||||
|
||||
/// Closes the open interaction and retires it as one step.
|
||||
fn retire_step(session: &mut Session) {
|
||||
session.end_interaction().expect("close");
|
||||
for interaction in session.closed_interactions() {
|
||||
session.retire_interaction(&interaction).expect("retire");
|
||||
}
|
||||
}
|
||||
|
||||
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
|
||||
fn catch_up(follower: &mut Session, host: &Session) {
|
||||
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
|
||||
follower.follow(missing, host.head_rev()).expect("follow");
|
||||
}
|
||||
|
||||
/// A peer that joins now and holds what the host holds.
|
||||
fn fresh_follower(host: &Session) -> Session {
|
||||
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
|
||||
}
|
||||
|
||||
/// Runs `steps` random edits and history operations from `seed`. After each one the document must be well formed, the
|
||||
/// snapshot must be what history folds to, and a peer following the host must hold the same document.
|
||||
pub(super) fn simulate<S: Scenario>(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
|
||||
let mut random = Random::new(seed);
|
||||
let mut host = Session::with_identity(PeerId(1), UserId(1));
|
||||
let document = [
|
||||
RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: ROOT_NETWORK,
|
||||
index: 0,
|
||||
export: Some(empty_export()),
|
||||
},
|
||||
];
|
||||
host.stage_ops(document).expect("stage the document");
|
||||
retire_step(&mut host);
|
||||
let mut follower = fresh_follower(&host);
|
||||
|
||||
for step in 0..steps {
|
||||
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
|
||||
match random.below(12) {
|
||||
0..=5 => {
|
||||
let ops = S::random_edit(&mut random, &mut host);
|
||||
if ops.is_empty() {
|
||||
continue;
|
||||
}
|
||||
log.push(format!("{step}: edit {}", summarize(&ops)));
|
||||
host.stage_ops(ops).expect("stage");
|
||||
retire_step(&mut host);
|
||||
catch_up(&mut follower, &host);
|
||||
}
|
||||
6 if host.can_undo() => {
|
||||
log.push(format!("{step}: undo"));
|
||||
host.undo().expect("undo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
7 if host.can_redo() => {
|
||||
log.push(format!("{step}: redo"));
|
||||
host.redo().expect("redo");
|
||||
follower = fresh_follower(&host);
|
||||
}
|
||||
8 => {
|
||||
let steps = line_steps(&host);
|
||||
// Not the newest step, which going back to would leave everything as it is
|
||||
let Some(target) = random.pick(&steps[1.min(steps.len())..]) else { continue };
|
||||
log.push(format!("{step}: go back to {target:?}"));
|
||||
let (moved, _) = host.move_head_to(target).expect("go back");
|
||||
follower.apply_head_move(&moved).expect("follow the move");
|
||||
}
|
||||
9 => {
|
||||
let steps = line_steps(&host);
|
||||
// The first step makes the document, which nothing can do without
|
||||
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
|
||||
log.push(format!("{step}: remove {target:?}"));
|
||||
let (mut added, _) = added_and_removed(&host, target);
|
||||
// A node the line had before the step stays
|
||||
let earlier = live_before(&host, target);
|
||||
added.retain(|id| !earlier.contains(id));
|
||||
let (moved, _) = host.drop_interaction(target).expect("remove the step");
|
||||
follower.apply_head_move(&moved).expect("follow the removal");
|
||||
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the removed step's nodes {kept:?} are still there"), log));
|
||||
}
|
||||
10 | 11 => {
|
||||
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
|
||||
log.push(format!("{step}: bring back {target:?}"));
|
||||
let (mut added, removed) = added_and_removed(&host, target);
|
||||
// A node the line already had from this step and deleted since stays deleted
|
||||
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
|
||||
// As does one a newer deletion took on the step's own line
|
||||
let lost = lost_on_its_line(&host, target, &added);
|
||||
added.retain(|id| !lost.contains(id));
|
||||
host.restore_interaction(target).expect("bring back");
|
||||
catch_up(&mut follower, &host);
|
||||
let registry = host.retired_registry();
|
||||
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
|
||||
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
|
||||
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's nodes {missing:?} are missing"), log));
|
||||
assert!(kept.is_empty(), "{}", context(&format!("the nodes {kept:?} the brought back step deleted are still there"), log));
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
let what = log.last().cloned().unwrap_or_default();
|
||||
assert_consistent::<S>(&context(&what, log), &host);
|
||||
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
|
||||
assert!(
|
||||
follower.retired_registry().value_equal(host.retired_registry()),
|
||||
"{}",
|
||||
context("the follower holds another document", log)
|
||||
);
|
||||
}
|
||||
host
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
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 {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
TransferCurve(Vec<[f64; 2]>),
|
||||
TypeDefault(Type),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `Type` a paint input's lack of a paint stores.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Type {
|
||||
Concrete(TypeDescriptor),
|
||||
Item(Box<Type>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeDescriptor {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// 'Bevel & Emboss' gained a texture with its depth, and a gloss contour and a slope contour with its range, set to no texture and straight contours across the whole slope to keep the bevel as it was.
|
||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@1 => @2)]
|
||||
pub fn bevel_and_emboss_v1(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture, its depth, the slope contour's range, the gloss and slope contours' antialiasing, and the gloss and slope contours.
|
||||
fn added_inputs() -> [NodeInput; 7] {
|
||||
let straight = || literal(Tagged::TransferCurve(vec![[0., 0.], [1., 1.]]));
|
||||
let no_paint = Tagged::TypeDefault(Type::Item(Box::new(Type::Concrete(TypeDescriptor {
|
||||
name: "graphic_types::graphic::Graphic".to_string(),
|
||||
}))));
|
||||
|
||||
[
|
||||
literal(no_paint),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Bool(false)),
|
||||
literal(Tagged::Bool(false)),
|
||||
straight(),
|
||||
straight(),
|
||||
]
|
||||
}
|
||||
|
||||
#[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(13, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelAndEmbossV1, &contract());
|
||||
check_undo(&BevelAndEmbossV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_options_that_leave_the_bevel_as_it_was() {
|
||||
let inputs: Vec<_> = (0..13).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BevelAndEmbossV1);
|
||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&BevelAndEmbossV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||
}
|
||||
}
|
||||
@@ -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("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||
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 };
|
||||
|
||||
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(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlurV2, &contract());
|
||||
check_undo(&BlurV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&BlurV2);
|
||||
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 radius = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, blur), [literal(Tagged::None), radius, number(0.), number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Drop Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
|
||||
#[migration("blending_nodes::effects::DropShadowNode"@1 => @2)]
|
||||
pub fn drop_shadow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DropShadowV1, &contract());
|
||||
check_undo(&DropShadowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&DropShadowV1);
|
||||
let drop_shadow = fixture.add(decl!("blending_nodes::effects::DropShadowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&DropShadowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, drop_shadow), Some(decl!("blending_nodes::effects::DropShadowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, drop_shadow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Inner Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
|
||||
#[migration("blending_nodes::effects::InnerGlowNode"@1 => @2)]
|
||||
pub fn inner_glow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerGlowV1, &contract());
|
||||
check_undo(&InnerGlowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerGlowV1);
|
||||
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerGlowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Inner Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
|
||||
#[migration("blending_nodes::effects::InnerShadowNode"@1 => @2)]
|
||||
pub fn inner_shadow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[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| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerShadowV1, &contract());
|
||||
check_undo(&InnerShadowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerShadowV1);
|
||||
let inner_shadow = fixture.add(decl!("blending_nodes::effects::InnerShadowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerShadowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_shadow), Some(decl!("blending_nodes::effects::InnerShadowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_shadow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
MaskMode(MaskMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MaskMode {
|
||||
Luminance,
|
||||
}
|
||||
|
||||
/// 'Mask' became an effect masking any graphic by any other, keeping its content and mask and gaining its mode, density, feather, and invert at their defaults.
|
||||
#[migration("raster_nodes::std_nodes::MaskNode"@1 => "blending_nodes::masks::MaskNode"@2)]
|
||||
pub fn mask_by_any_graphic(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::MaskMode(MaskMode::Luminance)));
|
||||
inputs.push(literal(Tagged::Number(100.)));
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
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(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MaskByAnyGraphic, &contract());
|
||||
check_undo(&MaskByAnyGraphic, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_content_and_mask_and_adds_the_defaults() {
|
||||
let (content, stencil) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&MaskByAnyGraphic);
|
||||
let mask = fixture.add(decl!("raster_nodes::std_nodes::MaskNode"@1), vec![content.clone(), stencil.clone()]);
|
||||
let migrated = fixture.migrate(&MaskByAnyGraphic).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, mask), Some(decl!("blending_nodes::masks::MaskNode"@2)));
|
||||
let defaults = [
|
||||
literal(Tagged::MaskMode(MaskMode::Luminance)),
|
||||
literal(Tagged::Number(100.)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::Bool(false)),
|
||||
];
|
||||
assert_eq!(fixture.inputs(&migrated, mask), [[content, stencil].as_slice(), &defaults].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,14 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod blur_v2;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_shadow_v1;
|
||||
mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod renames;
|
||||
mod satin_v1;
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Outer Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
|
||||
#[migration("blending_nodes::effects::OuterGlowNode"@1 => @2)]
|
||||
pub fn outer_glow_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[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| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OuterGlowV1, &contract());
|
||||
check_undo(&OuterGlowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OuterGlowV1);
|
||||
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&OuterGlowV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Outline' gained a blend mode after its color, set to Normal, which composites the outline as before.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@1 => @2)]
|
||||
pub fn outline_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[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(&OutlineV1, &contract());
|
||||
check_undo(&OutlineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV1);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
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),
|
||||
}
|
||||
|
||||
/// 'Outline' takes its color as any paint now, and gained a Contour Gradient option, set off to keep painting by the paint's own placement.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@2 => @3)]
|
||||
pub fn outline_v2(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(&OutlineV2, &contract());
|
||||
check_undo(&OutlineV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_contour_gradient_off() {
|
||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV2);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.push(literal(Tagged::Bool(false)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Node, migration};
|
||||
|
||||
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
|
||||
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let contract = SourceContract {
|
||||
display_names: &["Color Overlay"],
|
||||
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
|
||||
};
|
||||
check_commutation(&PaintOverlayFromColorOverlay, &contract);
|
||||
check_undo(&PaintOverlayFromColorOverlay, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
|
||||
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
|
||||
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
|
||||
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
BlendMode(BlendMode),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum BlendMode {
|
||||
Normal,
|
||||
}
|
||||
|
||||
/// 'Satin' gained a blend mode after its color, set to Normal to keep compositing the shading as before.
|
||||
#[migration("blending_nodes::effects::SatinNode"@1 => @2)]
|
||||
pub fn satin_v1(inputs: &mut Inputs) {
|
||||
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
}
|
||||
|
||||
#[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| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SatinV1, &contract());
|
||||
check_undo(&SatinV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
|
||||
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&SatinV1);
|
||||
let satin = fixture.add(decl!("blending_nodes::effects::SatinNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&SatinV1).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, satin), Some(decl!("blending_nodes::effects::SatinNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, satin), 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;
|
||||
@@ -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,15 +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() {
|
||||
self.export_dialog.artboards = document.artboard_names().into_iter().collect();
|
||||
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();
|
||||
@@ -130,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,
|
||||
}
|
||||
+158
@@ -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";
|
||||
@@ -131,26 +155,15 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let scale_description = match self.file_type {
|
||||
FileType::Pdf => "Resolution of the images of effects and other content PDF can't draw itself, where 1 is 300 DPI.",
|
||||
_ => "Size of the exported image relative to the document's size.",
|
||||
};
|
||||
let resolution = vec![
|
||||
TextLabel::new("Scale Factor")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(100))
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.scale_factor))
|
||||
.unit("")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.tooltip_label("Scale Factor")
|
||||
.tooltip_description(scale_description)
|
||||
.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(),
|
||||
@@ -160,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
|
||||
@@ -199,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);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
+220
-29
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -96,11 +96,6 @@ impl FileType {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the file holds vector content rather than an image of the export's area.
|
||||
pub fn is_vector(self) -> bool {
|
||||
matches!(self, FileType::Svg | FileType::Pdf)
|
||||
}
|
||||
|
||||
pub fn file_filter(self) -> FileFilter {
|
||||
let name = match self {
|
||||
FileType::Png => "PNG Image",
|
||||
@@ -137,7 +132,8 @@ impl FileType {
|
||||
FileType::Bmp => ImageFormat::Bmp,
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg | FileType::Pdf => return Err(format!("{} cannot be exported from an image buffer", self.extension().to_uppercase())),
|
||||
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());
|
||||
@@ -172,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),
|
||||
}
|
||||
|
||||
|
||||
@@ -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],
|
||||
])
|
||||
|
||||
@@ -25,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,
|
||||
@@ -33,7 +34,10 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowTechnique, Graphic};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode,
|
||||
};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -398,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>,
|
||||
@@ -458,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>,
|
||||
@@ -1097,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"
|
||||
@@ -1265,8 +1326,13 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1446,6 +1512,11 @@ macro_rules! known_item_types {
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -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;
|
||||
@@ -1694,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() {
|
||||
@@ -2445,12 +2456,15 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// The document's artboards with their names, called "Artboard" while left unnamed.
|
||||
/// 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())
|
||||
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(), &[]))
|
||||
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());
|
||||
@@ -3244,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 {
|
||||
@@ -5299,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,
|
||||
},
|
||||
|
||||
+2
-1
@@ -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};
|
||||
|
||||
@@ -886,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,16 +197,19 @@ 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)
|
||||
.expect("Text to Vector node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
@@ -213,13 +217,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
// Build the chain `Text -> Transform -> Fill -> layer`, keeping the text native so backends lay out and draw its glyphs
|
||||
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
|
||||
let text_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
let text_to_vector_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
@@ -722,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);
|
||||
@@ -864,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);
|
||||
@@ -876,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.
|
||||
@@ -887,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();
|
||||
@@ -925,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 {
|
||||
@@ -1013,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
|
||||
|
||||
@@ -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};
|
||||
@@ -242,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),
|
||||
],
|
||||
@@ -709,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();
|
||||
@@ -812,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.);
|
||||
@@ -872,6 +879,46 @@ fn static_input_inspector() -> InputInspector {
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
||||
"wrapping_range_slider".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
let field = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
|
||||
|
||||
let mut number_input = NumberInput::default().mode_increment();
|
||||
let mut period = None;
|
||||
if let Some(field) = field {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(display_decimal_places) = field.number_display_decimal_places {
|
||||
number_input = number_input.display_decimal_places(display_decimal_places);
|
||||
}
|
||||
if let Some(number_step) = field.number_step {
|
||||
number_input = number_input.step(number_step);
|
||||
}
|
||||
period = field.number_soft_min.zip(field.number_soft_max);
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let row = match period {
|
||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||
}
|
||||
_ => {
|
||||
log::error!("A wrapping range slider needs finite soft bounds at both ends");
|
||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||
}
|
||||
};
|
||||
Ok(vec![LayoutGroup::row(row)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
|
||||
"type_choice".to_string(),
|
||||
@@ -917,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(
|
||||
@@ -1185,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
|
||||
@@ -1242,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(
|
||||
@@ -1677,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;
|
||||
|
||||
|
||||
@@ -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::*;
|
||||
@@ -31,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,
|
||||
@@ -40,7 +42,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, GlowTechnique, Graphic, 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;
|
||||
@@ -268,10 +270,23 @@ impl SliderRange {
|
||||
fn value(self, position: f64) -> f64 {
|
||||
(self.min + position * (self.max - self.min)).clamp(self.min, self.max)
|
||||
}
|
||||
|
||||
/// The `value` moved into the bounds by whole periods of their width, for a periodic number like an angle.
|
||||
fn wrapped(self, value: f64) -> f64 {
|
||||
if (self.min..=self.max).contains(&value) {
|
||||
return value;
|
||||
}
|
||||
self.min + (value - self.min).rem_euclid(self.max - self.min)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
|
||||
let identifier = parameter_widgets_info
|
||||
.network_interface
|
||||
.reference(¶meter_widgets_info.node_id, parameter_widgets_info.selection_network_path)?;
|
||||
@@ -279,6 +294,7 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
|
||||
|
||||
match input.as_value()? {
|
||||
TaggedValue::Number(value) => Some(*value),
|
||||
TaggedValue::Angle(angle) => Some(angle.to_degrees()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -297,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();
|
||||
}
|
||||
@@ -329,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);
|
||||
|
||||
@@ -379,15 +396,20 @@ 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)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -442,6 +464,11 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<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::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().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(),
|
||||
@@ -882,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(¶meter_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.");
|
||||
@@ -898,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(),
|
||||
@@ -909,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(),
|
||||
@@ -924,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(),
|
||||
@@ -935,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(),
|
||||
@@ -1187,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
|
||||
@@ -1197,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));
|
||||
@@ -1297,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(¶meter_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(¶meter_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(¶meter_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(¶meter_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(¶meter_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(¶meter_widgets_info);
|
||||
@@ -1398,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)],
|
||||
@@ -2377,13 +2783,14 @@ fn value_slider(
|
||||
}
|
||||
|
||||
/// A row with a range slider and a 60px number input for the number at `parameter_widgets_info`. The slider's 0..1 position maps
|
||||
/// to the number through `position_of` and `value_at`, and double-click restores `default`.
|
||||
/// to the number through `position_of` and `value_at`, a typed number is stored as `typed_value` gives it, and double-click restores `default`.
|
||||
fn slider_row(
|
||||
parameter_widgets_info: ParameterWidgetsInfo,
|
||||
number_props: NumberInput,
|
||||
default: Option<f64>,
|
||||
position_of: impl Fn(f64) -> f64,
|
||||
value_at: impl Fn(f64) -> f64 + 'static + Send + Sync,
|
||||
typed_value: impl Fn(f64) -> f64 + 'static + Send + Sync,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
@@ -2416,7 +2823,7 @@ fn slider_row(
|
||||
number_props
|
||||
.value(Some(current))
|
||||
.sizing(WidgetSizing::fixed(60))
|
||||
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(x.value.unwrap_or_default()), node_id, index))
|
||||
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(typed_value(x.value.unwrap_or_default())), node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
@@ -2432,6 +2839,19 @@ pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo,
|
||||
slider.default,
|
||||
move |value| slider.position(value),
|
||||
move |position| slider.value(position),
|
||||
|value| value,
|
||||
)
|
||||
}
|
||||
|
||||
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
||||
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||
slider_row(
|
||||
parameter_widgets_info,
|
||||
number_props,
|
||||
slider.default,
|
||||
move |value| slider.position(slider.wrapped(value)),
|
||||
move |position| slider.value(position),
|
||||
move |value| slider.wrapped(value),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2756,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);
|
||||
}
|
||||
}
|
||||
@@ -2778,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)];
|
||||
|
||||
@@ -2797,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));
|
||||
|
||||
@@ -2856,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![
|
||||
@@ -2903,6 +3311,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
Some(1.),
|
||||
|gamma| MarkerScale::Gamma.position(gamma),
|
||||
|position| MarkerScale::Gamma.value(position),
|
||||
|gamma| gamma,
|
||||
);
|
||||
|
||||
vec![LayoutGroup::row(exposure), LayoutGroup::row(offset), LayoutGroup::row(gamma_correction)]
|
||||
@@ -3184,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());
|
||||
@@ -3258,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;
|
||||
}
|
||||
@@ -3686,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();
|
||||
@@ -3695,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,
|
||||
@@ -3715,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();
|
||||
|
||||
@@ -4002,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))
|
||||
}
|
||||
@@ -4027,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,
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -22,7 +22,6 @@ pub struct ResourceMessageHandler {
|
||||
pub embedded: EmbeddedResources,
|
||||
#[serde(skip)]
|
||||
pending_resolves: HashSet<ResourceId>,
|
||||
/// Resources that failed to load, which rendering no longer waits on, even during a retry.
|
||||
#[serde(skip)]
|
||||
failed_resolves: HashSet<ResourceId>,
|
||||
}
|
||||
@@ -219,8 +218,6 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
ResourceMessage::ResolveFailed { resource_id } => {
|
||||
self.pending_resolves.remove(&resource_id);
|
||||
self.failed_resolves.insert(resource_id);
|
||||
|
||||
// Rendering stops waiting on the resource and draws a fallback in its place
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
@@ -236,20 +233,6 @@ impl ResourceMessageHandler {
|
||||
self.registry.is_empty() && self.embedded.is_empty()
|
||||
}
|
||||
|
||||
/// Whether a resource lacks its data and hasn't failed to load, which rendering waits for.
|
||||
pub fn awaiting_resources(&self) -> bool {
|
||||
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
|
||||
}
|
||||
|
||||
/// Changes whenever a resource gains, loses, or changes its data. Summed per resource since the registry's order isn't stable. O(resolved resources).
|
||||
pub fn resolved_hash(&self) -> u64 {
|
||||
self.registry.resolved().fold(0, |sum, info| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(info.id, info.hash).hash(&mut hasher);
|
||||
sum.wrapping_add(hasher.finish())
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
|
||||
let embedded = self
|
||||
.registry
|
||||
@@ -275,6 +258,18 @@ impl ResourceMessageHandler {
|
||||
self.registry.delete(&id);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn awaiting_resources(&self) -> bool {
|
||||
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
|
||||
}
|
||||
|
||||
pub fn resolved_hash(&self) -> u64 {
|
||||
self.registry.resolved().fold(0, |sum, info| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(info.id, info.hash).hash(&mut hasher);
|
||||
sum.wrapping_add(hasher.finish())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
|
||||
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user