mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90d5c809cd | ||
|
|
995f6a1da6 | ||
|
|
5eace77e08 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
|
||||
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
|
||||
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
|
||||
Generated
+10
-174
@@ -1226,7 +1226,6 @@ dependencies = [
|
||||
"kurbo",
|
||||
"log",
|
||||
"lyon_geom",
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
@@ -1239,7 +1238,7 @@ dependencies = [
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"tinyvec",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
@@ -2136,9 +2135,6 @@ name = "float-cmp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fnv"
|
||||
@@ -2158,15 +2154,6 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5b38ad915f6dadd993ced50848a8291a543bd41ca62bc10740d5e64e2ab4cfd7"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "font-types"
|
||||
version = "0.12.7"
|
||||
@@ -2208,7 +2195,7 @@ dependencies = [
|
||||
"linebender_resource_handle",
|
||||
"memmap2",
|
||||
"parlance",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -2692,7 +2679,6 @@ dependencies = [
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
"reqwest",
|
||||
"svg-convert",
|
||||
"text-nodes",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
@@ -3052,7 +3038,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
@@ -3087,40 +3073,6 @@ 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"
|
||||
@@ -3474,12 +3426,6 @@ dependencies = [
|
||||
"quick-error",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09e54e57b4c48b40f7aec75635392b12b3421fa26fe8b4332e63138ed278459c"
|
||||
|
||||
[[package]]
|
||||
name = "imagesize"
|
||||
version = "0.15.0"
|
||||
@@ -3852,33 +3798,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "krilla"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27da593198b20eeba65caeb73c2bbeec3e53ab08fa549898312ce81c4fce5e33"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bumpalo",
|
||||
"flate2",
|
||||
"float-cmp",
|
||||
"gif",
|
||||
"image-webp",
|
||||
"imagesize 0.14.0",
|
||||
"indexmap",
|
||||
"pdf-writer",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
"smallvec",
|
||||
"subsetter",
|
||||
"tiny-skia-path",
|
||||
"xmp-writer",
|
||||
"yoke",
|
||||
"zune-jpeg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "kurbo"
|
||||
version = "0.13.1"
|
||||
@@ -5112,7 +5031,7 @@ dependencies = [
|
||||
"parlance",
|
||||
"parley_data",
|
||||
"parley_emoji",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5143,18 +5062,6 @@ dependencies = [
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pdf-writer"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"itoa",
|
||||
"memchr",
|
||||
"ryu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "peer-transport"
|
||||
version = "0.0.0"
|
||||
@@ -5957,16 +5864,6 @@ dependencies = [
|
||||
"yasna",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.39.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4ed38b89c2c77ff968c524145ad65fb010f38af5c7a224b53b81d47ac2daa81"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "read-fonts"
|
||||
version = "0.41.0"
|
||||
@@ -5974,7 +5871,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"font-types 0.12.7",
|
||||
"font-types",
|
||||
"once_cell",
|
||||
]
|
||||
|
||||
@@ -6120,15 +6017,13 @@ dependencies = [
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"hayro-syntax",
|
||||
"krilla",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
@@ -6706,12 +6601,6 @@ version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||
|
||||
[[package]]
|
||||
name = "ryu"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
||||
|
||||
[[package]]
|
||||
name = "same-file"
|
||||
version = "1.0.6"
|
||||
@@ -7073,16 +6962,6 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.42.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c34617370ae968efb7161bb2beb517d9084659aae19e24b89e3db25b46e4564"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "skrifa"
|
||||
version = "0.44.0"
|
||||
@@ -7090,7 +6969,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"read-fonts 0.41.0",
|
||||
"read-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7269,18 +7148,6 @@ version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "subsetter"
|
||||
version = "0.2.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "38803281d1c23166c5ebcb455439a5d2afe711cc909cf88af72448c297756ad6"
|
||||
dependencies = [
|
||||
"kurbo",
|
||||
"rustc-hash 2.1.3",
|
||||
"skrifa 0.42.1",
|
||||
"write-fonts",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "substring"
|
||||
version = "1.4.5"
|
||||
@@ -7296,18 +7163,6 @@ version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "svg-convert"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"usvg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "svgtypes"
|
||||
version = "0.16.2"
|
||||
@@ -7463,7 +7318,7 @@ dependencies = [
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"thiserror 2.0.21",
|
||||
"titlecase",
|
||||
"tsify",
|
||||
@@ -8063,14 +7918,14 @@ dependencies = [
|
||||
"flate2",
|
||||
"fontdb",
|
||||
"harfrust",
|
||||
"imagesize 0.15.0",
|
||||
"imagesize",
|
||||
"kurbo",
|
||||
"log",
|
||||
"pico-args",
|
||||
"roxmltree 0.21.2",
|
||||
"simplecss",
|
||||
"siphasher",
|
||||
"skrifa 0.44.0",
|
||||
"skrifa",
|
||||
"strict-num",
|
||||
"svgtypes",
|
||||
"tiny-skia-path",
|
||||
@@ -9413,19 +9268,6 @@ dependencies = [
|
||||
"toml 0.5.11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "write-fonts"
|
||||
version = "0.48.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cb731d4c4d93eacc69a1ad2f270f905788a98e4a3438267bcafbe08d3431c8d8"
|
||||
dependencies = [
|
||||
"font-types 0.11.3",
|
||||
"indexmap",
|
||||
"kurbo",
|
||||
"log",
|
||||
"read-fonts 0.39.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "writeable"
|
||||
version = "0.6.4"
|
||||
@@ -9566,12 +9408,6 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
|
||||
[[package]]
|
||||
name = "xmp-writer"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee"
|
||||
|
||||
[[package]]
|
||||
name = "yansi"
|
||||
version = "1.0.1"
|
||||
|
||||
@@ -99,7 +99,6 @@ graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
svg-convert = { path = "node-graph/libraries/svg-convert" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
blending-nodes = { path = "node-graph/nodes/blending" }
|
||||
graphene-core = { path = "node-graph/nodes/gcore" }
|
||||
@@ -223,8 +222,6 @@ 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 = [
|
||||
|
||||
Generated
BIN
Binary file not shown.
@@ -57,10 +57,6 @@ 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,12 +473,6 @@ 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,11 +52,9 @@ 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,8 +38,6 @@ 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
|
||||
@@ -80,11 +78,6 @@ 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,8 +382,7 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
|
||||
if !visited.insert(current) {
|
||||
return None;
|
||||
}
|
||||
// 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) {
|
||||
let (in_network, input) = match registry.removed_nodes.get(¤t) {
|
||||
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
|
||||
None => known.primary.get(¤t).cloned()?,
|
||||
};
|
||||
|
||||
@@ -1,238 +0,0 @@
|
||||
//! 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,12 +1,64 @@
|
||||
//! 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.
|
||||
//! 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.
|
||||
//!
|
||||
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
|
||||
|
||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
|
||||
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);
|
||||
@@ -24,124 +76,365 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
|
||||
}
|
||||
}
|
||||
|
||||
/// A single stack of layers off the export.
|
||||
struct Stack;
|
||||
fn on(id: NodeId) -> NodeInput {
|
||||
NodeInput::Node { id, index: 0 }
|
||||
}
|
||||
|
||||
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))));
|
||||
}
|
||||
ops
|
||||
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))));
|
||||
}
|
||||
// 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 {
|
||||
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: 1,
|
||||
new_input: value(random.below(100)),
|
||||
}]
|
||||
}
|
||||
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)),
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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");
|
||||
/// 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);
|
||||
}
|
||||
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:?})");
|
||||
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;
|
||||
}
|
||||
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 => {
|
||||
// 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");
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_operations_keep_the_stack_whole_and_peers_converged() {
|
||||
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
|
||||
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);
|
||||
for seed in 0..seeds {
|
||||
simulate::<Stack>(seed, steps, &mut Vec::new());
|
||||
simulate(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::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
|
||||
let histories = |seed| simulate(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}");
|
||||
}
|
||||
@@ -150,7 +443,9 @@ 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 host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
|
||||
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
|
||||
let host = simulate(seed, steps, &mut log);
|
||||
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
|
||||
}
|
||||
@@ -12,25 +12,9 @@ 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,33 +1033,6 @@ 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]
|
||||
|
||||
@@ -1,315 +0,0 @@
|
||||
//! 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,7 +417,6 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
||||
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
|
||||
export_names: attributes.get_or_default(network::EXPORT_NAMES),
|
||||
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
|
||||
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("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.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
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,14 +1,3 @@
|
||||
//! 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;
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// '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);
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DIAMETER: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The diameter is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("brush_nodes::BrushStrokesNode"@1 => @2)]
|
||||
pub fn brush_strokes_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DIAMETER) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DIAMETER as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BrushStrokesV1, &contract());
|
||||
check_undo(&BrushStrokesV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&BrushStrokesV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let brush_strokes = fixture.add(decl!("brush_nodes::BrushStrokesNode"@1), vec![literal(Tagged::None), number(0.), number(40.), number(0.), number(100.)]);
|
||||
let migrated = fixture.migrate(&BrushStrokesV1).unwrap();
|
||||
|
||||
let diameter = literal(Tagged::Length(TypedLength { value: 40., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, brush_strokes), [literal(Tagged::None), number(0.), diameter, number(0.), number(100.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
//! Migrations of the nodes in `brush_nodes`.
|
||||
|
||||
mod brush_strokes_v1;
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::BevelNode"@1 => @2)]
|
||||
pub fn bevel_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelV1, &contract());
|
||||
check_undo(&BevelV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&BevelV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let bevel = fixture.add(decl!("core_types::vector::BevelNode"@1), vec![literal(Tagged::None), number(10.)]);
|
||||
let migrated = fixture.migrate(&BevelV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), [literal(Tagged::None), distance]);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TOLERANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::DecimateNode"@1 => @2)]
|
||||
pub fn decimate_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
TOLERANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DecimateV1, &contract());
|
||||
check_undo(&DecimateV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&DecimateV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let decimate = fixture.add(decl!("core_types::vector::DecimateNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||
let migrated = fixture.migrate(&DecimateV1).unwrap();
|
||||
|
||||
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, decimate), [literal(Tagged::None), tolerance]);
|
||||
}
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DIRECTION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The direction is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::ExtrudeNode"@1 => @2)]
|
||||
pub fn extrude_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DIRECTION) else { return };
|
||||
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(DIRECTION as u32, lengths(pixels));
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ExtrudeV1, &contract());
|
||||
check_undo(&ExtrudeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&ExtrudeV1);
|
||||
let node = fixture.add(
|
||||
decl!("core_types::vector::ExtrudeNode"@1),
|
||||
vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.])), literal(Tagged::None)],
|
||||
);
|
||||
let migrated = fixture.migrate(&ExtrudeV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.]), literal(Tagged::None)]);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const MAX_DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The max distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::JitterPointsNode"@1 => @2)]
|
||||
pub fn jitter_points_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(MAX_DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
MAX_DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&JitterPointsV1, &contract());
|
||||
check_undo(&JitterPointsV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&JitterPointsV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let jitter_points = fixture.add(decl!("core_types::vector::JitterPointsNode"@1), vec![literal(Tagged::None), number(5.), number(0.), number(1.)]);
|
||||
let migrated = fixture.migrate(&JitterPointsV1).unwrap();
|
||||
|
||||
let max_distance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, jitter_points), [literal(Tagged::None), max_distance, number(0.), number(1.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
//! Migrations of the nodes in `core_types`.
|
||||
|
||||
mod bevel_v1;
|
||||
mod decimate_v1;
|
||||
mod extrude_v1;
|
||||
mod jitter_points_v1;
|
||||
mod offset_path_v1;
|
||||
mod offset_points_v1;
|
||||
mod point_inside_v1;
|
||||
mod round_corners_v1;
|
||||
mod sample_polyline_v1;
|
||||
mod scatter_points_v2;
|
||||
mod simplify_v1;
|
||||
mod weld_v1;
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::OffsetPathNode"@1 => @2)]
|
||||
pub fn offset_path_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OffsetPathV1, &contract());
|
||||
check_undo(&OffsetPathV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&OffsetPathV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let offset_path = fixture.add(decl!("core_types::vector::OffsetPathNode"@1), vec![literal(Tagged::None), number(10.), number(0.), number(4.)]);
|
||||
let migrated = fixture.migrate(&OffsetPathV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, offset_path), [literal(Tagged::None), distance, number(0.), number(4.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::OffsetPointsNode"@1 => @2)]
|
||||
pub fn offset_points_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OffsetPointsV1, &contract());
|
||||
check_undo(&OffsetPointsV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&OffsetPointsV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let offset_points = fixture.add(decl!("core_types::vector::OffsetPointsNode"@1), vec![literal(Tagged::None), number(10.)]);
|
||||
let migrated = fixture.migrate(&OffsetPointsV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, offset_points), [literal(Tagged::None), distance]);
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const POINT: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::PointInsideNode"@1 => @2)]
|
||||
pub fn point_inside_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(POINT) else { return };
|
||||
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(POINT as u32, lengths(pixels));
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| match slot {
|
||||
POINT => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PointInsideV1, &contract());
|
||||
check_undo(&PointInsideV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&PointInsideV1);
|
||||
let node = fixture.add(decl!("core_types::vector::PointInsideNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
|
||||
let migrated = fixture.migrate(&PointInsideV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
const MIN_ANGLE_THRESHOLD: usize = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The radius is a length and the minimum angle threshold is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("core_types::vector::RoundCornersNode"@1 => @2)]
|
||||
pub fn round_corners_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(RADIUS) {
|
||||
inputs.set(RADIUS as u32, length(pixels));
|
||||
}
|
||||
if let Some(degrees) = number_at(MIN_ANGLE_THRESHOLD) {
|
||||
inputs.set(MIN_ANGLE_THRESHOLD as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RoundCornersV1, &contract());
|
||||
check_undo(&RoundCornersV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
|
||||
let mut fixture = Fixture::new(&RoundCornersV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let round_corners = fixture.add(
|
||||
decl!("core_types::vector::RoundCornersNode"@1),
|
||||
vec![literal(Tagged::None), number(10.), number(0.5), number(100.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RoundCornersV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, round_corners), [literal(Tagged::None), length(10.), number(0.5), number(100.), angle(5.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SEPARATION: usize = 2;
|
||||
const START_OFFSET: usize = 4;
|
||||
const STOP_OFFSET: usize = 5;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The separation and start and stop offsets are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("core_types::vector::SamplePolylineNode"@1 => @2)]
|
||||
pub fn sample_polyline_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [SEPARATION, START_OFFSET, STOP_OFFSET] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SamplePolylineV1, &contract());
|
||||
check_undo(&SamplePolylineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&SamplePolylineV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let sample_polyline = fixture.add(
|
||||
decl!("core_types::vector::SamplePolylineNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(100.), number(100.), number(10.), number(20.), number(0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&SamplePolylineV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, sample_polyline),
|
||||
[literal(Tagged::None), number(0.), length(100.), number(100.), length(10.), length(20.), number(0.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SEPARATION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The separation is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::ScatterPointsNode"@2 => @3)]
|
||||
pub fn scatter_points_v2(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(SEPARATION) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
SEPARATION as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ScatterPointsV2, &contract());
|
||||
check_undo(&ScatterPointsV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&ScatterPointsV2);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let scatter_points = fixture.add(decl!("core_types::vector::ScatterPointsNode"@2), vec![literal(Tagged::None), number(10.), number(0.)]);
|
||||
let migrated = fixture.migrate(&ScatterPointsV2).unwrap();
|
||||
|
||||
let separation = literal(Tagged::Length(TypedLength { value: 10., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, scatter_points), [literal(Tagged::None), separation, number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TOLERANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The tolerance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::SimplifyNode"@1 => @2)]
|
||||
pub fn simplify_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(TOLERANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
TOLERANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SimplifyV1, &contract());
|
||||
check_undo(&SimplifyV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&SimplifyV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let simplify = fixture.add(decl!("core_types::vector::SimplifyNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||
let migrated = fixture.migrate(&SimplifyV1).unwrap();
|
||||
|
||||
let tolerance = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, simplify), [literal(Tagged::None), tolerance]);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DISTANCE: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The distance is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("core_types::vector::WeldNode"@1 => @2)]
|
||||
pub fn weld_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(DISTANCE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
DISTANCE as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&WeldV1, &contract());
|
||||
check_undo(&WeldV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&WeldV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let weld = fixture.add(decl!("core_types::vector::WeldNode"@1), vec![literal(Tagged::None), number(0.1), number(0.)]);
|
||||
let migrated = fixture.migrate(&WeldV1).unwrap();
|
||||
|
||||
let distance = literal(Tagged::Length(TypedLength { value: 0.1, unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, weld), [literal(Tagged::None), distance, number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod pack_strips_v1;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod stroke_v1;
|
||||
mod vary_colors_from_assign_colors;
|
||||
@@ -1,73 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SEPARATION: usize = 1;
|
||||
const STRIP_MAX_LENGTH: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The separation and strip max length are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("graphene_core::vector::PackStripsNode"@1 => @2)]
|
||||
pub fn pack_strips_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [SEPARATION, STRIP_MAX_LENGTH] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PackStripsV1, &contract());
|
||||
check_undo(&PackStripsV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&PackStripsV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let pack_strips = fixture.add(decl!("graphene_core::vector::PackStripsNode"@1), vec![literal(Tagged::None), number(10.), number(1000.), number(0.)]);
|
||||
let migrated = fixture.migrate(&PackStripsV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, pack_strips), [literal(Tagged::None), length(10.), length(1000.), number(0.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const WEIGHT: usize = 2;
|
||||
const DASH_OFFSET: usize = 8;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The weight and dash offset are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("graphene_core::vector::StrokeNode"@1 => @2)]
|
||||
pub fn stroke_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [WEIGHT, DASH_OFFSET] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(9, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&StrokeV1, &contract());
|
||||
check_undo(&StrokeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&StrokeV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let stroke = fixture.add(
|
||||
decl!("graphene_core::vector::StrokeNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(2.), number(0.), number(0.), number(0.), number(4.), number(0.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&StrokeV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, stroke),
|
||||
[literal(Tagged::None), number(0.), length(2.), number(0.), number(0.), number(0.), number(4.), number(0.), length(5.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod rasterize_v1;
|
||||
mod renames;
|
||||
mod text_v1;
|
||||
@@ -0,0 +1,68 @@
|
||||
use migration_core::{Inputs, MigrationError, NodeInput, migration};
|
||||
use serde::Serialize;
|
||||
|
||||
const EXECUTOR: u32 = 2;
|
||||
const EXECUTOR_SCOPE: &str = "graphene_std::platform_application_io::WgpuExecutorNode";
|
||||
|
||||
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
|
||||
#[derive(Serialize)]
|
||||
enum Reflected {
|
||||
DocumentNodePath,
|
||||
}
|
||||
|
||||
/// Rasterize gained an input holding its own document node path. Nodes stored without the executor input get it first, so the path lands after it.
|
||||
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||
pub fn rasterize_v1(inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
if inputs.len() < EXECUTOR as usize {
|
||||
return Err(MigrationError::invariant("Rasterize has Data and Footprint inputs"));
|
||||
}
|
||||
if inputs.len() == EXECUTOR as usize {
|
||||
inputs.push(NodeInput::Scope(EXECUTOR_SCOPE.into()));
|
||||
}
|
||||
|
||||
inputs.push_reflection(Reflected::DocumentNodePath);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
fn migrate(inputs: Vec<NodeInput>) -> Vec<NodeInput> {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(decl!("graphene_std::platform_application_io::RasterizeNode"@1), inputs);
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let own_path = &migrated.node_instances[&rasterize].inputs()[3];
|
||||
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
|
||||
|
||||
fixture.inputs(&migrated, rasterize)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RasterizeV1, &contract());
|
||||
check_undo(&RasterizeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gives_the_node_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.), NodeInput::Scope(EXECUTOR_SCOPE.into())];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Reflection]].concat());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_node_stored_without_its_executor_gets_it_before_its_path() {
|
||||
let inputs = vec![literal(1.), literal(2.)];
|
||||
|
||||
assert_eq!(migrate(inputs.clone()), [inputs, vec![NodeInput::Scope(EXECUTOR_SCOPE.into()), NodeInput::Reflection]].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SIZE: usize = 3;
|
||||
const LETTER_SPACING: usize = 5;
|
||||
const LETTER_TILT: usize = 6;
|
||||
const MAX_WIDTH: usize = 8;
|
||||
const MAX_HEIGHT: usize = 10;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The size, letter spacing, and max sizes are lengths and the letter tilt is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("graphene_std::text::TextNode"@1 => @2)]
|
||||
pub fn text_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [SIZE, LETTER_SPACING, MAX_WIDTH, MAX_HEIGHT] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
if let Some(degrees) = number_at(LETTER_TILT) {
|
||||
inputs.set(LETTER_TILT as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(12, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&TextV1, &contract());
|
||||
check_undo(&TextV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_lengths_and_an_angle() {
|
||||
let mut fixture = Fixture::new(&TextV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let text = fixture.add(
|
||||
decl!("graphene_std::text::TextNode"@1),
|
||||
vec![
|
||||
literal(Tagged::None),
|
||||
number(0.),
|
||||
number(0.),
|
||||
number(24.),
|
||||
number(1.2),
|
||||
number(2.),
|
||||
number(10.),
|
||||
number(0.),
|
||||
number(100.),
|
||||
number(0.),
|
||||
number(100.),
|
||||
number(0.),
|
||||
],
|
||||
);
|
||||
let migrated = fixture.migrate(&TextV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, text),
|
||||
[
|
||||
literal(Tagged::None),
|
||||
number(0.),
|
||||
number(0.),
|
||||
length(24.),
|
||||
number(1.2),
|
||||
length(2.),
|
||||
angle(10.),
|
||||
number(0.),
|
||||
length(100.),
|
||||
number(0.),
|
||||
length(100.),
|
||||
number(0.)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const LOCATION: usize = 1;
|
||||
const DIMENSIONS: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The location and dimensions are pairs of lengths, which keep the pixels they held. Wired Vec2s still feed them, read as pixels.
|
||||
#[migration("graphic_nodes::artboard::CreateArtboardNode"@1 => @2)]
|
||||
pub fn create_artboard_v1(node: &Node, inputs: &mut Inputs) {
|
||||
for slot in [LOCATION, DIMENSIONS] {
|
||||
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
inputs.set(slot as u32, lengths(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
LOCATION | DIMENSIONS => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&CreateArtboardV1, &contract());
|
||||
check_undo(&CreateArtboardV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vec2s_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&CreateArtboardV1);
|
||||
let none = || literal(Tagged::None);
|
||||
let artboard = fixture.add(
|
||||
decl!("graphic_nodes::artboard::CreateArtboardNode"@1),
|
||||
vec![none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([1920., 1080.])), none(), none()],
|
||||
);
|
||||
let migrated = fixture.migrate(&CreateArtboardV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, artboard), [none(), lengths([10., 20.]), lengths([1920., 1080.]), none(), none()]);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const OFFSET: usize = 2;
|
||||
const ANGLE: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The offset is a length and the angle is an angle, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("graphic_nodes::graphic::MirrorNode"@1 => @2)]
|
||||
pub fn mirror_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(OFFSET) {
|
||||
inputs.set(OFFSET as u32, length(pixels));
|
||||
}
|
||||
if let Some(degrees) = number_at(ANGLE) {
|
||||
inputs.set(ANGLE as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MirrorV1, &contract());
|
||||
check_undo(&MirrorV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_a_length_and_an_angle() {
|
||||
let mut fixture = Fixture::new(&MirrorV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let mirror = fixture.add(
|
||||
decl!("graphic_nodes::graphic::MirrorNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(20.), number(45.), number(1.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&MirrorV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, mirror), [literal(Tagged::None), number(0.), length(20.), angle(45.), number(1.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
//! Migrations of the nodes in `graphic_nodes`.
|
||||
|
||||
mod create_artboard_v1;
|
||||
mod mirror_v1;
|
||||
@@ -2,13 +2,8 @@
|
||||
//! `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;
|
||||
@@ -1,47 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, migration};
|
||||
|
||||
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||
#[migration("math_nodes::MathFormulaNode"@2 => @3)]
|
||||
pub fn math_formula_v2(inputs: &mut Inputs) {
|
||||
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
1 => literal(Tagged::String("a + b".to_string())),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFormulaV2, &contract());
|
||||
check_undo(&MathFormulaV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolution_is_read_from_the_scope() {
|
||||
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("a * 2".to_string())), literal(Tagged::Number(0.))];
|
||||
|
||||
let mut fixture = Fixture::new(&MathFormulaV2);
|
||||
let formula = fixture.add(decl!("math_nodes::MathFormulaNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&MathFormulaV2).unwrap();
|
||||
|
||||
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||
assert_eq!(fixture.inputs(&migrated, formula), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
use migration_core::{Inputs, NodeInput, migration};
|
||||
|
||||
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
|
||||
pub fn math_function_v2(inputs: &mut Inputs) {
|
||||
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
String(String),
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
1 => literal(Tagged::String("x".to_string())),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFunctionV2, &contract());
|
||||
check_undo(&MathFunctionV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_resolution_is_read_from_the_scope() {
|
||||
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
|
||||
|
||||
let mut fixture = Fixture::new(&MathFunctionV2);
|
||||
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
|
||||
|
||||
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||
assert_eq!(fixture.inputs(&migrated, function), expected);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod math_formula_from_math_f;
|
||||
mod math_formula_v2;
|
||||
mod math_function_v2;
|
||||
mod renames;
|
||||
@@ -3,21 +3,3 @@
|
||||
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);
|
||||
@@ -1,131 +0,0 @@
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, Inputs, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
DVec2([f64; 2]),
|
||||
MandelbrotFractal(MandelbrotFractal),
|
||||
MandelbrotExterior(MandelbrotExterior),
|
||||
MandelbrotInterior(MandelbrotInterior),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotFractal {
|
||||
ClassicMandelbrot,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotExterior {
|
||||
SmoothEscape,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum MandelbrotInterior {
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// How far the old unit square, which spanned the complex plane from -2 to 1, placed the plane's origin from the pattern's.
|
||||
const OLD_ORIGIN: [f64; 2] = [2. / 3., 0.5];
|
||||
|
||||
/// 'Mandelbrot' gained a scale and settings for its fractal, its slice toward the Julia set, and its interior and exterior, and the complex plane's origin moved to the pattern's.
|
||||
/// A third of a unit's scale and a Transform moving the pattern back to the old origin keep its look.
|
||||
#[migration("raster_nodes::std_nodes::MandelbrotNode"@2 => @3)]
|
||||
pub fn mandelbrot_v2(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
for input in new_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let origin = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
inputs: vec![
|
||||
NodeInput::Node { id: node.id(), index: 0 },
|
||||
literal(Tagged::DVec2(OLD_ORIGIN)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::DVec2([1., 1.])),
|
||||
literal(Tagged::DVec2([0., 0.])),
|
||||
],
|
||||
},
|
||||
"origin",
|
||||
);
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: origin, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// The Transform takes the pattern's place, with the pattern before it
|
||||
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
|
||||
attributes.set(origin, POSITION, &stored);
|
||||
}
|
||||
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
|
||||
}
|
||||
|
||||
/// The settings 'Mandelbrot' gained, in the order of its parameters, with the scale matching the old unit square's three units of the plane.
|
||||
fn new_inputs() -> [NodeInput; 10] {
|
||||
[
|
||||
literal(Tagged::MandelbrotFractal(MandelbrotFractal::ClassicMandelbrot)),
|
||||
literal(Tagged::MandelbrotExterior(MandelbrotExterior::SmoothEscape)),
|
||||
literal(Tagged::MandelbrotInterior(MandelbrotInterior::Flat)),
|
||||
literal(Tagged::Integer(1)),
|
||||
literal(Tagged::Number(1. / 3.)),
|
||||
literal(Tagged::Integer(256)),
|
||||
literal(Tagged::Number(2.)),
|
||||
literal(Tagged::Number(0.)),
|
||||
literal(Tagged::DVec2([0., 0.])),
|
||||
literal(Tagged::DVec2([-0.8, 0.156])),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(1, |_, _| literal(Tagged::None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MandelbrotV2, &contract());
|
||||
check_undo(&MandelbrotV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_primary_input_and_adds_the_settings() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV2);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
|
||||
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
|
||||
|
||||
let mut expected = vec![literal(Tagged::None)];
|
||||
expected.extend(new_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, mandelbrot), Some(decl!("raster_nodes::std_nodes::MandelbrotNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, mandelbrot), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn whatever_read_the_pattern_reads_it_moved_back_to_the_old_origin() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV2);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@2), vec![literal(Tagged::None)]);
|
||||
let consumer = fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]);
|
||||
let migrated = fixture.migrate(&MandelbrotV2).unwrap();
|
||||
|
||||
let NodeInput::Node { id: origin, .. } = fixture.inputs(&migrated, consumer)[0] else {
|
||||
panic!("the consumer should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, origin), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
|
||||
|
||||
let inputs = fixture.inputs(&migrated, origin);
|
||||
assert_eq!(inputs[0], NodeInput::Node { id: mandelbrot, index: 0 });
|
||||
assert_eq!(inputs[1], literal(Tagged::DVec2(OLD_ORIGIN)));
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
|
||||
pub fn median_filter_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MedianFilterV1, &contract());
|
||||
check_undo(&MedianFilterV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&MedianFilterV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let median_filter = fixture.add(decl!("raster_nodes::filter::MedianFilterNode"@1), vec![literal(Tagged::None), number(5.)]);
|
||||
let migrated = fixture.migrate(&MedianFilterV1).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 5., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, median_filter), [literal(Tagged::None), radius]);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mandelbrot_v2;
|
||||
mod median_filter_v1;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
//! Migrations of the nodes in `repeat_nodes`.
|
||||
|
||||
mod repeat_array_v1;
|
||||
mod repeat_radial_v1;
|
||||
@@ -1,98 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const DIRECTION: usize = 1;
|
||||
const ANGLE: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
Angle(TypedAngle),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The direction is a pair of lengths and the angle is an angle, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||
#[migration("repeat_nodes::repeat_nodes::RepeatArrayNode"@1 => @2)]
|
||||
pub fn repeat_array_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||
|
||||
if let Some(Tagged::DVec2(pixels)) = literal_at(DIRECTION) {
|
||||
inputs.set(DIRECTION as u32, direction(pixels));
|
||||
}
|
||||
if let Some(Tagged::Number(degrees)) = literal_at(ANGLE) {
|
||||
inputs.set(ANGLE as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn direction(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| match slot {
|
||||
0 => literal(Tagged::None),
|
||||
DIRECTION => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::Number(random.below(100) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RepeatArrayV1, &contract());
|
||||
check_undo(&RepeatArrayV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
|
||||
let mut fixture = Fixture::new(&RepeatArrayV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let repeat_array = fixture.add(
|
||||
decl!("repeat_nodes::repeat_nodes::RepeatArrayNode"@1),
|
||||
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 50.])), number(90.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RepeatArrayV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, repeat_array), [literal(Tagged::None), direction([100., 50.]), angle(90.), number(5.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,96 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const START_ANGLE: usize = 1;
|
||||
const RADIUS: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The start angle is an angle and the radius is a length, which keep the numbers of degrees and pixels they held. Wired numbers still feed them, read as degrees and pixels.
|
||||
#[migration("repeat_nodes::repeat_nodes::RepeatRadialNode"@1 => @2)]
|
||||
pub fn repeat_radial_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(RADIUS) {
|
||||
inputs.set(RADIUS as u32, length(pixels));
|
||||
}
|
||||
if let Some(degrees) = number_at(START_ANGLE) {
|
||||
inputs.set(START_ANGLE as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RepeatRadialV1, &contract());
|
||||
check_undo(&RepeatRadialV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_degrees_and_pixels_become_an_angle_and_a_length() {
|
||||
let mut fixture = Fixture::new(&RepeatRadialV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let repeat_radial = fixture.add(
|
||||
decl!("repeat_nodes::repeat_nodes::RepeatRadialNode"@1),
|
||||
vec![literal(Tagged::None), number(45.), number(5.), number(5.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RepeatRadialV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, repeat_radial), [literal(Tagged::None), angle(45.), length(5.), number(5.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
//! Migrations of the nodes in `transform_nodes`.
|
||||
|
||||
mod transform_v1;
|
||||
mod vary_rotations_v2;
|
||||
@@ -1,125 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TRANSLATION: usize = 1;
|
||||
const ROTATION: usize = 2;
|
||||
const SKEW: usize = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
Angle(TypedAngle),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
AngleVec2(TypedAngleVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngleVec2 {
|
||||
value: [f64; 2],
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The translation is a pair of lengths and the rotation and skew are angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||
#[migration("transform_nodes::transform_nodes::TransformNode"@1 => @2)]
|
||||
pub fn transform_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||
|
||||
if let Some(Tagged::DVec2(pixels)) = literal_at(TRANSLATION) {
|
||||
inputs.set(TRANSLATION as u32, translation(pixels));
|
||||
}
|
||||
if let Some(Tagged::Number(degrees)) = literal_at(ROTATION) {
|
||||
inputs.set(ROTATION as u32, rotation(degrees));
|
||||
}
|
||||
if let Some(Tagged::DVec2(degrees)) = literal_at(SKEW) {
|
||||
inputs.set(SKEW as u32, skew(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole-list counterpart of the Transform node, with parameters that migrate the same way.
|
||||
#[migration("transform_nodes::transform_nodes::TransformListNode"@1 => @2)]
|
||||
pub fn transform_list_v1(node: &Node, inputs: &mut Inputs) {
|
||||
transform_v1(node, inputs);
|
||||
}
|
||||
|
||||
fn translation(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn rotation(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
fn skew(degrees: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::AngleVec2(TypedAngleVec2 {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
0 => literal(Tagged::None),
|
||||
ROTATION => literal(Tagged::Number(random.below(360) as f64)),
|
||||
_ => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&TransformV1, &contract());
|
||||
check_undo(&TransformV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_and_degrees_become_typed_lengths_and_angles() {
|
||||
let mut fixture = Fixture::new(&TransformV1);
|
||||
let vec2 = |x: f64, y: f64| literal(Tagged::DVec2([x, y]));
|
||||
let transform = fixture.add(
|
||||
decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
vec![literal(Tagged::None), vec2(10., 20.), literal(Tagged::Number(45.)), vec2(2., 3.), vec2(15., 0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&TransformV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, transform),
|
||||
[literal(Tagged::None), translation([10., 20.]), rotation(45.), vec2(2., 3.), skew([15., 0.])]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const MIN: usize = 1;
|
||||
const MAX: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The ends of the range are angles, which keep the numbers of degrees they held. Wired numbers still feed them, read as degrees.
|
||||
#[migration("transform_nodes::transform_nodes::VaryRotationsNode"@2 => @3)]
|
||||
pub fn vary_rotations_v2(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [MIN, MAX] {
|
||||
if let Some(degrees) = number_at(slot) {
|
||||
inputs.set(slot as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&VaryRotationsV2, &contract());
|
||||
check_undo(&VaryRotationsV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_degrees_become_angles_in_degrees() {
|
||||
let mut fixture = Fixture::new(&VaryRotationsV2);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let vary_rotations = fixture.add(
|
||||
decl!("transform_nodes::transform_nodes::VaryRotationsNode"@2),
|
||||
vec![literal(Tagged::None), number(-180.), number(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&VaryRotationsV2).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, vary_rotations),
|
||||
[literal(Tagged::None), angle(-180.), angle(180.), number(0.5), number(0.), number(1.), number(0.), number(0.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
const START_ANGLE: usize = 2;
|
||||
const SWEEP_ANGLE: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The radius is a length and the start and sweep angles are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("vector_nodes::generator_nodes::ArcNode"@1 => @2)]
|
||||
pub fn arc_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(pixels) = number_at(RADIUS) {
|
||||
inputs.set(RADIUS as u32, length(pixels));
|
||||
}
|
||||
for slot in [START_ANGLE, SWEEP_ANGLE] {
|
||||
if let Some(degrees) = number_at(slot) {
|
||||
inputs.set(slot as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ArcV1, &contract());
|
||||
check_undo(&ArcV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_a_length_and_angles() {
|
||||
let mut fixture = Fixture::new(&ArcV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let arc = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::ArcNode"@1),
|
||||
vec![literal(Tagged::None), number(50.), number(0.), number(270.), number(1.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&ArcV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, arc), [literal(Tagged::None), length(50.), angle(0.), angle(270.), number(1.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const ARROW_TO: usize = 1;
|
||||
const SHAFT_WIDTH: usize = 2;
|
||||
const HEAD_WIDTH: usize = 3;
|
||||
const HEAD_LENGTH: usize = 4;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
Length(TypedLength),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The end point is a pair of lengths and the shaft and head sizes are lengths, which keep the pixels they held. Wired values still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::ArrowNode"@1 => @2)]
|
||||
pub fn arrow_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
if let Some(Tagged::DVec2(pixels)) = node.inputs().get(ARROW_TO).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
inputs.set(ARROW_TO as u32, lengths(pixels));
|
||||
}
|
||||
for slot in [SHAFT_WIDTH, HEAD_WIDTH, HEAD_LENGTH] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
0 => literal(Tagged::None),
|
||||
ARROW_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::Number(random.below(100) as f64)),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ArrowV1, &contract());
|
||||
check_undo(&ArrowV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&ArrowV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let arrow = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::ArrowNode"@1),
|
||||
vec![literal(Tagged::None), literal(Tagged::DVec2([100., 0.])), number(10.), number(30.), number(20.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&ArrowV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, arrow), [literal(Tagged::None), lengths([100., 0.]), length(10.), length(30.), length(20.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
|
||||
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&CircleV1, &contract());
|
||||
check_undo(&CircleV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&CircleV1);
|
||||
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
|
||||
let migrated = fixture.migrate(&CircleV1).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS_X: usize = 1;
|
||||
const RADIUS_Y: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::EllipseNode"@1 => @2)]
|
||||
pub fn ellipse_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [RADIUS_X, RADIUS_Y] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&EllipseV1, &contract());
|
||||
check_undo(&EllipseV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&EllipseV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let ellipse = fixture.add(decl!("vector_nodes::generator_nodes::EllipseNode"@1), vec![literal(Tagged::None), number(50.), number(25.)]);
|
||||
let migrated = fixture.migrate(&EllipseV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, ellipse), [literal(Tagged::None), length(50.), length(25.)]);
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SPACING: usize = 6;
|
||||
const ANGLES: usize = 7;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
AngleVec2(TypedAngleVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngleVec2 {
|
||||
value: [f64; 2],
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The spacing is a pair of lengths, filled from one number in both axes, and the isometric angles are a pair of angles, which keep the pixels and degrees they held. Wired values still feed them, read in those units.
|
||||
#[migration("vector_nodes::generator_nodes::GridNode"@1 => @2)]
|
||||
pub fn grid_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let literal_at = |slot: usize| node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input));
|
||||
|
||||
match literal_at(SPACING) {
|
||||
Some(Tagged::Number(pixels)) => inputs.set(SPACING as u32, lengths([pixels, pixels])),
|
||||
Some(Tagged::DVec2(pixels)) => inputs.set(SPACING as u32, lengths(pixels)),
|
||||
_ => {}
|
||||
}
|
||||
if let Some(Tagged::DVec2(degrees)) = literal_at(ANGLES) {
|
||||
inputs.set(ANGLES as u32, angles(degrees));
|
||||
}
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angles(degrees: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::AngleVec2(TypedAngleVec2 {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, slot| match slot {
|
||||
SPACING if random.below(2) == 0 => literal(Tagged::Number(random.below(100) as f64)),
|
||||
SPACING | ANGLES => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GridV1, &contract());
|
||||
check_undo(&GridV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixels_and_degrees_become_typed_lengths_and_angles() {
|
||||
let mut fixture = Fixture::new(&GridV1);
|
||||
let none = || literal(Tagged::None);
|
||||
let square = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::GridNode"@1),
|
||||
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::Number(10.)), literal(Tagged::DVec2([30., 30.]))],
|
||||
);
|
||||
let rectangular = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::GridNode"@1),
|
||||
vec![none(), none(), none(), none(), none(), none(), literal(Tagged::DVec2([10., 20.])), literal(Tagged::DVec2([30., 60.]))],
|
||||
);
|
||||
let migrated = fixture.migrate(&GridV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, square),
|
||||
[none(), none(), none(), none(), none(), none(), lengths([10., 10.]), angles([30., 30.])]
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, rectangular),
|
||||
[none(), none(), none(), none(), none(), none(), lengths([10., 20.]), angles([30., 60.])]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const TIP_ANGLE: usize = 6;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The tip angle is an angle, which keeps the number of degrees it held. A wired number still feeds it, read as degrees.
|
||||
#[migration("vector_nodes::generator_nodes::HeartNode"@1 => @2)]
|
||||
pub fn heart_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(TIP_ANGLE) else { return };
|
||||
let Some(Tagged::Number(degrees)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
TIP_ANGLE as u32,
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&HeartV1, &contract());
|
||||
check_undo(&HeartV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_degrees_becomes_an_angle_in_degrees() {
|
||||
let mut fixture = Fixture::new(&HeartV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let heart = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::HeartNode"@1),
|
||||
vec![literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), number(75.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&HeartV1).unwrap();
|
||||
|
||||
let tip_angle = literal(Tagged::Angle(TypedAngle { value: 75., unit: AngleUnit::Degree }));
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, heart),
|
||||
[literal(Tagged::None), number(70.), number(0.), number(0.), number(70.), number(50.), tip_angle]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const LINE_TO: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
DVec2([f64; 2]),
|
||||
LengthVec2(TypedLengthVec2),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLengthVec2 {
|
||||
value: [f64; 2],
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The end point is a pair of lengths, which keeps the pixels it held. A wired Vec2 still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::LineNode"@1 => @2)]
|
||||
pub fn line_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(LINE_TO) else { return };
|
||||
let Some(Tagged::DVec2(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(LINE_TO as u32, lengths(pixels));
|
||||
}
|
||||
|
||||
fn lengths(pixels: [f64; 2]) -> NodeInput {
|
||||
literal(Tagged::LengthVec2(TypedLengthVec2 {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, slot| match slot {
|
||||
LINE_TO => literal(Tagged::DVec2([random.below(100) as f64, random.below(100) as f64])),
|
||||
_ => literal(Tagged::None),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&LineV1, &contract());
|
||||
check_undo(&LineV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_vec2_of_pixels_becomes_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&LineV1);
|
||||
let node = fixture.add(decl!("vector_nodes::generator_nodes::LineNode"@1), vec![literal(Tagged::None), literal(Tagged::DVec2([30., 40.]))]);
|
||||
let migrated = fixture.migrate(&LineV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, node), [literal(Tagged::None), lengths([30., 40.])]);
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,4 @@
|
||||
//! Migrations of the nodes in `vector_nodes`.
|
||||
|
||||
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;
|
||||
@@ -1,69 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const SIZE: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The size is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::QrCodeNode"@1 => @2)]
|
||||
pub fn qr_code_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(SIZE) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(SIZE as u32, length(pixels));
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, slot| if slot == SIZE { literal(Tagged::Number(random.below(100) as f64)) } else { literal(Tagged::None) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&QrCodeV1, &contract());
|
||||
check_undo(&QrCodeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&QrCodeV1);
|
||||
let none = || literal(Tagged::None);
|
||||
let qr_code = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::QrCodeNode"@1),
|
||||
vec![none(), none(), none(), literal(Tagged::Number(200.)), none(), none()],
|
||||
);
|
||||
let migrated = fixture.migrate(&QrCodeV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, qr_code), [none(), none(), none(), length(200.), none(), none()]);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const WIDTH: usize = 1;
|
||||
const HEIGHT: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The width and height are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::RectangleNode"@1 => @2)]
|
||||
pub fn rectangle_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [WIDTH, HEIGHT] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RectangleV1, &contract());
|
||||
check_undo(&RectangleV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&RectangleV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let rectangle = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
vec![literal(Tagged::None), number(100.), number(80.), number(0.), number(1.), number(0.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&RectangleV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, rectangle),
|
||||
[literal(Tagged::None), length(100.), length(80.), number(0.), number(1.), number(0.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS: usize = 2;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::RegularPolygonNode"@1 => @2)]
|
||||
pub fn regular_polygon_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
inputs.set(
|
||||
RADIUS as u32,
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RegularPolygonV1, &contract());
|
||||
check_undo(&RegularPolygonV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||
let mut fixture = Fixture::new(&RegularPolygonV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let polygon = fixture.add(decl!("vector_nodes::generator_nodes::RegularPolygonNode"@1), vec![literal(Tagged::None), number(6.), number(50.)]);
|
||||
let migrated = fixture.migrate(&RegularPolygonV1).unwrap();
|
||||
|
||||
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||
assert_eq!(fixture.inputs(&migrated, polygon), [literal(Tagged::None), number(6.), radius]);
|
||||
}
|
||||
}
|
||||
@@ -6,5 +6,3 @@ rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_n
|
||||
// Version 2 only adds `InjectFootprint` to the context bounds, so stored nodes keep their layout
|
||||
rename!("core_types::vector::AreaNode"@1 => @2);
|
||||
rename!("core_types::vector::CentroidNode"@1 => @2);
|
||||
// Version 2 only lets its output carry an error, so stored nodes keep their layout
|
||||
rename!("core_types::vector::ScatterPointsNode"@1 => @2);
|
||||
@@ -1,105 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const START_ANGLE: usize = 3;
|
||||
const INNER_RADIUS: usize = 4;
|
||||
const OUTER_RADIUS: usize = 5;
|
||||
const ANGULAR_RESOLUTION: usize = 6;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
Angle(TypedAngle),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedAngle {
|
||||
value: f64,
|
||||
unit: AngleUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum AngleUnit {
|
||||
Degree,
|
||||
}
|
||||
|
||||
/// The radii are lengths and the start angle and angular resolution are angles, which keep the numbers of pixels and degrees they held. Wired numbers still feed them, read as pixels and degrees.
|
||||
#[migration("vector_nodes::generator_nodes::SpiralNode"@1 => @2)]
|
||||
pub fn spiral_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [INNER_RADIUS, OUTER_RADIUS] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
for slot in [START_ANGLE, ANGULAR_RESOLUTION] {
|
||||
if let Some(degrees) = number_at(slot) {
|
||||
inputs.set(slot as u32, angle(degrees));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle(degrees: f64) -> NodeInput {
|
||||
literal(Tagged::Angle(TypedAngle {
|
||||
value: degrees,
|
||||
unit: AngleUnit::Degree,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SpiralV1, &contract());
|
||||
check_undo(&SpiralV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_and_degrees_become_lengths_and_angles() {
|
||||
let mut fixture = Fixture::new(&SpiralV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let spiral = fixture.add(
|
||||
decl!("vector_nodes::generator_nodes::SpiralNode"@1),
|
||||
vec![literal(Tagged::None), number(0.), number(5.), number(0.), number(0.), number(25.), number(90.)],
|
||||
);
|
||||
let migrated = fixture.migrate(&SpiralV1).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fixture.inputs(&migrated, spiral),
|
||||
[literal(Tagged::None), number(0.), number(5.), angle(0.), length(0.), length(25.), angle(90.)]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
use migration_core::{Inputs, Node, NodeInput, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const RADIUS_1: usize = 2;
|
||||
const RADIUS_2: usize = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Length(TypedLength),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypedLength {
|
||||
value: f64,
|
||||
unit: LengthUnit,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum LengthUnit {
|
||||
Pixel,
|
||||
}
|
||||
|
||||
/// The radii are lengths, which keep the numbers of pixels they held. Wired numbers still feed them, read as pixels.
|
||||
#[migration("vector_nodes::generator_nodes::StarNode"@1 => @2)]
|
||||
pub fn star_v1(node: &Node, inputs: &mut Inputs) {
|
||||
let number_at = |slot: usize| match node.inputs().get(slot).and_then(|slot| literal_of::<Tagged>(&slot.input)) {
|
||||
Some(Tagged::Number(number)) => Some(number),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
for slot in [RADIUS_1, RADIUS_2] {
|
||||
if let Some(pixels) = number_at(slot) {
|
||||
inputs.set(slot as u32, length(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn length(pixels: f64) -> NodeInput {
|
||||
literal(Tagged::Length(TypedLength {
|
||||
value: pixels,
|
||||
unit: LengthUnit::Pixel,
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&StarV1, &contract());
|
||||
check_undo(&StarV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_of_pixels_become_lengths_in_pixels() {
|
||||
let mut fixture = Fixture::new(&StarV1);
|
||||
let number = |number: f64| literal(Tagged::Number(number));
|
||||
let star = fixture.add(decl!("vector_nodes::generator_nodes::StarNode"@1), vec![literal(Tagged::None), number(5.), number(50.), number(25.)]);
|
||||
let migrated = fixture.migrate(&StarV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, star), [literal(Tagged::None), number(5.), length(50.), length(25.)]);
|
||||
}
|
||||
}
|
||||
@@ -18,8 +18,7 @@ pub const NODE_GLIDE_TIME_CONSTANT_MILLISECONDS: f64 = 30.;
|
||||
pub const VIEWPORT_ZOOM_WHEEL_RATE: f64 = (1. / 600.) * 3.;
|
||||
pub const VIEWPORT_ZOOM_MOUSE_RATE: f64 = 1. / 400.;
|
||||
pub const VIEWPORT_ZOOM_SCALE_MIN: f64 = 0.000_000_1;
|
||||
/// Deep enough to reach the limits of 64-bit precision, which still places each pixel precisely around document coordinates in the thousands.
|
||||
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000_000_000.;
|
||||
pub const VIEWPORT_ZOOM_SCALE_MAX: f64 = 10_000.;
|
||||
pub const VIEWPORT_ZOOM_MIN_FRACTION_COVER: f64 = 0.01;
|
||||
pub const VIEWPORT_ZOOM_LEVELS: [f64; 74] = [
|
||||
0.0001, 0.000125, 0.00016, 0.0002, 0.00025, 0.00032, 0.0004, 0.0005, 0.00064, 0.0008, 0.001, 0.0016, 0.002, 0.0025, 0.0032, 0.004, 0.005, 0.0064, 0.008, 0.01, 0.01125, 0.015, 0.02, 0.025, 0.03,
|
||||
|
||||
@@ -6,8 +6,6 @@ use crate::messages::prelude::*;
|
||||
pub enum DialogMessage {
|
||||
// Sub-messages
|
||||
#[child]
|
||||
DocumentSetupDialog(DocumentSetupDialogMessage),
|
||||
#[child]
|
||||
ExportDialog(ExportDialogMessage),
|
||||
#[child]
|
||||
NewDocumentDialog(NewDocumentDialogMessage),
|
||||
@@ -36,7 +34,6 @@ pub enum DialogMessage {
|
||||
localized_commit_year: String,
|
||||
},
|
||||
RequestDemoArtworkDialog,
|
||||
RequestDocumentSetupDialog,
|
||||
RequestExportDialog,
|
||||
RequestLicensesDialogWithLocalizedCommitDate {
|
||||
localized_commit_year: String,
|
||||
|
||||
@@ -4,7 +4,6 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
|
||||
use crate::messages::frontend::utility_types::ExportBounds;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct DialogMessageContext<'a> {
|
||||
@@ -17,7 +16,6 @@ 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,
|
||||
@@ -29,7 +27,6 @@ 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 }),
|
||||
@@ -103,25 +100,30 @@ 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();
|
||||
let artboards = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
.filter(|&layer| document.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = document
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect();
|
||||
|
||||
self.export_dialog.artboards = artboards;
|
||||
|
||||
if let ExportBounds::Artboard(layer) = self.export_dialog.bounds
|
||||
&& !self.export_dialog.artboards.iter().any(|(artboard, _)| *artboard == layer)
|
||||
&& !self.export_dialog.artboards.contains_key(&layer)
|
||||
{
|
||||
self.export_dialog.bounds = self.export_dialog.default_bounds();
|
||||
self.export_dialog.bounds_chosen = false;
|
||||
self.export_dialog.bounds = ExportBounds::AllArtwork;
|
||||
}
|
||||
|
||||
self.export_dialog.has_selection = document.network_interface.selected_nodes().selected_layers(document.metadata()).next().is_some();
|
||||
@@ -143,9 +145,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
||||
name: portfolio.generate_new_document_name(None),
|
||||
infinite: false,
|
||||
width: TypedLength::pixels(1920.),
|
||||
height: TypedLength::pixels(1080.),
|
||||
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||
dimensions: glam::UVec2::new(1920, 1080),
|
||||
};
|
||||
self.new_document_dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DocumentSetupDialogMessage {
|
||||
Resolution { pixels_per_inch: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
-158
@@ -1,158 +0,0 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
|
||||
|
||||
/// A dialog to allow users to change the settings of the active document.
|
||||
#[derive(Debug, Clone, ExtractField)]
|
||||
pub struct DocumentSetupDialogMessageHandler {
|
||||
pub pixels_per_inch: f64,
|
||||
}
|
||||
|
||||
impl Default for DocumentSetupDialogMessageHandler {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
|
||||
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
|
||||
match message {
|
||||
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||
|
||||
DocumentSetupDialogMessage::Submit => {
|
||||
// The settings apply as one undo step, which ending the transaction drops if nothing changed
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||
pixels_per_inch: self.pixels_per_inch,
|
||||
});
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
}
|
||||
}
|
||||
|
||||
self.send_dialog_to_frontend(responses);
|
||||
}
|
||||
|
||||
advertise_actions!(DocumentSetupDialogUpdate;
|
||||
);
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
|
||||
const ICON: &'static str = "File";
|
||||
const TITLE: &'static str = "Document Setup";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![
|
||||
TextButton::new("OK")
|
||||
.emphasized(true)
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for DocumentSetupDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
|
||||
|
||||
Layout(vec![LayoutGroup::row(resolution)])
|
||||
}
|
||||
}
|
||||
|
||||
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
|
||||
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
|
||||
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
|
||||
|
||||
vec![
|
||||
TextLabel::new("Resolution")
|
||||
.table_align(true)
|
||||
.sizing(WidgetSizing::fixed(90))
|
||||
.tooltip_label("Resolution")
|
||||
.tooltip_description(description)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(pixels_per_inch))
|
||||
.unit(" PPI")
|
||||
.min(1.)
|
||||
.max(100_000.)
|
||||
.tooltip_label("Resolution")
|
||||
.tooltip_description(description)
|
||||
// Matches the width of the New Document dialog's Name field
|
||||
.sizing(WidgetSizing::default().min_width(204))
|
||||
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
|
||||
editor.active_document().network_interface.pixels_per_inch()
|
||||
}
|
||||
|
||||
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
|
||||
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
|
||||
}
|
||||
|
||||
async fn confirm(editor: &mut EditorTestUtils) {
|
||||
editor
|
||||
.handle_message(DialogMessage::CloseAndThen {
|
||||
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let layer_count = editor.active_document().metadata().all_layers().count();
|
||||
|
||||
open_and_set_resolution(&mut editor, 300.).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
|
||||
confirm(&mut editor).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||
|
||||
// Undoing reverts only the resolution, leaving the rectangle drawn before it
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 96.);
|
||||
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
|
||||
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
open_and_set_resolution(&mut editor, 300.).await;
|
||||
confirm(&mut editor).await;
|
||||
|
||||
open_and_set_resolution(&mut editor, 150.).await;
|
||||
editor.handle_message(DialogMessage::Close).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
|
||||
|
||||
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
|
||||
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||
confirm(&mut editor).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
mod document_setup_dialog_message;
|
||||
mod document_setup_dialog_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
|
||||
@@ -14,10 +14,7 @@ pub struct ExportDialogMessageHandler {
|
||||
pub file_type: FileType,
|
||||
pub scale_factor: f64,
|
||||
pub bounds: ExportBounds,
|
||||
/// Whether the bounds were picked in the dialog, rather than left at the default of the file type, which a change of file type replaces.
|
||||
pub bounds_chosen: bool,
|
||||
/// Each artboard with its name, from the top of the Layers panel down.
|
||||
pub artboards: Vec<(LayerNodeIdentifier, String)>,
|
||||
pub artboards: HashMap<LayerNodeIdentifier, String>,
|
||||
pub has_selection: bool,
|
||||
}
|
||||
|
||||
@@ -27,7 +24,6 @@ impl Default for ExportDialogMessageHandler {
|
||||
file_type: Default::default(),
|
||||
scale_factor: 1.,
|
||||
bounds: Default::default(),
|
||||
bounds_chosen: false,
|
||||
artboards: Default::default(),
|
||||
has_selection: false,
|
||||
}
|
||||
@@ -40,23 +36,20 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
let ExportDialogMessageContext { portfolio } = context;
|
||||
|
||||
match message {
|
||||
ExportDialogMessage::FileType { file_type } => {
|
||||
self.file_type = file_type;
|
||||
if !self.bounds_chosen {
|
||||
self.bounds = self.default_bounds();
|
||||
}
|
||||
}
|
||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||
ExportDialogMessage::ExportBounds { bounds } => {
|
||||
self.bounds = bounds;
|
||||
self.bounds_chosen = true;
|
||||
}
|
||||
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
|
||||
|
||||
ExportDialogMessage::Submit => {
|
||||
let bounds = self.current_bounds();
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
let bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
||||
ExportBounds::AllArtwork
|
||||
} else {
|
||||
self.bounds
|
||||
};
|
||||
|
||||
let artboard_name = match bounds {
|
||||
ExportBounds::Artboard(layer) => self.artboards.iter().find(|(artboard, _)| *artboard == layer).map(|(_, name)| name.clone()),
|
||||
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
||||
@@ -77,23 +70,6 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
);
|
||||
}
|
||||
|
||||
impl ExportDialogMessageHandler {
|
||||
/// The bounds a file type starts with: each artboard as its own page for a PDF, or otherwise all the artwork.
|
||||
pub fn default_bounds(&self) -> ExportBounds {
|
||||
if self.file_type == FileType::Pdf { ExportBounds::AllArtboards } else { ExportBounds::AllArtwork }
|
||||
}
|
||||
|
||||
/// The chosen bounds, falling back to the default and then "All Artwork" in place of a choice that isn't currently available.
|
||||
fn current_bounds(&self) -> ExportBounds {
|
||||
let available = |bounds: &ExportBounds| match bounds {
|
||||
ExportBounds::Selection => self.has_selection,
|
||||
ExportBounds::AllArtboards => self.file_type == FileType::Pdf && !self.artboards.is_empty(),
|
||||
ExportBounds::AllArtwork | ExportBounds::Artboard(_) => true,
|
||||
};
|
||||
[self.bounds, self.default_bounds()].into_iter().find(available).unwrap_or(ExportBounds::AllArtwork)
|
||||
}
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
const ICON: &'static str = "File";
|
||||
const TITLE: &'static str = "Export";
|
||||
@@ -118,9 +94,9 @@ impl DialogLayoutHolder for ExportDialogMessageHandler {
|
||||
|
||||
impl LayoutHolder for ExportDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
// The vector types, then the raster ones
|
||||
// The vector type, then the raster ones
|
||||
let file_types = [
|
||||
vec![(FileType::Svg, "SVG"), (FileType::Pdf, "PDF")],
|
||||
vec![(FileType::Svg, "SVG")],
|
||||
vec![
|
||||
(FileType::Png, "PNG"),
|
||||
(FileType::Jpg, "JPG"),
|
||||
@@ -163,7 +139,7 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.increment_step(0.5)
|
||||
.disabled(matches!(self.file_type, FileType::Svg | FileType::Pdf))
|
||||
.disabled(self.file_type == FileType::Svg)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
|
||||
.sizing(WidgetSizing::default().min_width(200))
|
||||
.widget_instance(),
|
||||
@@ -173,12 +149,15 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
(ExportBounds::AllArtwork, "All Artwork".to_string(), false),
|
||||
(ExportBounds::Selection, "Selection".to_string(), !self.has_selection),
|
||||
];
|
||||
// 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()];
|
||||
let artboards = self.artboards.iter().map(|(&layer, name)| (ExportBounds::Artboard(layer), name.to_string(), false)).collect();
|
||||
let choices = [standard_bounds, artboards];
|
||||
|
||||
let current_bounds = self.current_bounds();
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
let current_bounds = if !self.has_selection && self.bounds == ExportBounds::Selection {
|
||||
ExportBounds::AllArtwork
|
||||
} else {
|
||||
self.bounds
|
||||
};
|
||||
let index = choices.iter().flatten().position(|(bounds, _, _)| *bounds == current_bounds).unwrap_or(0);
|
||||
|
||||
let mut entries = choices
|
||||
@@ -209,44 +188,3 @@ 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,7 +8,6 @@
|
||||
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,14 +1,12 @@
|
||||
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: TypedLength },
|
||||
DimensionsY { height: TypedLength },
|
||||
Resolution { pixels_per_inch: f64 },
|
||||
DimensionsX { width: f64 },
|
||||
DimensionsY { height: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
+29
-220
@@ -1,34 +1,16 @@
|
||||
use crate::messages::dialog::document_setup_dialog::resolution_row;
|
||||
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::node_inspector::length_decimal_places;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use glam::DVec2;
|
||||
use glam::UVec2;
|
||||
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, ExtractField)]
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct NewDocumentDialogMessageHandler {
|
||||
pub name: String,
|
||||
pub infinite: bool,
|
||||
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,
|
||||
}
|
||||
}
|
||||
pub dimensions: UVec2,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -37,38 +19,24 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
||||
match message {
|
||||
NewDocumentDialogMessage::Name { name } => self.name = name,
|
||||
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
||||
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::DimensionsX { width } => self.dimensions.x = width as u32,
|
||||
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
|
||||
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 pixels.x > 0. && pixels.y > 0. {
|
||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
||||
// Finite canvas: create an artboard with the specified dimensions
|
||||
responses.add(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: DVec2::ZERO,
|
||||
dimensions,
|
||||
location: glam::DVec2::ZERO,
|
||||
dimensions: self.dimensions.as_dvec2(),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
});
|
||||
responses.add(NavigationMessage::CanvasPan { delta: pixels });
|
||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
@@ -139,191 +107,32 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
// 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![
|
||||
let scale = vec![
|
||||
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
dimension_field(self.width, "W")
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into())
|
||||
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())
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
dimension_field(self.height, "H")
|
||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into())
|
||||
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())
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into());
|
||||
|
||||
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(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);
|
||||
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,6 @@ pub enum FileType {
|
||||
Tga,
|
||||
Ico,
|
||||
Svg,
|
||||
Pdf,
|
||||
}
|
||||
|
||||
impl FileType {
|
||||
@@ -92,7 +91,6 @@ impl FileType {
|
||||
FileType::Tga => "tga",
|
||||
FileType::Ico => "ico",
|
||||
FileType::Svg => "svg",
|
||||
FileType::Pdf => "pdf",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,7 +104,6 @@ impl FileType {
|
||||
FileType::Tga => "TGA Image",
|
||||
FileType::Ico => "ICO Image",
|
||||
FileType::Svg => "SVG Image",
|
||||
FileType::Pdf => "PDF Document",
|
||||
};
|
||||
FileFilter {
|
||||
name: name.into(),
|
||||
@@ -133,7 +130,6 @@ impl FileType {
|
||||
FileType::Tga => ImageFormat::Tga,
|
||||
FileType::Ico => ImageFormat::Ico,
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
FileType::Pdf => return Err("PDF cannot be exported from an image buffer".to_string()),
|
||||
};
|
||||
if self == FileType::Ico && (width > 256 || height > 256) {
|
||||
return Err("An ICO image can be at most 256 pixels wide and tall. Lower the scale factor or choose a smaller export area.".to_string());
|
||||
@@ -168,8 +164,6 @@ pub enum ExportBounds {
|
||||
#[default]
|
||||
AllArtwork,
|
||||
Selection,
|
||||
/// Each artboard as its own page, for a file type that holds pages.
|
||||
AllArtboards,
|
||||
Artboard(LayerNodeIdentifier),
|
||||
}
|
||||
|
||||
@@ -234,7 +228,6 @@ mod tests {
|
||||
#[test]
|
||||
fn file_types_that_cannot_hold_the_image_say_so() {
|
||||
assert!(FileType::Svg.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Pdf.encode(1, 1, vec![0; 4]).is_err());
|
||||
assert!(FileType::Png.encode(2, 2, vec![0; 4]).is_err());
|
||||
|
||||
let too_large = FileType::Ico.encode(257, 1, vec![0; 257 * 4]).unwrap_err();
|
||||
|
||||
@@ -417,20 +417,16 @@ 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, 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));
|
||||
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
|
||||
|
||||
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
|
||||
if number_input.value == Some(evaluated) && number_input.unit == unit {
|
||||
if number_input.value == Some(evaluated) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -708,41 +704,21 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`.
|
||||
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)
|
||||
/// 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)
|
||||
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
|
||||
.ok()?
|
||||
.eval(&context)
|
||||
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
|
||||
.ok()?;
|
||||
|
||||
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it
|
||||
let 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() {
|
||||
let real = value.as_real()?;
|
||||
if real.is_nan() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut validated = in_field_unit;
|
||||
let mut validated = real;
|
||||
if let Some(min) = number_input.min {
|
||||
validated = validated.max(min);
|
||||
}
|
||||
@@ -753,17 +729,5 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
|
||||
validated = validated.round();
|
||||
}
|
||||
|
||||
// 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))
|
||||
Some(validated)
|
||||
}
|
||||
@@ -247,14 +247,6 @@ 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")]
|
||||
@@ -615,7 +607,6 @@ pub enum MathExpressionRole {
|
||||
Function,
|
||||
Keyword,
|
||||
Operator,
|
||||
Unit,
|
||||
Bracket,
|
||||
MatrixLiteral,
|
||||
Error,
|
||||
@@ -632,7 +623,6 @@ 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,13 +181,6 @@ 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],
|
||||
])
|
||||
|
||||
@@ -16,8 +16,8 @@ use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
use graphene_std::raster::{
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior,
|
||||
NoiseType, RedGreenBlue, RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::text::TextAlign;
|
||||
@@ -25,7 +25,6 @@ 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,
|
||||
@@ -34,10 +33,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode,
|
||||
};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowTechnique, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -402,10 +398,6 @@ macro_rules! inspectable_types {
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<Length>,
|
||||
List<Angle>,
|
||||
List<LengthVec2>,
|
||||
List<AngleVec2>,
|
||||
List<i64>,
|
||||
List<bool>,
|
||||
List<DVec2>,
|
||||
@@ -444,9 +436,6 @@ macro_rules! inspectable_types {
|
||||
List<CellularDistanceFunction>,
|
||||
List<CellularReturnType>,
|
||||
List<DomainWarpType>,
|
||||
List<MandelbrotFractal>,
|
||||
List<MandelbrotExterior>,
|
||||
List<MandelbrotInterior>,
|
||||
List<RealTimeMode>,
|
||||
List<GridType>,
|
||||
List<GridTopology>,
|
||||
@@ -466,10 +455,6 @@ macro_rules! inspectable_types {
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<Length>,
|
||||
Item<Angle>,
|
||||
Item<LengthVec2>,
|
||||
Item<AngleVec2>,
|
||||
Item<i64>,
|
||||
Item<bool>,
|
||||
Item<DVec2>,
|
||||
@@ -508,9 +493,6 @@ macro_rules! inspectable_types {
|
||||
Item<CellularDistanceFunction>,
|
||||
Item<CellularReturnType>,
|
||||
Item<DomainWarpType>,
|
||||
Item<MandelbrotFractal>,
|
||||
Item<MandelbrotExterior>,
|
||||
Item<MandelbrotInterior>,
|
||||
Item<RealTimeMode>,
|
||||
Item<GridType>,
|
||||
Item<GridTopology>,
|
||||
@@ -1109,55 +1091,6 @@ 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"
|
||||
@@ -1326,13 +1259,8 @@ 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,
|
||||
@@ -1363,9 +1291,6 @@ impl_table_item_layout_for_choice_enum!(
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
@@ -1512,11 +1437,6 @@ macro_rules! known_item_types {
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
@@ -1552,9 +1472,6 @@ macro_rules! known_item_types {
|
||||
CellularDistanceFunction,
|
||||
CellularReturnType,
|
||||
DomainWarpType,
|
||||
MandelbrotFractal,
|
||||
MandelbrotExterior,
|
||||
MandelbrotInterior,
|
||||
RealTimeMode,
|
||||
GridType,
|
||||
GridTopology,
|
||||
|
||||
@@ -266,11 +266,6 @@ 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,
|
||||
},
|
||||
@@ -324,6 +319,9 @@ pub enum DocumentMessage {
|
||||
UpdateTextFrames {
|
||||
text_frames: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateFootprintAreas {
|
||||
footprint_areas: HashMap<NodeId, DAffine2>,
|
||||
},
|
||||
UpdateClipTargets {
|
||||
clip_targets: HashSet<NodeId>,
|
||||
},
|
||||
|
||||
@@ -53,7 +53,6 @@ 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;
|
||||
@@ -1695,16 +1694,6 @@ 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() {
|
||||
@@ -1925,6 +1914,9 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_text_frames(layer_text_frames);
|
||||
}
|
||||
DocumentMessage::UpdateFootprintAreas { footprint_areas } => {
|
||||
self.network_interface.update_footprint_areas(footprint_areas);
|
||||
}
|
||||
DocumentMessage::UpdateClipTargets { clip_targets } => {
|
||||
self.network_interface.update_clip_targets(clip_targets);
|
||||
}
|
||||
@@ -2167,14 +2159,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
} else {
|
||||
self.network_interface.document_bounds_document_space(true)
|
||||
};
|
||||
// With nothing to frame, like a generator's pattern filling the plane, a tiny area at the origin is framed, which centers the origin at 100%
|
||||
let bounds = bounds.unwrap_or([DVec2::splat(-1.), DVec2::splat(1.)]);
|
||||
|
||||
if self.document_ptz.flip {
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
if let Some(bounds) = bounds {
|
||||
if self.document_ptz.flip {
|
||||
responses.add(NavigationMessage::CanvasFlip);
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
} else {
|
||||
warn!("Cannot zoom due to no bounds")
|
||||
}
|
||||
responses.add(NavigationMessage::CanvasTiltSet { angle_radians: 0. });
|
||||
responses.add(NavigationMessage::FitViewportToBounds { bounds, prevent_zoom_past_100: true });
|
||||
}
|
||||
DocumentMessage::Noop => (),
|
||||
}
|
||||
@@ -2456,23 +2449,6 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.document_metadata()
|
||||
}
|
||||
|
||||
/// Each artboard with its name, from the top of the Layers panel down.
|
||||
pub fn artboard_names(&self) -> Vec<(LayerNodeIdentifier, String)> {
|
||||
self.metadata()
|
||||
.all_layers()
|
||||
.filter(|&layer| self.network_interface.is_artboard(&layer.to_node(), &[]))
|
||||
.map(|layer| {
|
||||
let name = self
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|node| node.persistent_metadata.display_name.clone())
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or_else(|| "Artboard".to_string());
|
||||
(layer, name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn breadcrumb_network_path(&self) -> &[NodeId] {
|
||||
&self.breadcrumb_network_path
|
||||
}
|
||||
@@ -3258,10 +3234,7 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
|
||||
pub fn current_hash(&self) -> u64 {
|
||||
// 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()
|
||||
self.network_interface.document_network().current_hash()
|
||||
}
|
||||
|
||||
pub fn is_auto_saved(&self) -> bool {
|
||||
@@ -4757,8 +4730,8 @@ pub fn navigation_controls(ptz: &PTZ, navigation_handler: &NavigationMessageHand
|
||||
vec![
|
||||
NumberInput::new(Some(navigation_handler.snapped_zoom(ptz.zoom()) * 100.))
|
||||
.unit("%")
|
||||
.min(crate::consts::VIEWPORT_ZOOM_SCALE_MIN * 100.)
|
||||
.max(crate::consts::VIEWPORT_ZOOM_SCALE_MAX * 100.)
|
||||
.min(0.000001)
|
||||
.max(1000000.)
|
||||
.tooltip_label(if node_graph { "Node Graph Zoom" } else { "Canvas Zoom" })
|
||||
.sizing(WidgetSizing::default().min_width(80))
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
@@ -4825,69 +4798,6 @@ mod document_message_handler_tests {
|
||||
use crate::messages::portfolio::document::utility_types::misc::GridType;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn zooming_to_fit_nothing_centers_the_origin_at_100_percent() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
|
||||
// Zoomed, panned, and tilted away in a document with nothing to frame
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 7. }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasPan { delta: DVec2::new(300., -200.) }).await;
|
||||
editor.handle_message(NavigationMessage::CanvasTiltSet { angle_radians: 0.5 }).await;
|
||||
|
||||
editor.handle_message(DocumentMessage::ZoomCanvasToFitAll).await;
|
||||
|
||||
let ptz = editor.active_document().document_ptz;
|
||||
assert_eq!(ptz.zoom(), 1.);
|
||||
assert_eq!(ptz.tilt(), 0.);
|
||||
assert!(ptz.pan.length() < 1e-9, "the view is panned by {}", ptz.pan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn zooming_to_100_percent_reaches_it_with_only_a_tiny_shape_in_the_document() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
|
||||
// A shape about a millionth of a unit across, drawn while zoomed far in
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: 10_000_000. }).await;
|
||||
editor.draw_ellipse(100., 100., 110., 110.).await;
|
||||
assert!(editor.active_document().network_interface.document_bounds_document_space(true).is_some());
|
||||
|
||||
editor.handle_message(DocumentMessage::ZoomCanvasTo100Percent).await;
|
||||
assert_eq!(editor.active_document().document_ptz.zoom(), 1.);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wheeling_in_at_the_deepest_zoom_leaves_the_view_in_place() {
|
||||
use crate::consts::VIEWPORT_ZOOM_SCALE_MAX;
|
||||
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.set_viewport_size(DVec2::ZERO, DVec2::new(800., 600.)).await;
|
||||
editor.handle_message(NavigationMessage::CanvasZoomSet { zoom_factor: VIEWPORT_ZOOM_SCALE_MAX }).await;
|
||||
let pan = editor.active_document().document_ptz.pan;
|
||||
|
||||
// Ctrl+wheel zooming in, which heads toward the pointer away from the viewport's center
|
||||
let editor_mouse_state = EditorPointerState {
|
||||
editor_position: DVec2::new(100., 100.),
|
||||
scroll_delta: ScrollDelta { x: 0., y: -100., z: 0. },
|
||||
..Default::default()
|
||||
};
|
||||
editor
|
||||
.input(InputPreprocessorMessage::WheelScroll {
|
||||
editor_mouse_state,
|
||||
modifier_keys: ModifierKeys::CONTROL,
|
||||
})
|
||||
.await;
|
||||
|
||||
let ptz = editor.active_document().document_ptz;
|
||||
assert_eq!(ptz.zoom(), VIEWPORT_ZOOM_SCALE_MAX);
|
||||
assert_eq!(ptz.pan, pan);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_bottom_layer_leaves_the_layer_above_it_the_empty_stack_value() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -5316,7 +5226,7 @@ mod document_message_handler_tests {
|
||||
.handle_message(GraphOperationMessage::NewArtboard {
|
||||
id: NodeId::new(),
|
||||
location: DVec2::ZERO,
|
||||
dimensions: graphene_std::units::TypedLengthVec2::pixels(DVec2::splat(200.)),
|
||||
dimensions: DVec2::splat(200.),
|
||||
background: Color::WHITE,
|
||||
clip: true,
|
||||
})
|
||||
|
||||
@@ -7,7 +7,6 @@ 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;
|
||||
@@ -137,7 +136,7 @@ pub enum GraphOperationMessage {
|
||||
NewArtboard {
|
||||
id: NodeId,
|
||||
location: DVec2,
|
||||
dimensions: TypedLengthVec2,
|
||||
dimensions: DVec2,
|
||||
background: Color,
|
||||
clip: bool,
|
||||
},
|
||||
|
||||
+1
-2
@@ -14,7 +14,6 @@ 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};
|
||||
|
||||
@@ -887,7 +886,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::Length(TypedLength::pixels(diameter)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(flow), false)),
|
||||
]);
|
||||
|
||||
@@ -4,40 +4,34 @@ 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, keeping each in the unit it was typed in.
|
||||
/// Update the inputs of the transform node to match a new transform
|
||||
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.);
|
||||
|
||||
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), &[]);
|
||||
}
|
||||
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),
|
||||
&[],
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: This should be extracted from the graph at the location of the transform node.
|
||||
@@ -69,14 +63,16 @@ impl LayerBounds {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
/// 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 };
|
||||
|
||||
let rotation = rotation.to_radians();
|
||||
let skew = DVec2::new(skew.x.to_radians().tan(), skew.y.to_radians().tan());
|
||||
|
||||
@@ -15,7 +15,6 @@ 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};
|
||||
@@ -69,12 +68,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: TypedLengthVec2, background: Color, clip: bool) -> LayerNodeIdentifier {
|
||||
pub fn create_artboard(&mut self, new_id: NodeId, location: DVec2, dimensions: DVec2, 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::LengthVec2(TypedLengthVec2::pixels(location)), false)),
|
||||
Some(NodeInput::value(TaggedValue::LengthVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(location), false)),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(dimensions), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(background), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(clip), false)),
|
||||
]);
|
||||
@@ -197,14 +196,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.font_size)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), 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::Number(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_width.unwrap_or(100.))), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Length(TypedLength::pixels(typesetting.max_height.unwrap_or(100.))), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(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)
|
||||
@@ -730,14 +729,13 @@ 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, pixels_per_inch))
|
||||
.map_or(acc, |document_node| acc * transform_utils::get_current_transform(&document_node.inputs))
|
||||
})
|
||||
};
|
||||
let prior_combined = compose(prior_transforms);
|
||||
@@ -873,7 +871,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::Length(TypedLength::pixels(stroke.weight)), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(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);
|
||||
@@ -885,7 +883,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::Length(TypedLength::pixels(stroke.dash_offset)), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(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.
|
||||
@@ -896,10 +894,7 @@ 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, self.network_interface.pixels_per_inch()),
|
||||
transform_node_id,
|
||||
))
|
||||
Some((transform_utils::get_current_transform(&document_node.inputs), transform_node_id))
|
||||
})
|
||||
.unzip();
|
||||
let layer_transform = layer_transform.unwrap_or_default();
|
||||
@@ -937,7 +932,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, self.network_interface.pixels_per_inch()))
|
||||
.map(|node| transform_utils::get_current_transform(&node.inputs))
|
||||
.unwrap_or(DAffine2::IDENTITY);
|
||||
parent_inverse * transform * local_transform.inverse() * current_transform_node_value
|
||||
} else {
|
||||
@@ -1025,37 +1020,16 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
dimensions.y = -dimensions.y;
|
||||
location.y -= dimensions.y;
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
/// Set the input, refresh the Inspector, and run the document graph if skip_rerender is false
|
||||
|
||||
Loaded 100 of 309 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user