Compare commits

..
Author SHA1 Message Date
Keavon Chambers 3e380b8cd7 Carry units through the math parser's lone-operator reductions 2026-11-26 02:35:56 -08:00
Keavon Chambers 634c30bebf Give exported SVGs a physical size and let Math f(x) take lengths and angles 2026-11-26 02:35:56 -08:00
Keavon Chambers 1e912de804 Add a resolution and lengths in any unit to the New Document dialog 2026-11-26 02:35:56 -08:00
Keavon Chambers ea9c44e003 Add typed length and angle values with a per-document resolution 2026-11-26 02:35:55 -08:00
Keavon Chambers 6a28b82b91 Add units of measure to the math expression language 2026-11-26 02:34:34 -08:00
Keavon Chambers 30164b921e New node: 'Feather' (#5028) 2026-11-26 02:30:33 -08:00
Keavon Chambers b10aa51efb Allow the 'Mask' node to mask any graphic with any other graphic (#5027) 2026-11-26 00:20:22 -08:00
Keavon Chambers 5d00e45354 Add gloss contours, bevel profiles, and textures to the 'Bevel & Emboss' node (#5026) 2026-11-25 22:16:50 -08:00
Keavon Chambers 69c0dd140d Add support to the 'Outline' node for any graphic as paint, plus contour gradients (#5025)
Allow any paint in the 'Outline' node and add contour gradients
2026-11-25 20:02:34 -08:00
Keavon Chambers 9a8269c953 Add a "Blend Mode" parameter to the 'Drop/Inner Shadow', 'Outer/Inner Glow', 'Satin', and 'Outline' effect nodes (#5024)
Add a "Blend Mode" parameter to the '* Shadow', '* Glow', 'Satin', and 'Outline' effect nodes
2026-11-25 18:59:28 -08:00
Timon 76361baaa1 Replace missing resource warnings with a 'Missing Resource' node that reports an error (#5018)
* Revert "Fix documents not rendering when a font or image is missing or fails to load (#4986)"

* Stop holding back rendering for resources that failed to load

* Recompile the graph when a resource loads

* Place a missing resource node for resources without a hash

* Evaluate a missing resource as the empty resource with its error

* Fix tests
2026-11-26 01:13:19 +00:00
Keavon Chambers f569120bf6 New node: 'Bevel & Emboss' (#5023)
New node: 'Bevel & Emboss', which gives graphics a raised or sunken look
2026-11-25 14:50:50 -08:00
Timon 0df1e16233 Move network output tracking out of the executor into a handle returned by updates (#5019)
* Let the dynamic executor hold several networks, each executed and kept alive by a handle to its output

* Review
2026-11-25 22:19:19 +00:00
Aditya Amol KuchekarandDennis Kobert 65bb0ff838 Fix dangling inputs when a History panel step is removed (#5017)
* Fix dangling inputs when a history step is removed

A node the line never saw gets a placeholder tombstone, which holds no
inputs, so reconnect returned nothing instead of falling back to the
primary input history kept. The input was left naming a node the
document no longer has, and that state is what history folds to.

* Share the history simulation harness and add a regression test

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-25 22:08:20 +00:00
Keavon Chambers d5a7504e3a New nodes: 'Inner Glow', 'Satin', and 'Outline' (#5022) 2026-11-25 14:14:26 -08:00
Keavon Chambers fa65c1f8dc Replace the 'Color Overlay' node with a 'Paint Overlay' node supporting any graphic (#5020)
Replace the 'Color Overlay' node with a 'Paint Overlay' node using any graphic
2026-11-25 13:54:46 -08:00
173 changed files with 16732 additions and 4909 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/38176c494d7cf0bde3bdf45e6a318ae6a9d89229.tar.gz
2ae24506ff786b2b684f5d23bd326a69f5f4551855f19e4ef2b0324f9ec14e5d
https://github.com/Keavon/graphite-branded-assets/archive/9d0fa5caefd7d28f51b55220b405b7d76d05a991.tar.gz
a146abe79fa20b6d96f8009279a5a3342dd01596e5eb6a43e4c1f5e1199f1d9f
Generated
+11 -145
View File
@@ -1226,6 +1226,7 @@ dependencies = [
"kurbo",
"log",
"lyon_geom",
"math-parser",
"node-macro",
"num-derive",
"num-traits",
@@ -1238,7 +1239,7 @@ dependencies = [
"rustc-hash 2.1.3",
"serde",
"serde_json",
"skrifa 0.44.0",
"skrifa",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -2135,9 +2136,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"
@@ -2157,15 +2155,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"
@@ -2207,7 +2196,7 @@ dependencies = [
"linebender_resource_handle",
"memmap2",
"parlance",
"read-fonts 0.41.0",
"read-fonts",
"smallvec",
]
@@ -2444,21 +2433,6 @@ dependencies = [
"serde_core",
]
[[package]]
name = "glifo"
version = "0.4.0"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"bytemuck",
"foldhash 0.2.0",
"hashbrown 0.17.1",
"log",
"peniko",
"skrifa 0.44.0",
"smallvec",
"vello_common",
]
[[package]]
name = "glob"
version = "0.3.4"
@@ -3066,7 +3040,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"read-fonts 0.41.0",
"read-fonts",
"smallvec",
]
@@ -3454,12 +3428,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"
@@ -3832,33 +3800,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"
@@ -5092,7 +5033,7 @@ dependencies = [
"parlance",
"parley_data",
"parley_emoji",
"skrifa 0.44.0",
"skrifa",
]
[[package]]
@@ -5123,18 +5064,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"
@@ -5937,16 +5866,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"
@@ -5954,7 +5873,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709"
dependencies = [
"bytemuck",
"font-types 0.12.7",
"font-types",
"once_cell",
]
@@ -6097,19 +6016,16 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"glifo",
"graphene-application-io",
"graphene-hash",
"graphene-resource",
"graphic-types",
"krilla",
"kurbo",
"log",
"num-traits",
"parley",
"raster-kernels",
"serde",
"skrifa 0.44.0",
"skrifa",
"text-nodes",
"usvg",
"vector-types",
@@ -6687,12 +6603,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"
@@ -7054,16 +6964,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"
@@ -7071,7 +6971,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68"
dependencies = [
"bytemuck",
"read-fonts 0.41.0",
"read-fonts",
]
[[package]]
@@ -7250,18 +7150,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"
@@ -7444,7 +7332,7 @@ dependencies = [
"rand",
"serde",
"serde_json",
"skrifa 0.44.0",
"skrifa",
"thiserror 2.0.21",
"titlecase",
"tsify",
@@ -8044,14 +7932,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",
@@ -8136,7 +8024,6 @@ dependencies = [
"repeat-nodes",
"rustc-hash 2.1.3",
"serde",
"text-nodes",
"thiserror 2.0.21",
"tokio",
"tsify",
@@ -8213,7 +8100,6 @@ version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
dependencies = [
"bytemuck",
"glifo",
"hashbrown 0.17.1",
"log",
"thiserror 2.0.21",
@@ -8696,7 +8582,6 @@ dependencies = [
"raster-kernels",
"raster-types",
"rendering",
"text-nodes",
"thiserror 2.0.21",
"vello_gpu",
"web-sys",
@@ -9397,19 +9282,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"
@@ -9550,12 +9422,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"
+1 -4
View File
@@ -215,9 +215,7 @@ url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support", "text"] }
glifo = { version = "0.4", default-features = false, features = ["std"] }
krilla = { version = "0.8", default-features = false, features = ["raster-images"] }
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
usvg = "0.49"
simplecss = "0.2"
parley = { version = "0.12", default-features = false, features = ["std"] }
@@ -320,4 +318,3 @@ fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "2
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
glifo = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
@@ -57,6 +57,10 @@ pub mod network {
pub const IMPORT_METADATA: &str = "ui::import_metadata";
pub const EXPORT_NAMES: &str = "ui::export_names";
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
/// is the default, CSS's 96. Only the root network's applies.
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
}
pub mod delta {
@@ -473,6 +473,12 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
.map_err(map_serialization_error(network::PINNED_ORDER))?;
}
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
attributes
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
}
Ok(())
}
+2
View File
@@ -52,9 +52,11 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
#[cfg(test)]
mod tests {
mod bookkeeping;
mod branch_simulation;
mod crdt;
mod history_simulation;
mod projection;
mod round_trip;
mod sessions;
mod simulation;
}
@@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry {
pub import_metadata: Vec<InputMetadataEntry>,
pub export_names: Vec<String>,
pub export_descriptions: Vec<String>,
/// The document's pixels per inch, where it differs from the default.
pub pixels_per_inch: Option<f64>,
}
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -78,6 +80,11 @@ pub trait NodeMetadataSource {
Vec::new()
}
/// The network's pixels per inch, where it differs from the default.
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
None
}
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
Vec::new()
}
+2 -1
View File
@@ -382,7 +382,8 @@ fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, k
if !visited.insert(current) {
return None;
}
let (in_network, input) = match registry.removed_nodes.get(&current) {
// 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(&current).filter(|tombstone| !tombstone.placeholder) {
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
None => known.primary.get(&current).cloned()?,
};
@@ -0,0 +1,238 @@
//! Deterministic simulation of a document whose chains branch off inputs past the primary one, with every history
//! operation mixed in. After every operation nothing may name a node the document no longer has.
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
/// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Place {
Export(u32),
Input(NodeId, u32),
}
fn place_value(registry: &Registry, place: Place) -> Option<NodeInput> {
match place {
Place::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
Place::Export(index) => registry.networks.get(&ROOT_NETWORK)?.exports.get(index as usize)?.target.clone(),
}
}
fn set_place(place: Place, input: NodeInput) -> RegistryDelta {
match place {
Place::Input(id, index) => RegistryDelta::ChangeNodeInput { id, index, new_input: input },
Place::Export(index) => RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index,
export: Some(input),
},
}
}
/// Every slot naming a node, and the node it names, in a fixed order.
fn naming_places(registry: &Registry) -> Vec<(Place, NodeId)> {
let mut places = Vec::new();
for (&id, node) in &registry.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 &registry.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(&registry);
let nodes = under(&registry, 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(&registry, 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(&registry, 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(&registry)
.into_iter()
.filter(|(_, named)| *named == node)
.map(|(place, _)| set_place(place, below(&registry, 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(&registry, layer) else { return Vec::new() };
vec![
set_place(place, below(&registry, 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(&registry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
.collect();
let Some(host) = random.pick(&hosts) else { return Vec::new() };
let mut gone = under(&registry, 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(&registry)
.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 &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
for (index, slot) in node.inputs.iter().enumerate() {
assert_ne!(slot.input, empty_export(), "{context}: input {index} of {id:?} holds the empty export's value");
}
}
}
}
#[test]
fn history_operations_keep_a_branching_document_whole() {
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
for seed in 0..seeds {
simulate::<Branching>(seed, steps, &mut Vec::new());
}
}
@@ -1,64 +1,12 @@
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
//! head moves must hold the same document.
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation mixed in.
//! After every operation the document must still be a well-formed stack.
//!
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
use std::collections::HashSet;
/// What every layer's implementation names, so nodes need no proto-node declarations. The first layer drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the stack is empty, of another type than what the bottom layer rests on.
fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// The layers from the top of the stack down, following each layer's first input.
fn stack(registry: &Registry) -> Vec<NodeId> {
let mut layers = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
break;
}
layers.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
layers
}
/// What feeds into `layer` from below.
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
registry.node_instances[&layer].inputs[0].input.clone()
}
/// Points what sits directly above `layer`, a layer or the export, at `input`.
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
let layers = stack(registry);
@@ -76,365 +24,124 @@ fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> Registr
}
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
/// A single stack of layers off the export.
struct Stack;
fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
ops
}
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, 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(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
}
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = std::collections::HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The layers live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.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 &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
fn assert_consistent(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
impl Scenario for Stack {
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let leaf = (!registry.networks.contains_key(&LEAF)).then(|| RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
});
let mut ops: Vec<RegistryDelta> = leaf.into_iter().collect();
ops.extend([
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
]);
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
ops
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
8 => {
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
continue;
};
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A layer the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A layer the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.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 &registry.node_instances {
if let Implementation::Network(network) = &node.implementation {
assert!(registry.networks.contains_key(network), "{context}: {id:?} is built from {network:?}, which is gone");
}
}
let layers = stack(registry);
if let Some(bottom) = layers.last() {
assert_ne!(below(registry, *bottom), empty_export(), "{context}: the bottom layer {bottom:?} rests on the empty export's value");
}
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
}
#[test]
fn history_operations_keep_the_stack_whole_and_peers_converged() {
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let (seeds, steps) = (from_env("SEEDS", 200), from_env("STEPS", 80));
for seed in 0..seeds {
simulate(seed, steps, &mut Vec::new());
simulate::<Stack>(seed, steps, &mut Vec::new());
}
}
/// A seed fixes the run, so one that fails can be replayed.
#[test]
fn a_seed_fixes_the_history_run() {
let histories = |seed| simulate(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
let histories = |seed| simulate::<Stack>(seed, 60, &mut Vec::new()).history().map(|delta| delta.id).collect::<Vec<_>>();
for seed in 0..5 {
assert_eq!(histories(seed), histories(seed), "seed {seed}");
}
@@ -443,9 +150,7 @@ fn a_seed_fixes_the_history_run() {
#[test]
#[ignore]
fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
let mut log = Vec::new();
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let host = simulate(seed, steps, &mut log);
let host = simulate::<Stack>(from_env("SEED", 0), from_env("STEPS", 80), &mut log);
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
}
@@ -12,9 +12,25 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
/// Note: This only works for complete networks with all inputs resolved.
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
use graph_craft::document::value::TaggedValue;
let mut network = network.clone();
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
let resolution_node = NodeId(u64::MAX);
network.nodes.insert(
resolution_node,
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
..Default::default()
},
);
network
.scope_injections
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
let compiler = Compiler {};
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
@@ -1033,6 +1033,33 @@ fn deleting_a_node_without_inputs_gives_the_input_it_fed_its_earlier_value() {
assert_eq!(registry.node_instances[&consumer].inputs()[1].input, earlier_value);
}
/// Bringing back a step that writes to a node the line never had reconnects an input naming that node to what history
/// holds as its primary input, though the write leaves only a placeholder of it.
#[test]
fn bringing_back_a_step_reconnects_past_a_node_the_line_never_had() {
let (source, consumer) = (NodeId(1), NodeId(2));
let source_value = NodeInput::Value {
value: Value::from(serde_json::json!("under the source")),
exposed: false,
};
let mut source_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
source_node.inputs[0].input = source_value.clone();
let mut consumer_node = Node::new(NetworkId(5), Implementation::ProtoNode(ResourceId::new()), 1);
consumer_node.inputs[0].input = NodeInput::Node { id: source, index: 0 };
let mut session = Session::with_peer(PeerId(1));
let base = step(&mut session, add_network(5));
step(&mut session, RegistryDelta::AddNode { id: source, node: source_node });
session.commit_op_for_test(RegistryDelta::AddNode { id: consumer, node: consumer_node }).expect("commit");
let consumed = step(&mut session, change_node_attribute(source, "position", serde_json::json!(1)));
session.move_head_to(base).expect("go back to before the source");
session.restore_interaction(consumed).expect("bring the consumer back");
let registry = session.retired_registry();
assert!(registry.removed_nodes.get(&source).is_some_and(|tombstone| tombstone.placeholder));
assert_eq!(registry.node_instances[&consumer].inputs()[0].input, source_value);
}
/// Undo of a retired step names the person's latest step, not the device's. A fresh copy of the document under a new
/// peer id still undoes what its user did from the old one, and nobody else's.
#[test]
@@ -0,0 +1,315 @@
//! Shared harness of the deterministic history simulations: a seeded generator, every history operation the History
//! panel offers, and the checks each run makes after every operation.
use crate::{Network, NetworkId, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use std::collections::{HashMap, HashSet};
/// What every node's implementation names, so nodes need no proto-node declarations. The first node drawn brings it,
/// as the editor's first layer brings the subgraph every later one is built from.
pub(super) const LEAF: NetworkId = NetworkId(1);
/// What the export holds while the document is empty, of another type than what a chain's bottom rests on.
pub(super) fn empty_export() -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!("empty")),
exposed: false,
}
}
/// A small xorshift generator, so a seed fixes the run.
pub(super) struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
pub(super) fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
pub(super) fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// A kind of document the simulation edits.
pub(super) trait Scenario {
/// One interaction's ops for a random edit, as the editor would stage them.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta>;
/// Panics with `context` when `registry` is not a document this scenario allows.
fn assert_well_formed(context: &str, registry: &Registry);
}
/// The nodes down the chain off the export, following each one's primary input.
pub(super) fn stack(registry: &Registry) -> Vec<NodeId> {
let mut nodes = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if nodes.contains(&id) {
break;
}
nodes.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
nodes
}
/// What feeds into `node` from below.
pub(super) fn below(registry: &Registry, node: NodeId) -> NodeInput {
registry.node_instances[&node].inputs[0].input.clone()
}
pub(super) fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
pub(super) fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// Reads a number from the environment variable `name`, so a run can be widened or replayed.
pub(super) fn from_env<T: std::str::FromStr>(name: &str, default: T) -> T {
std::env::var(name).ok().and_then(|text| text.parse().ok()).unwrap_or(default)
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
RegistryDelta::AddNetwork { id, .. } => format!("add network {}", id.0),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The nodes the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The nodes the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The nodes live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
fn assert_consistent<S: Scenario>(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
S::assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
/// Runs `steps` random edits and history operations from `seed`. After each one the document must be well formed, the
/// snapshot must be what history folds to, and a peer following the host must hold the same document.
pub(super) fn simulate<S: Scenario>(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let document = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(empty_export()),
},
];
host.stage_ops(document).expect("stage the document");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = S::random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
}
8 => {
let steps = line_steps(&host);
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&steps[1.min(steps.len())..]) else { continue };
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
}
9 => {
let steps = line_steps(&host);
// The first step makes the document, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A node the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's nodes {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A node the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's nodes {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the nodes {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent::<S>(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
}
+1
View File
@@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES),
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
}
}
@@ -0,0 +1,80 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
TransferCurve(Vec<[f64; 2]>),
TypeDefault(Type),
}
/// Frozen mirror of the `Type` a paint input's lack of a paint stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
Item(Box<Type>),
}
#[derive(Serialize, Deserialize)]
struct TypeDescriptor {
name: String,
}
/// 'Bevel & Emboss' gained a texture with its depth, and a gloss contour and a slope contour with its range, set to no texture and straight contours across the whole slope to keep the bevel as it was.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@1 => @2)]
pub fn bevel_and_emboss_v1(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// The texture, its depth, the slope contour's range, the gloss and slope contours' antialiasing, and the gloss and slope contours.
fn added_inputs() -> [NodeInput; 7] {
let straight = || literal(Tagged::TransferCurve(vec![[0., 0.], [1., 1.]]));
let no_paint = Tagged::TypeDefault(Type::Item(Box::new(Type::Concrete(TypeDescriptor {
name: "graphic_types::graphic::Graphic".to_string(),
}))));
[
literal(no_paint),
literal(Tagged::Number(100.)),
literal(Tagged::Number(100.)),
literal(Tagged::Bool(false)),
literal(Tagged::Bool(false)),
straight(),
straight(),
]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(13, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV1, &contract());
check_undo(&BevelAndEmbossV1, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_options_that_leave_the_bevel_as_it_was() {
let inputs: Vec<_> = (0..13).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV1);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@1), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV1).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@2)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Drop Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
#[migration("blending_nodes::effects::DropShadowNode"@1 => @2)]
pub fn drop_shadow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DropShadowV1, &contract());
check_undo(&DropShadowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&DropShadowV1);
let drop_shadow = fixture.add(decl!("blending_nodes::effects::DropShadowNode"@1), inputs.clone());
let migrated = fixture.migrate(&DropShadowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, drop_shadow), Some(decl!("blending_nodes::effects::DropShadowNode"@2)));
assert_eq!(fixture.inputs(&migrated, drop_shadow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Inner Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
#[migration("blending_nodes::effects::InnerGlowNode"@1 => @2)]
pub fn inner_glow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerGlowV1, &contract());
check_undo(&InnerGlowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerGlowV1);
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@1), inputs.clone());
let migrated = fixture.migrate(&InnerGlowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@2)));
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Inner Shadow' gained a blend mode after its color, set to Normal to keep compositing the shadow as before.
#[migration("blending_nodes::effects::InnerShadowNode"@1 => @2)]
pub fn inner_shadow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InnerShadowV1, &contract());
check_undo(&InnerShadowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&InnerShadowV1);
let inner_shadow = fixture.add(decl!("blending_nodes::effects::InnerShadowNode"@1), inputs.clone());
let migrated = fixture.migrate(&InnerShadowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, inner_shadow), Some(decl!("blending_nodes::effects::InnerShadowNode"@2)));
assert_eq!(fixture.inputs(&migrated, inner_shadow), expected);
}
}
@@ -0,0 +1,59 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
MaskMode(MaskMode),
}
#[derive(Serialize, Deserialize)]
enum MaskMode {
Luminance,
}
/// 'Mask' became an effect masking any graphic by any other, keeping its content and mask and gaining its mode, density, feather, and invert at their defaults.
#[migration("raster_nodes::std_nodes::MaskNode"@1 => "blending_nodes::masks::MaskNode"@2)]
pub fn mask_by_any_graphic(inputs: &mut Inputs) {
inputs.push(literal(Tagged::MaskMode(MaskMode::Luminance)));
inputs.push(literal(Tagged::Number(100.)));
inputs.push(literal(Tagged::Number(0.)));
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MaskByAnyGraphic, &contract());
check_undo(&MaskByAnyGraphic, &contract());
}
#[test]
fn keeps_the_content_and_mask_and_adds_the_defaults() {
let (content, stencil) = (literal(1.), literal(2.));
let mut fixture = Fixture::new(&MaskByAnyGraphic);
let mask = fixture.add(decl!("raster_nodes::std_nodes::MaskNode"@1), vec![content.clone(), stencil.clone()]);
let migrated = fixture.migrate(&MaskByAnyGraphic).unwrap();
assert_eq!(fixture.declaration_of(&migrated, mask), Some(decl!("blending_nodes::masks::MaskNode"@2)));
let defaults = [
literal(Tagged::MaskMode(MaskMode::Luminance)),
literal(Tagged::Number(100.)),
literal(Tagged::Number(0.)),
literal(Tagged::Bool(false)),
];
assert_eq!(fixture.inputs(&migrated, mask), [[content, stencil].as_slice(), &defaults].concat());
}
}
@@ -1,3 +1,13 @@
//! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1;
mod drop_shadow_v1;
mod inner_glow_v1;
mod inner_shadow_v1;
mod mask_by_any_graphic;
mod outer_glow_v1;
mod outline_v1;
mod outline_v2;
mod paint_overlay_from_color_overlay;
mod renames;
mod satin_v1;
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Outer Glow' gained a blend mode after its color, set to Normal to keep compositing the glow as before.
#[migration("blending_nodes::effects::OuterGlowNode"@1 => @2)]
pub fn outer_glow_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OuterGlowV1, &contract());
check_undo(&OuterGlowV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OuterGlowV1);
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@1), inputs.clone());
let migrated = fixture.migrate(&OuterGlowV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@2)));
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Outline' gained a blend mode after its color, set to Normal, which composites the outline as before.
#[migration("blending_nodes::effects::OutlineNode"@1 => @2)]
pub fn outline_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV1, &contract());
check_undo(&OutlineV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV1);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@1), inputs.clone());
let migrated = fixture.migrate(&OutlineV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@2)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,45 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Outline' takes its color as any paint now, and gained a Contour Gradient option, set off to keep painting by the paint's own placement.
#[migration("blending_nodes::effects::OutlineNode"@2 => @3)]
pub fn outline_v2(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV2, &contract());
check_undo(&OutlineV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_contour_gradient_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV2);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@2), inputs.clone());
let migrated = fixture.migrate(&OutlineV2).unwrap();
let mut expected = inputs;
expected.push(literal(Tagged::Bool(false)));
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@3)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,43 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Node, migration};
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
attributes.remove(node.id(), DISPLAY_NAME);
}
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::TimeStamp;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
#[test]
fn rewrites_history() {
let contract = SourceContract {
display_names: &["Color Overlay"],
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
};
check_commutation(&PaintOverlayFromColorOverlay, &contract);
check_undo(&PaintOverlayFromColorOverlay, &contract);
}
#[test]
fn only_the_old_default_name_is_cleared() {
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
}
}
}
@@ -0,0 +1,50 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
BlendMode(BlendMode),
}
#[derive(Serialize, Deserialize)]
enum BlendMode {
Normal,
}
/// 'Satin' gained a blend mode after its color, set to Normal to keep compositing the shading as before.
#[migration("blending_nodes::effects::SatinNode"@1 => @2)]
pub fn satin_v1(inputs: &mut Inputs) {
inputs.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&SatinV1, &contract());
check_undo(&SatinV1, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_normal_after_the_color() {
let inputs: Vec<_> = (0..7).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&SatinV1);
let satin = fixture.add(decl!("blending_nodes::effects::SatinNode"@1), inputs.clone());
let migrated = fixture.migrate(&SatinV1).unwrap();
let mut expected = inputs;
expected.insert(2, literal(Tagged::BlendMode(BlendMode::Normal)));
assert_eq!(fixture.declaration_of(&migrated, satin), Some(decl!("blending_nodes::effects::SatinNode"@2)));
assert_eq!(fixture.inputs(&migrated, satin), expected);
}
}
@@ -0,0 +1,47 @@
use migration_core::{Inputs, NodeInput, migration};
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
pub fn math_function_v2(inputs: &mut Inputs) {
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
String(String),
}
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::String("x".to_string())),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&MathFunctionV2, &contract());
check_undo(&MathFunctionV2, &contract());
}
#[test]
fn the_resolution_is_read_from_the_scope() {
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
let mut fixture = Fixture::new(&MathFunctionV2);
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
assert_eq!(fixture.inputs(&migrated, function), expected);
}
}
@@ -1,4 +1,5 @@
//! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f;
mod math_function_v2;
mod renames;
@@ -0,0 +1,65 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&CircleV1, &contract());
check_undo(&CircleV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&CircleV1);
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
let migrated = fixture.migrate(&CircleV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
}
}
@@ -1,4 +1,5 @@
//! Migrations of the nodes in `vector_nodes`.
mod circle_v1;
mod path_from_path_network;
mod renames;
@@ -6,6 +6,8 @@ use crate::messages::prelude::*;
pub enum DialogMessage {
// Sub-messages
#[child]
DocumentSetupDialog(DocumentSetupDialogMessage),
#[child]
ExportDialog(ExportDialogMessage),
#[child]
NewDocumentDialog(NewDocumentDialogMessage),
@@ -34,6 +36,7 @@ pub enum DialogMessage {
localized_commit_year: String,
},
RequestDemoArtworkDialog,
RequestDocumentSetupDialog,
RequestExportDialog,
RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: String,
@@ -4,6 +4,7 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
use crate::messages::frontend::utility_types::ExportBounds;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
#[derive(ExtractField)]
pub struct DialogMessageContext<'a> {
@@ -16,6 +17,7 @@ pub struct DialogMessageContext<'a> {
pub struct DialogMessageHandler {
on_dismiss: Option<Message>,
redisplay: Option<Message>,
document_setup_dialog: DocumentSetupDialogMessageHandler,
export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler,
@@ -27,6 +29,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let DialogMessageContext { portfolio, preferences } = context;
match message {
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
@@ -100,10 +103,34 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let dialog = DemoArtworkDialog;
dialog.send_dialog_to_frontend(responses);
}
DialogMessage::RequestDocumentSetupDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
pixels_per_inch: document.network_interface.pixels_per_inch(),
};
self.document_setup_dialog.send_dialog_to_frontend(responses);
}
}
DialogMessage::RequestExportDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
self.export_dialog.artboards = document.artboard_names().into_iter().collect();
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.contains_key(&layer)
@@ -130,7 +157,9 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
self.new_document_dialog = NewDocumentDialogMessageHandler {
name: portfolio.generate_new_document_name(None),
infinite: false,
dimensions: glam::UVec2::new(1920, 1080),
width: TypedLength::pixels(1920.),
height: TypedLength::pixels(1080.),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
};
self.new_document_dialog.send_dialog_to_frontend(responses);
}
@@ -0,0 +1,9 @@
use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DocumentSetupDialogMessage {
Resolution { pixels_per_inch: f64 },
Submit,
}
@@ -0,0 +1,158 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
/// A dialog to allow users to change the settings of the active document.
#[derive(Debug, Clone, ExtractField)]
pub struct DocumentSetupDialogMessageHandler {
pub pixels_per_inch: f64,
}
impl Default for DocumentSetupDialogMessageHandler {
fn default() -> Self {
Self {
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
}
#[message_handler_data]
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
DocumentSetupDialogMessage::Submit => {
// The settings apply as one undo step, which ending the transaction drops if nothing changed
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
responses.add(DocumentMessage::EndTransaction);
}
}
self.send_dialog_to_frontend(responses);
}
advertise_actions!(DocumentSetupDialogUpdate;
);
}
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "Document Setup";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("OK")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for DocumentSetupDialogMessageHandler {
fn layout(&self) -> Layout {
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
Layout(vec![LayoutGroup::row(resolution)])
}
}
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
vec![
TextLabel::new("Resolution")
.table_align(true)
.sizing(WidgetSizing::fixed(90))
.tooltip_label("Resolution")
.tooltip_description(description)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(pixels_per_inch))
.unit(" PPI")
.min(1.)
.max(100_000.)
.tooltip_label("Resolution")
.tooltip_description(description)
// Matches the width of the New Document dialog's Name field
.sizing(WidgetSizing::default().min_width(204))
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
.widget_instance(),
]
}
#[cfg(test)]
mod tests {
use crate::test_utils::test_prelude::*;
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
editor.active_document().network_interface.pixels_per_inch()
}
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
}
async fn confirm(editor: &mut EditorTestUtils) {
editor
.handle_message(DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
})
.await;
}
#[tokio::test]
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer_count = editor.active_document().metadata().all_layers().count();
open_and_set_resolution(&mut editor, 300.).await;
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
// Undoing reverts only the resolution, leaving the rectangle drawn before it
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96.);
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(pixels_per_inch(&editor), 300.);
}
#[tokio::test]
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
open_and_set_resolution(&mut editor, 300.).await;
confirm(&mut editor).await;
open_and_set_resolution(&mut editor, 150.).await;
editor.handle_message(DialogMessage::Close).await;
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
}
}
@@ -0,0 +1,7 @@
mod document_setup_dialog_message;
mod document_setup_dialog_message_handler;
#[doc(inline)]
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
#[doc(inline)]
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
@@ -94,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"),
@@ -131,25 +131,14 @@ impl LayoutHolder for ExportDialogMessageHandler {
.widget_instance(),
];
let scale_description = match self.file_type {
FileType::Pdf => "Resolution of the images of effects and other content PDF can't draw itself, where 1 is 300 DPI.",
_ => "Size of the exported image relative to the document's size.",
};
let resolution = vec![
TextLabel::new("Scale Factor")
.table_align(true)
.sizing(WidgetSizing::fixed(100))
.tooltip_label("Scale Factor")
.tooltip_description(scale_description)
.widget_instance(),
TextLabel::new("Scale Factor").table_align(true).sizing(WidgetSizing::fixed(100)).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.scale_factor))
.unit("")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.increment_step(0.5)
.tooltip_label("Scale Factor")
.tooltip_description(scale_description)
.disabled(self.file_type == FileType::Svg)
.on_update(|number_input: &NumberInput| ExportDialogMessage::ScaleFactor { factor: number_input.value.unwrap() }.into())
.sizing(WidgetSizing::default().min_width(200))
+1
View File
@@ -8,6 +8,7 @@
mod dialog_message;
mod dialog_message_handler;
pub mod document_setup_dialog;
pub mod export_dialog;
pub mod new_document_dialog;
pub mod preferences_dialog;
@@ -1,12 +1,14 @@
use crate::messages::prelude::*;
use graphene_std::units::TypedLength;
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum NewDocumentDialogMessage {
Name { name: String },
Infinite { infinite: bool },
DimensionsX { width: f64 },
DimensionsY { height: f64 },
DimensionsX { width: TypedLength },
DimensionsY { height: TypedLength },
Resolution { pixels_per_inch: f64 },
Submit,
}
@@ -1,16 +1,33 @@
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::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::UVec2;
use glam::DVec2;
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength};
/// A dialog to allow users to set some initial options about a new document.
#[derive(Debug, Clone, Default, ExtractField)]
#[derive(Debug, Clone, ExtractField)]
pub struct NewDocumentDialogMessageHandler {
pub name: String,
pub infinite: bool,
pub dimensions: UVec2,
pub width: TypedLength,
pub height: TypedLength,
pub pixels_per_inch: f64,
}
impl Default for NewDocumentDialogMessageHandler {
fn default() -> Self {
Self {
name: String::new(),
infinite: false,
width: TypedLength::default(),
height: TypedLength::default(),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
}
#[message_handler_data]
@@ -19,24 +36,37 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
match message {
NewDocumentDialogMessage::Name { name } => self.name = name,
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
NewDocumentDialogMessage::DimensionsX { width } => {
self.width = whole_pixels(width);
self.height = self.in_unit(self.height, self.width.unit);
}
NewDocumentDialogMessage::DimensionsY { height } => {
self.height = whole_pixels(height);
self.width = self.in_unit(self.width, self.height.unit);
}
NewDocumentDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
NewDocumentDialogMessage::Submit => {
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
// Like the artboard, the resolution is part of the document's starting state rather than an undo step
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
let dimensions = self.artboard_dimensions();
if self.infinite {
// Infinite canvas: add a locked white background layer
graph_modification_utils::new_background_layer(0, responses);
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
} else if dimensions.x > 0. && dimensions.y > 0. {
// Finite canvas: create an artboard with the specified dimensions
responses.add(GraphOperationMessage::NewArtboard {
id: NodeId::new(),
location: glam::DVec2::ZERO,
dimensions: self.dimensions.as_dvec2(),
location: DVec2::ZERO,
dimensions,
background: Color::WHITE,
clip: true,
});
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
responses.add(NavigationMessage::CanvasPan { delta: dimensions });
}
responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -107,32 +137,150 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
.widget_instance(),
];
let scale = vec![
// Each dimension shows the unit it was typed in and keeps any length unit typed into it
let dimension_field = |length: TypedLength, label: &str| {
NumberInput::new(Some(length.value))
.label(label)
.unit(unit_suffix(length.unit.symbol()))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(self.pixels_per_inch)
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
};
let dimensions = vec![
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(self.dimensions.x as f64))
.label("W")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
dimension_field(self.width, "W")
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into())
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
NumberInput::new(Some(self.dimensions.y as f64))
.label("H")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
dimension_field(self.height, "H")
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into())
.widget_instance(),
];
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into());
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(dimensions), LayoutGroup::row(resolution)])
}
}
impl NewDocumentDialogMessageHandler {
/// A dimension converted into `unit` at the chosen resolution, keeping its size.
fn in_unit(&self, length: TypedLength, unit: LengthUnit) -> TypedLength {
whole_pixels(TypedLength {
value: length.unit.convert(length.value, unit, self.pixels_per_inch),
unit,
})
}
/// The artboard's size in whole pixels, converting a dimension typed in a physical unit at the chosen resolution.
pub fn artboard_dimensions(&self) -> DVec2 {
let pixels = |length: TypedLength| length.to_length(self.pixels_per_inch).pixels().round();
DVec2::new(pixels(self.width), pixels(self.height))
}
}
/// 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 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<DVec2> {
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())?;
match node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value()? {
TaggedValue::DVec2(dimensions) => Some(*dimensions),
_ => None,
}
}
#[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_dimensions(&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_dimensions(&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_dimensions(&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_dimensions(&editor), Some(DVec2::new(2480., 3508.)));
}
}
+1 -10
View File
@@ -78,7 +78,6 @@ pub enum FileType {
Tga,
Ico,
Svg,
Pdf,
}
impl FileType {
@@ -92,15 +91,9 @@ impl FileType {
FileType::Tga => "tga",
FileType::Ico => "ico",
FileType::Svg => "svg",
FileType::Pdf => "pdf",
}
}
/// Whether the file holds vector content rather than an image of the export's area.
pub fn is_vector(self) -> bool {
matches!(self, FileType::Svg | FileType::Pdf)
}
pub fn file_filter(self) -> FileFilter {
let name = match self {
FileType::Png => "PNG Image",
@@ -111,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(),
@@ -137,7 +129,7 @@ impl FileType {
FileType::Bmp => ImageFormat::Bmp,
FileType::Tga => ImageFormat::Tga,
FileType::Ico => ImageFormat::Ico,
FileType::Svg | FileType::Pdf => return Err(format!("{} cannot be exported from an image buffer", self.extension().to_uppercase())),
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
};
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());
@@ -236,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,16 +417,20 @@ impl LayoutMessageHandler {
}
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
Value::String(expression) => {
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else {
return;
};
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
if number_input.value == Some(evaluated) {
if number_input.value == Some(evaluated) && number_input.unit == unit {
return;
}
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
responses.add((number_input.on_commit.callback)(&()));
number_input.value = Some(evaluated);
number_input.unit = unit;
responses.add((number_input.on_update.callback)(number_input));
}
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
@@ -704,21 +708,41 @@ fn populate_computed_display_fields(layout: &mut Layout) {
}
}
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
let value = math_parser::evaluate(expression)
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`.
pub fn unit_suffix(symbol: &str) -> String {
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() }
}
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
let value = math_parser::ast::Node::try_parse_from_str(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()?
.eval(&context)
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?;
let real = value.as_real()?;
if real.is_nan() {
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it
let field_unit = math_parser::units::Unit::named(number_input.unit.trim());
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
(Some(quantity), Some(unit)) => {
let read = quantity
.read_in(unit, number_input.pixels_per_inch)
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
.ok()?
.as_real()?;
(read, Some(*quantity))
}
_ => (value.as_real()?, None),
};
if in_field_unit.is_nan() {
return None;
}
let mut validated = real;
let mut validated = in_field_unit;
if let Some(min) = number_input.min {
validated = validated.max(min);
}
@@ -729,5 +753,17 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
validated = validated.round();
}
Some(validated)
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it
let kept_unit = quantity.and_then(|quantity| {
let symbol = quantity.unit.single()?.definition().symbol;
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
});
if let Some((quantity, symbol)) = kept_unit
&& validated == in_field_unit
&& let Some(kept_value) = quantity.value.as_real()
{
return Some((kept_value, Some(symbol.to_string())));
}
Some((validated, None))
}
@@ -247,6 +247,14 @@ pub struct NumberInput {
#[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))]
pub unit_is_hidden_when_editing: bool,
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
#[serde(skip)]
pub kept_units: Vec<String>,
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
#[serde(skip)]
#[derivative(Default(value = "96."))]
pub pixels_per_inch: f64,
// Tooltips
#[serde(rename = "tooltipLabel")]
@@ -607,6 +615,7 @@ pub enum MathExpressionRole {
Function,
Keyword,
Operator,
Unit,
Bracket,
MatrixLiteral,
Error,
@@ -623,6 +632,7 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
Role::Function => Self::Function,
Role::Keyword => Self::Keyword,
Role::Operator => Self::Operator,
Role::Unit => Self::Unit,
Role::Bracket => Self::Bracket,
Role::MatrixLiteral => Self::MatrixLiteral,
Role::Error => Self::Error,
@@ -181,6 +181,13 @@ impl LayoutHolder for MenuBarMessageHandler {
.on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document),
],
vec![
MenuListEntry::new("Document Setup…")
.label("Document Setup…")
.icon("Settings")
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))]
vec![preferences],
])
@@ -25,6 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::Footprint;
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::units::{Angle, Length};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
@@ -33,7 +34,10 @@ use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowTechnique, Graphic};
use graphene_std::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
MaskMode,
};
use kurbo::BezPath;
use std::any::Any;
use std::ops::Range;
@@ -398,6 +402,8 @@ macro_rules! inspectable_types {
List<Generator>,
List<String>,
List<f64>,
List<Length>,
List<Angle>,
List<i64>,
List<bool>,
List<DVec2>,
@@ -458,6 +464,8 @@ macro_rules! inspectable_types {
Item<Generator>,
Item<String>,
Item<f64>,
Item<Length>,
Item<Angle>,
Item<i64>,
Item<bool>,
Item<DVec2>,
@@ -1097,6 +1105,30 @@ 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 u8 {
fn type_name() -> &'static str {
"Byte"
@@ -1265,8 +1297,13 @@ macro_rules! impl_table_item_layout_for_choice_enum {
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
BevelDirection,
BevelTechnique,
BevelStyle,
EffectKind,
Generator,
GlowSource,
MaskMode,
GradientForm,
GradientSpread,
GradientSpace,
@@ -1446,6 +1483,11 @@ macro_rules! known_item_types {
Effects,
Effect,
EffectKind,
GlowSource,
MaskMode,
BevelStyle,
BevelDirection,
BevelTechnique,
DashPattern,
BoxCorners,
TransferCurve,
@@ -266,6 +266,11 @@ pub enum DocumentMessage {
SetRenderMode {
render_mode: RenderMode,
},
/// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports.
/// The caller wraps it in a transaction to make it one undo step.
SetPixelsPerInch {
pixels_per_inch: f64,
},
ShowNodeInGraph {
node_id: NodeId,
},
@@ -53,6 +53,7 @@ use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::{GradientStops, RenderMode};
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
@@ -1694,6 +1695,16 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.render_mode = render_mode;
responses.add_front(NodeGraphMessage::RunDocumentGraph);
}
DocumentMessage::SetPixelsPerInch { pixels_per_inch } => {
if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() {
return;
}
self.network_interface.set_pixels_per_inch(pixels_per_inch);
// Lengths typed in a physical unit change their size in pixels, so the graph runs again
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(InspectorMessage::Refresh);
}
DocumentMessage::ShowNodeInGraph { node_id } => {
// The node is in the document network, so the graph first leaves any nested network it's showing
if !self.breadcrumb_network_path.is_empty() {
@@ -2445,20 +2456,6 @@ impl DocumentMessageHandler {
self.network_interface.document_metadata()
}
/// The document's artboards with their names, called "Artboard" while left unnamed.
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
}
@@ -3244,7 +3241,10 @@ impl DocumentMessageHandler {
}
pub fn current_hash(&self) -> u64 {
self.network_interface.document_network().current_hash()
// The resolution lives in the network's metadata rather than the network, but changing it changes the document
let mut hasher = std::collections::hash_map::DefaultHasher::new();
(self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher);
hasher.finish()
}
pub fn is_auto_saved(&self) -> bool {
@@ -206,6 +206,9 @@ impl<'a> ModifyInputsContext<'a> {
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)
.expect("Text to Vector node does not exist")
.default_node_template();
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
.expect("Transform node does not exist")
.default_node_template();
@@ -213,13 +216,17 @@ impl<'a> ModifyInputsContext<'a> {
.expect("Fill node does not exist")
.default_node_template();
// Build the chain `Text -> Transform -> Fill -> layer`, keeping the text native so backends lay out and draw its glyphs
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
let text_id = NodeId::new();
self.network_interface.insert_node(text_id, text, &[]);
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
let text_to_vector_id = NodeId::new();
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
let transform_id = NodeId::new();
self.network_interface.insert_node(transform_id, transform, &[]);
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
@@ -872,6 +872,46 @@ fn static_input_inspector() -> InputInspector {
))])
}),
);
map.insert(
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
"wrapping_range_slider".to_string(),
Box::new(|node_id, index, context| {
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
let field = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
let mut number_input = NumberInput::default().mode_increment();
let mut period = None;
if let Some(field) = field {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
if let Some(display_decimal_places) = field.number_display_decimal_places {
number_input = number_input.display_decimal_places(display_decimal_places);
}
if let Some(number_step) = field.number_step {
number_input = number_input.step(number_step);
}
period = field.number_soft_min.zip(field.number_soft_max);
}
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
let row = match period {
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
let default = node_inspector::definition_default_number(&parameter_widgets_info);
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
}
_ => {
log::error!("A wrapping range slider needs finite soft bounds at both ends");
node_inspector::number_widget(parameter_widgets_info, number_input)
}
};
Ok(vec![LayoutGroup::row(row)])
}),
);
map.insert(
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
"type_choice".to_string(),
@@ -2,6 +2,7 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
use super::utility_types::FrontendGraphDataType;
use crate::messages::layout::layout_message_handler::unit_suffix;
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*;
@@ -31,6 +32,7 @@ use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit, TypedAngle, TypedLength};
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
@@ -40,7 +42,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, GlowTechnique, Graphic, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -268,10 +270,18 @@ impl SliderRange {
fn value(self, position: f64) -> f64 {
(self.min + position * (self.max - self.min)).clamp(self.min, self.max)
}
/// The `value` moved into the bounds by whole periods of their width, for a periodic number like an angle.
fn wrapped(self, value: f64) -> f64 {
if (self.min..=self.max).contains(&value) {
return value;
}
self.min + (value - self.min).rem_euclid(self.max - self.min)
}
}
/// The number a parameter's definition gives it by default, which a slider's double-click restores.
fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
pub(crate) fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> Option<f64> {
let identifier = parameter_widgets_info
.network_interface
.reference(&parameter_widgets_info.node_id, parameter_widgets_info.selection_network_path)?;
@@ -297,7 +307,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
step,
} = options;
let mut number_input = NumberInput::default();
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch());
if slider {
number_input = number_input.mode_range();
}
@@ -379,6 +389,8 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
},
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<Angle>(x) => angle_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(),
@@ -388,6 +400,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
// ============
// STRUCT TYPES
// ============
@@ -442,6 +455,11 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -882,6 +900,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
@@ -898,6 +917,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
.on_commit(commit_value)
.widget_instance(),
@@ -909,6 +929,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -924,6 +945,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
.on_commit(commit_value)
.widget_instance(),
@@ -935,6 +957,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer)
.disabled(disabled)
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
.on_commit(commit_value)
.widget_instance(),
@@ -1303,6 +1326,92 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
widgets
}
/// Converts a field's bounds from the unit they're given in into the unit its value is shown in.
fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput {
let convert = |bound: Option<f64>| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound });
NumberInput {
min: convert(number_input.min),
max: convert(number_input.max),
range_min: convert(number_input.range_min),
range_max: convert(number_input.range_max),
..number_input
}
}
/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the
/// field's bounds given in pixels.
pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let length = match input.as_non_exposed_value() {
Some(&TaggedValue::Length(length)) => length,
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
_ => return widgets,
};
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(length.value))
.unit(unit_suffix(length.unit.symbol()))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(pixels_per_inch)
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
TaggedValue::Length(TypedLength {
value: input.value.unwrap_or_default(),
unit,
})
}))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the
/// field's bounds given in degrees.
pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid.");
return vec![];
};
let angle = match input.as_non_exposed_value() {
Some(&TaggedValue::Angle(angle)) => angle,
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
_ => return widgets,
};
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_angle(Angle::from_degrees(degrees)));
widgets.extend_from_slice(&[
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
number_props
.value(Some(angle.value))
.unit(unit_suffix(angle.unit.symbol()))
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
TaggedValue::Angle(TypedAngle {
value: input.value.unwrap_or_default(),
unit,
})
}))
.on_commit(commit_value)
.widget_instance(),
]);
widgets
}
// TODO: Auto-generate this enum dropdown menu widget
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1403,6 +1512,7 @@ fn wire_element(ty: &Type) -> Type {
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(Length), concrete!(Angle)],
vec![concrete!(DVec2)],
vec![concrete!(DAffine2)],
vec![concrete!(Artboard)],
@@ -2377,13 +2487,14 @@ fn value_slider(
}
/// A row with a range slider and a 60px number input for the number at `parameter_widgets_info`. The slider's 0..1 position maps
/// to the number through `position_of` and `value_at`, and double-click restores `default`.
/// to the number through `position_of` and `value_at`, a typed number is stored as `typed_value` gives it, and double-click restores `default`.
fn slider_row(
parameter_widgets_info: ParameterWidgetsInfo,
number_props: NumberInput,
default: Option<f64>,
position_of: impl Fn(f64) -> f64,
value_at: impl Fn(f64) -> f64 + 'static + Send + Sync,
typed_value: impl Fn(f64) -> f64 + 'static + Send + Sync,
) -> Vec<WidgetInstance> {
let mut widgets = start_widgets(&parameter_widgets_info);
@@ -2416,7 +2527,7 @@ fn slider_row(
number_props
.value(Some(current))
.sizing(WidgetSizing::fixed(60))
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(x.value.unwrap_or_default()), node_id, index))
.on_update(update_value_at_index(move |x: &NumberInput| tagged_value(typed_value(x.value.unwrap_or_default())), node_id, index))
.on_commit(commit_value)
.widget_instance(),
]);
@@ -2432,6 +2543,19 @@ pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo,
slider.default,
move |value| slider.position(value),
move |position| slider.value(position),
|value| value,
)
}
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
slider_row(
parameter_widgets_info,
number_props,
slider.default,
move |value| slider.position(slider.wrapped(value)),
move |position| slider.value(position),
move |value| slider.wrapped(value),
)
}
@@ -2903,6 +3027,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
Some(1.),
|gamma| MarkerScale::Gamma.position(gamma),
|position| MarkerScale::Gamma.value(position),
|gamma| gamma,
);
vec![LayoutGroup::row(exposure), LayoutGroup::row(offset), LayoutGroup::row(gamma_correction)]
@@ -4027,7 +4152,10 @@ mod tests {
fn math_expression_errors_quote_the_expression_safely() {
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
assert_eq!(
description("7 % 3").as_deref(),
Some("`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`")
);
// A quoted token like `*` is a code span, so it can't pair with another into italics
let error = description("2 * * 3").unwrap();
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color,
"Gradient" => Self::Gradient,
"String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster,
@@ -22,7 +22,6 @@ pub struct ResourceMessageHandler {
pub embedded: EmbeddedResources,
#[serde(skip)]
pending_resolves: HashSet<ResourceId>,
/// Resources that failed to load, which rendering no longer waits on, even during a retry.
#[serde(skip)]
failed_resolves: HashSet<ResourceId>,
}
@@ -219,8 +218,6 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
ResourceMessage::ResolveFailed { resource_id } => {
self.pending_resolves.remove(&resource_id);
self.failed_resolves.insert(resource_id);
// Rendering stops waiting on the resource and draws a fallback in its place
responses.add(NodeGraphMessage::RunDocumentGraph);
}
}
@@ -236,20 +233,6 @@ impl ResourceMessageHandler {
self.registry.is_empty() && self.embedded.is_empty()
}
/// Whether a resource lacks its data and hasn't failed to load, which rendering waits for.
pub fn awaiting_resources(&self) -> bool {
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
}
/// Changes whenever a resource gains, loses, or changes its data. Summed per resource since the registry's order isn't stable. O(resolved resources).
pub fn resolved_hash(&self) -> u64 {
self.registry.resolved().fold(0, |sum, info| {
let mut hasher = DefaultHasher::new();
(info.id, info.hash).hash(&mut hasher);
sum.wrapping_add(hasher.finish())
})
}
pub async fn embed_resources(&mut self, resources_load_handle: Box<dyn LoadResource>) {
let embedded = self
.registry
@@ -275,6 +258,18 @@ impl ResourceMessageHandler {
self.registry.delete(&id);
});
}
pub fn awaiting_resources(&self) -> bool {
self.registry.unresolved().any(|info| !self.failed_resolves.contains(&info.id))
}
pub fn resolved_hash(&self) -> u64 {
self.registry.resolved().fold(0, |sum, info| {
let mut hasher = DefaultHasher::new();
(info.id, info.hash).hash(&mut hasher);
sum.wrapping_add(hasher.finish())
})
}
}
// TODO: Eventually remove this document upgrade code
@@ -296,6 +296,29 @@ fn pinned_order_round_trips_through_the_registry() {
);
}
/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence.
#[test]
fn pixels_per_inch_round_trips_through_the_registry() {
let round_trip = |pixels_per_inch: f64| {
let mut document = open_demo("changing-seasons.graphite");
document.network_interface.set_pixels_per_inch(pixels_per_inch);
let network = document.network_interface.document_network().clone();
let view = StorageMetadataView::new(&document.network_interface);
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
let declarations = conversion.declarations;
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries);
(
rebuilt.pixels_per_inch(),
rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch,
)
};
assert_eq!(round_trip(300.), (300., Some(300.)));
assert_eq!(round_trip(96.), (96., None));
}
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
/// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test]
@@ -105,6 +105,7 @@ impl NodeNetworkInterface {
match change {
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch),
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
@@ -75,6 +75,7 @@ pub enum NetworkMetadataChange {
Reference(Option<String>),
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
PinnedOrder(Vec<NodeId>),
PixelsPerInch(Option<f64>),
ImportMetadata(Vec<InputMetadata>),
ExportNames(Vec<String>),
ExportDescriptions(Vec<String>),
@@ -256,6 +257,12 @@ impl EditorDelta {
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
}
}
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => AttributeDelta {
key: network_attr::PIXELS_PER_INCH.to_string(),
value: pixels_per_inch
.map(|pixels_per_inch| serialize_attribute(network_attr::PIXELS_PER_INCH, &pixels_per_inch))
.transpose()?,
},
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
@@ -1254,6 +1254,19 @@ impl NodeNetworkInterface {
self.transaction_modified();
}
/// Sets how many pixels make an inch in the document, stored only where it differs from the default.
pub fn set_pixels_per_inch(&mut self, pixels_per_inch: f64) {
let stored = (pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH).then_some(pixels_per_inch);
let Some(mut network) = self.network_mut(&[]) else {
log::error!("Could not get the root network in set_pixels_per_inch");
return;
};
network.set_pixels_per_inch(stored);
self.transaction_modified();
}
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_visibility");
@@ -128,10 +128,18 @@ impl NodeNetworkInterface {
});
let mut hasher = std::hash::DefaultHasher::new();
(self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
(self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher);
hasher.finish()
}
/// How many pixels make an inch in the document, which sizes the lengths typed in a physical unit.
pub fn pixels_per_inch(&self) -> f64 {
self.network_metadata(&[])
.and_then(|metadata| metadata.persistent_metadata.pixels_per_inch)
.filter(|pixels_per_inch| pixels_per_inch.is_finite() && *pixels_per_inch > 0.)
.unwrap_or(graphene_std::units::DEFAULT_PIXELS_PER_INCH)
}
/// Get the specified document node in the nested network based on node_id and network_path
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
self.query(network_path, "document_node", |view| view.node(node_id))
@@ -143,6 +143,9 @@ impl NodeNetworkInterface {
if current_metadata.pinned_node_order != target.metadata.pinned_order {
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
}
if current_metadata.pixels_per_inch != target.metadata.pixels_per_inch {
deltas.push(change(NetworkMetadataChange::PixelsPerInch(target.metadata.pixels_per_inch)));
}
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
@@ -111,6 +111,10 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
}
fn pixels_per_inch(&self, network: NetworkLocation) -> Option<f64> {
self.network_persistent(network)?.pixels_per_inch
}
}
impl DocumentSettings<'_> {
@@ -307,6 +311,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
network_metadata.persistent_metadata.reference = Some(reference);
}
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
network_metadata.persistent_metadata.pixels_per_inch = entry.pixels_per_inch;
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
network_metadata.persistent_metadata.export_names = entry.export_names;
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
@@ -538,6 +538,16 @@ impl NetworkMut<'_> {
changed
}
/// How many pixels make an inch in the document, or `None` for the default.
pub(crate) fn set_pixels_per_inch(&mut self, pixels_per_inch: Option<f64>) -> bool {
let changed = self.metadata.pixels_per_inch != pixels_per_inch;
self.metadata.pixels_per_inch = pixels_per_inch;
if changed {
self.emit(NetworkMetadataChange::PixelsPerInch(pixels_per_inch));
}
changed
}
/// The display order of pinned nodes in the Inspector.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order;
@@ -511,6 +511,7 @@ impl NodeNetworkInterface {
.into_iter()
.chain([
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch),
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
@@ -291,6 +291,7 @@ impl NodeTemplateImplementation {
reference,
node_metadata,
pinned_node_order,
pixels_per_inch: None,
previewing,
navigation_metadata,
selection_undo_history: Default::default(),
@@ -674,6 +674,9 @@ pub struct NodeNetworkPersistentMetadata {
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
#[serde(default)]
pub pinned_node_order: Vec<NodeId>,
/// How many pixels make an inch, which sizes lengths typed in a physical unit, or `None` for the default of 96. Only the root network's applies.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pixels_per_inch: Option<f64>,
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
pub previewing: Previewing,
@@ -539,8 +539,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::ChannelMixerNode",
],
},
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -548,6 +549,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
"raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
@@ -652,8 +654,13 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
aliases: &["graphene_raster_nodes::std_nodes::MandelbrotNode", "graphene_std::raster::MandelbrotNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
aliases: &["graphene_raster_nodes::std_nodes::MaskNode", "graphene_std::raster::MaskNode", "graphene_std::raster::MaskImageNode"],
node: graphene_std::blending_nodes::masks::mask::IDENTIFIER,
aliases: &[
"raster_nodes::std_nodes::MaskNode",
"graphene_raster_nodes::std_nodes::MaskNode",
"graphene_std::raster::MaskNode",
"graphene_std::raster::MaskImageNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::posterize::IDENTIFIER,
@@ -1280,6 +1287,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *new == graphene_std::vector::weld::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Merge by Distance");
}
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
@@ -1458,7 +1468,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// Lex a static expression once, learning both whether it lexes at all and whether it references `B`
let static_expression = match expression.as_value() {
Some(TaggedValue::String(expression)) => Some(expression.clone()),
Some(TaggedValue::String(expression)) => Some(read_old_inverse_functions_as_radians(expression)),
_ => None,
};
let mut references_b = false;
@@ -2201,6 +2211,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 3;
}
// 'Mask' gained its mode, density, feather, and invert inputs when it learned to mask any graphic, which take the definition's defaults
if reference == DefinitionIdentifier::ProtoNode(graphene_std::blending_nodes::masks::mask::IDENTIFIER) && inputs_count == 2 {
let definition = resolve_document_node_type(&reference)?;
let mut template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
inputs_count = 6;
}
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
@@ -2370,6 +2392,24 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 5;
}
// 'Drop Shadow', 'Inner Shadow', and 'Outer Glow' gained a blend mode after their color, set to Normal to keep compositing them as before
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
let lacks_blend_mode = |identifier: ProtoNodeIdentifier, count: usize| reference == DefinitionIdentifier::ProtoNode(identifier) && inputs_count == count;
if lacks_blend_mode(drop_shadow::IDENTIFIER, 8) || lacks_blend_mode(inner_shadow::IDENTIFIER, 7) || lacks_blend_mode(outer_glow::IDENTIFIER, 7) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().enumerate() {
let index = if index < 2 { index } else { index + 1 };
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
let normal = NodeInput::value(TaggedValue::BlendMode(graphene_std::blending::BlendMode::Normal), false);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), normal, network_path);
inputs_count += 1;
}
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
@@ -2604,7 +2644,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
];
for (parameter, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -4006,6 +4045,88 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(())
}
/// The old "Math" node's inverse trigonometric functions, each with the builtin that replaced it.
const OLD_INVERSE_FUNCTIONS: [(&str, &str); 6] = [("invsin", "asin"), ("invcos", "acos"), ("invtan", "atan"), ("invcsc", "acsc"), ("invsec", "asec"), ("invcot", "acot")];
/// The old "Math" node's expression with each inverse trigonometric call, like `invsin(A)`, spelled as the builtin that replaced it
/// and divided by `rad` as `(asin(A)/rad)`, since the builtin gives an angle where the old function gave plain radians.
fn read_old_inverse_functions_as_radians(expression: &str) -> String {
rewrite_old_inverse_calls(expression, 0)
}
/// Rewrites the calls in `source`, read by the old grammar's ASCII names and numbers, nested `depth` calls deep.
fn rewrite_old_inverse_calls(source: &str, depth: usize) -> String {
// Beyond the nesting an expression may have, the rest stays as written
const MAX_DEPTH: usize = 32;
let mut result = String::with_capacity(source.len());
let mut position = 0;
while let Some(character) = source[position..].chars().next() {
let start = position;
// A number ends before a name juxtaposed after it, as in `2invsin(A)`, though an exponent like `2e3` is part of it
if character.is_ascii_digit() || character == '.' {
let bytes = &source.as_bytes()[start..];
let mut length = bytes.iter().take_while(|byte| byte.is_ascii_digit() || **byte == b'.').count();
if matches!(bytes.get(length), Some(b'e' | b'E')) {
let sign = usize::from(matches!(bytes.get(length + 1), Some(b'+' | b'-')));
let digits = bytes.iter().skip(length + 1 + sign).take_while(|byte| byte.is_ascii_digit()).count();
if digits > 0 {
length += 1 + sign + digits;
}
}
position += length;
result.push_str(&source[start..position]);
continue;
}
if !(character.is_ascii_alphabetic() || character == '_') {
position += character.len_utf8();
result.push(character);
continue;
}
let name_length = source[start..]
.find(|character: char| !(character.is_ascii_alphanumeric() || character == '_'))
.unwrap_or(source.len() - start);
position = start + name_length;
let name = &source[start..position];
// The call's arguments run to the parenthesis closing the one after its name, and may hold more calls
let after_name = &source[position..];
let open = position + after_name.len() - after_name.trim_start().len();
if let Some((_, builtin)) = OLD_INVERSE_FUNCTIONS.iter().find(|(old, _)| *old == name)
&& depth < MAX_DEPTH
&& let Some(close) = closing_parenthesis(&source[open..])
{
result.push_str(&format!("({builtin}({})/rad)", rewrite_old_inverse_calls(&source[open + 1..open + close], depth + 1)));
position = open + close + 1;
continue;
}
result.push_str(name);
}
result
}
/// The byte offset of the parenthesis closing the one `text` begins with, or `None` where it begins otherwise or never closes.
fn closing_parenthesis(text: &str) -> Option<usize> {
if !text.starts_with('(') {
return None;
}
let mut depth = 0;
for (index, character) in text.char_indices() {
match character {
'(' => depth += 1,
')' if depth == 1 => return Some(index),
')' => depth -= 1,
_ => {}
}
}
None
}
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
@@ -4814,10 +4935,11 @@ mod tests {
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
let node = &document.network_interface.document_network().nodes[&node_id];
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(node.inputs.len(), 3);
assert_eq!(node.inputs.len(), 4);
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
assert_eq!(node.inputs.get(3), Some(&NodeInput::scope(graphene_std::units::PIXELS_PER_INCH_SCOPE)));
}
// The same upgrade on a node whose value comes from upstream, where restoring the inputs has to preserve the wire
@@ -4849,7 +4971,7 @@ mod tests {
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.inputs.len(), 3);
assert_eq!(node.inputs.len(), 4);
assert!(
matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id),
"the upstream wire was dropped by the upgrade, leaving {:?}",
@@ -4897,6 +5019,48 @@ mod tests {
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
}
#[test]
fn old_inverse_functions_read_as_the_plain_radians_they_gave() {
let read = read_old_inverse_functions_as_radians;
assert_eq!(read("invsin(A) + 1"), "(asin(A)/rad) + 1");
assert_eq!(read("2invcos (B)^2"), "2(acos(B)/rad)^2");
assert_eq!(read("invtan(invsin(A) * 2)"), "(atan((asin(A)/rad) * 2)/rad)");
assert_eq!(read("sin(invcot(A))"), "sin((acot(A)/rad))");
assert_eq!(read("2e3invsec(A)"), "2e3(asec(A)/rad)");
for unchanged in ["invsinh(A)", "B_invsin(A)", "invsin", "invsin(A", "sin(A) + π", ""] {
assert_eq!(read(unchanged), unchanged);
}
// The rewritten expression gives the number the old one did
let result = math_parser::evaluate(&read("invtan(1) + 1")).unwrap().unwrap();
assert!((result.as_real().unwrap() - (std::f64::consts::FRAC_PI_4 + 1.)).abs() < 1e-12);
}
#[test]
fn an_old_math_node_keeps_the_plain_radians_its_inverse_functions_gave() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
let math_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node(
math_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::MathNode")),
inputs: vec![
NodeInput::value(TaggedValue::Number(1.), false),
NodeInput::value(TaggedValue::String("invtan(A) + 1".into()), false),
NodeInput::value(TaggedValue::Number(0.), false),
],
..Default::default()
},
&[],
);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("(atan(x)/rad) + 1".into())));
}
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
#[test]
@@ -4963,8 +5127,8 @@ mod tests {
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.len(),
3,
"the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
4,
"the old `B` input should be dropped, leaving the value, the expression, the output-type witness, and the resolution"
);
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
@@ -5713,6 +5877,54 @@ mod tests {
}
}
#[test]
fn shadows_and_glows_from_before_their_blend_mode_open_blending_normally() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::blending::BlendMode;
use graphene_std::blending_nodes::effects::{drop_shadow, inner_shadow, outer_glow};
let saved_nodes = [(drop_shadow::IDENTIFIER, 8), (inner_shadow::IDENTIFIER, 7), (outer_glow::IDENTIFIER, 7)];
let template = |identifier: &ProtoNodeIdentifier| {
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier.clone())).expect("the definition should exist");
definition.default_node_template()
};
// Each node as saved before the blend mode, with each number marked by its index so the shift shows
let mut document = DocumentMessageHandler::default();
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
let mut inputs = template(identifier).inputs;
inputs.remove(2);
inputs.truncate(*count);
for (input_index, input) in inputs.iter_mut().enumerate() {
if matches!(input.as_value(), Some(TaggedValue::Number(_))) {
*input = NodeInput::value(TaggedValue::Number(input_index as f64), false);
}
}
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(identifier.clone()),
inputs,
..Default::default()
};
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
}
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
for (index, (identifier, count)) in saved_nodes.iter().enumerate() {
let node = opened.network_interface.document_node(&NodeId(index as u64 + 1), &[]).expect("the node should still exist");
let name = identifier.as_str();
assert_eq!(node.inputs.len(), template(identifier).inputs.len(), "{name} should take the current shape");
assert_eq!(node.inputs[2], NodeInput::value(TaggedValue::BlendMode(BlendMode::Normal), false), "{name} should blend normally");
for (input_index, input) in node.inputs.iter().enumerate().take(count + 1).skip(3) {
if let Some(TaggedValue::Number(number)) = input.as_value() {
assert_eq!(*number, (input_index - 1) as f64, "{name} should move its input {} past the blend mode", input_index - 1);
}
}
}
}
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
#[test]
fn removed_nodes_open_as_their_stand_ins() {
@@ -989,16 +989,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} => {
let document_id = self.active_document_id.expect("Tried to render non-existent document");
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
// An export now would capture the fallbacks drawn in place of fonts and images still loading
if document.resources.awaiting_resources() {
responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: "The document's fonts or images are still loading. Try again once they finish.".to_string(),
});
return;
}
let export_config = ExportConfig {
name,
file_type,
@@ -1035,7 +1025,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
return;
};
// Skip rendering while a resource is still loading, so its fallback isn't drawn in the meantime.
// Skip rendering while a resource is still loading, so its error isn't shown in the meantime.
// Each load queues `RunDocumentGraph` when it succeeds or fails, so the render goes ahead once none are left.
if document.resources.awaiting_resources() {
return;
+1
View File
@@ -11,6 +11,7 @@ pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext,
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler};
pub use crate::messages::dialog::document_setup_dialog::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant, DocumentSetupDialogMessageHandler};
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
@@ -194,9 +194,15 @@ impl RadiusHandle {
// The size is snapped, which keeps whichever sign the radius has come to
let snapped_radius = snap_session.snap_value(view, position_of, self.free_radius.abs(), on_screen_per_unit, equal_radii) * self.free_radius.signum();
// A radius typed in a unit like millimeters stays in it
let input_connector = InputConnector::node(node_id, radius_parameter);
let radius = match document.network_interface.input_from_connector(&input_connector, &[]).and_then(|input| input.as_value()) {
Some(existing @ TaggedValue::Length(_)) => existing.length_in_same_unit(snapped_radius, document.network_interface.pixels_per_inch()),
_ => TaggedValue::Number(snapped_radius),
};
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, radius_parameter),
input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
input_connector,
input: NodeInput::value(radius, false),
});
responses.add(NodeGraphMessage::RunDocumentGraph);
}
@@ -12,6 +12,7 @@ use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
use crate::messages::tool::tool_messages::tool_prelude::*;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::units::TypedLength;
#[derive(Clone, Debug, Default)]
pub struct CircleGizmoHandler {
@@ -108,7 +109,7 @@ impl Circle {
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput),
input: NodeInput::value(TaggedValue::Number(radius), false),
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false),
});
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
@@ -421,11 +421,7 @@ pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) ->
pub fn extract_circle_radius(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<f64> {
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER))?;
let Some(&TaggedValue::Number(radius)) = node_inputs.get(1)?.as_value() else {
return None;
};
Some(radius)
node_inputs.get(1)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch())
}
/// Calculate the viewport position of as a star vertex given its index
+16 -39
View File
@@ -7,7 +7,7 @@ use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::proto::{GraphErrorType, GraphErrors};
use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
@@ -27,7 +27,7 @@ mod recompile_tests;
mod runtime;
pub use runtime::*;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct ExecutionRequest {
execution_id: u64,
render_config: RenderConfig,
@@ -271,6 +271,7 @@ impl NodeGraphExecutor {
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -284,7 +285,6 @@ impl NodeGraphExecutor {
self.inspect_context_overrides = ContextOverrides::default();
}
// The compile looks up each resource's data in the registry, so a resource that loads reruns it like an edit to the network does
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone();
@@ -302,6 +302,7 @@ impl NodeGraphExecutor {
previewed,
layers,
observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.map_err(|e| e.to_string())?;
} else if inspected_node_changed {
@@ -356,7 +357,7 @@ impl NodeGraphExecutor {
render_mode: document.render_mode,
for_export: false,
for_eyedropper: false,
metadata: None,
pixels_per_inch: None,
};
// Execute the node graph
@@ -424,7 +425,7 @@ impl NodeGraphExecutor {
render_mode,
for_export: false,
for_eyedropper: true,
metadata: None,
pixels_per_inch: None,
};
// Execute the node graph
@@ -449,12 +450,10 @@ impl NodeGraphExecutor {
let previewed = document.network_interface.previewed_nodes();
let resources = document.resources.registry.clone();
let export_format = match export_config.file_type {
FileType::Svg => graphene_std::application_io::ExportFormat::Svg,
FileType::Pdf => graphene_std::application_io::ExportFormat::Pdf {
artboards_as_pages: export_config.bounds == ExportBounds::AllArtwork,
},
_ => graphene_std::application_io::ExportFormat::Raster,
let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg
} else {
graphene_std::application_io::ExportFormat::Raster
};
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
@@ -487,10 +486,8 @@ impl NodeGraphExecutor {
render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true,
for_eyedropper: false,
metadata: Some(graphene_std::application_io::ExportMetadata {
title: export_config.name.clone(),
artboard_names: (document.artboard_names().into_iter()).map(|(layer, name)| (layer.to_node(), name)).collect(),
}),
// A document at CSS's 96 pixels per inch exports as it always has, in unitless pixels
pixels_per_inch: Some(document.network_interface.pixels_per_inch()).filter(|pixels_per_inch| *pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH),
};
// Execute the node graph
@@ -501,6 +498,7 @@ impl NodeGraphExecutor {
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -709,13 +707,6 @@ impl NodeGraphExecutor {
if let Err((_, e)) = &result {
log::trace!("Gradient migration measurement compile: {e}");
}
// A fallback drawn in place of a missing font or image would be measured instead, so the fills wait for a later open
if node_graph_warnings.iter().any(|warning| matches!(warning.error, GraphErrorType::MissingResource { .. })) {
self.cancel_gradient_migration();
self.gradient_migration_attempted.insert(document_id);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
continue;
}
@@ -907,6 +898,7 @@ impl NodeGraphExecutor {
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
pixels_per_inch: document.network_interface.pixels_per_inch(),
}))
.is_err()
{
@@ -932,7 +924,7 @@ impl NodeGraphExecutor {
render_mode: document.render_mode,
for_export: false,
for_eyedropper: false,
metadata: None,
pixels_per_inch: None,
};
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
@@ -1064,11 +1056,6 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
return;
}
RenderOutputType::Pdf { data } => {
log::error!("Invalid node graph output type: a PDF document of {} bytes", data.len());
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
return;
}
}
let RenderMetadata {
@@ -1136,20 +1123,10 @@ impl NodeGraphExecutor {
content: svg.into_bytes().into(),
});
}
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Pdf { data }, ..
}) if file_type == FileType::Pdf => {
responses.add(FrontendMessage::TriggerSaveFile {
name,
folder,
filters,
content: data.into(),
});
}
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Buffer { data, width, height },
..
}) if !file_type.is_vector() => {
}) if file_type != FileType::Svg => {
let content = match file_type.encode(width, height, data) {
Ok(content) => content.into(),
Err(description) => {
+62 -201
View File
@@ -3,12 +3,12 @@ use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task};
use graph_craft::application_io::resource::{Resource, ResourceRegistry};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::{GraphError, GraphErrorType, GraphErrors};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::ops::ConvertAsync;
@@ -18,7 +18,7 @@ use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer;
@@ -43,6 +43,7 @@ pub struct NodeRuntime {
pub(super) executor: DynamicExecutor,
#[cfg(not(test))]
executor: DynamicExecutor,
output: OutputHandle,
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
@@ -123,6 +124,8 @@ pub struct GraphUpdate {
pub(super) layers: Vec<Vec<NodeId>>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>,
/// The document's pixels per inch, which sizes lengths typed in a physical unit.
pub(super) pixels_per_inch: f64,
}
/// Replaces each network's primary export with its previewed node.
@@ -134,28 +137,6 @@ pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId
}
}
/// A warning for each input holding a resource the registry can't resolve, placed in the first instance of a network that several nodes share.
fn missing_resource_warnings(network: &NodeNetwork, resources: &ResourceRegistry) -> GraphErrors {
network
.recursive_nodes()
.flat_map(|(node_id, node, network_path)| {
node.inputs.iter().enumerate().filter_map(move |(index, input)| {
let NodeInput::Value { tagged_value, .. } = input else { return None };
let TaggedValue::Resource(resource_id) = &**tagged_value else { return None };
resources.hash(resource_id).is_none().then(|| GraphError {
node_path: [network_path.as_slice(), &[*node_id]].concat(),
identifier: match &node.implementation {
DocumentNodeImplementation::ProtoNode(identifier) => identifier.as_str().to_string().into(),
_ => Default::default(),
},
error: GraphErrorType::MissingResource { index },
})
})
})
.collect()
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExportConfig {
pub name: String,
@@ -170,6 +151,7 @@ impl NodeRuntime {
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
Self {
executor: DynamicExecutor::default(),
output: OutputHandle::default(),
receiver,
sender,
editor_wake,
@@ -260,6 +242,7 @@ impl NodeRuntime {
previewed,
layers,
observations,
pixels_per_inch,
}) = graph
else {
return;
@@ -272,7 +255,7 @@ impl NodeRuntime {
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(&network);
let result = self.update_network(network.clone(), pixels_per_inch);
self.compile_failed = result.is_err();
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
@@ -294,12 +277,12 @@ impl NodeRuntime {
let dirty = self.dirty.swap(false, Ordering::Acquire);
let mut texture = None;
if let Some(export) = self.pending_export.clone() {
if let Some(export) = self.pending_export {
if dirty {
self.run_export(export).await;
}
} else {
let viewport = if dirty { self.pending.clone() } else { None };
let viewport = if dirty { self.pending } else { None };
if let Some(document_id) = self.pending_thumbnails.take()
&& viewport.is_none()
@@ -336,10 +319,9 @@ impl NodeRuntime {
}
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
let execution_id = request.execution_id;
self.thumbnails.set_scale(request.render_config.scale);
let mut result = self.evaluate(request.clone())?;
let mut result = self.evaluate(request)?;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
#[cfg(all(target_family = "wasm", feature = "wasm"))]
@@ -391,7 +373,7 @@ impl NodeRuntime {
None
};
self.respond(execution_id, result, observations).await;
self.respond(request.execution_id, result, observations).await;
texture
}
@@ -436,7 +418,6 @@ impl NodeRuntime {
}
async fn run_export(&mut self, request: ExecutionRequest) {
let execution_id = request.execution_id;
let result = self.evaluate(request);
if matches!(result, Some(ExecutionResult::Pending)) {
return;
@@ -453,12 +434,12 @@ impl NodeRuntime {
*data = RenderOutputType::Buffer { data: buffer, width, height };
}
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.respond(execution_id, result, observations).await;
self.respond(request.execution_id, result, observations).await;
}
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
// Eyedropper should use the same time and pointer to not invalidate the cache
if let Some(viewport) = &self.pending {
if let Some(viewport) = self.pending {
request.render_config.time = viewport.render_config.time;
request.render_config.pointer = viewport.render_config.pointer;
}
@@ -486,11 +467,10 @@ impl NodeRuntime {
render_config.export_format = ExportFormat::Svg;
}
let for_export = render_config.for_export;
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => {
@@ -544,23 +524,12 @@ impl NodeRuntime {
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
}
fn update_network(&mut self, graph: &NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph.clone(), self.editor_api.clone(), self.async_runtime().handle());
fn update_network(&mut self, graph: NodeNetwork, pixels_per_inch: f64) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle(), pixels_per_inch);
// A missing resource compiles as the empty one, which its consumers draw with a fallback, and warns on the nodes using it
let resource_missing = std::cell::Cell::new(false);
let resolve_resource = |resource_id| {
self.resources.hash(&resource_id).or_else(|| {
resource_missing.set(true);
Some(Resource::empty().hash())
})
};
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &resolve_resource) {
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
}
if resource_missing.get() {
self.node_graph_warnings = missing_resource_warnings(graph, &self.resources);
}
// We assume only one output
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
@@ -575,10 +544,14 @@ impl NodeRuntime {
}
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings.extend(warnings);
self.node_graph_warnings = warnings;
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
let updated = self.executor.update(proto_network).map(|(output, types)| {
self.output = output;
types
});
let result = updated.map_err(|(types, e)| {
self.node_graph_errors.clone_from(&e);
(types, format!("{e:?}"))
});
@@ -594,7 +567,7 @@ impl NodeRuntime {
paths.into()
};
let mut errors = Vec::new();
let output = self.executor.output();
let output = self.output.node();
let mut pending = vec![(vec![paths(output)], output, error)];
while let Some((mut trace, node, error)) = pending.pop() {
let passed = self.executor.trace_error(node, error);
@@ -791,7 +764,7 @@ mod tests {
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
editor.runtime.pending.as_ref().map(|request| request.execution_id)
editor.runtime.pending.map(|request| request.execution_id)
}
#[tokio::test]
@@ -911,59 +884,22 @@ mod tests {
}
#[tokio::test]
async fn a_missing_resource_renders_with_a_warning_on_its_node() {
async fn a_resource_that_loads_recompiles_the_unchanged_network() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use graph_craft::application_io::resource::ResourceId;
use graphene_std::raster_nodes::std_nodes::image;
let mut editor = editor().await;
// The layer shows an 'Image' node holding an image the document has no record of
let image_node = NodeId::new();
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(image_node),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor), "the graph should render with the missing image left empty");
assert!(editor.portfolio_message_handler_mut().executor.take_evaluation_errors().is_none());
let resolved_types = &editor.active_document().network_interface.resolved_types;
assert!(resolved_types.node_graph_errors.is_empty(), "{:?}", resolved_types.node_graph_errors);
let warnings = resolved_types.node_graph_warnings.as_slice();
let expected = GraphErrorType::MissingResource { index: 1 };
assert!(matches!(warnings, [warning] if warning.node_path == [image_node] && warning.error == expected), "{warnings:?}");
}
#[tokio::test]
async fn a_resource_that_fails_to_load_renders_with_a_fallback_until_it_loads() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use crate::test_utils::test_prelude::{Color, Image};
use graph_craft::application_io::resource::{DataSource, ResourceHash, ResourceId};
use graphene_std::raster_nodes::std_nodes::image;
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back the graph's warnings and whether it drew an image.
async fn render_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> (GraphErrors, bool) {
/// Handles the message, lets the runtime compile and evaluate whatever it queued, and gives back whether it drew an image.
async fn image_drawn_after(editor: &mut EditorTestUtils, message: impl Into<Message>) -> bool {
editor.dispatch(message);
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
let image_drawn = messages
messages
.iter()
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()));
let resolved_types = &editor.active_document().network_interface.resolved_types;
assert!(resolved_types.node_graph_errors.is_empty(), "{:?}", resolved_types.node_graph_errors);
(resolved_types.node_graph_warnings.clone(), image_drawn)
.any(|message| matches!(message, FrontendMessage::UpdateImageData { canvas_ids_in_use, .. } if !canvas_ids_in_use.is_empty()))
}
let mut editor = editor().await;
@@ -990,71 +926,50 @@ mod tests {
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
let (warnings, _) = render_after(&mut editor, NodeGraphMessage::RunDocumentGraph).await;
assert!(warnings.is_empty(), "the graph shouldn't run while the image may still load: {warnings:?}");
// Failing to load sends the network while the image has no data
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
let (warnings, image_drawn) = render_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
let expected = GraphErrorType::MissingResource { index: 1 };
assert!(
matches!(warnings.as_slice(), [warning] if warning.node_path == [image_node] && warning.error == expected),
"{warnings:?}"
);
assert!(!image_drawn, "the image that failed to load should be left empty");
image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: failed }).await;
// Loading it later, as a retry would, has to recompile the unchanged network
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
let hash = ResourceHash::from(data.as_ref());
editor.dispatch(ResourceStorageMessage::Store { data });
let resolved = ResourceMessage::Resolved { resource_id, source, hash }.into();
let (warnings, image_drawn) = render_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await;
assert!(warnings.is_empty(), "the warning should clear once the image loads: {warnings:?}");
assert!(image_drawn, "the image should be drawn once it loads");
assert!(image_drawn_after(&mut editor, PortfolioMessage::DocumentPassMessage { document_id, message: resolved }).await);
}
#[tokio::test]
async fn an_export_is_refused_while_its_resources_load() {
async fn a_missing_resource_renders_with_an_error_traced_through_its_node() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use graph_craft::application_io::resource::{DataSource, ResourceId};
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
use graph_craft::application_io::resource::ResourceId;
use graphene_std::platform_application_io::MissingResourceError;
use graphene_std::raster_nodes::std_nodes::image;
/// Requests an export and lets the runtime evaluate whatever was sent, giving back whether it explained a refusal and whether it exported.
async fn refused_and_exported(editor: &mut EditorTestUtils) -> (bool, bool) {
let messages = editor.dispatch(PortfolioMessage::SubmitDocumentExport {
name: "export".to_string(),
file_type: FileType::Svg,
scale_factor: 1.,
bounds: ExportBounds::AllArtwork,
artboard_name: None,
artboard_count: 0,
});
let refused = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
editor.runtime.update();
editor.runtime.run().await;
(refused, exported(editor))
}
let mut editor = editor().await;
let document_id = editor.portfolio_message_handler().active_document_id.unwrap();
// An 'Image' node whose image is known only by where to load it from
let resource_id = ResourceId::new();
let source = DataSource::Url("https://example.com/image.png".parse().unwrap());
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source);
let template = resolve_proto_node_type(image::IDENTIFIER)
.unwrap()
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Resource(resource_id), false))]);
editor.active_document_mut().network_interface.insert_node(NodeId::new(), template, &[]);
// The layer shows an 'Image' node holding an image the document has no record of
let image_node = NodeId::new();
let missing_image = NodeInput::value(TaggedValue::Resource(ResourceId::new()), false);
let template = resolve_proto_node_type(image::IDENTIFIER).unwrap().node_template_input_override([None, Some(missing_image)]);
editor.active_document_mut().network_interface.insert_node(image_node, template, &[]);
let layer = editor.active_document().metadata().all_layers().next().unwrap();
editor.dispatch(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(image_node),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
let outcome = refused_and_exported(&mut editor).await;
assert_eq!(outcome, (true, false), "the export shouldn't capture the image's fallback while it may still load");
send_update(&mut editor);
editor.runtime.update();
editor.runtime.run().await;
assert!(evaluated(&mut editor));
// Once the image fails to load, its fallback is all there is to export
let failed = ResourceMessage::ResolveFailed { resource_id }.into();
editor.dispatch(PortfolioMessage::DocumentPassMessage { document_id, message: failed });
let outcome = refused_and_exported(&mut editor).await;
assert_eq!(outcome, (false, true), "the export should go ahead once nothing is left loading");
let errors = editor.portfolio_message_handler_mut().executor.take_evaluation_errors().unwrap();
assert!(
errors
.iter()
.any(|(error, trace)| error.is::<MissingResourceError>() && trace.iter().flatten().any(|path| **path == [image_node])),
"{errors:?}"
);
}
#[tokio::test]
@@ -1083,60 +998,6 @@ mod tests {
}
}
#[tokio::test]
async fn a_pdf_export_saves_a_pdf_document() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
send_export(&mut editor, FileType::Pdf);
editor.runtime.update();
editor.runtime.run().await;
let saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { name, content, .. } => Some((name, content)),
_ => None,
});
let Some((name, content)) = saved else { panic!("the export should save a file") };
assert!(name.ends_with(".pdf"), "the file should be named as a PDF: {name}");
assert!(content.starts_with(b"%PDF-"), "the file should hold a PDF document");
}
#[tokio::test]
async fn a_pdf_export_draws_effects_as_images_the_gpu_renders() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use graphene_std::blending_nodes::effects::drop_shadow;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let node_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
// The export waits for the render node to read the image of the shadowed rectangle back into the PDF
send_export(&mut editor, FileType::Pdf);
let mut saved = None;
for _ in 0..100 {
editor.runtime.update();
editor.runtime.run().await;
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
_ => None,
});
if saved.is_some() {
break;
}
}
let Some(saved) = saved else { panic!("the export never finished") };
assert!(saved.starts_with(b"%PDF-"), "the file should hold a PDF document");
let embeds_image = saved.windows(b"/Subtype/Image".len()).any(|window| window == b"/Subtype/Image");
assert!(embeds_image, "the shadowed rectangle should be an image the GPU rendered");
}
#[tokio::test]
async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
@@ -1151,6 +1151,7 @@
--math-basis-j: #66c14a;
--math-basis-k: #76b6ff;
--math-variable: #fff9a8;
--math-unit: #eeeeee;
--math-function: #c9c2ff;
--math-operator: #ffffff;
--math-bracket: #f2b532;
@@ -1202,6 +1203,11 @@
color: var(--math-function);
}
// A unit is set upright beside its number, unlike the italic variables
.unit {
color: var(--math-unit);
}
// A keyword is an operator spelled as a word
.operator,
.keyword {
@@ -75,6 +75,9 @@
let inputRangeElement: HTMLInputElement | undefined;
let text = exact ?? displayText(value, unit);
let editing = false;
// While editing, the unit a number typed without one is read in shows faintly after the text
$: ghostUnit = editing && exact === undefined && unit.trim() !== "" && !endsInUnit(text) ? unit : "";
let isDragging = false;
let pressingArrow = false;
let repeatTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
@@ -118,7 +121,7 @@
let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined;
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
$: watchValue(value, unit);
$: watchValue(value, unit, min, max);
$: if (exact !== undefined && !editing) text = exact;
$: present = exact !== undefined || value !== undefined;
// A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown
@@ -176,8 +179,8 @@
// TRACKING AND UPDATING THE VALUE
// ===============================
// Called only when `value` is changed from outside this component.
function watchValue(value: number | undefined, unit: string) {
// Called only when `value`, its unit, or its bounds are changed from outside this component.
function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined) {
// Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag)
if (rangeSliderClickDragState === "Dragging") return;
@@ -381,6 +384,11 @@
return `${number}`;
}
// Whether typed text ends in a unit (or a name), so no unit is assumed after it
function endsInUnit(typed: string): boolean {
return /[\p{L}%°'"]\s*$/u.test(typed);
}
// Removes the trailing "s" from a unit if the quantity is 1.
function unPluralize(unit: string, quantity: number): string {
if (quantity !== 1 || !unit.endsWith("s")) return unit;
@@ -1002,6 +1010,9 @@
>{text.slice(markedDigit + 1)}</span
>
{/if}
{#if ghostUnit}
<span class="ghost-unit">{text}<span class="unit">{ghostUnit}</span></span>
{/if}
{#if present}
{#if mode === "Increment" && incrementBehavior !== "None"}
<button
@@ -1103,6 +1114,24 @@
display: none;
}
// Laid out like the field's text while it's edited, which it mirrors in transparent characters before the faint unit
.ghost-unit {
position: absolute;
inset: 0;
margin: 0 8px;
padding: 3px 0;
line-height: calc(var(--widget-height) - 6px);
text-align: left;
white-space: pre;
overflow: hidden;
color: transparent;
pointer-events: none;
.unit {
color: var(--color-8-uppergray);
}
}
// A disabled field's underline only marks the stepped digit, with no press target to hover or drag
&.disabled .digit-mark .marked::after {
pointer-events: none;
+8
View File
@@ -124,6 +124,7 @@ import NodeAsVector from "/../branding/assets/16x16-nodes/node-as-vector.svg";
import NodeAverage from "/../branding/assets/16x16-nodes/node-average.svg";
import NodeBakeTransform from "/../branding/assets/16x16-nodes/node-bake-transform.svg";
import NodeBasicBrush from "/../branding/assets/16x16-nodes/node-basic-brush.svg";
import NodeBevelAndEmboss from "/../branding/assets/16x16-nodes/node-bevel-and-emboss.svg";
import NodeBevel from "/../branding/assets/16x16-nodes/node-bevel.svg";
import NodeBlackAndWhite from "/../branding/assets/16x16-nodes/node-black-and-white.svg";
import NodeBlendMode from "/../branding/assets/16x16-nodes/node-blend-mode.svg";
@@ -223,6 +224,7 @@ import NodeImageToChannels from "/../branding/assets/16x16-nodes/node-image-to-c
import NodeImage from "/../branding/assets/16x16-nodes/node-image.svg";
import NodeIndexPoints from "/../branding/assets/16x16-nodes/node-index-points.svg";
import NodeIndices from "/../branding/assets/16x16-nodes/node-indices.svg";
import NodeInnerGlow from "/../branding/assets/16x16-nodes/node-inner-glow.svg";
import NodeInnerShadow from "/../branding/assets/16x16-nodes/node-inner-shadow.svg";
import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-transform.svg";
import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg";
@@ -277,6 +279,7 @@ import NodeOpacity from "/../branding/assets/16x16-nodes/node-opacity.svg";
import NodeOpenEnds from "/../branding/assets/16x16-nodes/node-open-ends.svg";
import NodeOriginsToPolyline from "/../branding/assets/16x16-nodes/node-origins-to-polyline.svg";
import NodeOuterGlow from "/../branding/assets/16x16-nodes/node-outer-glow.svg";
import NodeOutline from "/../branding/assets/16x16-nodes/node-outline.svg";
import NodePackStrips from "/../branding/assets/16x16-nodes/node-pack-strips.svg";
import NodePassthrough from "/../branding/assets/16x16-nodes/node-passthrough.svg";
import NodePathIsClosed from "/../branding/assets/16x16-nodes/node-path-is-closed.svg";
@@ -325,6 +328,7 @@ import NodeRoot from "/../branding/assets/16x16-nodes/node-root.svg";
import NodeRoundCorners from "/../branding/assets/16x16-nodes/node-round-corners.svg";
import NodeRound from "/../branding/assets/16x16-nodes/node-round.svg";
import NodeSamplePolyline from "/../branding/assets/16x16-nodes/node-sample-polyline.svg";
import NodeSatin from "/../branding/assets/16x16-nodes/node-satin.svg";
import NodeScatterPoints from "/../branding/assets/16x16-nodes/node-scatter-points.svg";
import NodeSelectiveColor from "/../branding/assets/16x16-nodes/node-selective-color.svg";
import NodeSeparatePaths from "/../branding/assets/16x16-nodes/node-separate-paths.svg";
@@ -415,6 +419,7 @@ export const ICON_16X16_NODES = {
NodeBakeTransform: { svg: NodeBakeTransform, size: 16 },
NodeBasicBrush: { svg: NodeBasicBrush, size: 16 },
NodeBevel: { svg: NodeBevel, size: 16 },
NodeBevelAndEmboss: { svg: NodeBevelAndEmboss, size: 16 },
NodeBlackAndWhite: { svg: NodeBlackAndWhite, size: 16 },
NodeBlend: { svg: NodeBlend, size: 16 },
NodeBlendMode: { svg: NodeBlendMode, size: 16 },
@@ -513,6 +518,7 @@ export const ICON_16X16_NODES = {
NodeImageToChannels: { svg: NodeImageToChannels, size: 16 },
NodeIndexPoints: { svg: NodeIndexPoints, size: 16 },
NodeIndices: { svg: NodeIndices, size: 16 },
NodeInnerGlow: { svg: NodeInnerGlow, size: 16 },
NodeInnerShadow: { svg: NodeInnerShadow, size: 16 },
NodeInvert: { svg: NodeInvert, size: 16 },
NodeInvertTransform: { svg: NodeInvertTransform, size: 16 },
@@ -567,6 +573,7 @@ export const ICON_16X16_NODES = {
NodeOpenEnds: { svg: NodeOpenEnds, size: 16 },
NodeOriginsToPolyline: { svg: NodeOriginsToPolyline, size: 16 },
NodeOuterGlow: { svg: NodeOuterGlow, size: 16 },
NodeOutline: { svg: NodeOutline, size: 16 },
NodePackStrips: { svg: NodePackStrips, size: 16 },
NodePassthrough: { svg: NodePassthrough, size: 16 },
NodePath: { svg: NodePath, size: 16 },
@@ -615,6 +622,7 @@ export const ICON_16X16_NODES = {
NodeRound: { svg: NodeRound, size: 16 },
NodeRoundCorners: { svg: NodeRoundCorners, size: 16 },
NodeSamplePolyline: { svg: NodeSamplePolyline, size: 16 },
NodeSatin: { svg: NodeSatin, size: 16 },
NodeScatterPoints: { svg: NodeScatterPoints, size: 16 },
NodeSelectiveColor: { svg: NodeSelectiveColor, size: 16 },
NodeSeparatePaths: { svg: NodeSeparatePaths, size: 16 },
+4
View File
@@ -37,6 +37,10 @@ macro_rules! generate_benchmarks {
}
generate_benchmarks! {
"1 + 2 * 3 - 4 / 5",
"pi + e - tau",
"sin(1) + cos(2)",
"(1.5 + 2.5) * 3.5",
"(3 * (4 + sqrt(25)) - cos(pi/3) * (2^3)) + 5 * e", // Mixed nested functions, constants, and operations
"((5 + 2 * (3 - sqrt(49)))^2) / (1 + sqrt(16)) + tau / 2", // Complex nested expression with constants
"log(100, 10) + (5 * sin(pi/4) + sqrt(81)) / (2 * phi)", // Logarithmic and trigonometric functions
+47 -2
View File
@@ -1,4 +1,6 @@
use crate::constants::{MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix};
use crate::constants::{BuiltinFunction, MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix};
use crate::quantity::{BuilderUnits, MatrixValueUnit, RegionResult, UnitRule};
use crate::units::UnitId;
use crate::value::Value;
#[derive(Debug, Clone, PartialEq)]
@@ -96,6 +98,11 @@ pub enum Syntax<'src> {
first: Box<Syntax<'src>>,
rest: Vec<(BinaryOp, Syntax<'src>)>,
},
/// A number juxtaposed with units after a `/`, like the `2mm` of `x / 2mm`, which only a dividend with a unit divides by whole.
Measure {
number: Box<Syntax<'src>>,
units: Vec<Syntax<'src>>,
},
/// The cases of math's `cases` notation, `{a if cond, b otherwise}`: disjoint conditions in no meaningful order, with `otherwise` holding when none of them do.
Piecewise {
cases: Vec<Case<'src>>,
@@ -157,10 +164,17 @@ pub enum Node {
pub enum ValueNode {
Lit(Literal),
Var(String),
/// A unit's spelling, resolved as the expression is read, which a host's binding of the name still shadows.
Unit {
name: String,
unit: UnitId,
},
FnCall {
name: String,
expr: Vec<ValueNode>,
},
/// A call of a builtin taking values, found as the expression is read so evaluating it looks nothing up by name.
BuiltinCall(Box<BuiltinCall>),
BinOp {
lhs: Box<ValueNode>,
op: BinaryOp,
@@ -183,16 +197,24 @@ pub enum ValueNode {
matrix: Box<MatrixNode>,
value: Box<ValueNode>,
},
/// A quotient by a measure, which is the whole divisor where the dividend has a unit. A plain dividend is divided by the
/// measure's number alone and then takes its units, so `x / 2mm` is half of `x` in millimeters.
MeasureQuotient {
dividend: Box<ValueNode>,
measure: Box<Measure>,
},
/// A function of a matrix with a value result, like `det(A)`.
OfMatrix {
function: MatrixToValue,
unit: MatrixValueUnit,
matrix: Box<MatrixNode>,
},
/// A function of a value and regions with a value result, like `within(p, R)`.
OfValueAndRegions {
function: ValueOfRegions,
result: RegionResult,
value: Box<ValueNode>,
regions: Vec<MatrixNode>,
regions: Box<[MatrixNode]>,
/// The value after the regions, where the builtin takes one, like `smoothstep`'s continuity.
trailing: Option<Box<ValueNode>>,
},
@@ -215,6 +237,28 @@ pub enum ValueNode {
},
}
/// A call of a builtin function of values with the rule for its units.
#[derive(Debug)]
pub struct BuiltinCall {
/// The builtin's name, which a base-suffixed form like `log2` gives without its suffix.
pub name: String,
/// The spelling by which a host's function would shadow the builtin, or `None` behind the `\` prefix.
pub host_name: Option<String>,
pub function: BuiltinFunction,
pub rule: UnitRule,
pub arguments: Vec<ValueNode>,
/// The second argument a base-suffixed form like `log2(x)` bakes into its name.
pub suffix: Option<f64>,
}
/// A number juxtaposed with units after a `/`, like the `2mm` of `x / 2mm`.
#[derive(Debug)]
pub struct Measure {
pub number: ValueNode,
/// The units as read, any of which a `where` definition or a host's binding of its spelling may shadow.
pub units: Vec<ValueNode>,
}
/// A subexpression evaluating to a matrix.
#[derive(Debug)]
pub enum MatrixNode {
@@ -226,6 +270,7 @@ pub enum MatrixNode {
/// A function building a matrix from values, like `rotation(angle)`.
FromValues {
function: ValuesToMatrix,
units: BuilderUnits,
arguments: Vec<ValueNode>,
},
/// The range `a..b`.
+57 -3
View File
@@ -1,10 +1,11 @@
//! The names an editor offers to finish the one being typed.
use crate::constants::{BUILTIN_FUNCTION_ALIASES, SUFFIXED_FORMS};
use crate::documentation::{BUILTIN_FUNCTIONS, Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip};
use crate::documentation::{BUILTIN_FUNCTIONS, Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, unit_tooltip};
use crate::lexer::{CONSTANT_SPELLINGS, Constant, KEYWORDS, Lexer, Token, offset_in, operand_ended};
use crate::parser::{keywords_accepted_after, parse_quietly};
use crate::sort::names_in_scope;
use crate::units::{UNITS, unit_named};
use std::borrow::Cow;
/// What an offered name is, by which the offers are grouped.
@@ -14,6 +15,8 @@ pub enum CompletionKind {
Local,
Function,
Constant,
/// A unit of measure, like `mm`.
Unit,
Keyword,
/// The typeset alias of an operator typed in ASCII, like `≤` for `<=`.
Operator,
@@ -234,6 +237,42 @@ pub fn completions(source: &str, caret: usize, asked: bool) -> Completions<'_> {
});
let constants = identity.into_iter().chain(constants).collect::<Vec<_>>();
// A unit is offered right after a number, where units are written, by a spelling that begins with what's typed, with a symbol that
// can't be typed, like `°` or `µm`, leading its words
let after_number = Lexer::new(source.get(..start).unwrap_or_default())
.last()
.is_some_and(|token| matches!(token, Token::Integer(_) | Token::Float(_)));
let units = UNITS.iter().filter(|_| after_number).filter_map(|definition| {
let typeable = |spelling: &str| spelling.chars().all(|c| c.is_ascii_alphanumeric());
let fitting = |spelling: &str| fit(typed, spelling).filter(|closeness| *closeness != Fit::Scattered);
let best = definition.spellings.iter().filter(|spelling| typeable(spelling)).filter_map(|spelling| fitting(spelling)).min()?;
// Its symbol and singular name stand for every spelling, so plurals and abbreviations don't crowd the list
let words: Vec<(&str, Fit)> = [definition.symbol, definition.name].into_iter().filter(|word| typeable(word)).fold(Vec::new(), |mut words, word| {
if !words.iter().any(|(existing, _)| *existing == word) {
words.push((word, fitting(word).unwrap_or(Fit::Scattered)));
}
words
});
let tooltip = unit_named(definition.symbol).map(unit_tooltip);
let symbol = (!typeable(definition.symbol)).then(|| Candidate {
name: definition.symbol,
parameters: None,
tooltip: tooltip.clone(),
fit: best,
prefixed: false,
});
let words = words.into_iter().map(move |(word, closeness)| Candidate {
name: word,
parameters: None,
tooltip: tooltip.clone(),
fit: closeness,
prefixed: prefixed(word, false),
});
Some(symbol.into_iter().chain(words))
});
let units = units.flatten().collect::<Vec<_>>();
// A keyword is offered only where the grammar takes one, which is asked only once one is typed toward
let keywords = KEYWORDS.into_iter().filter(|_| !builtins_only).filter_map(|(keyword, token)| {
Some(Candidate {
@@ -260,6 +299,7 @@ pub fn completions(source: &str, caret: usize, asked: bool) -> Completions<'_> {
(locals, CompletionKind::Local),
(functions, CompletionKind::Function),
(constants, CompletionKind::Constant),
(units, CompletionKind::Unit),
(keywords, CompletionKind::Keyword),
]
.into_iter()
@@ -516,12 +556,12 @@ mod tests {
#[test]
fn definitions_are_offered_where_they_can_be_read() {
assert_eq!(names("2 rad‸ where radius = 2"), ["radius"]);
assert_eq!(names("2 rad‸ where radius = 2"), ["radius", "rad", "radian"]);
assert_eq!(names("ea‸(2) where ease(t) = t^2"), ["ease"]);
assert_eq!(names("sig‸ where sigma = 1"), ["sigma", "sign"]);
// A parameter is read only in its function's body, and a clause's names only within its parentheses, which the called name is outside of
assert_eq!(names("f(1) where f(radius) = 2 rad‸"), ["radius"]);
assert_eq!(names("f(1) where f(radius) = 2 rad‸"), ["radius", "rad", "radian"]);
assert!(names("(f(1) where f(radius) = 2 radius) + rad‸").is_empty());
assert!(names("(2 where radius = 1) + rad‸").is_empty());
assert!(!names("fo‸(2 where foo = 1)").contains(&"foo".to_string()));
@@ -672,4 +712,18 @@ mod tests {
assert_eq!(crate::evaluate(ascii).unwrap().unwrap(), crate::evaluate(typeset).unwrap().unwrap(), "`{typeset}`");
}
}
#[test]
fn units_are_offered_after_a_number() {
for unit in ["m", "meter", "mm", "millimeter", "min", "minute"] {
assert!(names("5m‸").contains(&unit.to_string()), "`{unit}` should be offered");
}
let degrees = names("5 de‸");
let symbol = degrees.iter().position(|name| name == "°").unwrap();
assert_eq!(degrees[symbol + 1], "degree", "the symbol leads its words");
assert!(names("5 inc‸").contains(&"in".to_string()));
// Elsewhere a unit's spelling stays a name like any other, so it doesn't crowd the builtins
assert!(!names("m‸").contains(&"meter".to_string()));
assert!(!names("x m‸").contains(&"meter".to_string()));
}
}
+52 -5
View File
@@ -1,4 +1,6 @@
use crate::matrix::Matrix;
use crate::quantity::{MatrixQuantity, Quantity};
use crate::units::DEFAULT_PIXELS_PER_INCH;
use crate::value::Value;
use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
@@ -11,6 +13,16 @@ pub trait ValueProvider {
fn get_matrix(&self, _name: &str) -> Option<Matrix> {
None
}
/// The value bound to a name with the unit it is measured in, which is plain unless a host measures it.
fn get_quantity(&self, name: &str) -> Option<Quantity> {
self.get_value(name).map(Quantity::plain)
}
/// The matrix bound to a name with the units of its linear part and translation, which are plain unless a host measures them.
fn get_matrix_quantity(&self, name: &str) -> Option<MatrixQuantity> {
self.get_matrix(name).map(MatrixQuantity::plain)
}
}
pub trait FunctionProvider {
@@ -34,6 +46,14 @@ impl<V: ValueProvider> ValueProvider for &V {
fn get_matrix(&self, name: &str) -> Option<Matrix> {
(**self).get_matrix(name)
}
fn get_quantity(&self, name: &str) -> Option<Quantity> {
(**self).get_quantity(name)
}
fn get_matrix_quantity(&self, name: &str) -> Option<MatrixQuantity> {
(**self).get_matrix_quantity(name)
}
}
impl ValueProvider for NothingMap {
@@ -73,20 +93,47 @@ impl FunctionProvider for NothingMap {
pub struct EvalContext<V: ValueProvider, F: FunctionProvider> {
values: V,
functions: F,
/// The size of the `px` unit, as the count of pixels in an inch.
pixels_per_inch: f64,
}
impl Default for EvalContext<NothingMap, NothingMap> {
fn default() -> Self {
Self {
values: NothingMap,
functions: NothingMap,
}
Self::new(NothingMap, NothingMap)
}
}
impl<V: ValueProvider, F: FunctionProvider> EvalContext<V, F> {
pub fn new(values: V, functions: F) -> Self {
Self { values, functions }
Self {
values,
functions,
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
/// Sizes the `px` unit as an inch over this count, where a count that isn't positive and finite keeps the default.
pub fn with_pixels_per_inch(mut self, pixels_per_inch: f64) -> Self {
if pixels_per_inch.is_finite() && pixels_per_inch > 0. {
self.pixels_per_inch = pixels_per_inch;
}
self
}
pub fn pixels_per_inch(&self) -> f64 {
self.pixels_per_inch
}
pub fn get_quantity(&self, name: &str) -> Option<Quantity> {
self.values.get_quantity(name)
}
pub fn get_matrix_quantity(&self, name: &str) -> Option<MatrixQuantity> {
self.values.get_matrix_quantity(name)
}
pub fn provides_function(&self, name: &str) -> bool {
self.functions.provides(name)
}
pub fn get_value(&self, name: &str) -> Option<Value> {
+41 -12
View File
@@ -8,6 +8,7 @@ use crate::lexer::{Constant, Token};
use crate::matrix::Matrix;
use crate::quaternion::Quaternion;
use crate::reducer::{Reducer, classify_reducer};
use crate::units::UnitId;
use crate::value::Value;
/// Hover text, as the tooltip Markdown subset: code spans, fenced code blocks, bold, and italic.
@@ -189,7 +190,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[−π/2, π/2]",
doc(
"The angle whose sine is `x`. Outside its domain, the result climbs into the complex plane.",
&[("asin(1)", "π/2"), ("asin(2)", "π/2 - 1.317i")],
&[("asin(1)", "π/2 rad"), ("asin(2)", "(π/2 - 1.317i) rad")],
),
),
function(
@@ -200,7 +201,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[0, π]",
doc(
"The angle whose cosine is `x`. Outside its domain, the result climbs into the complex plane.",
&[("acos(-1)", "π"), ("acos(2)", "1.317i")],
&[("acos(-1)", "π rad"), ("acos(2)", "1.317i rad")],
),
),
function(
@@ -209,7 +210,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
Treatment::InPlane,
&[parameter("x", "[−∞, ∞]", "the tangent")],
"[−π/2, π/2]",
doc("The angle whose tangent is `x`.", &[("atan(1)", "π/4"), ("atan(∞)", "π/2")]),
doc("The angle whose tangent is `x`.", &[("atan(1)", "π/4 rad"), ("atan(∞)", "π/2 rad")]),
),
function(
"atan2",
@@ -217,7 +218,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
Treatment::RealOnly,
&[parameter("y", "[−∞, ∞]", "the point's `y` coordinate"), parameter("x", "[−∞, ∞]", "the point's `x` coordinate")],
"[−π, π]",
doc("The angle from the positive `x` axis to the point `(x, y)`.", &[("atan2(1, 1)", "π/4"), ("atan2(0, -1)", "π")]),
doc("The angle from the positive `x` axis to the point `(x, y)`.", &[("atan2(1, 1)", "π/4 rad"), ("atan2(0, -1)", "π rad")]),
),
function(
"acsc",
@@ -227,7 +228,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[−π/2, π/2]",
doc(
"The angle whose cosecant is `x`, `asin(1/x)`. Outside its domain, the result climbs into the complex plane, except that 0 is an error.",
&[("acsc(2)", "π/6")],
&[("acsc(2)", "π/6 rad")],
),
),
function(
@@ -238,7 +239,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[0, π]",
doc(
"The angle whose secant is `x`, `acos(1/x)`. Outside its domain, the result climbs into the complex plane, except that 0 is an error.",
&[("asec(2)", "π/3")],
&[("asec(2)", "π/3 rad")],
),
),
function(
@@ -247,7 +248,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
Treatment::InPlane,
&[parameter("x", "[−∞, ∞]", "the cotangent")],
"[−π/2, π/2]",
doc("The angle whose cotangent is `x`, `atan(1/x)`.", &[("acot(1)", "π/4")]),
doc("The angle whose cotangent is `x`, `atan(1/x)`.", &[("acot(1)", "π/4 rad")]),
),
// Hyperbolic functions
function(
@@ -736,7 +737,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[−π, π]",
doc(
"How far `a` must turn to face `b`, signed by the turn's direction seen from `+k`. `angle(i, v)` is the heading of `v`.",
&[("angle(i, j)", "π/2"), ("angle(j, i)", "-π/2")],
&[("angle(i, j)", "π/2 rad"), ("angle(j, i)", "-π/2 rad")],
),
),
function(
@@ -1090,6 +1091,28 @@ const IDENTITY: Doc = doc(
&[("I (3i + 4j)", "3i + 4j")],
);
/// The hover text for a unit, naming what it measures and its other spellings.
pub fn unit_tooltip(unit: UnitId) -> Tooltip {
let definition = unit.definition();
let mut label = definition.name.to_string();
if let Some(first) = label.get(..1) {
label = first.to_uppercase() + &label[1..];
}
let others: Vec<String> = definition.spellings.iter().skip(1).map(|spelling| format!("`{spelling}`")).collect();
let spellings = match others.as_slice() {
[] => String::new(),
[only] => format!(" Also written {only}."),
[rest @ .., last] => format!(" Also written {} or {last}.", rest.join(", ")),
};
Tooltip {
label,
form: Some(definition.symbol.to_string()),
description: format!("A unit of {}.{spellings}", definition.dimension.noun()),
signature: None,
}
}
/// The hover text for the identity matrix `I`.
pub fn identity_tooltip() -> Tooltip {
documented("Identity Matrix", "I".to_string(), &IDENTITY, Treatment::Whole, "")
@@ -1712,11 +1735,17 @@ mod tests {
use super::*;
use crate::object::Object;
/// Whether two results agree to the few digits the documentation rounds them to, matrices entry by entry.
/// Whether two results agree to the few digits the documentation rounds them to, matrices entry by entry, and values in their units.
fn agree(actual: &Object, expected: &Object) -> bool {
if let (Object::Value(actual), Object::Value(expected)) = (actual, expected)
&& actual.unit != expected.unit
{
return false;
}
let parts = |object: &Object| match object {
Object::Value(Value::Number(number)) => number.to_quaternion().parts().to_vec(),
Object::Matrix(matrix) => matrix.rows.iter().chain([&matrix.translation]).flat_map(|row| row.parts()).collect(),
Object::Value(quantity) => quantity.number().to_quaternion().parts().to_vec(),
Object::Matrix(matrix) => matrix.matrix.rows.iter().chain([&matrix.matrix.translation]).flat_map(|row| row.parts()).collect(),
};
let close = |actual: f64, expected: f64| {
if expected.is_infinite() {
@@ -1752,7 +1781,7 @@ mod tests {
fn every_treatment_matches_how_the_function_evaluates() {
let evaluate = |expression: &str| crate::evaluate(expression).ok()?.ok();
let number = |expression: &str| match evaluate(expression) {
Some(Object::Value(Value::Number(number))) => number.to_quaternion(),
Some(Object::Value(quantity)) => quantity.number().to_quaternion(),
result => panic!("`{expression}` should be a number, not {result:?}"),
};
let close = |actual: Quaternion, expected: Quaternion| actual.parts().iter().zip(expected.parts()).all(|(actual, expected)| (actual - expected).abs() <= 1e-9);
+450 -170
View File
@@ -1,10 +1,12 @@
use crate::ast::{BinaryOp, Clause, Literal, Local, MatrixNode, Node, SortedCase, UnaryOp, ValueNode};
use crate::ast::{BinaryOp, BuiltinCall, Clause, Literal, Local, MatrixNode, Measure, Node, SortedCase, UnaryOp, ValueNode};
use crate::constants::{Builtin, MatrixToValue, SuffixedFunction, ValueOfRegions, builtin_function, suffixed_function};
use crate::context::{EvalContext, FunctionProvider, ValueProvider};
use crate::lexer::Constant;
use crate::matrix::{Matrix, Region};
use crate::object::Object;
use crate::quantity::{self, MatrixQuantity, MatrixValueUnit, Quantity, RegionResult, UnitRule, unit_rule};
use crate::quaternion::Quaternion;
use crate::units::{Unit, unit_named};
use crate::value::{Number, Value};
use std::cell::OnceCell;
use thiserror::Error;
@@ -58,18 +60,58 @@ pub enum EvalError {
#[error("Value of {0} is not a number")]
NotANumber(String),
#[error(transparent)]
Units(Box<UnitMismatch>),
#[error("An exponent in an angle unit rotates, so it can't also have a plain part")]
AngleExponentWithPlainPart,
#[error("The units are too far apart in size to combine")]
UnitOverflow,
}
/// Why units don't fit an operation, boxed within [`EvalError`] so the error every evaluation step returns stays small.
#[derive(Debug, Error)]
pub enum UnitMismatch {
#[error("A value in `{left}` can't be {verb} one in `{right}`, since they measure different things")]
IncompatibleUnits { verb: &'static str, left: String, right: String },
#[error("A plain number can't be {verb} a value in `{unit}`, so give it a unit too, like `1 {unit}`")]
PlainWithUnit { verb: &'static str, unit: String },
#[error("`{function}` takes plain numbers, not a value in `{unit}`")]
UnitsNotAccepted { function: String, unit: String },
#[error("`{function}` takes a plain number, since its result would depend on the unit, so round a value in `{unit}` with `snap(x, 1 {unit})`")]
RoundingWithUnits { function: String, unit: String },
#[error("`{function}` takes an angle or a plain number, not a value in `{unit}`")]
AngleExpected { function: String, unit: String },
#[error("The power leaves `{0}` with a fractional exponent")]
FractionalUnitPower(String),
#[error("An exponent can't be in `{0}`")]
ExponentWithUnits(String),
}
impl From<UnitMismatch> for EvalError {
fn from(mismatch: UnitMismatch) -> Self {
Self::Units(Box::new(mismatch))
}
}
/// Settles an operation's result: no operation may produce NaN, so an indeterminate form is an error, and the value takes
/// its canonical form so that a zero imaginary part or a signed zero never changes a later result.
// Inlined with the canonical form it calls, since these run after every operation where a call would cost as much as the work
#[inline(always)]
fn settle(value: Value) -> Result<Value, EvalError> {
let Value::Number(number) = value;
fn settle(quantity: Quantity) -> Result<Quantity, EvalError> {
let number = quantity.number();
if number.is_nan() {
return Err(EvalError::Indeterminate);
}
Ok(Value::Number(number.canonical()))
Ok(Quantity::new(Value::Number(number.canonical()), quantity.unit))
}
/// Settles a matrix result like [`settle`] does a value, with signed zeros made plain zero.
@@ -80,35 +122,90 @@ pub(crate) fn settle_matrix(matrix: Matrix) -> Result<Matrix, EvalError> {
Ok(matrix.map(|entry| if entry == 0. { 0. } else { entry }))
}
fn settle_matrix_quantity(matrix: MatrixQuantity) -> Result<MatrixQuantity, EvalError> {
Ok(MatrixQuantity {
matrix: settle_matrix(matrix.matrix)?,
..matrix
})
}
/// The binary operation on two evaluated values, settled.
#[inline(always)]
fn binary(lhs: Quantity, op: BinaryOp, rhs: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
if !lhs.is_plain() || !rhs.is_plain() {
return settle(quantity::unit_binary_op(lhs, op, rhs, pixels_per_inch)?);
}
// Plain numbers, the common case, take the arithmetic directly
let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
EvalError::NotATruthValue
} else {
EvalError::OperatorTypeError
};
let number = lhs.number().binary_op(op, rhs.number()).ok_or(rejected)?;
settle(Quantity::of_number(number, Unit::NONE))
}
/// A quotient by a measure, which is the whole divisor where the dividend has a unit, and otherwise divides by the measure's
/// number before its units multiply in. Kept out of the evaluator's frame, which nesting multiplies.
#[inline(never)]
fn measure_quotient<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, dividend: &ValueNode, measure: &Measure) -> Result<Quantity, EvalError> {
let pixels_per_inch = scope.pixels_per_inch();
let dividend = dividend.eval_in(scope)?;
let number = measure.number.eval_in(scope)?;
let units = measure
.units
.iter()
.try_fold(Quantity::plain(Value::from_i64(1)), |units, unit| binary(units, BinaryOp::Mul, unit.eval_in(scope)?, pixels_per_inch))?;
// A name the host or a `where` definition binds is no unit, so the measure then reads left to right as written
fn is_unit<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, node: &ValueNode) -> bool {
match node {
ValueNode::Unit { name, .. } => name.starts_with('\\') || scope.context.get_quantity(name).is_none(),
ValueNode::BinOp { lhs, op: BinaryOp::Pow, .. } => is_unit(scope, lhs),
_ => false,
}
}
if measure.units.iter().all(|unit| is_unit(scope, unit)) && !dividend.unit.dimension().is_none() {
binary(dividend, BinaryOp::Div, binary(number, BinaryOp::Mul, units, pixels_per_inch)?, pixels_per_inch)
} else {
binary(binary(dividend, BinaryOp::Div, number, pixels_per_inch)?, BinaryOp::Mul, units, pixels_per_inch)
}
}
/// The canonical form of a value the host supplied for `name`, like [`settle`], except that NaN (which only a host can
/// supply) is an error naming its source.
#[inline(always)]
fn canonical_host_value(name: &str, value: Value) -> Result<Value, EvalError> {
let Value::Number(number) = value;
fn canonical_host_value(name: &str, quantity: Quantity) -> Result<Quantity, EvalError> {
let number = quantity.number();
if number.is_nan() {
return Err(EvalError::NotANumber(name.to_string()));
}
Ok(Value::Number(number.canonical()))
Ok(Quantity::new(Value::Number(number.canonical()), quantity.unit))
}
/// Resolves a name against the environment before the builtin constants, so a binding of exactly that spelling shadows the builtin.
/// The `\` prefix skips the environment.
fn resolve_value<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Value> {
let constant = |name: &str| Constant::from_name(name).map(|constant| Value::Number(constant.value()));
/// Resolves a name against the environment before the builtin constants and units, so a binding of exactly that spelling shadows
/// the builtin. The `\` prefix skips the environment.
fn resolve_value<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Quantity> {
let builtin = |name: &str| {
Constant::from_name(name)
.map(|constant| Quantity::plain(Value::Number(constant.value())))
.or_else(|| unit_named(name).map(|unit| Quantity::new(Value::from_i64(1), Unit::of(unit))))
};
match name.strip_prefix('\\') {
Some(builtin_name) => constant(builtin_name),
None => context.get_value(name).or_else(|| constant(name)),
Some(builtin_name) => builtin(builtin_name),
None => context.get_quantity(name).or_else(|| builtin(name)),
}
}
/// Resolves a matrix's name like [`resolve_value`], with `I` the one builtin.
fn resolve_matrix<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Matrix> {
let constant = |name: &str| (name == "I").then_some(Matrix::IDENTITY);
fn resolve_matrix<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<MatrixQuantity> {
let constant = |name: &str| (name == "I").then_some(MatrixQuantity::plain(Matrix::IDENTITY));
match name.strip_prefix('\\') {
Some(builtin_name) => constant(builtin_name),
None => context.get_matrix(name).or_else(|| constant(name)),
None => context.get_matrix_quantity(name).or_else(|| constant(name)),
}
}
@@ -131,6 +228,10 @@ impl<'a, V: ValueProvider, F: FunctionProvider> Scope<'a, V, F> {
}
frame.ok_or(EvalError::OperatorTypeError)
}
fn pixels_per_inch(&self) -> f64 {
self.context.pixels_per_inch()
}
}
/// The definitions of one `where` clause, or the arguments of one call, each evaluated on its first read and at most once.
@@ -159,9 +260,9 @@ enum Bound<'a, T> {
// Each sort reads through `where` definitions by an outlined function, keeping its frames out of the recursive evaluator's, and
// called from several sites since wasm-opt inlines a function with one call site
#[inline(never)]
fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<ValueNode>) -> Result<Value, EvalError> {
fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<ValueNode>) -> Result<Quantity, EvalError> {
match bound {
Bound::Local(local) => read(scope, local)?.as_value().copied().ok_or(EvalError::OperatorTypeError),
Bound::Local(local) => read(scope, local)?.as_quantity().copied().ok_or(EvalError::OperatorTypeError),
Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body {
Node::Value(body) => body.eval_in(scope),
Node::Matrix(_) => Err(EvalError::OperatorTypeError),
@@ -171,9 +272,9 @@ fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, b
}
#[inline(never)]
fn bound_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<MatrixNode>) -> Result<Matrix, EvalError> {
fn bound_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<MatrixNode>) -> Result<MatrixQuantity, EvalError> {
match bound {
Bound::Local(local) => read(scope, local)?.as_matrix().copied().ok_or(EvalError::OperatorTypeError),
Bound::Local(local) => read(scope, local)?.as_matrix_quantity().copied().ok_or(EvalError::OperatorTypeError),
Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body {
Node::Matrix(body) => body.eval_in(scope),
Node::Value(_) => Err(EvalError::OperatorTypeError),
@@ -252,8 +353,11 @@ fn holding_case<'a, T, V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_,
let mut holding = None;
let mut overlapping = false;
for case in cases {
let Value::Number(condition) = case.condition.eval_in(scope)?;
match condition.as_bool() {
let condition = case.condition.eval_in(scope)?;
if !condition.is_plain() {
return Err(EvalError::NotATruthValue);
}
match condition.number().as_bool() {
Some(false) => {}
Some(true) if holding.is_none() => holding = Some(&case.value),
Some(true) => overlapping = true,
@@ -268,8 +372,8 @@ fn holding_case<'a, T, V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_,
/// An operand of a matrix operation, holding a matrix on the stack since the operation consumes it at once.
enum Operand {
Value(Value),
Matrix(Matrix),
Value(Quantity),
Matrix(MatrixQuantity),
}
impl Node {
@@ -283,30 +387,40 @@ impl Node {
/// An operation with a matrix result: a value on the left acts as `L_q`, matrices compose, sums are pointwise or attach a
/// value as translation, division is times-inverse, and powers are whole.
fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand) -> Result<Matrix, EvalError> {
fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand, pixels_per_inch: f64) -> Result<MatrixQuantity, EvalError> {
use BinaryOp as Op;
match (lhs, op, rhs) {
(Operand::Value(Value::Number(q)), Op::Mul, Operand::Matrix(b)) => settle_matrix(Matrix::left_multiplication(q.to_quaternion()).compose(b)),
(Operand::Matrix(a), Op::Mul, Operand::Matrix(b)) => settle_matrix(a.compose(b)),
(lhs, Op::Div, Operand::Matrix(b)) => matrix_binary_op(lhs, Op::Mul, Operand::Matrix(b.inverse().ok_or(EvalError::SingularMatrix)?)),
(Operand::Matrix(a), Op::Add, Operand::Matrix(b)) => settle_matrix(a + b),
(Operand::Matrix(a), Op::Sub, Operand::Matrix(b)) => settle_matrix(a - b),
(Operand::Matrix(a), Op::Add, Operand::Value(Value::Number(t))) | (Operand::Value(Value::Number(t)), Op::Add, Operand::Matrix(a)) => settle_matrix(a.translated(t.to_quaternion())),
(Operand::Matrix(a), Op::Sub, Operand::Value(Value::Number(t))) => settle_matrix(a.translated(-t.to_quaternion())),
(Operand::Value(Value::Number(t)), Op::Sub, Operand::Matrix(a)) => settle_matrix((-a).translated(t.to_quaternion())),
(Operand::Matrix(a), Op::Pow, Operand::Value(Value::Number(exponent))) => {
let result = match (lhs, op, rhs) {
(Operand::Value(q), Op::Mul, Operand::Matrix(b)) => {
let left_multiplication = MatrixQuantity {
matrix: Matrix::left_multiplication(q.number().to_quaternion()),
linear: q.unit,
translation: Unit::NONE,
};
left_multiplication.compose(&b, pixels_per_inch)?
}
(Operand::Matrix(a), Op::Mul, Operand::Matrix(b)) => a.compose(&b, pixels_per_inch)?,
(lhs, Op::Div, Operand::Matrix(b)) => return matrix_binary_op(lhs, Op::Mul, Operand::Matrix(b.inverse(pixels_per_inch)?), pixels_per_inch),
(Operand::Matrix(a), Op::Add | Op::Sub, Operand::Matrix(b)) => a.sum(op, &b, pixels_per_inch)?,
(Operand::Matrix(a), Op::Add | Op::Sub, Operand::Value(t)) => a.translated(op, t, pixels_per_inch)?,
(Operand::Value(t), Op::Add, Operand::Matrix(a)) => a.translated(Op::Add, t, pixels_per_inch)?,
(Operand::Value(t), Op::Sub, Operand::Matrix(a)) => a.negated().translated(Op::Add, t, pixels_per_inch)?,
(Operand::Matrix(a), Op::Pow, Operand::Value(exponent)) => {
if !exponent.is_plain() {
return Err(EvalError::from(UnitMismatch::ExponentWithUnits(exponent.unit.to_string())));
}
// A whole exponent is a composition power, a negative one of the inverse, with an integer read exactly past 2^53
let whole = match exponent {
let whole = match exponent.number() {
Number::Integer(integer) => integer,
real => real
.as_real()
.filter(|real| real.fract() == 0. && real.abs() < i64::MAX as f64)
.ok_or(EvalError::FractionalMatrixPower)? as i64,
};
settle_matrix(a.power(whole).ok_or(EvalError::SingularMatrix)?)
a.power(whole, pixels_per_inch)?
}
_ => Err(EvalError::OperatorTypeError),
}
_ => return Err(EvalError::OperatorTypeError),
};
settle_matrix_quantity(result)
}
impl Node {
@@ -327,98 +441,43 @@ impl Node {
}
impl ValueNode {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Value, EvalError> {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Quantity, EvalError> {
self.eval_in(&Scope::root(context))
}
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Value, EvalError> {
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Quantity, EvalError> {
match self {
ValueNode::Lit(lit) => match lit {
Literal::Integer(integer) => Ok(Value::from_i64(*integer)),
Literal::Float(float) => Ok(Value::from_f64(*float)),
Literal::Integer(integer) => Ok(Quantity::plain(Value::from_i64(*integer))),
Literal::Float(float) => Ok(Quantity::plain(Value::from_f64(*float))),
},
ValueNode::BinOp { lhs, op, rhs } => match (lhs.eval_in(scope)?, rhs.eval_in(scope)?) {
(Value::Number(lhs), Value::Number(rhs)) => {
// Logic rejects operands that aren't truth values, while the other operators reject operand types they don't support
let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
EvalError::NotATruthValue
} else {
EvalError::OperatorTypeError
};
settle(Value::Number(lhs.binary_op(*op, rhs).ok_or(rejected)?))
ValueNode::BinOp { lhs, op, rhs } => binary(lhs.eval_in(scope)?, *op, rhs.eval_in(scope)?, scope.pixels_per_inch()),
ValueNode::MeasureQuotient { dividend, measure } => measure_quotient(scope, dividend, measure),
ValueNode::UnaryOp { expr, op } => {
let operand = expr.eval_in(scope)?;
if !operand.is_plain() {
return settle(quantity::unary_op(operand, *op)?);
}
},
ValueNode::UnaryOp { expr, op } => match expr.eval_in(scope)? {
Value::Number(num) => {
let rejected = if *op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError };
settle(Value::Number(num.unary_op(*op).ok_or(rejected)?))
}
},
ValueNode::Comparison { first, rest } => {
let Value::Number(first) = first.eval_in(scope)?;
let rest = rest
.iter()
.map(|(op, operand)| operand.eval_in(scope).map(|Value::Number(number)| (*op, number)))
.collect::<Result<Vec<(BinaryOp, Number)>, EvalError>>()?;
// A `!=` chain asserts every pair distinct, while the ordered chains assert each adjacent pair's relation; every pair is checked so an unsupported comparison errors regardless of the others
let holds = if rest.iter().all(|(op, _)| *op == BinaryOp::Neq) {
let numbers: Vec<Number> = std::iter::once(first).chain(rest.iter().map(|(_, number)| *number)).collect();
numbers.iter().enumerate().all(|(index, a)| numbers[index + 1..].iter().all(|b| a != b))
} else {
let mut holds = true;
let mut previous = first;
for (op, number) in rest {
holds &= previous.binary_op(op, number).ok_or(EvalError::OperatorTypeError)?.as_bool() == Some(true);
previous = number;
}
holds
};
Ok(Value::from_bool(holds))
let rejected = if *op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError };
settle(Quantity::of_number(operand.number().unary_op(*op).ok_or(rejected)?, Unit::NONE))
}
ValueNode::Comparison { first, rest } => comparison_chain(scope, first, rest),
ValueNode::Var(name) => {
let value = resolve_value(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?;
canonical_host_value(name, value)
}
ValueNode::FnCall { name, expr } => {
// Arguments land in a stack buffer when they fit (builtins take at most 5), avoiding a heap allocation per call
let mut stack_values = [Value::from_i64(0); 5];
let heap_values: Vec<Value>;
let values: &[Value] = if expr.len() <= stack_values.len() {
for (slot, argument) in stack_values.iter_mut().zip(expr) {
*slot = argument.eval_in(scope)?;
}
&stack_values[..expr.len()]
} else {
heap_values = expr.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Value>, EvalError>>()?;
&heap_values
};
// A host-supplied function shadows the builtin of the same name, unless the `\` prefix asks for the language's own
let (prefixed, bare_name) = match name.strip_prefix('\\') {
Some(bare_name) => (true, bare_name),
None => (false, name.as_str()),
};
if !prefixed && let Some(value) = scope.context.run_function(bare_name, values) {
settle(canonical_host_value(bare_name, value)?)
} else if let Some(Builtin::Values { function, .. }) = builtin_function(bare_name) {
settle(function(values).ok_or(EvalError::TypeError)?)
} else if let Some(SuffixedFunction { function, argument, .. }) = suffixed_function(bare_name) {
// A base-suffixed call like `log10(x)` runs the two-argument form with the suffix baked in as its second argument
let [value] = values else { return Err(EvalError::TypeError) };
settle(function(&[*value, Value::from_f64(argument)]).ok_or(EvalError::TypeError)?)
} else if let Some(value) = resolve_value(scope.context, name)
&& let [Value::Number(argument)] = values
{
// A known value applied to one argument is implicit multiplication, so `x(2)` matches `2(3)` and `i(16)`
let Value::Number(value) = canonical_host_value(name, value)?;
settle(Value::Number(value.binary_op(BinaryOp::Mul, *argument).ok_or(EvalError::OperatorTypeError)?))
} else {
Err(EvalError::MissingFunction(name.to_string()))
ValueNode::Unit { name, unit } => {
// A host's binding of the spelling shadows the unit, unless the `\` prefix asks for the unit
let bound = (!name.starts_with('\\')).then(|| scope.context.get_quantity(name)).flatten();
match bound {
Some(value) => canonical_host_value(name, value),
None => Ok(Quantity::new(Value::from_i64(1), Unit::of(*unit))),
}
}
ValueNode::FnCall { name, expr } => function_call(scope, name, expr),
ValueNode::BuiltinCall(call) => builtin_call(scope, call),
// Only the chosen value is evaluated, so an error in any other case's value is never raised
ValueNode::Piecewise { cases, otherwise } => match (holding_case(scope, cases)?, otherwise) {
(Some(value), _) => value.eval_in(scope),
@@ -426,8 +485,14 @@ impl ValueNode {
(None, None) => Err(EvalError::NoCaseHolds),
},
ValueNode::Apply { matrix, value } => value_of_matrix(scope, MatrixValueCase::Apply(matrix, value)),
ValueNode::OfMatrix { function, matrix } => value_of_matrix(scope, MatrixValueCase::OfMatrix(*function, matrix)),
ValueNode::OfValueAndRegions { function, value, regions, trailing } => value_of_matrix(scope, MatrixValueCase::OfValueAndRegions(*function, value, regions, trailing.as_deref())),
ValueNode::OfMatrix { function, unit, matrix } => value_of_matrix(scope, MatrixValueCase::OfMatrix(*function, *unit, matrix)),
ValueNode::OfValueAndRegions {
function,
result,
value,
regions,
trailing,
} => value_of_matrix(scope, MatrixValueCase::OfValueAndRegions(*function, *result, value, regions, trailing.as_deref())),
ValueNode::MatrixComparison { matrices, distinct } => value_of_matrix(scope, MatrixValueCase::Comparison(matrices, *distinct)),
ValueNode::Local(local) => bound_value(scope, Bound::Local(*local)),
ValueNode::Call { function, arguments } => bound_value(scope, Bound::Call(*function, arguments)),
@@ -436,134 +501,349 @@ impl ValueNode {
}
}
/// A chain of comparisons, outlined to keep its buffers out of the recursive evaluator's frame.
#[inline(never)]
fn comparison_chain<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, first: &ValueNode, rest: &[(BinaryOp, ValueNode)]) -> Result<Quantity, EvalError> {
let first = first.eval_in(scope)?;
let rest = rest
.iter()
.map(|(op, operand)| operand.eval_in(scope).map(|quantity| (*op, quantity)))
.collect::<Result<Vec<(BinaryOp, Quantity)>, EvalError>>()?;
let (first, rest) = quantity::comparison_operands(first, &rest, scope.pixels_per_inch())?;
// A `!=` chain asserts every pair distinct, while the ordered chains assert each adjacent pair's relation; every pair is checked so an unsupported comparison errors regardless of the others
let holds = if rest.iter().all(|(op, _)| *op == BinaryOp::Neq) {
let numbers: Vec<Number> = std::iter::once(first).chain(rest.iter().map(|(_, number)| *number)).collect();
numbers.iter().enumerate().all(|(index, a)| numbers[index + 1..].iter().all(|b| a != b))
} else {
let mut holds = true;
let mut previous = first;
for (op, number) in rest {
holds &= previous.binary_op(op, number).ok_or(EvalError::OperatorTypeError)?.as_bool() == Some(true);
previous = number;
}
holds
};
Ok(Quantity::plain(Value::from_bool(holds)))
}
/// A call of a builtin found as the expression was read, kept apart from the recursive evaluator so its argument buffers stay out of the evaluator's frame in unoptimized builds.
fn builtin_call<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, call: &BuiltinCall) -> Result<Quantity, EvalError> {
if call.suffix.is_some() && call.arguments.len() != 1 {
return Err(EvalError::TypeError);
}
// Arguments land in stack buffers when they fit (builtins take at most 5), each value beside its unit
let count = call.arguments.len() + usize::from(call.suffix.is_some());
let mut stack_values = [Value::from_i64(0); 5];
let mut stack_units = [Unit::NONE; 5];
let (mut heap_values, mut heap_units): (Vec<Value>, Vec<Unit>);
let (values, units): (&mut [Value], &mut [Unit]) = if count <= stack_values.len() {
(&mut stack_values[..count], &mut stack_units[..count])
} else {
heap_values = vec![Value::from_i64(0); count];
heap_units = vec![Unit::NONE; count];
(&mut heap_values, &mut heap_units)
};
for ((value, unit), argument) in values.iter_mut().zip(units.iter_mut()).zip(&call.arguments) {
let Quantity {
value: argument_value,
unit: argument_unit,
} = argument.eval_in(scope)?;
*value = argument_value;
*unit = argument_unit;
}
// A host may supply a function the expression wasn't read with, which shadows the builtin as it would have then
if let Some(host_name) = &call.host_name
&& scope.context.provides_function(host_name)
{
let arguments: Vec<Quantity> = values.iter().zip(units.iter()).take(call.arguments.len()).map(|(value, unit)| Quantity::new(*value, *unit)).collect();
if let Some(value) = host_function(scope, host_name, &arguments)? {
return settle(canonical_host_value(host_name, Quantity::plain(value))?);
}
}
if let Some(suffix) = call.suffix {
values[count - 1] = Value::from_f64(suffix);
}
settle(quantity::run_builtin_on_parts(&call.name, call.rule, call.function, values, units, scope.pixels_per_inch())?)
}
/// A call of a host function or a builtin, outlined to keep its argument buffer out of the recursive evaluator's frame.
#[inline(never)]
fn function_call<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, name: &str, expr: &[ValueNode]) -> Result<Quantity, EvalError> {
// Arguments land in a stack buffer when they fit (builtins take at most 5), avoiding a heap allocation per call
let mut stack_values = [Quantity::plain(Value::from_i64(0)); 5];
let heap_values: Vec<Quantity>;
let arguments: &[Quantity] = if expr.len() <= stack_values.len() {
for (slot, argument) in stack_values.iter_mut().zip(expr) {
*slot = argument.eval_in(scope)?;
}
&stack_values[..expr.len()]
} else {
heap_values = expr.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?;
&heap_values
};
// A host-supplied function shadows the builtin of the same name, unless the `\` prefix asks for the language's own
let (prefixed, bare_name) = match name.strip_prefix('\\') {
Some(bare_name) => (true, bare_name),
None => (false, name),
};
if !prefixed && let Some(value) = host_function(scope, bare_name, arguments)? {
settle(canonical_host_value(bare_name, Quantity::plain(value))?)
} else if let Some(Builtin::Values { function, .. }) = builtin_function(bare_name) {
let rule = unit_rule(bare_name).unwrap_or(UnitRule::Plain);
settle(quantity::run_builtin(bare_name, rule, function, arguments, scope.pixels_per_inch())?)
} else if let Some(SuffixedFunction { name: base_name, function, argument }) = suffixed_function(bare_name) {
// A base-suffixed call like `log10(x)` runs the two-argument form with the suffix baked in as its second argument
let [value] = arguments else { return Err(EvalError::TypeError) };
let rule = unit_rule(base_name).unwrap_or(UnitRule::Plain);
let arguments = [*value, Quantity::plain(Value::from_f64(argument))];
settle(quantity::run_builtin(base_name, rule, function, &arguments, scope.pixels_per_inch())?)
} else if let Some(value) = resolve_value(scope.context, name)
&& let [argument] = arguments
{
// A known value applied to one argument is implicit multiplication, so `x(2)` matches `2(3)` and `i(16)`
let value = canonical_host_value(name, value)?;
settle(quantity::binary_op(value, BinaryOp::Mul, *argument, scope.pixels_per_inch())?)
} else {
Err(EvalError::MissingFunction(name.to_string()))
}
}
/// Runs the host's function of the name, which takes plain numbers, or gives `None` where the host has none.
fn host_function<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, name: &str, arguments: &[Quantity]) -> Result<Option<Value>, EvalError> {
if !scope.context.provides_function(name) {
return Ok(None);
}
let arguments: Vec<Quantity> = arguments.iter().map(|argument| argument.plain_if_dimensionless()).collect();
if let Some(argument) = arguments.iter().find(|argument| !argument.is_plain()) {
return Err(EvalError::from(UnitMismatch::UnitsNotAccepted {
function: name.to_string(),
unit: argument.unit.to_string(),
}));
}
let values: Vec<Value> = arguments.iter().map(|argument| argument.value).collect();
Ok(scope.context.run_function(name, &values))
}
/// A value computed from matrices.
enum MatrixValueCase<'a> {
Apply(&'a MatrixNode, &'a ValueNode),
OfMatrix(MatrixToValue, &'a MatrixNode),
OfValueAndRegions(ValueOfRegions, &'a ValueNode, &'a [MatrixNode], Option<&'a ValueNode>),
OfMatrix(MatrixToValue, MatrixValueUnit, &'a MatrixNode),
OfValueAndRegions(ValueOfRegions, RegionResult, &'a ValueNode, &'a [MatrixNode], Option<&'a ValueNode>),
Comparison(&'a [MatrixNode], bool),
}
/// A region with the unit of the values it holds.
#[derive(Clone, Copy)]
struct UnitRegion {
region: Region,
unit: Unit,
}
// One function for every value taken from a matrix, called from several sites, since wasm-opt inlines a function with one call site back into the evaluator whatever its attributes say
#[cold]
#[inline(never)]
fn value_of_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, case: MatrixValueCase) -> Result<Value, EvalError> {
fn value_of_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, case: MatrixValueCase) -> Result<Quantity, EvalError> {
let pixels_per_inch = scope.pixels_per_inch();
match case {
MatrixValueCase::Apply(matrix, value) => {
let matrix = matrix.eval_in(scope)?;
let Value::Number(value) = value.eval_in(scope)?;
settle(Value::from(matrix.apply(value.to_quaternion())))
let value = value.eval_in(scope)?;
settle(matrix.apply(value, pixels_per_inch)?)
}
MatrixValueCase::OfMatrix(function, matrix) => settle(function(matrix.eval_in(scope)?)),
MatrixValueCase::OfValueAndRegions(function, value, regions, trailing) => {
MatrixValueCase::OfMatrix(function, unit, matrix) => {
let matrix = matrix.eval_in(scope)?;
let unit = quantity::matrix_value_result_unit(unit, &matrix)?;
settle(Quantity::new(function(matrix.matrix), unit))
}
MatrixValueCase::OfValueAndRegions(function, result_unit, value, regions, trailing) => {
let value = value.eval_in(scope)?;
// A range literal is kept by its corners, which may be infinite where no matrix can hold them
let region_of = |region: &MatrixNode| -> Result<Region, EvalError> {
let region_of = |region: &MatrixNode| -> Result<UnitRegion, EvalError> {
match region {
MatrixNode::Range { from, to } => {
let (Value::Number(from), Value::Number(to)) = (from.eval_in(scope)?, to.eval_in(scope)?);
Ok(Region::Range(from, to))
let (from, to, unit) = quantity::range_corners(from.eval_in(scope)?, to.eval_in(scope)?, pixels_per_inch)?;
Ok(UnitRegion {
region: Region::Range(from, to),
unit,
})
}
region => {
let matrix = region.eval_in(scope)?;
let unit = matrix.region_unit();
Ok(UnitRegion {
region: Region::Map(matrix.as_region_in(unit, pixels_per_inch)?),
unit,
})
}
region => region.eval_in(scope).map(Region::Map),
}
};
// The range functions take at most two regions as parsed, which land in a stack buffer, while a longer list a host built goes to the heap
let mut stack_regions = [Region::Range(Number::Integer(0), Number::Integer(0)); 2];
let heap_regions: Vec<Region>;
let regions: &[Region] = if regions.len() <= stack_regions.len() {
let placeholder = UnitRegion {
region: Region::Range(Number::Integer(0), Number::Integer(0)),
unit: Unit::NONE,
};
let mut stack_regions = [placeholder; 2];
let heap_regions: Vec<UnitRegion>;
let unit_regions: &[UnitRegion] = if regions.len() <= stack_regions.len() {
for (slot, region) in stack_regions.iter_mut().zip(regions) {
*slot = region_of(region)?;
}
&stack_regions[..regions.len()]
} else {
heap_regions = regions.iter().map(region_of).collect::<Result<Vec<Region>, EvalError>>()?;
heap_regions = regions.iter().map(region_of).collect::<Result<Vec<UnitRegion>, EvalError>>()?;
&heap_regions
};
let trailing = trailing.map(|trailing| trailing.eval_in(scope)).transpose()?;
settle(function(value, regions, trailing)?)
// The value is measured in the first region's unit, and a remap's result in the last's
let Some(first) = unit_regions.first() else { return Err(EvalError::TypeError) };
let value = Quantity::of_number(quantity::into_region_unit(value, first.unit, pixels_per_inch)?, Unit::NONE);
let mut stack_plain_regions = [placeholder.region; 2];
let heap_plain_regions: Vec<Region>;
let plain_regions: &[Region] = if unit_regions.len() <= stack_plain_regions.len() {
for (slot, unit_region) in stack_plain_regions.iter_mut().zip(unit_regions) {
*slot = unit_region.region;
}
&stack_plain_regions[..unit_regions.len()]
} else {
heap_plain_regions = unit_regions.iter().map(|unit_region| unit_region.region).collect();
&heap_plain_regions
};
let trailing = match trailing.map(|trailing| trailing.eval_in(scope)).transpose()? {
Some(trailing) if !trailing.is_plain() => return Err(EvalError::SmoothstepContinuity),
trailing => trailing.map(|trailing| trailing.value),
};
let result = function(value.value, plain_regions, trailing)?;
let unit = match result_unit {
RegionResult::FirstRegion => first.unit,
RegionResult::LastRegion => unit_regions.last().map_or(Unit::NONE, |region| region.unit),
RegionResult::Plain => Unit::NONE,
};
settle(Quantity::new(result, unit))
}
MatrixValueCase::Comparison(matrices, distinct) => {
// A chain lands in a stack buffer when it fits, the usual case
let mut stack_matrices = [Matrix::ZERO; 4];
let heap_matrices: Vec<Matrix>;
let matrices: &[Matrix] = if matrices.len() <= stack_matrices.len() {
let mut stack_matrices = [MatrixQuantity::plain(Matrix::ZERO); 4];
let heap_matrices: Vec<MatrixQuantity>;
let matrices: &[MatrixQuantity] = if matrices.len() <= stack_matrices.len() {
for (slot, matrix) in stack_matrices.iter_mut().zip(matrices) {
*slot = matrix.eval_in(scope)?;
}
&stack_matrices[..matrices.len()]
} else {
heap_matrices = matrices.iter().map(|matrix| matrix.eval_in(scope)).collect::<Result<Vec<Matrix>, EvalError>>()?;
heap_matrices = matrices.iter().map(|matrix| matrix.eval_in(scope)).collect::<Result<Vec<MatrixQuantity>, EvalError>>()?;
&heap_matrices
};
let holds = if distinct {
matrices.iter().enumerate().all(|(index, a)| matrices[index + 1..].iter().all(|b| !a.same_entries(*b)))
} else {
matrices.windows(2).all(|pair| pair[0].same_entries(pair[1]))
// Matrices compare in the first one's units, which every other must share in dimension
let Some(first) = matrices.first() else { return Err(EvalError::TypeError) };
let translation_unit = matrices.iter().map(|matrix| matrix.translation).find(|unit| !unit.is_none()).unwrap_or(Unit::NONE);
let in_first_units = |matrix: &MatrixQuantity| -> Result<Matrix, EvalError> {
if matrix.linear == first.linear && matrix.translation == translation_unit {
return Ok(matrix.matrix);
}
matrix.in_units(first.linear, translation_unit, pixels_per_inch)
};
Ok(Value::from_bool(holds))
let plain = matrices.iter().map(in_first_units).collect::<Result<Vec<Matrix>, EvalError>>()?;
let holds = if distinct {
plain.iter().enumerate().all(|(index, a)| plain[index + 1..].iter().all(|b| !a.same_entries(*b)))
} else {
plain.windows(2).all(|pair| pair[0].same_entries(pair[1]))
};
Ok(Quantity::plain(Value::from_bool(holds)))
}
}
}
impl MatrixNode {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Matrix, EvalError> {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<MatrixQuantity, EvalError> {
self.eval_in(&Scope::root(context))
}
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Matrix, EvalError> {
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<MatrixQuantity, EvalError> {
let pixels_per_inch = scope.pixels_per_inch();
match self {
MatrixNode::Var(name) => {
let matrix = resolve_matrix(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?;
if matrix.is_nan() {
if matrix.matrix.is_nan() {
return Err(EvalError::NotANumber(name.clone()));
}
settle_matrix(matrix)
settle_matrix_quantity(matrix)
}
MatrixNode::Literal { entries, by_rows } => {
let mut quaternions = [Quaternion::ZERO; 4];
if entries.len() > quaternions.len() {
if entries.len() > 4 {
return Err(EvalError::TypeError);
}
for (slot, entry) in quaternions.iter_mut().zip(entries) {
let Value::Number(number) = entry.eval_in(scope)?;
*slot = number.to_quaternion();
}
let quantities = entries.iter().map(|entry| entry.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?;
let (quaternions, unit) = quantity::literal_entries(&quantities, pixels_per_inch)?;
let entries = &quaternions[..entries.len()];
let matrix = if *by_rows { Matrix::from_rows(entries) } else { Matrix::from_columns(entries) };
settle_matrix(matrix.ok_or(EvalError::TypeError)?)
let matrix = if *by_rows { Matrix::from_rows(&quaternions) } else { Matrix::from_columns(&quaternions) };
settle_matrix_quantity(MatrixQuantity {
matrix: matrix.ok_or(EvalError::TypeError)?,
linear: unit,
translation: Unit::NONE,
})
}
MatrixNode::FromValues { function, arguments } => {
MatrixNode::FromValues { function, units, arguments } => {
// The builders take at most three arguments as parsed, which land in a stack buffer, while a longer list a host built goes to the heap
let mut stack_values = [Value::from_i64(0); 3];
let heap_values: Vec<Value>;
let values: &[Value] = if arguments.len() <= stack_values.len() {
let mut stack_values = [Quantity::plain(Value::from_i64(0)); 3];
let heap_values: Vec<Quantity>;
let quantities: &[Quantity] = if arguments.len() <= stack_values.len() {
for (slot, argument) in stack_values.iter_mut().zip(arguments) {
*slot = argument.eval_in(scope)?;
}
&stack_values[..arguments.len()]
} else {
heap_values = arguments.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Value>, EvalError>>()?;
heap_values = arguments.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?;
&heap_values
};
settle_matrix(function(values).ok_or(EvalError::TypeError)?)
let (values, linear) = quantity::builder_arguments(*units, quantities)?;
settle_matrix_quantity(MatrixQuantity {
matrix: function(&values).ok_or(EvalError::TypeError)?,
linear,
translation: Unit::NONE,
})
}
MatrixNode::Range { from, to } => {
let (Value::Number(from), Value::Number(to)) = (from.eval_in(scope)?, to.eval_in(scope)?);
settle_matrix(Matrix::range(from.to_quaternion(), to.to_quaternion()))
let (from, to, unit) = quantity::range_corners(from.eval_in(scope)?, to.eval_in(scope)?, pixels_per_inch)?;
let matrix = Matrix::range(from.to_quaternion(), to.to_quaternion());
let translation = if matrix.translation == Quaternion::ZERO { Unit::NONE } else { unit };
settle_matrix_quantity(MatrixQuantity { matrix, linear: unit, translation })
}
MatrixNode::OfMatrix { function, matrix } => settle_matrix(function(matrix.eval_in(scope)?)),
MatrixNode::BinOp { lhs, op, rhs } => matrix_binary_op(lhs.operand(scope)?, *op, rhs.operand(scope)?),
MatrixNode::OfMatrix { function, matrix } => {
let matrix = matrix.eval_in(scope)?;
let result = function(matrix.matrix);
let translation = if result.translation == Quaternion::ZERO { Unit::NONE } else { matrix.translation };
settle_matrix_quantity(MatrixQuantity {
matrix: result,
linear: matrix.linear,
translation,
})
}
MatrixNode::BinOp { lhs, op, rhs } => matrix_binary_op(lhs.operand(scope)?, *op, rhs.operand(scope)?, pixels_per_inch),
MatrixNode::UnaryOp { expr, op } => {
let matrix = expr.eval_in(scope)?;
match op {
UnaryOp::Pos => Ok(matrix),
UnaryOp::Neg => settle_matrix(-matrix),
UnaryOp::Transpose if matrix.is_linear() => settle_matrix(matrix.transposed()),
UnaryOp::Neg => settle_matrix_quantity(matrix.negated()),
UnaryOp::Transpose if matrix.matrix.is_linear() => settle_matrix_quantity(MatrixQuantity {
matrix: matrix.matrix.transposed(),
..matrix
}),
UnaryOp::Transpose => Err(EvalError::AffineTranspose),
UnaryOp::Not | UnaryOp::Fac | UnaryOp::Magnitude => Err(EvalError::OperatorTypeError),
}
@@ -601,7 +881,7 @@ mod tests {
expr: vec![ValueNode::Lit(Literal::Float(2.))],
};
let result = call.eval(&EvalContext::new(SingleValue(5.), NothingMap)).unwrap();
assert_eq!(result, Value::from_f64(10.));
assert_eq!(result.value, Value::from_f64(10.));
}
#[test]
@@ -619,7 +899,7 @@ mod tests {
#[test]
fn $name() {
let result = $expr.eval(&EvalContext::default()).unwrap();
assert_eq!(result, $expected);
assert_eq!(result.value, $expected);
}
)*
};
+47 -3
View File
@@ -1,10 +1,11 @@
//! The roles the lexer and grammar give each stretch of source, for an editor to color and typeset an expression as it is typed.
use crate::constants::{builtin_function, suffixed_function};
use crate::documentation::{Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, matrix_literal_tooltip, range_tooltip, reducer_tooltip};
use crate::documentation::{Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, matrix_literal_tooltip, range_tooltip, reducer_tooltip, unit_tooltip};
use crate::lexer::{Constant, Lexer, Token, names_matrix, operand_ended};
use crate::parser::parse_quietly;
use crate::sort::{NameUse, name_uses};
use crate::units::unit_named;
use std::collections::HashMap;
/// What a stretch of source is, as far as its spelling and its neighbors say.
@@ -20,6 +21,8 @@ pub enum Role {
Function,
Keyword,
Operator,
/// A unit of measure, like `mm` or `%`, which a name binding no local reaches.
Unit,
/// A grouping delimiter: a parenthesis, a brace, or a magnitude bar.
Bracket,
/// A matrix literal's brackets and separators, and a range's `..`.
@@ -134,6 +137,8 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
Role::Function
} else if matches!(bare, "i" | "j" | "k") {
Role::Basis
} else if unit_named(bare).is_some() && !called {
Role::Unit
} else {
Role::Variable
}
@@ -145,6 +150,7 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
(Some(NameUse::Local | NameUse::LocalFunction), _) => None,
(_, Role::Function) => function_tooltip(bare),
(_, Role::Matrix) => (bare == "I").then(identity_tooltip),
(_, Role::Unit) => unit_named(bare).map(unit_tooltip),
_ => Constant::from_name(bare).map(constant_tooltip),
};
highlights.push(Highlight {
@@ -205,6 +211,10 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
});
}
Token::DotDot => highlights.push(plain(start, end, Role::MatrixLiteral)),
Token::Percent => highlights.push(Highlight {
tooltip: unit_named("%").map(unit_tooltip),
..plain(start, end, Role::Unit)
}),
Token::Error(_) => highlights.push(plain(start, end, Role::Error)),
_ => highlights.push(Highlight {
tooltip: operator,
@@ -428,7 +438,7 @@ mod tests {
// A matrix's name applied to an argument is its product, and a matrix literal's separators are told from a call's
assert_eq!(
read("[a, b; c] max(a, b) M(v) 1..5 \\pi θ Δx m@"),
read("[a, b; c] max(a, b) M(v) 1..5 \\pi θ Δx q@"),
[
("[", MatrixLiteral, 0, None),
("a", Variable, 0, None),
@@ -453,7 +463,7 @@ mod tests {
("\\pi", Variable, 0, None),
("θ", Variable, 0, None),
("Δx", Matrix, 0, None),
("m", Variable, 0, None),
("q", Variable, 0, None),
("@", Error, 0, None),
]
);
@@ -730,4 +740,38 @@ mod tests {
]
);
}
#[test]
fn units_are_upright_and_documented() {
let roles = |source: &str| {
highlight(source, false)
.into_iter()
.map(|highlight| (source[highlight.start..highlight.end].to_string(), highlight.role))
.collect::<Vec<_>>()
};
assert_eq!(
roles("5mm + 50% + 45° + 5'6\""),
[
("5".to_string(), Role::Number),
("mm".to_string(), Role::Unit),
("+".to_string(), Role::Operator),
("50".to_string(), Role::Number),
("%".to_string(), Role::Unit),
("+".to_string(), Role::Operator),
("45".to_string(), Role::Number),
("°".to_string(), Role::Unit),
("+".to_string(), Role::Operator),
("5".to_string(), Role::Number),
("'".to_string(), Role::Unit),
("6".to_string(), Role::Number),
("\"".to_string(), Role::Unit),
]
);
// A definition of a unit's spelling makes it a variable
assert_eq!(roles("2m where m = 3")[1].1, Role::Variable);
let tooltip = highlight("5mm", false)[1].tooltip.clone().unwrap();
assert_eq!(tooltip.label, "Millimeter");
assert_eq!(tooltip.description, "A unit of length. Also written `millimeter` or `millimeters`.");
}
}
+18 -6
View File
@@ -1,4 +1,5 @@
use crate::quaternion::Quaternion;
use crate::units::unit_named;
use crate::value::{Complex, Number};
use chumsky::input::{Input, ValueInput};
use chumsky::span::SimpleSpan;
@@ -33,7 +34,7 @@ pub enum Token<'src> {
DotDot,
Plus,
Minus,
/// Reserved for percentages, so the parser never matches it and its error points a C-style remainder to `mod(a, b)`.
/// The percent unit, which only follows the number it is a percentage of.
Percent,
Star,
Slash,
@@ -221,14 +222,16 @@ fn keyword(word: &str) -> Option<Token<'static>> {
KEYWORDS.into_iter().find_map(|(spelling, token)| (word == spelling).then_some(token))
}
/// Whether a name is a matrix's by the case rule: an uppercase-initial identifier, read after the `\` prefix.
/// Whether a name is a matrix's by the case rule: an uppercase-initial identifier, read after the `\` prefix, other than the
/// spelling of a unit like `Hz`.
#[inline]
pub fn names_matrix(name: &str) -> bool {
let name = name.strip_prefix('\\').unwrap_or(name);
match name.as_bytes().first() {
let uppercase = match name.as_bytes().first() {
Some(byte) if byte.is_ascii() => byte.is_ascii_uppercase(),
_ => name.starts_with(char::is_uppercase),
}
};
uppercase && unit_named(name).is_none()
}
/// Whether an operand has just ended after the token, given whether one had before it. A `!` leaves that as it was, since a factorial
@@ -242,9 +245,15 @@ pub(crate) fn operand_ended(token: &Token, after_operand: bool) -> bool {
}
}
/// Whether a character ends an operand: a name, a number, a closing parenthesis, brace, or bracket, or the `∞` literal.
/// Whether a character ends an operand: a name, a number, a closing parenthesis, brace, or bracket, the `∞` literal, or a
/// unit symbol that isn't a letter.
fn ends_operand(c: char) -> bool {
c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | ']' | '∞')
c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | ']' | '∞') || is_unit_symbol(c)
}
/// Whether a character is a whole unit spelled by a symbol rather than letters: degrees, feet, inches, or percent.
pub(crate) fn is_unit_symbol(c: char) -> bool {
matches!(c, '°' | '\'' | '"' | '%')
}
/// Reads every `|` in the source up front, since each depends on what precedes it: a bar opens a magnitude where an operand
@@ -539,6 +548,9 @@ impl<'a> Lexer<'a> {
// A symbol can't be a name, so unlike `inf`, no binding can shadow `∞`
'∞' => Float(f64::INFINITY),
// The units spelled by a symbol rather than letters read as names, like `deg`, `ft`, and `in`
'°' | '\'' | '"' => Ident(&self.input[start..self.pos]),
// Typeset math symbol aliases
'∧' => AndAnd,
'∨' => OrOr,
+17 -7
View File
@@ -9,11 +9,16 @@ pub mod lexer;
pub mod matrix;
pub mod object;
pub mod parser;
pub mod quantity;
pub mod quaternion;
pub mod reducer;
pub mod sort;
pub mod units;
pub mod value;
#[cfg(test)]
mod units_tests;
use context::EvalContext;
use executer::EvalError;
use object::Object;
@@ -68,7 +73,7 @@ mod tests {
#[test]
fn percent_is_not_the_remainder() {
// `%` is reserved for percentages, so a C-style remainder is a parse error naming the function that computes it
for input in ["5 % 3", "x % 2", "%", "50%"] {
for input in ["5 % 3", "x % 2", "%", "50% 2", "5 + %"] {
let error = evaluate(input).unwrap_err().to_string();
assert!(error.contains("`mod(a, b)`"), "`{input}` gave the error `{error}`");
}
@@ -90,7 +95,7 @@ mod tests {
#[test]
fn error_spans_begin_at_the_token() {
for (input, expected) in [("2 %", "at 2..3"), ("x if 1", "at 3..5")] {
for (input, expected) in [("7 % 3", "at 2..3"), ("x if 1", "at 3..5")] {
let error = evaluate(input).unwrap_err().to_string();
assert!(error.ends_with(expected), "`{input}` gave the error `{error}`");
}
@@ -120,7 +125,11 @@ mod tests {
assert_eq!(message("`abc").span(), Some(0..4));
assert_eq!(
message("7 % 3").parts(),
[Code("%".into()), Text(" is reserved for percentages, so the remainder is written ".into()), Code("mod(a, b)".into()),]
[
Code("%".into()),
Text(" makes the number before it a percentage, so the remainder is written ".into()),
Code("mod(a, b)".into()),
]
);
assert_eq!(message("7 % 3").span(), Some(2..3));
assert_eq!(message("sin(I)").parts(), [Text("A matrix stands where a value is needed".into())]);
@@ -168,10 +177,11 @@ mod tests {
let negations = format!("{}1", "-".repeat(127));
// Each matrix in a product is evaluated a level deeper than the last, with the largest frames of any chain
let product = format!("{}1", "I ".repeat(127));
let measures = format!("1mm{}", " / 2mm".repeat(42));
let nested = format!("{}1{}", "(".repeat(32), ")".repeat(32));
let bindings = (0..99).map(|n| format!("a{n} = I a{}", n + 1)).collect::<Vec<_>>().join(", ");
let bindings = format!("a0 where {bindings}, a99 = 1");
for source in [&sum, &negations, &product, &nested, &bindings] {
for source in [&sum, &negations, &product, &measures, &nested, &bindings] {
assert!(evaluate(source).is_ok(), "`{source}` should be read");
highlight::highlight(source, false);
completion::completions(source, source.len(), true);
@@ -989,8 +999,8 @@ mod tests {
// Storage is never observable, so a value compares by its four parts and a matrix by its twenty entries, with infinities matched exactly
let entries = |object: &Object| match object {
Object::Value(Value::Number(number)) => number.to_quaternion().parts().to_vec(),
Object::Matrix(matrix) => matrix.rows.iter().chain([&matrix.translation]).flat_map(|row| row.parts()).collect::<Vec<f64>>(),
Object::Value(quantity) => quantity.number().to_quaternion().parts().to_vec(),
Object::Matrix(matrix) => matrix.matrix.rows.iter().chain([&matrix.matrix.translation]).flat_map(|row| row.parts()).collect::<Vec<f64>>(),
};
assert!(actual.as_matrix().is_some() == expected.as_matrix().is_some(), "`{input}`: expected {expected}, got {actual}");
if let (Some(actual), Some(expected)) = (actual.as_matrix(), expected.as_matrix()) {
@@ -1830,7 +1840,7 @@ mod tests {
#[test]
fn smoothstep_eases_along_a_rotated_box() {
// The parameter is read in the box's own frame, so the ease follows a rotated box's axes and lands on the parameter's
let Value::Number(number) = *evaluate("smoothstep(-0.5i + 0.25j, rotation(pi/2) (0..(i + j)))").unwrap().unwrap().as_value().unwrap();
let Value::Number(number) = evaluate("smoothstep(-0.5i + 0.25j, rotation(pi/2) (0..(i + j)))").unwrap().unwrap().as_value().unwrap();
for (part, expected) in number.to_quaternion().parts().into_iter().zip([0., 0.15625, 0.5, 0.]) {
assert!((part - expected).abs() < 1e-12, "{part} against {expected}");
}
+40 -19
View File
@@ -1,20 +1,21 @@
use crate::matrix::Matrix;
use crate::quantity::{MatrixQuantity, Quantity};
use crate::value::Value;
use std::fmt;
/// What an expression evaluates to, one of the language's two sorts: a value or a matrix. The matrix is boxed so that a
/// value, the common case, stays small.
/// What an expression evaluates to, one of the language's two sorts: a value or a matrix, each with the units it is measured in.
/// The matrix is boxed so that a value, the common case, stays small.
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
Value(Value),
Matrix(Box<Matrix>),
Value(Quantity),
Matrix(Box<MatrixQuantity>),
}
/// Generates readers that see a value's parts and nothing of a matrix.
/// Generates readers that see a value's parts read as a plain number and nothing of a matrix.
macro_rules! value_readers {
($($fn_name:ident: $type:ty),* $(,)?) => {
$(
#[doc = concat!("Reads the object as [`Value::", stringify!($fn_name), "`] does, or `None` for a matrix.")]
#[doc = concat!("Reads the object as [`Value::", stringify!($fn_name), "`] does once read as a plain number, or `None` for a matrix or a value with a dimension other than an angle.")]
pub fn $fn_name(&self) -> Option<$type> {
self.as_value()?.$fn_name()
}
@@ -23,36 +24,44 @@ macro_rules! value_readers {
}
impl Object {
/// The value with its unit, or `None` for a matrix.
#[inline]
pub fn as_value(&self) -> Option<&Value> {
pub fn as_quantity(&self) -> Option<&Quantity> {
match self {
Self::Value(value) => Some(value),
Self::Value(quantity) => Some(quantity),
Self::Matrix(_) => None,
}
}
/// The value read as a plain number, as [`Quantity::as_plain`] reads it, or `None` for a matrix.
#[inline]
pub fn as_matrix(&self) -> Option<&Matrix> {
pub fn as_value(&self) -> Option<Value> {
self.as_quantity()?.as_plain()
}
/// The matrix with its units, or `None` for a value.
#[inline]
pub fn as_matrix_quantity(&self) -> Option<&MatrixQuantity> {
match self {
Self::Value(_) => None,
Self::Matrix(matrix) => Some(matrix),
}
}
/// The matrix, or `None` for a value or a matrix with units.
#[inline]
pub fn as_matrix(&self) -> Option<Matrix> {
self.as_matrix_quantity().filter(|matrix| matrix.is_plain()).map(|matrix| matrix.matrix)
}
#[inline]
pub fn into_value(self) -> Option<Value> {
match self {
Self::Value(value) => Some(value),
Self::Matrix(_) => None,
}
self.as_value()
}
#[inline]
pub fn into_matrix(self) -> Option<Matrix> {
match self {
Self::Value(_) => None,
Self::Matrix(matrix) => Some(*matrix),
}
self.as_matrix()
}
value_readers! {
@@ -74,12 +83,24 @@ impl Object {
impl<T: Into<Value>> From<T> for Object {
fn from(value: T) -> Self {
Self::Value(value.into())
Self::Value(Quantity::plain(value.into()))
}
}
impl From<Quantity> for Object {
fn from(quantity: Quantity) -> Self {
Self::Value(quantity)
}
}
impl From<Matrix> for Object {
fn from(matrix: Matrix) -> Self {
Self::Matrix(Box::new(MatrixQuantity::plain(matrix)))
}
}
impl From<MatrixQuantity> for Object {
fn from(matrix: MatrixQuantity) -> Self {
Self::Matrix(Box::new(matrix))
}
}
@@ -87,7 +108,7 @@ impl From<Matrix> for Object {
impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Value(value) => value.fmt(f),
Self::Value(quantity) => quantity.fmt(f),
Self::Matrix(matrix) => matrix.fmt(f),
}
}
+137 -4
View File
@@ -2,6 +2,7 @@ use crate::ast::{BinaryOp, Binding, CallWhere, Case, Literal, Node, Syntax, Unar
use crate::context::{FunctionProvider, NothingMap};
use crate::lexer::{LexError, Lexer, Span, Token};
use crate::sort::sorted;
use crate::units::unit_named;
use chumsky::cache::{Cache, Cached};
use chumsky::error::{EmptyErr, LabelError, RichPattern, RichReason};
use chumsky::input::ValueInput;
@@ -297,7 +298,7 @@ fn parse(src: &str) -> Result<Syntax<'_>, ParseError> {
let after_operand = e.expected().any(|pattern| matches!(pattern, RichPattern::Token(token) if **token == Token::EqEq));
match e.found() {
Some(Token::Percent) => ErrorMessage::from_prose("`%` is reserved for percentages, so the remainder is written `mod(a, b)`").at(e.span()),
Some(Token::Percent) => ErrorMessage::from_prose("`%` follows the number it makes a percentage, like `50%`, so the remainder is written `mod(a, b)`").at(e.span()),
Some(Token::If) => ErrorMessage::from_prose("`if` joins a case's value to its condition, like `{a if x > 0, b otherwise}`").at(e.span()),
Some(Token::Otherwise) => ErrorMessage::from_prose("`otherwise` ends the one case with no condition, like `{a if x > 0, b otherwise}`").at(e.span()),
Some(Token::Equals) if after_operand => ErrorMessage::from_prose("`=` names a value in a `where` clause, so equality is written `==`").at(e.span()),
@@ -368,6 +369,128 @@ where
}
/// The expression, within the names its `where` clause defines if it has one.
/// A factor of a product chain after the first, with the operator before it, whether that operator is juxtaposition, and where
/// the factor stands.
#[derive(Clone)]
struct ProductLink<'src> {
op: BinaryOp,
factor: Syntax<'src>,
implicit: bool,
span: Span,
}
/// Whether a factor is a unit by its spelling, or a power of one like `mm^2`.
fn is_unit(syntax: &Syntax) -> bool {
match syntax {
Syntax::Var(name) => unit_named(name).is_some(),
Syntax::BinOp { lhs, op: BinaryOp::Pow, .. } => is_unit(lhs),
_ => false,
}
}
/// Whether a factor spells a unit anywhere in its arithmetic, like `10mm` or `(1mm + 2mm)`, though not within a call.
fn spells_unit(syntax: &Syntax) -> bool {
match syntax {
Syntax::BinOp { lhs, rhs, .. } => is_unit(syntax) || spells_unit(lhs) || spells_unit(rhs),
Syntax::UnaryOp { expr, .. } => spells_unit(expr),
Syntax::Product { first, rest } => spells_unit(first) || rest.iter().any(|(_, factor)| spells_unit(factor)),
Syntax::Measure { .. } => true,
_ => is_unit(syntax),
}
}
/// Whether a factor is a number literal, signed or not.
fn is_number(syntax: &Syntax) -> bool {
match syntax {
Syntax::Lit(_) => true,
Syntax::UnaryOp {
op: UnaryOp::Neg | UnaryOp::Pos,
expr,
} => is_number(expr),
_ => false,
}
}
pub(crate) fn juxtaposed<'src>(lhs: Syntax<'src>, rhs: Syntax<'src>) -> Syntax<'src> {
Syntax::BinOp {
lhs: Box::new(lhs),
op: BinaryOp::Mul,
rhs: Box::new(rhs),
}
}
/// Groups the units of a product chain as they read. After a `/`, a number juxtaposed with units is a [`Syntax::Measure`], which
/// evaluation divides by as the dividend's units decide, though a percentage like `50%` is always one divisor. Feet then inches
/// like `5'6"` sum, and a factor juxtaposed after a percentage's `%` is reported, since `7 % 3` is likely a remainder.
fn group_units<'src>(first: Syntax<'src>, links: Vec<ProductLink<'src>>, mut report: impl FnMut(Span, &'static str)) -> (Syntax<'src>, Vec<(BinaryOp, Syntax<'src>)>) {
// A chain spelling no unit, the common case, has nothing to group
if !links.iter().any(|link| spells_unit(&link.factor)) {
return (first, links.into_iter().map(|link| (link.op, link.factor)).collect());
}
for pair in links.windows(2) {
if matches!(pair[0].factor, Syntax::Var("%")) && pair[1].implicit {
report(pair[0].span, "`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`");
}
}
let mut factors: Vec<(BinaryOp, Syntax<'src>, bool)> = std::iter::once((BinaryOp::Mul, first, false))
.chain(links.into_iter().map(|link| (link.op, link.factor, link.implicit)))
.collect();
// Feet then inches written together are their sum
let mut index = 0;
while index + 3 < factors.len() {
if let [(op, feet, implicit), (_, Syntax::Var("'"), true), (_, inches @ Syntax::Lit(_), true), (_, Syntax::Var("\""), true)] = &factors[index..index + 4]
&& is_number(feet)
{
// A sign before the feet applies to the whole measurement, so `-5'6"` is `-66in`
let (sign, feet) = match feet {
Syntax::UnaryOp {
op: op @ (UnaryOp::Neg | UnaryOp::Pos),
expr,
} => (Some(*op), (**expr).clone()),
feet => (None, feet.clone()),
};
let mut sum = Syntax::BinOp {
lhs: Box::new(juxtaposed(feet, Syntax::Var("'"))),
op: BinaryOp::Add,
rhs: Box::new(juxtaposed(inches.clone(), Syntax::Var("\""))),
};
if let Some(op) = sign {
sum = Syntax::UnaryOp { op, expr: Box::new(sum) };
}
let (op, implicit) = (*op, *implicit);
factors.splice(index..index + 4, [(op, sum, implicit)]);
}
index += 1;
}
// A number after a `/` and the units juxtaposed after it form a measure
let mut index = 1;
while index + 1 < factors.len() {
let numbered_divisor = factors[index].0 == BinaryOp::Div && is_number(&factors[index].1);
if numbered_divisor && factors[index + 1].2 && is_unit(&factors[index + 1].1) {
let end = (index + 1..factors.len()).find(|&end| !(factors[end].2 && is_unit(&factors[end].1))).unwrap_or(factors.len());
let mut measure = factors.drain(index..end).map(|(_, factor, _)| factor);
let number = measure.next().unwrap_or(Syntax::Lit(Literal::Integer(1)));
let units: Vec<Syntax<'src>> = measure.collect();
let divisor = if matches!(units.first(), Some(Syntax::Var("%"))) {
units.into_iter().fold(number, juxtaposed)
} else {
Syntax::Measure { number: Box::new(number), units }
};
factors.insert(index, (BinaryOp::Div, divisor, false));
}
index += 1;
}
let mut factors = factors.into_iter().map(|(op, factor, _)| (op, factor));
let first = factors.next().map_or(Syntax::Lit(Literal::Integer(1)), |(_, first)| first);
(first, factors.collect())
}
fn with_bindings<'src>((body, bindings): (Syntax<'src>, Option<Vec<Binding<'src>>>)) -> Syntax<'src> {
match bindings {
Some(bindings) => Syntax::Where { body: Box::new(body), bindings },
@@ -495,11 +618,21 @@ where
// Juxtaposed factors like `2pi` or `2sqrt(4)` multiply implicitly at the same precedence as `*` and `/`.
// The implicit operand is a `pow`, not a full unary, so `2 -3` stays a subtraction; the lexer rejects a number right after another number (`10 000` is not `10*000`).
let implicit_mul = pow.map(|rhs| (BinaryOp::Mul, rhs));
let implicit_mul = pow.map(|rhs| (BinaryOp::Mul, rhs, true));
// A `%` after a factor makes it a percentage, the factor times the percent unit
let percent = just(Token::Percent).to((BinaryOp::Mul, Syntax::Var("%"), true));
let link = choice((mul_op.then(unary.clone()).map(|(op, factor)| (op, factor, false)), percent, implicit_mul)).map_with(|(op, factor, implicit), extra| ProductLink {
op,
factor,
implicit,
span: extra.span(),
});
let product = unary
.clone()
.then(choice((mul_op.then(unary), implicit_mul)).repeated().collect::<Vec<_>>())
.map(|(first, mut rest): (Syntax<'src>, Vec<(BinaryOp, Syntax<'src>)>)| {
.then(link.repeated().collect::<Vec<_>>())
.validate(|(first, links): (Syntax<'src>, Vec<ProductLink<'src>>), _, emitter| {
let (first, mut rest) = group_units(first, links, |span, message| emitter.emit(CustomError::custom(span, message)));
// Two factors group only one way, while a longer chain is grouped by the sort pass, which knows the matrices
if rest.len() <= 1 {
return match rest.pop() {
+913
View File
@@ -0,0 +1,913 @@
//! Values and matrices with the units they are measured in, and the arithmetic that carries units through every operation and
//! builtin, so the builtins themselves only ever see plain numbers.
use crate::ast::{BinaryOp, UnaryOp};
use crate::constants::BuiltinFunction;
use crate::executer::{EvalError, UnitMismatch};
use crate::matrix::Matrix;
use crate::quaternion::Quaternion;
use crate::units::{Dimension, Size, Unit, UnitError, UnitId, common_unit};
use crate::value::{Number, Value};
use std::fmt;
/// A value with the unit it is measured in, which is [`Unit::NONE`] for a plain number.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Quantity {
pub value: Value,
pub unit: Unit,
}
impl Quantity {
#[inline(always)]
pub const fn plain(value: Value) -> Self {
Self { value, unit: Unit::NONE }
}
#[inline(always)]
pub const fn new(value: Value, unit: Unit) -> Self {
Self { value, unit }
}
#[inline(always)]
pub(crate) fn of_number(number: Number, unit: Unit) -> Self {
Self::new(Value::Number(number), unit)
}
#[inline(always)]
pub fn number(self) -> Number {
let Value::Number(number) = self.value;
number
}
#[inline(always)]
pub fn is_plain(self) -> bool {
self.unit.is_none()
}
pub fn dimension(self) -> Dimension {
self.unit.dimension()
}
/// Converts the value into `unit`, which must measure the same dimension, or is an error. A plain value converts only into no unit.
pub fn convert(self, unit: Unit, pixels_per_inch: f64) -> Result<Value, UnitError> {
let factor = self.unit.conversion(unit)?;
factor.apply(self.number(), pixels_per_inch).map(Value::Number).ok_or(UnitError::Overflow)
}
/// Reads the value in `unit` as a host field reads what was typed into it: a plain value is taken as already in `unit`, and
/// one with a unit converts from it.
pub fn read_in(self, unit: Unit, pixels_per_inch: f64) -> Result<Value, UnitError> {
if self.is_plain() {
return Ok(self.value);
}
self.convert(unit, pixels_per_inch)
}
/// Reads the value as a plain number: a dimensionless unit like `%` converts out, and an angle reads in radians, or `None` for
/// any other dimension.
pub fn as_plain(self) -> Option<Value> {
match self.dimension() {
Dimension::NONE => self.convert(Unit::NONE, 0.).ok(),
Dimension::ANGLE => self.convert(radians(), 0.).ok(),
_ => None,
}
}
/// The value with any dimensionless unit like `%` converted out, so it can stand where a plain number is needed.
pub(crate) fn plain_if_dimensionless(self) -> Self {
if self.unit.is_dimensionless() {
return self.convert(Unit::NONE, 0.).map(Self::plain).unwrap_or(self);
}
self
}
fn is_zero(self) -> bool {
self.number() == Number::Integer(0)
}
}
impl fmt::Display for Quantity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.unit.is_none() {
return self.value.fmt(f);
}
// A unit with only a denominator reads after the number's own `/`, like `5/s`
let unit = self.unit.to_string();
let unit = unit.strip_prefix("1/").map(|denominator| format!("/{denominator}")).unwrap_or(unit);
let separator = if self.unit.attaches_without_space() || unit.starts_with('/') { "" } else { " " };
// A value with several parts is grouped, so the unit applies to the whole of it
match self.number() {
Number::Complex(_) | Number::Quaternion(_) => write!(f, "({}){separator}{unit}", self.value),
_ => write!(f, "{}{separator}{unit}", self.value),
}
}
}
pub(crate) const fn radians() -> Unit {
Unit::of(UnitId::RADIAN)
}
/// Converts a number by a unit conversion factor.
fn scaled(number: Number, size: Size, pixels_per_inch: f64) -> Result<Number, EvalError> {
if size.is_one() {
return Ok(number);
}
size.apply(number, pixels_per_inch).ok_or(EvalError::UnitOverflow)
}
fn unit_error(error: UnitError, left: Unit, right: Unit, verb: &'static str) -> EvalError {
match error {
UnitError::Overflow => EvalError::UnitOverflow,
UnitError::FractionalPower => EvalError::from(UnitMismatch::FractionalUnitPower(left.to_string())),
UnitError::Incompatible if left.is_none() || right.is_none() => EvalError::from(UnitMismatch::PlainWithUnit {
verb,
unit: if left.is_none() { right } else { left }.to_string(),
}),
UnitError::Incompatible => EvalError::from(UnitMismatch::IncompatibleUnits {
verb,
left: left.to_string(),
right: right.to_string(),
}),
}
}
/// Two operands in one unit, for a sum or a comparison: the unit a sum of theirs is measured in, where a plain zero takes the
/// other's unit, as zero is the same in every unit, while any other plain number can't mix with a unit.
fn in_common_unit(lhs: Quantity, rhs: Quantity, verb: &'static str, pixels_per_inch: f64) -> Result<(Number, Number, Unit), EvalError> {
if lhs.unit == rhs.unit {
return Ok((lhs.number(), rhs.number(), lhs.unit));
}
if lhs.is_plain() && lhs.is_zero() {
return Ok((lhs.number(), rhs.number(), rhs.unit));
}
if rhs.is_plain() && rhs.is_zero() {
return Ok((lhs.number(), rhs.number(), lhs.unit));
}
if lhs.is_plain() || rhs.is_plain() {
let unit = if lhs.is_plain() { rhs.unit } else { lhs.unit };
return Err(EvalError::from(UnitMismatch::PlainWithUnit { verb, unit: unit.to_string() }));
}
if lhs.dimension() != rhs.dimension() {
return Err(unit_error(UnitError::Incompatible, lhs.unit, rhs.unit, verb));
}
let unit = common_unit(lhs.unit, rhs.unit, pixels_per_inch);
let convert = |operand: Quantity| -> Result<Number, EvalError> {
let factor = operand.unit.conversion(unit).map_err(|error| unit_error(error, operand.unit, unit, verb))?;
scaled(operand.number(), factor, pixels_per_inch)
};
Ok((convert(lhs)?, convert(rhs)?, unit))
}
/// Brings any count of operands into the unit a sum of them would be measured in, as `min`, `max`, and the statistics take them.
pub(crate) fn all_in_common_unit(operands: &[Quantity], verb: &'static str, pixels_per_inch: f64) -> Result<(Vec<Value>, Unit), EvalError> {
if operands.iter().all(|operand| operand.is_plain()) {
return Ok((operands.iter().map(|operand| operand.value).collect(), Unit::NONE));
}
// A plain zero takes whatever unit the others share
let mut common: Option<Unit> = None;
for operand in operands.iter().filter(|operand| !(operand.is_plain() && operand.is_zero())) {
common = Some(match common {
None => operand.unit,
Some(unit) if unit.is_none() != operand.is_plain() => {
let unit = if operand.is_plain() { unit } else { operand.unit };
return Err(EvalError::from(UnitMismatch::PlainWithUnit { verb, unit: unit.to_string() }));
}
Some(unit) if unit.dimension() != operand.dimension() => return Err(unit_error(UnitError::Incompatible, unit, operand.unit, verb)),
Some(unit) => common_unit(unit, operand.unit, pixels_per_inch),
});
}
let unit = common.unwrap_or(Unit::NONE);
let values = operands
.iter()
.map(|operand| into_region_unit(*operand, unit, pixels_per_inch).map(Value::Number))
.collect::<Result<Vec<Value>, EvalError>>()?;
Ok((values, unit))
}
/// A binary operation over quantities. Sums and comparisons bring both into one unit, products multiply their units, and a
/// power raises its base's unit, while logic takes only plain truth values.
#[inline]
pub(crate) fn binary_op(lhs: Quantity, op: BinaryOp, rhs: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
// Plain numbers skip the unit arithmetic, the common case
if lhs.is_plain() && rhs.is_plain() {
return plain_binary_op(lhs.number(), op, rhs.number()).map(|number| Quantity::of_number(number, Unit::NONE));
}
unit_binary_op(lhs, op, rhs, pixels_per_inch)
}
#[inline]
fn plain_binary_op(lhs: Number, op: BinaryOp, rhs: Number) -> Result<Number, EvalError> {
// Logic rejects operands that aren't truth values, while the other operators reject operand types they don't support
let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
EvalError::NotATruthValue
} else {
EvalError::OperatorTypeError
};
lhs.binary_op(op, rhs).ok_or(rejected)
}
// Out of line, keeping the plain arithmetic that dominates compact
#[inline(never)]
pub(crate) fn unit_binary_op(lhs: Quantity, op: BinaryOp, rhs: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
use BinaryOp as Op;
match op {
Op::Add | Op::Sub => {
let verb = if op == Op::Add { "added to" } else { "subtracted from" };
let (lhs, rhs, unit) = in_common_unit(lhs, rhs, verb, pixels_per_inch)?;
Ok(Quantity::of_number(plain_binary_op(lhs, op, rhs)?, unit))
}
Op::Lt | Op::Leq | Op::Gt | Op::Geq | Op::Eq | Op::Neq => {
let (lhs, rhs, _) = in_common_unit(lhs, rhs, "compared with", pixels_per_inch)?;
Ok(Quantity::of_number(plain_binary_op(lhs, op, rhs)?, Unit::NONE))
}
Op::Mul | Op::Div => {
let rhs_unit = if op == Op::Div { rhs.unit.inverse() } else { rhs.unit };
let (unit, scale) = lhs.unit.product(rhs_unit, pixels_per_inch).map_err(|error| unit_error(error, lhs.unit, rhs.unit, "multiplied by"))?;
// The left operand takes the conversion's numerator and a divisor its denominator, so `1in / 2.54cm` is exactly 1
let (numerator, denominator) = scale.split();
let (lhs, rhs) = (lhs.number(), rhs.number());
if let Some(exact) = exact_integer_product(lhs, op, rhs, scale) {
return Ok(Quantity::of_number(exact, unit));
}
let split = || -> Result<Number, EvalError> {
let lhs = scaled(lhs, numerator, pixels_per_inch)?;
if op == Op::Div {
plain_binary_op(lhs, op, scaled(rhs, denominator, pixels_per_inch)?)
} else {
scaled(plain_binary_op(lhs, op, rhs)?, denominator.inverse_exact(), pixels_per_inch)
}
};
let number = split()?;
// Near the limits of f64, scaling first or last may keep a finite result that scaling one operand overflowed
if !all_finite(number) && all_finite(lhs) && all_finite(rhs) {
let first = plain_binary_op(scaled(lhs, scale, pixels_per_inch)?, op, rhs)?;
let last = scaled(plain_binary_op(lhs, op, rhs)?, scale, pixels_per_inch)?;
let number = [first, last].into_iter().find(|number| all_finite(*number)).unwrap_or(number);
return Ok(Quantity::of_number(number, unit));
}
Ok(Quantity::of_number(number, unit))
}
Op::Pow => power(lhs, rhs),
Op::And | Op::Or => Err(EvalError::NotATruthValue),
}
}
/// A product or quotient of integers times a conversion's ratio, computed in 128 bits where it lands on an integer that fits.
fn exact_integer_product(lhs: Number, op: BinaryOp, rhs: Number, scale: Size) -> Option<Number> {
let (Number::Integer(lhs), Number::Integer(rhs)) = (lhs, rhs) else { return None };
let (numerator, denominator) = scale.rational(0.)?;
let (dividend, divisor) = match op {
BinaryOp::Mul => ((lhs as i128).checked_mul(rhs as i128)?.checked_mul(numerator)?, denominator),
_ => ((lhs as i128).checked_mul(numerator)?, (rhs as i128).checked_mul(denominator)?),
};
if divisor == 0 || dividend % divisor != 0 {
return None;
}
i64::try_from(dividend / divisor).ok().map(Number::Integer)
}
fn all_finite(number: Number) -> bool {
number.to_quaternion().parts().iter().all(|part| part.is_finite())
}
/// A power: a plain exponent raises the base's unit, which must land every unit on an integer power, while an exponent in an
/// angle unit with no plain part is the rotation `e^(i θ)`, read in radians.
fn power(base: Quantity, exponent: Quantity) -> Result<Quantity, EvalError> {
let (base, exponent) = (base.plain_if_dimensionless(), exponent.plain_if_dimensionless());
if !exponent.is_plain() {
let in_radians = exponent.convert(radians(), 0.).ok().map(|value| Quantity::plain(value).number());
return match in_radians {
Some(angle) if base.is_plain() && angle.to_quaternion().w == 0. => plain_binary_op(base.number(), BinaryOp::Pow, angle).map(|number| Quantity::of_number(number, Unit::NONE)),
Some(_) => Err(EvalError::AngleExponentWithPlainPart),
None => Err(EvalError::from(UnitMismatch::ExponentWithUnits(exponent.unit.to_string()))),
};
}
let number = plain_binary_op(base.number(), BinaryOp::Pow, exponent.number())?;
if base.is_plain() {
return Ok(Quantity::of_number(number, Unit::NONE));
}
// The exponent of a value with units must be real, and raises each unit's power
let real_exponent = exponent.number().as_real().ok_or_else(|| EvalError::from(UnitMismatch::FractionalUnitPower(base.unit.to_string())))?;
let unit = base.unit.power(real_exponent).map_err(|error| unit_error(error, base.unit, base.unit, "raised to"))?;
Ok(Quantity::of_number(number, unit))
}
/// A unary operation over a quantity: signs and the magnitude keep the unit, while the factorial and logic take plain numbers.
pub(crate) fn unary_op(operand: Quantity, op: UnaryOp) -> Result<Quantity, EvalError> {
let operand = if matches!(op, UnaryOp::Not | UnaryOp::Fac) { operand.plain_if_dimensionless() } else { operand };
let rejected = if op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError };
match op {
UnaryOp::Not if !operand.is_plain() => Err(EvalError::NotATruthValue),
UnaryOp::Fac if !operand.is_plain() => Err(EvalError::from(UnitMismatch::UnitsNotAccepted {
function: "!".to_string(),
unit: operand.unit.to_string(),
})),
_ => Ok(Quantity::of_number(operand.number().unary_op(op).ok_or(rejected)?, operand.unit)),
}
}
/// Compares a chain of quantities, all brought into one unit first.
pub(crate) fn comparison_operands(first: Quantity, rest: &[(BinaryOp, Quantity)], pixels_per_inch: f64) -> Result<(Number, Vec<(BinaryOp, Number)>), EvalError> {
if first.is_plain() && rest.iter().all(|(_, operand)| operand.is_plain()) {
return Ok((first.number(), rest.iter().map(|(op, operand)| (*op, operand.number())).collect()));
}
let operands: Vec<Quantity> = std::iter::once(first).chain(rest.iter().map(|(_, operand)| *operand)).collect();
let (values, _) = all_in_common_unit(&operands, "compared with", pixels_per_inch)?;
let numbers: Vec<Number> = values.into_iter().map(|Value::Number(number)| number).collect();
Ok((numbers[0], rest.iter().map(|(op, _)| *op).zip(numbers[1..].iter().copied()).collect()))
}
/// How a builtin taking values treats their units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnitRule {
/// Plain values only, like `ln` or `choose`.
Plain,
/// Plain values only, since the result would depend on the unit: `floor`, `ceil`, `round`, `trunc`, and `fract`.
Rounding,
/// Values of one dimension brought into one unit, with the result in it, like `min`, `abs`, `snap`, and `mean`.
Preserving,
/// Values of one dimension, with a plain result, like `sign`.
PreservingToPlain,
/// Values of one dimension, with the result in its square: `variance`.
Squared,
/// Anything, with a plain result: `count`.
Count,
/// An angle, or a plain value read as radians, with a plain result: the circular functions.
Circular,
/// Plain values with a result in radians: the inverse circular functions.
InverseCircular,
/// Coordinates of one dimension with a result in radians: `atan2`.
TwoArgumentArctangent,
/// A plain value, or an angle with no plain part read as radians: `exp`, the function of the rotation `e^(i θ)`.
Exponential,
/// The root of the given degree, which must land every unit on an integer power: `sqrt` and `cbrt`.
Root(u8),
/// A root whose degree is the plain second argument: `root`.
RootOfDegree,
/// The product of the two arguments' units: `dot` and `cross`.
Product,
/// Directions, whose units drop: `normalize` and `axis`.
Direction,
/// The angle between two directions of any units, in radians.
AngleBetween,
/// A value of any unit, which the result keeps, turned by an angle about a direction: `rotate`.
Rotate,
/// An angle about a direction, with a plain result: `rotor`.
Rotor,
/// Two endpoints of one dimension and a plain fraction between them: `lerp`.
Interpolate,
/// A value of any unit, which the result keeps, against a direction: `project`, `reject`, and `reflect`.
FirstArgument,
}
impl UnitRule {
/// The unit of the result for plain arguments, which is radians for a function giving an angle.
const fn plain_result_unit(self) -> Unit {
match self {
Self::InverseCircular | Self::TwoArgumentArctangent | Self::AngleBetween => radians(),
_ => Unit::NONE,
}
}
}
/// How a builtin taking values treats their units, or `None` for a name that is no builtin of values.
pub fn unit_rule(name: &str) -> Option<UnitRule> {
use UnitRule::*;
Some(match name {
"sin" | "cos" | "tan" | "csc" | "sec" | "cot" => Circular,
"asin" | "acos" | "atan" | "acsc" | "asec" | "acot" => InverseCircular,
"atan2" => TwoArgumentArctangent,
"sinh" | "cosh" | "tanh" | "csch" | "sech" | "coth" | "asinh" | "acosh" | "atanh" | "acsch" | "asech" | "acoth" => Plain,
"ln" | "log" | "xor" | "slerp" | "gcd" | "lcm" | "choose" | "pick" => Plain,
"exp" => Exponential,
"sqrt" => Root(2),
"cbrt" => Root(3),
"root" => RootOfDegree,
"floor" | "ceil" | "round" | "trunc" | "fract" => Rounding,
"hypot" | "abs" | "snap" | "mod" | "min" | "max" | "mean" | "median" | "mode" | "geomean" | "harmmean" | "rms" | "stdev" | "stdevpop" | "distance" | "conj" | "perp" => Preserving,
"sign" => PreservingToPlain,
"variance" | "variancepop" => Squared,
"count" => Count,
"lerp" => Interpolate,
"dot" | "cross" => Product,
"normalize" | "axis" => Direction,
"angle" => AngleBetween,
"rotate" => Rotate,
"rotor" => Rotor,
"project" | "reject" | "reflect" => FirstArgument,
_ => return None,
})
}
/// Reads an angle argument in radians, taking a plain value as radians already.
fn angle_in_radians(function: &str, argument: Quantity) -> Result<Value, EvalError> {
let argument = argument.plain_if_dimensionless();
if argument.is_plain() {
return Ok(argument.value);
}
argument.convert(radians(), 0.).map_err(|_| {
EvalError::from(UnitMismatch::AngleExpected {
function: function.to_string(),
unit: argument.unit.to_string(),
})
})
}
/// Reads an argument that must be plain, converting a dimensionless unit like `%` out.
fn plain_argument(function: &str, argument: Quantity, rule: UnitRule) -> Result<Value, EvalError> {
let argument = argument.plain_if_dimensionless();
if argument.is_plain() {
return Ok(argument.value);
}
let (function, unit) = (function.to_string(), argument.unit.to_string());
Err(if rule == UnitRule::Rounding {
EvalError::from(UnitMismatch::RoundingWithUnits { function, unit })
} else {
EvalError::from(UnitMismatch::UnitsNotAccepted { function, unit })
})
}
/// Runs a builtin taking values by its rule for units: the arguments are converted into the units it computes in and stripped,
/// so it sees plain numbers, and its result takes the unit that follows from theirs.
#[inline]
pub(crate) fn run_builtin(name: &str, rule: UnitRule, function: BuiltinFunction, arguments: &[Quantity], pixels_per_inch: f64) -> Result<Quantity, EvalError> {
// Plain arguments skip the unit rules, the common case, passing through a stack buffer when they fit
if arguments.iter().all(|argument| argument.is_plain()) {
let mut stack_values = [Value::from_i64(0); 5];
let heap_values: Vec<Value>;
let values: &[Value] = if arguments.len() <= stack_values.len() {
for (slot, argument) in stack_values.iter_mut().zip(arguments) {
*slot = argument.value;
}
&stack_values[..arguments.len()]
} else {
heap_values = arguments.iter().map(|argument| argument.value).collect();
&heap_values
};
let value = function(values).ok_or(EvalError::TypeError)?;
return Ok(Quantity::new(value, rule.plain_result_unit()));
}
run_builtin_with_units(name, rule, function, arguments, pixels_per_inch)
}
/// Runs a builtin over arguments gathered as values beside their units, which the evaluator keeps apart so plain ones need no copy.
#[inline]
pub(crate) fn run_builtin_on_parts(name: &str, rule: UnitRule, function: BuiltinFunction, values: &[Value], units: &[Unit], pixels_per_inch: f64) -> Result<Quantity, EvalError> {
if units.iter().all(|unit| unit.is_none()) {
let value = function(values).ok_or(EvalError::TypeError)?;
return Ok(Quantity::new(value, rule.plain_result_unit()));
}
let arguments: Vec<Quantity> = values.iter().zip(units).map(|(value, unit)| Quantity::new(*value, *unit)).collect();
run_builtin_with_units(name, rule, function, &arguments, pixels_per_inch)
}
#[inline(never)]
fn run_builtin_with_units(name: &str, rule: UnitRule, function: BuiltinFunction, arguments: &[Quantity], pixels_per_inch: f64) -> Result<Quantity, EvalError> {
use UnitRule::*;
let call = |values: &[Value]| function(values).ok_or(EvalError::TypeError);
let result_in = |value: Value, unit: Unit| Ok(Quantity::new(value, unit));
let plain_arguments = || arguments.iter().map(|argument| plain_argument(name, *argument, rule)).collect::<Result<Vec<Value>, EvalError>>();
match rule {
Plain | Rounding => result_in(call(&plain_arguments()?)?, Unit::NONE),
Preserving | PreservingToPlain | Squared => {
let (values, unit) = all_in_common_unit(arguments, "mixed with", pixels_per_inch)?;
let value = call(&values)?;
match rule {
Preserving => result_in(value, unit),
Squared => result_in(value, unit.power(2.).map_err(|error| unit_error(error, unit, unit, "squared"))?),
_ => result_in(value, Unit::NONE),
}
}
Count => result_in(call(&arguments.iter().map(|argument| argument.value).collect::<Vec<Value>>())?, Unit::NONE),
Circular => {
let angles = arguments.iter().map(|argument| angle_in_radians(name, *argument)).collect::<Result<Vec<Value>, EvalError>>()?;
result_in(call(&angles)?, Unit::NONE)
}
InverseCircular => result_in(call(&plain_arguments()?)?, radians()),
TwoArgumentArctangent => {
let (values, _) = all_in_common_unit(arguments, "mixed with", pixels_per_inch)?;
result_in(call(&values)?, radians())
}
Exponential => {
let [argument] = arguments else { return Err(EvalError::TypeError) };
let argument = argument.plain_if_dimensionless();
if argument.is_plain() {
return result_in(call(&[argument.value])?, Unit::NONE);
}
let angle = angle_in_radians(name, argument)?;
let Value::Number(number) = angle;
if number.to_quaternion().w != 0. {
return Err(EvalError::AngleExponentWithPlainPart);
}
result_in(call(&[angle])?, Unit::NONE)
}
Root(degree) => {
let [argument] = arguments else { return Err(EvalError::TypeError) };
let argument = argument.plain_if_dimensionless();
let unit = argument.unit.power(1. / degree as f64).map_err(|error| unit_error(error, argument.unit, argument.unit, "rooted"))?;
result_in(call(&[argument.value])?, unit)
}
RootOfDegree => {
let [argument, degree] = arguments else { return Err(EvalError::TypeError) };
let argument = argument.plain_if_dimensionless();
let degree = plain_argument(name, *degree, rule)?;
let unit = match degree.as_real() {
Some(degree) => argument.unit.power(1. / degree).map_err(|error| unit_error(error, argument.unit, argument.unit, "rooted"))?,
None if argument.is_plain() => Unit::NONE,
None => return Err(EvalError::from(UnitMismatch::FractionalUnitPower(argument.unit.to_string()))),
};
result_in(call(&[argument.value, degree])?, unit)
}
Product => {
let [a, b] = arguments else { return Err(EvalError::TypeError) };
let (unit, scale) = a.unit.product(b.unit, pixels_per_inch).map_err(|error| unit_error(error, a.unit, b.unit, "multiplied by"))?;
let Value::Number(number) = call(&[a.value, b.value])?;
Ok(Quantity::of_number(scaled(number, scale, pixels_per_inch)?, unit))
}
Direction => result_in(call(&arguments.iter().map(|argument| argument.value).collect::<Vec<Value>>())?, Unit::NONE),
AngleBetween => result_in(call(&arguments.iter().map(|argument| argument.value).collect::<Vec<Value>>())?, radians()),
Rotate => {
let [value, angle, axis @ ..] = arguments else { return Err(EvalError::TypeError) };
let mut values = vec![value.value, angle_in_radians(name, *angle)?];
values.extend(axis.iter().map(|axis| axis.value));
result_in(call(&values)?, value.unit)
}
Rotor => {
let [angle, axis @ ..] = arguments else { return Err(EvalError::TypeError) };
let mut values = vec![angle_in_radians(name, *angle)?];
values.extend(axis.iter().map(|axis| axis.value));
result_in(call(&values)?, Unit::NONE)
}
Interpolate => {
let [a, b, t] = arguments else { return Err(EvalError::TypeError) };
let (endpoints, unit) = all_in_common_unit(&[*a, *b], "mixed with", pixels_per_inch)?;
let t = plain_argument(name, *t, rule)?;
result_in(call(&[endpoints[0], endpoints[1], t])?, unit)
}
FirstArgument => {
let [value, direction] = arguments else { return Err(EvalError::TypeError) };
result_in(call(&[value.value, direction.value])?, value.unit)
}
}
}
/// A matrix with the units of its linear part and of its translation, so it maps a value in some unit to one in that unit times
/// the linear unit, plus the translation. A range from `0` to `10 mm` has both in `mm`, mapping a plain parameter to a length,
/// while a rotation is plain and leaves any unit as it was. A zero translation has no unit.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MatrixQuantity {
pub matrix: Matrix,
pub linear: Unit,
pub translation: Unit,
}
impl MatrixQuantity {
pub const fn plain(matrix: Matrix) -> Self {
Self {
matrix,
linear: Unit::NONE,
translation: Unit::NONE,
}
}
pub fn is_plain(&self) -> bool {
self.linear.is_none() && self.translation.is_none()
}
/// Builds the matrix from its linear part and its translation, dropping the unit of a zero translation.
fn from_parts(linear: Matrix, linear_unit: Unit, translation: Quantity) -> Self {
let translation_quaternion = translation.number().to_quaternion();
Self {
matrix: Matrix {
translation: translation_quaternion,
..linear
},
linear: linear_unit,
translation: if translation_quaternion == Quaternion::ZERO { Unit::NONE } else { translation.unit },
}
}
fn linear_part(&self) -> Matrix {
Matrix {
translation: Quaternion::ZERO,
..self.matrix
}
}
fn translation_part(&self) -> Quantity {
Quantity::of_number(Number::Quaternion(self.matrix.translation).canonical(), self.translation)
}
/// Multiplies the linear part's entries by a factor, as converting its unit does.
fn scaled_linear(linear: Matrix, size: Size, pixels_per_inch: f64) -> Result<Matrix, EvalError> {
if size.is_one() {
return Ok(linear);
}
let mut rows = linear.rows;
for (row, spanned) in rows.iter_mut().zip(linear.axes) {
if spanned {
*row = scaled(Number::Quaternion(*row), size, pixels_per_inch)?.to_quaternion();
}
}
Ok(Matrix { rows, ..linear })
}
/// The image of a value, `M v + c`, whose linear part is in the value's unit times the linear unit, and which the translation's unit must match.
pub(crate) fn apply(&self, value: Quantity, pixels_per_inch: f64) -> Result<Quantity, EvalError> {
if self.is_plain() && value.is_plain() {
return Ok(Quantity::of_number(Number::Quaternion(self.matrix.apply(value.number().to_quaternion())).canonical(), Unit::NONE));
}
// A plain zero is the same in every unit, so its image is the translation alone
if value.is_plain() && value.is_zero() {
return Ok(self.translation_part());
}
let linear = self.linear_part().apply(value.number().to_quaternion());
let (unit, scale) = value
.unit
.product(self.linear, pixels_per_inch)
.map_err(|error| unit_error(error, value.unit, self.linear, "multiplied by"))?;
let image = Quantity::of_number(scaled(Number::Quaternion(linear).canonical(), scale, pixels_per_inch)?, unit);
if self.matrix.translation == Quaternion::ZERO {
return Ok(image);
}
binary_op(image, BinaryOp::Add, self.translation_part(), pixels_per_inch)
}
/// The composition `A B`, applying `B` first.
pub(crate) fn compose(&self, inner: &Self, pixels_per_inch: f64) -> Result<Self, EvalError> {
if self.is_plain() && inner.is_plain() {
return Ok(Self::plain(self.matrix.compose(inner.matrix)));
}
let (linear_unit, scale) = self
.linear
.product(inner.linear, pixels_per_inch)
.map_err(|error| unit_error(error, self.linear, inner.linear, "composed with"))?;
let linear = Self::scaled_linear(self.linear_part().compose(inner.linear_part()), scale, pixels_per_inch)?;
let translation = self.apply(inner.translation_part(), pixels_per_inch)?;
Ok(Self::from_parts(linear, linear_unit, translation))
}
/// The inverse map, whose linear unit is the reciprocal and whose translation is in the translation's unit over the linear one.
pub(crate) fn inverse(&self, pixels_per_inch: f64) -> Result<Self, EvalError> {
let inverse = self.matrix.inverse().ok_or(EvalError::SingularMatrix)?;
if self.is_plain() {
return Ok(Self::plain(inverse));
}
let linear_unit = self.linear.inverse();
let translation_part = Quantity::of_number(Number::Quaternion(inverse.translation).canonical(), self.translation);
let (translation_unit, scale) = translation_part
.unit
.product(linear_unit, pixels_per_inch)
.map_err(|error| unit_error(error, self.translation, linear_unit, "divided by"))?;
let translation = Quantity::of_number(scaled(translation_part.number(), scale, pixels_per_inch)?, translation_unit);
let linear = Matrix {
translation: Quaternion::ZERO,
..inverse
};
Ok(Self::from_parts(linear, linear_unit, translation))
}
/// A whole power by repeated composition, where a negative one is of the inverse.
pub(crate) fn power(&self, exponent: i64, pixels_per_inch: f64) -> Result<Self, EvalError> {
if self.is_plain() {
return self.matrix.power(exponent).map(Self::plain).ok_or(EvalError::SingularMatrix);
}
// The zeroth power is the identity over the axes the matrix spans, as for a plain matrix
let identity = self.matrix.power(0).ok_or(EvalError::SingularMatrix)?;
let mut result = Self::plain(identity);
// By squaring, in O(log n) compositions, squaring only while bits remain
let (mut base, mut remaining) = (if exponent < 0 { self.inverse(pixels_per_inch)? } else { *self }, exponent.unsigned_abs());
while remaining > 0 {
if remaining & 1 == 1 {
result = result.compose(&base, pixels_per_inch)?;
}
remaining >>= 1;
if remaining > 0 {
base = base.compose(&base, pixels_per_inch)?;
}
}
Ok(result)
}
/// The pointwise sum or difference of two matrices, whose linear parts and translations must each match in dimension.
pub(crate) fn sum(&self, op: BinaryOp, other: &Self, pixels_per_inch: f64) -> Result<Self, EvalError> {
if self.is_plain() && other.is_plain() {
let matrix = if op == BinaryOp::Sub { self.matrix - other.matrix } else { self.matrix + other.matrix };
return Ok(Self::plain(matrix));
}
let verb = if op == BinaryOp::Sub { "subtracted from" } else { "added to" };
let linear_unit = if self.linear == other.linear {
self.linear
} else {
common_unit(self.linear, other.linear, pixels_per_inch)
};
let convert = |matrix: &Self| -> Result<Matrix, EvalError> {
let factor = matrix.linear.conversion(linear_unit).map_err(|error| unit_error(error, matrix.linear, linear_unit, verb))?;
Self::scaled_linear(matrix.linear_part(), factor, pixels_per_inch)
};
let (left, right) = (convert(self)?, convert(other)?);
let linear = if op == BinaryOp::Sub { left - right } else { left + right };
let translation = binary_op(self.translation_part(), op, other.translation_part(), pixels_per_inch)?;
Ok(Self::from_parts(linear, linear_unit, translation))
}
/// The matrix with a value attached as translation, or subtracted from it.
pub(crate) fn translated(&self, op: BinaryOp, by: Quantity, pixels_per_inch: f64) -> Result<Self, EvalError> {
let translation = binary_op(self.translation_part(), op, by, pixels_per_inch)?;
Ok(Self::from_parts(self.linear_part(), self.linear, translation))
}
pub(crate) fn negated(&self) -> Self {
Self { matrix: -self.matrix, ..*self }
}
/// The matrix's entries converted into the given linear and translation units, which must measure the same dimensions as its own.
pub(crate) fn in_units(&self, linear: Unit, translation: Unit, pixels_per_inch: f64) -> Result<Matrix, EvalError> {
let linear_factor = self.linear.conversion(linear).map_err(|error| unit_error(error, self.linear, linear, "compared with"))?;
let linear_part = Self::scaled_linear(self.linear_part(), linear_factor, pixels_per_inch)?;
let translation = into_region_unit(self.translation_part(), translation, pixels_per_inch)?.to_quaternion();
Ok(Matrix { translation, ..linear_part })
}
/// The matrix in plain numbers measured in `unit`, as a region of values in that unit: its linear part maps a plain parameter
/// to that unit, and its translation must match it.
pub(crate) fn as_region_in(&self, unit: Unit, pixels_per_inch: f64) -> Result<Matrix, EvalError> {
let linear_factor = self.linear.conversion(unit).map_err(|error| unit_error(error, self.linear, unit, "mixed with"))?;
let linear = Self::scaled_linear(self.linear_part(), linear_factor, pixels_per_inch)?;
let translation = self.translation_part();
let translation = if translation.is_zero() && translation.is_plain() {
Quaternion::ZERO
} else {
let factor = translation.unit.conversion(unit).map_err(|error| unit_error(error, translation.unit, unit, "mixed with"))?;
scaled(translation.number(), factor, pixels_per_inch)?.to_quaternion()
};
Ok(Matrix { translation, ..linear })
}
/// The unit of the values a region holds: its linear unit, or its translation's when the linear part is plain.
pub(crate) fn region_unit(&self) -> Unit {
if self.linear.is_none() { self.translation } else { self.linear }
}
}
impl fmt::Display for MatrixQuantity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.matrix.fmt(f)?;
if !self.linear.is_none() {
write!(f, " in {}", self.linear)?;
}
if !self.translation.is_none() && self.translation != self.linear {
write!(f, " translated in {}", self.translation)?;
}
Ok(())
}
}
/// The values of a matrix literal's entries brought into one unit, which becomes the matrix's linear unit.
pub(crate) fn literal_entries(entries: &[Quantity], pixels_per_inch: f64) -> Result<(Vec<Quaternion>, Unit), EvalError> {
let (values, unit) = all_in_common_unit(entries, "mixed with", pixels_per_inch)?;
Ok((values.into_iter().map(|Value::Number(number)| number.to_quaternion()).collect(), unit))
}
/// The corners of a range brought into one unit, with that unit.
pub(crate) fn range_corners(from: Quantity, to: Quantity, pixels_per_inch: f64) -> Result<(Number, Number, Unit), EvalError> {
in_common_unit(from, to, "mixed with", pixels_per_inch)
}
/// Converts a value into the unit it's measured against, where a plain zero matches any unit.
pub(crate) fn into_region_unit(value: Quantity, unit: Unit, pixels_per_inch: f64) -> Result<Number, EvalError> {
let value = if unit.is_none() { value.plain_if_dimensionless() } else { value };
if value.unit == unit || (value.is_plain() && value.is_zero()) {
return Ok(value.number());
}
if value.is_plain() || unit.is_none() {
let unit = if value.is_plain() { unit } else { value.unit };
return Err(EvalError::from(UnitMismatch::PlainWithUnit {
verb: "mixed with",
unit: unit.to_string(),
}));
}
let factor = value.unit.conversion(unit).map_err(|error| unit_error(error, value.unit, unit, "mixed with"))?;
scaled(value.number(), factor, pixels_per_inch)
}
/// The unit of a range function's result.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RegionResult {
/// The unit of the region the value is measured against: `clamp`.
FirstRegion,
/// The unit of the region the value is mapped into: `remap`.
LastRegion,
/// No unit: `within` and `smoothstep`.
Plain,
}
pub fn region_result(name: &str) -> RegionResult {
match name {
"clamp" => RegionResult::FirstRegion,
"remap" => RegionResult::LastRegion,
_ => RegionResult::Plain,
}
}
/// The unit of a value taken from a matrix.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MatrixValueUnit {
/// The translation's unit: `translation`.
Translation,
/// The linear unit to the power of the axes the matrix spans: `det`.
Determinant,
}
pub fn matrix_value_unit(name: &str) -> MatrixValueUnit {
match name {
"translation" => MatrixValueUnit::Translation,
_ => MatrixValueUnit::Determinant,
}
}
/// How a matrix builder reads its arguments' units.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuilderUnits {
/// The value's unit becomes the linear unit: `matrix` and `scale`.
Scaling,
/// An angle read in radians, about a direction of any unit: `rotation`.
Rotation,
/// Directions of any unit and a plain factor: `shear`.
Shear,
}
pub fn builder_units(name: &str) -> BuilderUnits {
match name {
"rotation" => BuilderUnits::Rotation,
"shear" => BuilderUnits::Shear,
_ => BuilderUnits::Scaling,
}
}
/// The plain arguments of a matrix builder with the linear unit of the matrix it builds.
pub(crate) fn builder_arguments(units: BuilderUnits, arguments: &[Quantity]) -> Result<(Vec<Value>, Unit), EvalError> {
match units {
BuilderUnits::Scaling => {
let [value] = arguments else { return Err(EvalError::TypeError) };
let value = value.plain_if_dimensionless();
Ok((vec![value.value], value.unit))
}
BuilderUnits::Rotation => {
let [angle, axis @ ..] = arguments else { return Err(EvalError::TypeError) };
let mut values = vec![angle_in_radians("rotation", *angle)?];
values.extend(axis.iter().map(|axis| axis.value));
Ok((values, Unit::NONE))
}
BuilderUnits::Shear => {
let [along, by, factor] = arguments else { return Err(EvalError::TypeError) };
let factor = plain_argument("shear", *factor, UnitRule::Plain)?;
Ok((vec![direction(*along)?, direction(*by)?, factor], Unit::NONE))
}
}
}
/// A direction given as a value: a plain one as it is, and one with a unit as its unit vector, since its size in that unit means nothing.
fn direction(value: Quantity) -> Result<Value, EvalError> {
let value = value.plain_if_dimensionless();
if value.is_plain() {
return Ok(value.value);
}
value.number().to_quaternion().normalized().map(Value::from).ok_or(EvalError::Indeterminate)
}
/// The unit of a value taken from a matrix by a function.
pub(crate) fn matrix_value_result_unit(unit: MatrixValueUnit, matrix: &MatrixQuantity) -> Result<Unit, EvalError> {
match unit {
MatrixValueUnit::Translation => Ok(matrix.translation),
MatrixValueUnit::Determinant => {
let spanned = matrix.matrix.axes.iter().filter(|spanned| **spanned).count();
matrix.linear.power(spanned as f64).map_err(|_| EvalError::UnitOverflow)
}
}
}
+161 -2
View File
@@ -1,11 +1,13 @@
use crate::ast::BinaryOp;
use crate::constants::{Builtin, BuiltinFunction, builtin_function};
use crate::context::{NothingMap, ValueProvider};
use crate::executer::settle_matrix;
use crate::documentation::BUILTIN_FUNCTIONS;
use crate::executer::{EvalError, settle_matrix};
use crate::lexer::{Lexer, Token};
use crate::matrix::Matrix;
use crate::object::Object;
use crate::parser::ParseError;
use crate::quantity::{self, Quantity, UnitRule, unit_rule};
use crate::value::{Number, Value};
use std::cmp::Ordering;
use std::collections::HashSet;
@@ -26,7 +28,12 @@ pub enum Reducer {
/// A single n-ary predicate asserting that every pair of items is distinct, like `a != b != c`.
ChainDistinct,
/// A single call of a variadic function over all items, like `min(a, b, c)`.
Function { function: BuiltinFunction, over_matrices: Option<MatrixFunction> },
Function {
function: BuiltinFunction,
/// The function's name, which decides how it treats the units of its items.
name: &'static str,
over_matrices: Option<MatrixFunction>,
},
}
/// The action of a variadic function across matrices: the mean is pointwise and the count counts, while the others need an
@@ -72,6 +79,7 @@ pub fn classify_reducer(source: &str, bindings: impl ValueProvider) -> Option<Re
match builtin_function(bare_name)? {
Builtin::Values { function, variadic: true } => Reducer::Function {
function,
name: BUILTIN_FUNCTIONS.iter().find(|documented| documented.name == bare_name)?.name,
over_matrices: matrix_function(bare_name),
},
_ => return None,
@@ -265,6 +273,107 @@ impl Reducer {
results.resize(items.len(), None);
results
}
/// Evaluates this reducer across items measured in units, carrying them as the written-out expression would, so `+` across lengths
/// gives a length. Gives `None` where [`Self::evaluate`] would, and an error where the units don't fit, like `gcd` across lengths.
pub fn evaluate_quantities(&self, items: &[Quantity], pixels_per_inch: f64) -> Result<Option<Quantity>, EvalError> {
// Plain items skip the unit arithmetic, the common case
if items.iter().all(|item| item.is_plain()) {
let values: Vec<Value> = items.iter().map(|item| item.value).collect();
return Ok(self.evaluate(&values).map(Quantity::plain));
}
if items.iter().any(|item| item.number().is_nan()) {
return Ok(None);
}
// Items take canonical form first, as in `evaluate_unsettled`
let items: Vec<Quantity> = items.iter().map(|item| Quantity::new(Value::Number(item.number().canonical()), item.unit)).collect();
let result = match self {
Reducer::FoldLeft(op) => {
let Some((first, rest)) = items.split_first() else {
return Ok(op.identity_element().map(Quantity::plain));
};
// A lone item meets no operator, so logic checks it is a truth value here, as `100%` is but `50%` isn't
let first = match op {
BinaryOp::And | BinaryOp::Or => {
let truth = first.plain_if_dimensionless();
if !truth.is_plain() || truth.number().as_bool().is_none() {
return Err(EvalError::NotATruthValue);
}
truth
}
_ => *first,
};
rest.iter().try_fold(first, |accumulated, item| quantity::binary_op(accumulated, *op, *item, pixels_per_inch))?
}
Reducer::FoldRight(op) => {
let Some((last, rest)) = items.split_last() else { return Ok(None) };
rest.iter().rev().try_fold(*last, |accumulated, item| quantity::binary_op(*item, *op, accumulated, pixels_per_inch))?
}
// A relation holds alike in every unit the items convert into, so they are compared as plain numbers in one
Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => {
let (values, _) = quantity::all_in_common_unit(&items, "compared with", pixels_per_inch)?;
return Ok(self.evaluate(&values).map(Quantity::plain));
}
Reducer::Function { function, name, .. } => quantity::run_builtin(name, unit_rule(name).unwrap_or(UnitRule::Plain), *function, &items, pixels_per_inch)?,
};
Ok(settle_quantity(result))
}
/// Evaluates this reducer across each leading run of the items, as [`Self::evaluate_quantities`] does for each run, though a comparison
/// brings the whole list into one unit first. Once a fold step fails, every longer run gives `None` after that first error.
pub fn evaluate_running_quantities(&self, items: &[Quantity], pixels_per_inch: f64) -> Vec<Result<Option<Quantity>, EvalError>> {
if items.iter().all(|item| item.is_plain()) {
let values: Vec<Value> = items.iter().map(|item| item.value).collect();
return self.evaluate_running(&values).into_iter().map(|result| Ok(result.map(Quantity::plain))).collect();
}
match self {
// O(n) by folding each item into the previous run's result
Reducer::FoldLeft(op) => {
let mut accumulated: Option<Quantity> = None;
let mut failed = false;
items
.iter()
.enumerate()
.map(|(index, item)| {
if failed {
return Ok(None);
}
let item = Quantity::new(Value::Number(item.number().canonical()), item.unit);
let step = match (index, accumulated) {
(0, _) => self.evaluate_quantities(&[item], pixels_per_inch),
(_, Some(previous)) if !item.number().is_nan() => quantity::binary_op(previous, *op, item, pixels_per_inch).map(settle_quantity),
_ => Ok(None),
};
accumulated = step.as_ref().ok().copied().flatten();
failed = accumulated.is_none();
step
})
.collect()
}
// O(n) by comparing the items as plain numbers in one unit
Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => match quantity::all_in_common_unit(items, "compared with", pixels_per_inch) {
Ok((values, _)) => self.evaluate_running(&values).into_iter().map(|result| Ok(result.map(Quantity::plain))).collect(),
Err(error) => std::iter::once(Err(error)).chain(std::iter::repeat_with(|| Ok(None))).take(items.len()).collect(),
},
// O(n²) since `^` groups from the right and a variadic builtin reads its whole list, so no run builds on a shorter one's result
Reducer::FoldRight(_) | Reducer::Function { .. } => (1..=items.len()).map(|count| self.evaluate_quantities(&items[..count], pixels_per_inch)).collect(),
}
}
}
/// A reduction's result in canonical form, or `None` for an indeterminate result, as [`settle`] gives for plain values.
fn settle_quantity(result: Quantity) -> Option<Quantity> {
settle(result.value).map(|value| Quantity::new(value, result.unit))
}
/// A reducer's result in canonical form, or `None` for an indeterminate result, since no operation produces NaN.
@@ -360,6 +469,7 @@ mod tests {
use crate::ast;
use crate::context::{EvalContext, NothingMap, ValueMap};
use crate::quaternion::Quaternion;
use crate::units::Unit;
use crate::value::Complex;
use std::collections::HashMap;
@@ -582,4 +692,53 @@ mod tests {
}
}
}
fn in_unit(unit: &str, values: &[f64]) -> Vec<Quantity> {
let unit = Unit::named(unit).unwrap();
values.iter().map(|&value| Quantity::new(Value::from_f64(value), unit)).collect()
}
#[test]
fn measured_items_carry_their_units() {
let reduce = |source: &str, items: &[Quantity]| classify_reducer(source, NothingMap).unwrap().evaluate_quantities(items, 96.);
let pixels = Unit::named("px").unwrap();
let total = reduce("+", &in_unit("px", &[1., 2., 3.])).unwrap().unwrap();
assert_eq!(total, Quantity::new(Value::from_i64(6), pixels));
assert_eq!(reduce("max", &in_unit("px", &[4., 9., 2.])).unwrap().unwrap(), Quantity::new(Value::from_i64(9), pixels));
assert_eq!(reduce("*", &in_unit("px", &[2., 3.])).unwrap().unwrap().unit, pixels.power(2.).unwrap());
assert_eq!(reduce("/", &in_unit("px", &[6., 3.])).unwrap().unwrap(), Quantity::plain(Value::from_i64(2)));
// Counts and relations are plain, whatever the items measure
assert_eq!(reduce("count", &in_unit("px", &[1., 2.])).unwrap().unwrap(), Quantity::plain(Value::from_i64(2)));
assert_eq!(reduce("<", &in_unit("rad", &[1., 2., 3.])).unwrap().unwrap(), Quantity::plain(Value::from_bool(true)));
assert_eq!(reduce("!=", &in_unit("rad", &[1., 2., 1.])).unwrap().unwrap(), Quantity::plain(Value::from_bool(false)));
// Items in different units of one dimension meet in a common unit, as `1in + 1px` does
let mixed = [in_unit("in", &[1.]), in_unit("px", &[1.])].concat();
assert_eq!(reduce("+", &mixed).unwrap().unwrap(), Quantity::new(Value::from_i64(97), pixels));
// A reduction that takes only plain numbers refuses measured items
assert!(reduce("gcd", &in_unit("px", &[2., 4.])).is_err());
assert!(reduce("&&", &in_unit("px", &[1.])).is_err());
assert!(reduce("^", &in_unit("px", &[2., 3.])).is_err());
assert_eq!(reduce("-", &[]).unwrap(), None);
}
#[test]
fn running_measured_results_match_each_leading_run() {
let lists = [
in_unit("px", &[3., 1., 4., 1., 5.]),
in_unit("rad", &[0.5, 2., 0., 2.]),
[in_unit("in", &[1.]), in_unit("px", &[2., 3.])].concat(),
];
for source in ["+", "-", "*", "/", "<", "==", "!=", "min", "max", "mean", "count", "gcd", "&&", "^"] {
let reducer = classify_reducer(source, NothingMap).unwrap();
for list in &lists {
let expected: Vec<Option<Quantity>> = (1..=list.len()).map(|count| reducer.evaluate_quantities(&list[..count], 96.).ok().flatten()).collect();
let running: Vec<Option<Quantity>> = reducer.evaluate_running_quantities(list, 96.).into_iter().map(|result| result.ok().flatten()).collect();
assert_eq!(running, expected, "`{source}` over {list:?}");
}
}
}
}
+88 -5
View File
@@ -1,7 +1,10 @@
use crate::ast::{BinaryOp, Binding, CallWhere, Case, Clause, Literal, Local, MatrixNode, Node, SortedCase, Syntax, UnaryOp, ValueNode};
use crate::constants::{Builtin, builtin_function, suffixed_function};
use crate::ast::{BinaryOp, Binding, BuiltinCall, CallWhere, Case, Clause, Literal, Local, MatrixNode, Measure, Node, SortedCase, Syntax, UnaryOp, ValueNode};
use crate::constants::{Builtin, SuffixedFunction, builtin_function, suffixed_function};
use crate::context::{FunctionProvider, NothingMap};
use crate::lexer::{names_matrix, offset_in};
use crate::parser::juxtaposed;
use crate::quantity::{UnitRule, builder_units, matrix_value_unit, region_result, unit_rule};
use crate::units::unit_named;
use std::borrow::Cow;
use std::fmt;
use std::ops::Range;
@@ -302,6 +305,10 @@ impl<'src> Sorter<'_, 'src> {
Syntax::Lit(literal) => Node::Value(ValueNode::Lit(literal)),
Syntax::Var(name) => self.name(name, 0),
Syntax::FnCall { name, expr } => self.call(name, expr, 0)?,
// A quotient by a measure is a product, which reads the measure by its dividend
Syntax::BinOp { lhs, op, rhs } if matches!(*rhs, Syntax::Measure { .. }) => self.sort(Syntax::Product { first: lhs, rest: vec![(op, *rhs)] })?,
// Standing alone, where only a failed product leaves one, a measure is its number times its units
Syntax::Measure { number, units } => self.sort(units.into_iter().fold(*number, juxtaposed))?,
Syntax::BinOp { lhs, op, rhs } => {
let lhs = self.sort(*lhs);
let rhs = self.sort(*rhs);
@@ -394,7 +401,10 @@ impl<'src> Sorter<'_, 'src> {
match local {
Some(local) => local,
None if names_matrix(name) => Node::Matrix(MatrixNode::Var(name.to_string())),
None => Node::Value(ValueNode::Var(name.to_string())),
None => match unit_named(name) {
Some(unit) => Node::Value(ValueNode::Unit { name: name.to_string(), unit }),
None => Node::Value(ValueNode::Var(name.to_string())),
},
}
}
@@ -508,6 +518,7 @@ impl<'src> Sorter<'_, 'src> {
Ok(match builtin {
Some(Builtin::OfMatrix(function)) => Node::Value(ValueNode::OfMatrix {
function,
unit: matrix_value_unit(bare_name),
matrix: Box::new(self.matrix(one(arguments).ok_or(invalid_arguments)?, VALUE_AS_MATRIX)?),
}),
Some(Builtin::MatrixOfMatrix(function)) => Node::Matrix(MatrixNode::OfMatrix {
@@ -520,6 +531,7 @@ impl<'src> Sorter<'_, 'src> {
}
Node::Matrix(MatrixNode::FromValues {
function,
units: builder_units(bare_name),
arguments: self.values(arguments)?,
})
}
@@ -537,10 +549,32 @@ impl<'src> Sorter<'_, 'src> {
.by_ref()
.take(region_count)
.map(|region| self.matrix(region, VALUE_AS_MATRIX))
.collect::<Result<Vec<MatrixNode>, SortError>>()?;
.collect::<Result<Box<[MatrixNode]>, SortError>>()?;
let trailing = arguments.next().map(|trailing| self.value(trailing, MATRIX_AS_VALUE).map(Box::new)).transpose()?;
Node::Value(ValueNode::OfValueAndRegions { function, value, regions, trailing })
Node::Value(ValueNode::OfValueAndRegions {
function,
result: region_result(bare_name),
value,
regions,
trailing,
})
}
Some(Builtin::Values { function, .. }) => Node::Value(ValueNode::BuiltinCall(Box::new(BuiltinCall {
name: bare_name.to_string(),
host_name: (!prefixed).then(|| bare_name.to_string()),
function,
rule: unit_rule(bare_name).unwrap_or(UnitRule::Plain),
arguments: self.values(arguments)?,
suffix: None,
}))),
None if !host_function && let Some(SuffixedFunction { name: base_name, function, argument }) = suffixed_function(bare_name) => Node::Value(ValueNode::BuiltinCall(Box::new(BuiltinCall {
name: base_name.to_string(),
host_name: (!prefixed).then(|| bare_name.to_string()),
function,
rule: unit_rule(base_name).unwrap_or(UnitRule::Plain),
arguments: self.values(arguments)?,
suffix: Some(argument),
}))),
_ => Node::Value(ValueNode::FnCall {
name: name.to_string(),
expr: self.values(arguments)?,
@@ -621,6 +655,22 @@ impl<'src> Sorter<'_, 'src> {
let mut accumulated = first;
while let Some((op, factor)) = rest.next() {
let factor = match (factor, accumulated) {
// A value's quotient by a measure is read by the value's units once evaluated
(Syntax::Measure { number, units }, Node::Value(dividend)) => {
accumulated = self.measure_quotient(dividend, *number, units)?;
continue;
}
(Syntax::Measure { number, units }, matrix) => {
accumulated = matrix;
self.measure_after_matrix(*number, units, rest)
}
(factor, value) => {
accumulated = value;
factor
}
};
accumulated = match (accumulated, self.sort(factor)?) {
(Node::Matrix(matrix), Node::Value(factor)) => {
// Dividing by a value applies the matrix to its reciprocal times the rest, so `M / v w` is `M (v⁻¹ w)`
@@ -636,6 +686,39 @@ impl<'src> Sorter<'_, 'src> {
Ok(accumulated)
}
/// The factor a matrix divides by for a measure. A matrix's units are known only once evaluated, so it's the whole measure, unless
/// a `where` definition makes one of the measure's names a variable, which then goes back to the product to multiply left to right.
#[inline(never)]
fn measure_after_matrix(&self, number: Syntax<'src>, units: Vec<Syntax<'src>>, rest: &mut std::vec::IntoIter<(BinaryOp, Syntax<'src>)>) -> Syntax<'src> {
fn name<'src>(unit: &Syntax<'src>) -> Option<&'src str> {
match unit {
Syntax::Var(name) => Some(name),
Syntax::BinOp { lhs, op: BinaryOp::Pow, .. } => name(lhs),
_ => None,
}
}
let defined = |unit: &Syntax<'src>| name(unit).is_some_and(|name| !name.starts_with('\\') && self.scopes.iter().any(|scope| scope.values.contains(&name)));
if !units.iter().any(defined) {
return units.into_iter().fold(number, juxtaposed);
}
let remaining = std::mem::take(rest);
*rest = units.into_iter().map(|unit| (BinaryOp::Mul, unit)).chain(remaining).collect::<Vec<_>>().into_iter();
number
}
/// Sorts a value's quotient by a measure, kept out of [`Self::product`], which recurses once per matrix and must keep a small frame.
#[inline(never)]
fn measure_quotient(&mut self, dividend: ValueNode, number: Syntax<'src>, units: Vec<Syntax<'src>>) -> Result<Node, SortError> {
let number = self.sort(number).and_then(|number| self.value(number, MATRIX_AS_VALUE));
let units = self.sort_each(units).into_iter().map(|unit| self.value(unit?, MATRIX_AS_VALUE)).collect::<Result<Vec<_>, _>>();
let measure = Box::new(Measure { number: number?, units: units? });
Ok(Node::Value(ValueNode::MeasureQuotient {
dividend: Box::new(dividend),
measure,
}))
}
/// A piecewise takes the sort of its cases, which must agree, under conditions that are values.
fn piecewise(&mut self, cases: Vec<Case<'src>>, otherwise: Option<Box<Syntax<'src>>>) -> Result<Node, SortError> {
let cases = cases
+791
View File
@@ -0,0 +1,791 @@
//! Units of measure: the units the language knows, the products of them a value is measured in, and the exact conversions
//! between units of one dimension.
use crate::ast::BinaryOp;
use crate::value::Number;
use std::f64::consts::PI;
use std::fmt;
/// The pixels per inch a host supplies when it gives no other, CSS's reference pixel.
pub const DEFAULT_PIXELS_PER_INCH: f64 = 96.;
/// The exponents of length, mass, time, and angle that a unit or a value measures, so a speed is `[1, 0, -1, 0]`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default, Hash)]
pub struct Dimension(pub [i16; 4]);
impl Dimension {
pub const NONE: Self = Self([0; 4]);
pub const LENGTH: Self = Self([1, 0, 0, 0]);
pub const MASS: Self = Self([0, 1, 0, 0]);
pub const TIME: Self = Self([0, 0, 1, 0]);
pub const ANGLE: Self = Self([0, 0, 0, 1]);
const AREA: Self = Self([2, 0, 0, 0]);
const VOLUME: Self = Self([3, 0, 0, 0]);
const FREQUENCY: Self = Self([0, 0, -1, 0]);
const SPEED: Self = Self([1, 0, -1, 0]);
const ACCELERATION: Self = Self([1, 0, -2, 0]);
const ANGULAR_SPEED: Self = Self([0, 0, -1, 1]);
pub fn is_none(self) -> bool {
self == Self::NONE
}
/// Whether the two share a base dimension, like an angular speed and a time, so a product of them can cancel it.
fn overlaps(self, other: Self) -> bool {
self.0.iter().zip(other.0).any(|(a, b)| *a != 0 && b != 0)
}
/// What this dimension is called, like `length` or `speed`.
pub fn noun(self) -> &'static str {
let description = self.description();
description.split_once(' ').map_or(description, |(_, noun)| noun)
}
/// What a value of this dimension is called, for error messages.
pub fn description(self) -> &'static str {
match self {
Self::NONE => "a plain number",
Self::LENGTH => "a length",
Self::AREA => "an area",
Self::VOLUME => "a volume",
Self::MASS => "a mass",
Self::TIME => "a duration",
Self::ANGLE => "an angle",
Self::FREQUENCY => "a frequency",
Self::SPEED => "a speed",
Self::ACCELERATION => "an acceleration",
Self::ANGULAR_SPEED => "an angular speed",
_ => "a compound quantity",
}
}
}
/// A size as an exact ratio of integers, times a power of π (since degrees and turns are fractions of radians' half and
/// whole turn) and a power of the inch per pixel (since a pixel is an inch over the host's pixels per inch).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Size {
numerator: i128,
denominator: i128,
pi: i8,
/// The power of the host's pixels per inch the size divides by.
pixel: i8,
}
const fn greatest_common_divisor(mut a: i128, mut b: i128) -> i128 {
a = a.abs();
b = b.abs();
while b != 0 {
let remainder = a % b;
a = b;
b = remainder;
}
a
}
impl Size {
pub(crate) const ONE: Self = Self::exact(1, 1);
const fn exact(numerator: i128, denominator: i128) -> Self {
Self {
numerator,
denominator,
pi: 0,
pixel: 0,
}
}
const fn with_pi(self, pi: i8) -> Self {
Self { pi, ..self }
}
/// The size in lowest terms with a positive denominator, or `None` for a zero denominator.
fn reduced(numerator: i128, denominator: i128, pi: i8, pixel: i8) -> Option<Self> {
if denominator == 0 {
return None;
}
let divisor = greatest_common_divisor(numerator, denominator);
let sign = denominator.signum();
Some(Self {
numerator: sign * numerator / divisor,
denominator: sign * denominator / divisor,
pi,
pixel,
})
}
fn times(self, other: Self) -> Option<Self> {
// Cross-reducing first keeps the products as small as they can be
let left = greatest_common_divisor(self.numerator, other.denominator).max(1);
let right = greatest_common_divisor(other.numerator, self.denominator).max(1);
let numerator = (self.numerator / left).checked_mul(other.numerator / right)?;
let denominator = (self.denominator / right).checked_mul(other.denominator / left)?;
Self::reduced(numerator, denominator, self.pi.checked_add(other.pi)?, self.pixel.checked_add(other.pixel)?)
}
fn inverse(self) -> Option<Self> {
Self::reduced(self.denominator, self.numerator, self.pi.checked_neg()?, self.pixel.checked_neg()?)
}
/// The reciprocal of a size that is a ratio of integers alone, which is always representable.
pub(crate) fn inverse_exact(self) -> Self {
self.inverse().unwrap_or(Self::ONE)
}
fn over(self, other: Self) -> Option<Self> {
self.times(other.inverse()?)
}
/// The size raised to an integer power, in O(|exponent|) exact multiplications.
fn power(self, exponent: i8) -> Option<Self> {
let base = if exponent < 0 { self.inverse()? } else { self };
(0..exponent.unsigned_abs()).try_fold(Self::ONE, |power, _| power.times(base))
}
pub(crate) fn is_one(self) -> bool {
self == Self::ONE
}
/// The size split into its numerator with any powers of π and the pixels per inch, and its denominator, so a product can
/// scale one operand by each before combining them, rounding no more than the conversions would on their own.
pub(crate) fn split(self) -> (Self, Self) {
(Self { denominator: 1, ..self }, Self::exact(self.denominator, 1))
}
/// The size as a ratio of integers with the pixels per inch substituted, or `None` where a power of π remains or the
/// pixels per inch is no short decimal.
pub(crate) fn rational(self, pixels_per_inch: f64) -> Option<(i128, i128)> {
if self.pi != 0 {
return None;
}
if self.pixel == 0 {
return Some((self.numerator, self.denominator));
}
// A pixel is an inch over the pixels per inch, read exactly when it has at most six decimal places
let (pixels, per) = (0..=6).find_map(|places| {
let scale = 10_i128.pow(places);
let scaled = pixels_per_inch * scale as f64;
(scaled.fract() == 0. && scaled.abs() < (1_u64 << 53) as f64 && scaled > 0.).then_some((scaled as i128, scale))
})?;
let size = self.with_pixel(0).times(Self::reduced(per, pixels, 0, 0)?.power(self.pixel)?)?;
Some((size.numerator, size.denominator))
}
const fn with_pixel(self, pixel: i8) -> Self {
Self { pixel, ..self }
}
/// Multiplies a number by the size: by the numerator, then the denominator, so an integer stays exact and a real rounds
/// once for each, then by any powers of π and the pixels per inch.
pub(crate) fn apply(self, number: Number, pixels_per_inch: f64) -> Option<Number> {
let integer = |integer: i128| i64::try_from(integer).map_or(Number::Real(integer as f64), Number::Integer);
if let Number::Integer(value) = number
&& self.pi == 0
&& self.pixel == 0
&& let Some(scaled) = (value as i128).checked_mul(self.numerator)
&& scaled % self.denominator == 0
&& let Ok(exact) = i64::try_from(scaled / self.denominator)
{
return Some(Number::Integer(exact));
}
let mut result = number;
if self.numerator != 1 {
result = result.binary_op(BinaryOp::Mul, integer(self.numerator))?.canonical();
}
if self.denominator != 1 {
result = result.binary_op(BinaryOp::Div, integer(self.denominator))?.canonical();
}
let power_of = |base: f64, exponent: i8| Number::Real(base.powi(exponent.unsigned_abs() as i32));
if self.pi != 0 {
let operation = if self.pi > 0 { BinaryOp::Mul } else { BinaryOp::Div };
result = result.binary_op(operation, power_of(PI, self.pi))?.canonical();
}
if self.pixel != 0 {
let operation = if self.pixel > 0 { BinaryOp::Div } else { BinaryOp::Mul };
result = result.binary_op(operation, power_of(pixels_per_inch, self.pixel))?.canonical();
}
Some(result)
}
}
/// One entry of the unit table.
#[derive(Debug)]
pub struct UnitDefinition {
/// The spelling results are written with.
pub symbol: &'static str,
/// The unit's name, for documentation and completions.
pub name: &'static str,
/// Every spelling naming the unit, its symbol first, then its other abbreviations and its singular and plural names.
pub spellings: &'static [&'static str],
pub dimension: Dimension,
/// The size in the coherent unit of its dimension: meters, kilograms, seconds, radians, and their products.
size: Size,
}
const fn unit(symbol: &'static str, name: &'static str, spellings: &'static [&'static str], dimension: Dimension, size: Size) -> UnitDefinition {
UnitDefinition {
symbol,
name,
spellings,
dimension,
size,
}
}
const fn ratio(numerator: i128, denominator: i128) -> Size {
Size::exact(numerator, denominator)
}
const INCH: Size = ratio(127, 5000);
const GALLON: Size = ratio(3_785_411_784, 1_000_000_000_000);
/// Every unit the language knows, related units together. The metric prefixes are spelled out per unit rather than applying to
/// any unit, since `min`, `ft`, and `cd` would otherwise also read as a milli-inch, a femto-tonne, and a centi-day.
pub const UNITS: [UnitDefinition; 54] = [
// Length
unit("px", "pixel", &["px", "pixel", "pixels"], Dimension::LENGTH, INCH.with_pixel(1)),
unit("pt", "point", &["pt", "point", "points"], Dimension::LENGTH, ratio(127, 360_000)),
unit("pc", "pica", &["pc", "pica", "picas"], Dimension::LENGTH, ratio(127, 30_000)),
unit("nm", "nanometer", &["nm", "nanometer", "nanometers"], Dimension::LENGTH, ratio(1, 1_000_000_000)),
unit(
"µm",
"micrometer",
&["µm", "μm", "um", "micrometer", "micrometers", "micron", "microns"],
Dimension::LENGTH,
ratio(1, 1_000_000),
),
unit("mm", "millimeter", &["mm", "millimeter", "millimeters"], Dimension::LENGTH, ratio(1, 1000)),
unit("cm", "centimeter", &["cm", "centimeter", "centimeters"], Dimension::LENGTH, ratio(1, 100)),
unit("m", "meter", &["m", "meter", "meters"], Dimension::LENGTH, ratio(1, 1)),
unit("km", "kilometer", &["km", "kilometer", "kilometers"], Dimension::LENGTH, ratio(1000, 1)),
unit("thou", "thou", &["thou"], Dimension::LENGTH, ratio(127, 5_000_000)),
unit("in", "inch", &["in", "\"", "inch", "inches"], Dimension::LENGTH, INCH),
unit("ft", "foot", &["ft", "'", "foot", "feet"], Dimension::LENGTH, ratio(381, 1250)),
unit("yd", "yard", &["yd", "yard", "yards"], Dimension::LENGTH, ratio(1143, 1250)),
unit("mi", "mile", &["mi", "mile", "miles"], Dimension::LENGTH, ratio(201_168, 125)),
unit("nmi", "nautical mile", &["nmi"], Dimension::LENGTH, ratio(1852, 1)),
// Area
unit("are", "are", &["are", "ares"], Dimension::AREA, ratio(100, 1)),
unit("hectare", "hectare", &["hectare", "hectares"], Dimension::AREA, ratio(10_000, 1)),
unit("acre", "acre", &["acre", "acres"], Dimension::AREA, ratio(40_468_564_224, 10_000_000)),
// Volume
unit("ml", "milliliter", &["ml", "milliliter", "milliliters"], Dimension::VOLUME, ratio(1, 1_000_000)),
unit("cl", "centiliter", &["cl", "centiliter", "centiliters"], Dimension::VOLUME, ratio(1, 100_000)),
unit("l", "liter", &["l", "liter", "liters"], Dimension::VOLUME, ratio(1, 1000)),
unit("floz", "fluid ounce", &["floz"], Dimension::VOLUME, ratio(3_785_411_784, 128_000_000_000_000)),
unit("cup", "cup", &["cup", "cups"], Dimension::VOLUME, ratio(3_785_411_784, 16_000_000_000_000)),
unit("pint", "pint", &["pint", "pints"], Dimension::VOLUME, ratio(3_785_411_784, 8_000_000_000_000)),
unit("qt", "quart", &["qt", "quart", "quarts"], Dimension::VOLUME, ratio(3_785_411_784, 4_000_000_000_000)),
unit("gal", "gallon", &["gal", "gallon", "gallons"], Dimension::VOLUME, GALLON),
// Mass
unit("µg", "microgram", &["µg", "μg", "ug", "microgram", "micrograms"], Dimension::MASS, ratio(1, 1_000_000_000)),
unit("mg", "milligram", &["mg", "milligram", "milligrams"], Dimension::MASS, ratio(1, 1_000_000)),
unit("g", "gram", &["g", "gram", "grams"], Dimension::MASS, ratio(1, 1000)),
unit("kg", "kilogram", &["kg", "kilogram", "kilograms"], Dimension::MASS, ratio(1, 1)),
unit("tonne", "tonne", &["tonne", "tonnes"], Dimension::MASS, ratio(1000, 1)),
unit("gr", "grain", &["gr", "grain", "grains"], Dimension::MASS, ratio(6_479_891, 100_000_000_000)),
unit("oz", "ounce", &["oz", "ounce", "ounces"], Dimension::MASS, ratio(28_349_523_125, 1_000_000_000_000)),
unit("lb", "pound", &["lb", "lbs", "pound", "pounds"], Dimension::MASS, ratio(45_359_237, 100_000_000)),
unit("ton", "ton", &["ton", "tons"], Dimension::MASS, ratio(90_718_474, 100_000)),
// Time
unit("ns", "nanosecond", &["ns", "nanosecond", "nanoseconds"], Dimension::TIME, ratio(1, 1_000_000_000)),
unit("µs", "microsecond", &["µs", "μs", "us", "microsecond", "microseconds"], Dimension::TIME, ratio(1, 1_000_000)),
unit("ms", "millisecond", &["ms", "millisecond", "milliseconds"], Dimension::TIME, ratio(1, 1000)),
unit("s", "second", &["s", "sec", "second", "seconds"], Dimension::TIME, ratio(1, 1)),
unit("min", "minute", &["min", "minute", "minutes"], Dimension::TIME, ratio(60, 1)),
unit("h", "hour", &["h", "hr", "hour", "hours"], Dimension::TIME, ratio(3600, 1)),
unit("day", "day", &["day", "days"], Dimension::TIME, ratio(86_400, 1)),
// Angle
unit("rad", "radian", &["rad", "radian", "radians"], Dimension::ANGLE, ratio(1, 1)),
unit("°", "degree", &["°", "deg", "degree", "degrees"], Dimension::ANGLE, ratio(1, 180).with_pi(1)),
unit("turn", "turn", &["turn", "turns"], Dimension::ANGLE, ratio(2, 1).with_pi(1)),
// Frequency
unit("Hz", "hertz", &["Hz", "hertz"], Dimension::FREQUENCY, ratio(1, 1)),
unit("kHz", "kilohertz", &["kHz", "kilohertz"], Dimension::FREQUENCY, ratio(1000, 1)),
unit("MHz", "megahertz", &["MHz", "megahertz"], Dimension::FREQUENCY, ratio(1_000_000, 1)),
unit("GHz", "gigahertz", &["GHz", "gigahertz"], Dimension::FREQUENCY, ratio(1_000_000_000, 1)),
// Angular speed
unit("rpm", "revolution per minute", &["rpm"], Dimension::ANGULAR_SPEED, ratio(1, 30).with_pi(1)),
unit("rps", "revolution per second", &["rps"], Dimension::ANGULAR_SPEED, ratio(2, 1).with_pi(1)),
// Speed
unit("mph", "mile per hour", &["mph"], Dimension::SPEED, ratio(1397, 3125)),
unit("knot", "knot", &["knot", "knots"], Dimension::SPEED, ratio(463, 900)),
// Dimensionless
unit("%", "percent", &["%", "percent"], Dimension::NONE, ratio(1, 100)),
];
/// An index into [`UNITS`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct UnitId(u8);
impl UnitId {
pub fn definition(self) -> &'static UnitDefinition {
&UNITS[self.0 as usize]
}
/// The unit whose symbol this is, found as the table is compiled, so naming a unit that isn't in it fails to build.
const fn of_symbol(symbol: &str) -> Self {
let mut index = 0;
while index < UNITS.len() {
if bytes_equal(UNITS[index].symbol.as_bytes(), symbol.as_bytes()) {
return Self(index as u8);
}
index += 1;
}
panic!("no unit has this symbol");
}
pub const RADIAN: Self = Self::of_symbol("rad");
pub const PIXEL: Self = Self::of_symbol("px");
}
const fn bytes_equal(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut index = 0;
while index < a.len() {
if a[index] != b[index] {
return false;
}
index += 1;
}
true
}
/// The unit a spelling names, like `mm` or `inches`, read after any `\` prefix.
pub fn unit_named(name: &str) -> Option<UnitId> {
let name = name.strip_prefix('\\').unwrap_or(name);
UNITS.iter().position(|unit| unit.spellings.contains(&name)).map(|index| UnitId(index as u8))
}
/// The unit each base dimension is coherently measured in, so a product of them needs no conversion factor.
fn coherent_unit(base: usize) -> UnitId {
const COHERENT: [UnitId; 4] = [UnitId::of_symbol("m"), UnitId::of_symbol("kg"), UnitId::of_symbol("s"), UnitId::RADIAN];
COHERENT[base]
}
/// A unit raised to a nonzero power within a [`Unit`], where an empty slot has unit 0 and exponent 0.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
struct Factor {
/// One more than the unit's index, so 0 marks an empty slot.
unit: u8,
exponent: i8,
}
impl Factor {
fn id(self) -> UnitId {
UnitId(self.unit - 1)
}
}
/// What a value is measured in: a product of at most four units from the table, each raised to a nonzero integer power, like
/// `km/h` or `m^2`. A value without one is plain.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub struct Unit {
/// Ordered by unit, with the empty slots last, so equal products compare equal.
factors: [Factor; 4],
}
/// Why units can't combine.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UnitError {
/// The units' sizes or powers are too far out to represent.
Overflow,
/// A power leaves a fractional exponent on a unit, like `sqrt(1mm)`.
FractionalPower,
/// The units measure different dimensions.
Incompatible,
}
impl Unit {
pub const NONE: Self = Self {
factors: [Factor { unit: 0, exponent: 0 }; 4],
};
/// The unit alone, to the first power.
pub const fn of(unit: UnitId) -> Self {
let mut result = Self::NONE;
result.factors[0] = Factor { unit: unit.0 + 1, exponent: 1 };
result
}
/// The unit a spelling names, like `mm`.
pub fn named(name: &str) -> Option<Self> {
unit_named(name).map(Self::of)
}
/// A product of units from their exponents, merging repeated units, or `None` past four distinct units or an exponent past ±127.
fn from_factors(factors: &[(UnitId, i8)]) -> Option<Self> {
let mut merged: Vec<(UnitId, i8)> = Vec::with_capacity(factors.len());
for &(unit, exponent) in factors {
match merged.iter_mut().find(|(existing, _)| *existing == unit) {
Some((_, total)) => *total = total.checked_add(exponent)?,
None => merged.push((unit, exponent)),
}
}
merged.retain(|(_, exponent)| *exponent != 0);
if merged.iter().any(|(_, exponent)| *exponent == i8::MIN) {
return None;
}
merged.sort_by_key(|(unit, _)| *unit);
if merged.len() > 4 {
return None;
}
let mut result = Self::NONE;
for (slot, (unit, exponent)) in result.factors.iter_mut().zip(merged) {
*slot = Factor { unit: unit.0 + 1, exponent };
}
Some(result)
}
fn entries(self) -> impl Iterator<Item = (UnitId, i8)> {
self.factors.into_iter().filter(|factor| factor.unit != 0).map(|factor| (factor.id(), factor.exponent))
}
#[inline(always)]
pub fn is_none(self) -> bool {
self.factors[0].unit == 0
}
/// The unit, if it is one unit to the first power, like `mm` but not `mm^2` or `km/h`.
pub fn single(self) -> Option<UnitId> {
let mut entries = self.entries();
match (entries.next(), entries.next()) {
(Some((unit, 1)), None) => Some(unit),
_ => None,
}
}
pub fn dimension(self) -> Dimension {
// Exponents stay within ±127 and a unit's dimension within ±3, so these sums can't overflow
let mut dimension = [0_i16; 4];
for (unit, exponent) in self.entries() {
for (total, base) in dimension.iter_mut().zip(unit.definition().dimension.0) {
*total += base * exponent as i16;
}
}
Dimension(dimension)
}
/// Whether the unit is a dimensionless one like `%`, which plain numbers don't add to but which folds away in products.
pub fn is_dimensionless(self) -> bool {
!self.is_none() && self.dimension().is_none()
}
/// The size of one of this unit in coherent units.
pub(crate) fn size(self) -> Option<Size> {
self.entries().try_fold(Size::ONE, |size, (unit, exponent)| size.times(unit.definition().size.power(exponent)?))
}
pub fn inverse(self) -> Self {
let mut result = self;
for factor in result.factors.iter_mut().filter(|factor| factor.unit != 0) {
factor.exponent = -factor.exponent;
}
result
}
/// The unit raised to a real power, which must leave every exponent an integer, like `0.5` on `mm^2`.
pub fn power(self, exponent: f64) -> Result<Self, UnitError> {
let factors = self
.entries()
.map(|(unit, power)| {
// A root's reciprocal exponent rounds, so a power within a hair of an integer counts as that integer
let raised = power as f64 * exponent;
let whole = raised.round();
if (raised - whole).abs() > 1e-9 {
return Err(UnitError::FractionalPower);
}
if !(-(i8::MAX as f64)..=i8::MAX as f64).contains(&whole) {
return Err(UnitError::Overflow);
}
Ok((unit, whole as i8))
})
.collect::<Result<Vec<_>, _>>()?;
Self::from_factors(&factors).ok_or(UnitError::Overflow)
}
/// The product of two units with the factor its number is multiplied by: units of one dimension merge into one, so a
/// value's units never mix (`mm in` is `mm^2`), units whose dimensions overlap expand to cancel (`rpm s` is a fraction of
/// a turn), and a dimensionless unit like `%` folds into the number beside any other unit or past its first power.
pub(crate) fn product(self, other: Self, pixels_per_inch: f64) -> Result<(Self, Size), UnitError> {
// A plain operand leaves the other's unit as it is, unless that is a percentage, which folds past its first power
let lone = match (self.is_none(), other.is_none()) {
(true, true) => return Ok((Self::NONE, Size::ONE)),
(true, false) => Some(other),
(false, true) => Some(self),
(false, false) => None,
};
if let Some(lone) = lone
&& lone.entries().all(|(unit, exponent)| exponent == 1 || !unit.definition().dimension.is_none())
{
return Ok((lone, Size::ONE));
}
let mut factors: Vec<(UnitId, i8)> = Vec::with_capacity(8);
for (unit, exponent) in self.entries().chain(other.entries()) {
match factors.iter_mut().find(|(existing, _)| *existing == unit) {
Some((_, total)) => *total = total.checked_add(exponent).ok_or(UnitError::Overflow)?,
None => factors.push((unit, exponent)),
}
}
factors.retain(|(_, exponent)| *exponent != 0);
let mut scale = Size::ONE;
loop {
// Two units of one dimension merge into the one a sum of them would be measured in
let same_dimension = pairs(factors.len()).find(|&(a, b)| factors[a].0.definition().dimension == factors[b].0.definition().dimension);
if let Some((a, b)) = same_dimension {
let (unit_a, unit_b) = (factors[a].0, factors[b].0);
let target = common_unit(Unit::of(unit_a), Unit::of(unit_b), pixels_per_inch);
let (from, into) = if target == Unit::of(unit_b) { (a, b) } else { (b, a) };
// Converting `from^e` into `into^e` multiplies by the ratio of their sizes to the `e`
let exponent = factors[from].1;
let ratio = factors[from].0.definition().size.over(factors[into].0.definition().size).ok_or(UnitError::Overflow)?;
scale = scale.times(ratio.power(exponent).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
factors[into].1 = factors[into].1.checked_add(exponent).ok_or(UnitError::Overflow)?;
factors.remove(from);
factors.retain(|(_, exponent)| *exponent != 0);
continue;
}
// Units whose dimensions overlap without matching expand into coherent units, where the shared dimension merges
let overlapping = pairs(factors.len()).find(|&(a, b)| factors[a].0.definition().dimension.overlaps(factors[b].0.definition().dimension));
if let Some((a, b)) = overlapping {
let expanded = [factors[a], factors[b]];
factors.retain(|(unit, _)| *unit != expanded[0].0 && *unit != expanded[1].0);
for (unit, exponent) in expanded {
scale = scale.times(unit.definition().size.power(exponent).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
push_coherent(&mut factors, unit.definition().dimension, exponent)?;
}
continue;
}
break;
}
// A dimensionless unit is a plain factor of the number beside any unit with a dimension, and a percentage of a percentage is one percentage
let has_dimension = factors.iter().any(|(unit, _)| !unit.definition().dimension.is_none());
for (unit, exponent) in factors.iter_mut().filter(|(unit, _)| unit.definition().dimension.is_none()) {
let folded = if has_dimension || *exponent < 0 { *exponent } else { *exponent - 1 };
scale = scale.times(unit.definition().size.power(folded).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
*exponent -= folded;
}
factors.retain(|(_, exponent)| *exponent != 0);
// Past four distinct units, everything is measured in coherent units, which take at most one per base dimension
if factors.len() > 4 {
let mut coherent = Vec::new();
for (unit, exponent) in factors {
scale = scale.times(unit.definition().size.power(exponent).ok_or(UnitError::Overflow)?).ok_or(UnitError::Overflow)?;
push_coherent(&mut coherent, unit.definition().dimension, exponent)?;
}
factors = coherent;
}
Ok((Self::from_factors(&factors).ok_or(UnitError::Overflow)?, scale))
}
/// The factor that converts a number in this unit into `target`, which must measure the same dimension.
pub(crate) fn conversion(self, target: Self) -> Result<Size, UnitError> {
if self.dimension() != target.dimension() {
return Err(UnitError::Incompatible);
}
if self == target {
return Ok(Size::ONE);
}
self.size().zip(target.size()).and_then(|(from, into)| from.over(into)).ok_or(UnitError::Overflow)
}
}
/// Every pair of distinct indices below `count`.
fn pairs(count: usize) -> impl Iterator<Item = (usize, usize)> {
(0..count).flat_map(move |a| (a + 1..count).map(move |b| (a, b)))
}
/// Adds the coherent units of a dimension raised to `exponent` to a list of factors.
fn push_coherent(factors: &mut Vec<(UnitId, i8)>, dimension: Dimension, exponent: i8) -> Result<(), UnitError> {
for (base, power) in dimension.0.into_iter().enumerate().filter(|(_, power)| *power != 0) {
let raised = i8::try_from(power * exponent as i16).ok().filter(|raised| *raised != i8::MIN).ok_or(UnitError::Overflow)?;
let unit = coherent_unit(base);
match factors.iter_mut().find(|(existing, _)| *existing == unit) {
Some((_, total)) => *total = total.checked_add(raised).ok_or(UnitError::Overflow)?,
None => factors.push((unit, raised)),
}
}
factors.retain(|(_, exponent)| *exponent != 0);
Ok(())
}
/// Whether a ratio's denominator divides a power of ten, so the ratio is a terminating decimal.
fn terminates(mut denominator: i128) -> bool {
for prime in [2, 5] {
while denominator % prime == 0 {
denominator /= prime;
}
}
denominator == 1
}
/// Which of two units of one dimension a sum of them is measured in: the one the other converts into by an integer, like
/// millimeters beside meters, or else by a terminating decimal, like meters beside feet, or else the one whose size has no
/// factor of π, like radians beside degrees, or else the left one.
pub fn common_unit(left: Unit, right: Unit, pixels_per_inch: f64) -> Unit {
if left == right {
return left;
}
let (Some(left_size), Some(right_size)) = (left.size(), right.size()) else { return left };
let Some(ratio) = left_size.over(right_size) else { return left };
// The ratio is how many of the right unit one of the left makes
match ratio.rational(pixels_per_inch) {
Some((_, 1)) => right,
Some((1, _)) => left,
Some((_, denominator)) if terminates(denominator) => right,
Some((numerator, _)) if terminates(numerator) => left,
Some(_) => left,
None if left_size.pi != 0 && right_size.pi == 0 => right,
None => left,
}
}
impl fmt::Display for Unit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let write_factor = |f: &mut fmt::Formatter<'_>, unit: UnitId, exponent: i8| {
let symbol = unit.definition().symbol;
if exponent.unsigned_abs() == 1 {
f.write_str(symbol)
} else {
write!(f, "{symbol}^{}", exponent.unsigned_abs())
}
};
let numerator: Vec<_> = self.entries().filter(|(_, exponent)| *exponent > 0).collect();
let denominator: Vec<_> = self.entries().filter(|(_, exponent)| *exponent < 0).collect();
if numerator.is_empty() && !denominator.is_empty() {
f.write_str("1")?;
}
for (index, (unit, exponent)) in numerator.iter().enumerate() {
if index > 0 {
f.write_str(" ")?;
}
write_factor(f, *unit, *exponent)?;
}
if !denominator.is_empty() {
f.write_str("/")?;
let grouped = denominator.len() > 1;
if grouped {
f.write_str("(")?;
}
for (index, (unit, exponent)) in denominator.iter().enumerate() {
if index > 0 {
f.write_str(" ")?;
}
write_factor(f, *unit, *exponent)?;
}
if grouped {
f.write_str(")")?;
}
}
Ok(())
}
}
impl Unit {
/// Whether a number is written right against this unit, like `45°` or `50%`, rather than with a space, like `5 mm`.
pub fn attaches_without_space(self) -> bool {
let first = self.entries().find(|(_, exponent)| *exponent > 0);
first.is_some_and(|(unit, _)| !unit.definition().symbol.starts_with(char::is_alphabetic))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn unit(name: &str) -> Unit {
Unit::named(name).unwrap_or_else(|| panic!("`{name}` should be a unit"))
}
#[test]
fn spellings_are_unique_and_symbols_lead() {
let mut seen = std::collections::HashSet::new();
for definition in &UNITS {
assert_eq!(definition.spellings[0], definition.symbol, "`{}` lists its symbol first", definition.name);
for spelling in definition.spellings {
assert!(seen.insert(*spelling), "`{spelling}` names two units");
}
}
}
#[test]
fn sums_take_the_unit_that_converts_exactly() {
let ppi = DEFAULT_PIXELS_PER_INCH;
assert_eq!(common_unit(unit("m"), unit("mm"), ppi), unit("mm"));
assert_eq!(common_unit(unit("mm"), unit("m"), ppi), unit("mm"));
assert_eq!(common_unit(unit("m"), unit("ft"), ppi), unit("m"));
assert_eq!(common_unit(unit("ft"), unit("m"), ppi), unit("m"));
assert_eq!(common_unit(unit("in"), unit("mm"), ppi), unit("mm"));
assert_eq!(common_unit(unit("in"), unit("px"), ppi), unit("px"));
assert_eq!(common_unit(unit("deg"), unit("rad"), ppi), unit("rad"));
assert_eq!(common_unit(unit("rad"), unit("deg"), ppi), unit("rad"));
assert_eq!(common_unit(unit("turn"), unit("deg"), ppi), unit("deg"));
assert_eq!(common_unit(unit("px"), unit("mm"), ppi), unit("px"));
assert_eq!(common_unit(unit("mm"), unit("px"), ppi), unit("mm"));
}
#[test]
fn products_merge_units_of_one_dimension() {
let ppi = DEFAULT_PIXELS_PER_INCH;
let (product, scale) = unit("mm").product(unit("in"), ppi).unwrap();
assert_eq!(product, unit("mm").power(2.).unwrap());
assert_eq!(scale.apply(Number::Integer(1), ppi), Some(Number::Real(25.4)));
let (quotient, scale) = unit("m").product(unit("mm").inverse(), ppi).unwrap();
assert_eq!(quotient, Unit::NONE);
assert_eq!(scale.apply(Number::Integer(1), ppi), Some(Number::Integer(1000)));
// An angular speed over a duration expands so the time cancels
let (angle, _) = unit("rpm").product(unit("s"), ppi).unwrap();
assert_eq!(angle.dimension(), Dimension::ANGLE);
// A percentage folds into the number beside a length, and stays once beside a plain number
let (length, scale) = unit("%").product(unit("mm"), ppi).unwrap();
assert_eq!(length, unit("mm"));
assert_eq!(scale.apply(Number::Integer(50), ppi).and_then(Number::as_real), Some(0.5));
let (percent, scale) = unit("%").product(unit("%"), ppi).unwrap();
assert_eq!(percent, unit("%"));
assert_eq!(scale.apply(Number::Integer(2500), ppi).and_then(Number::as_real), Some(25.));
}
#[test]
fn conversions_are_exact_ratios() {
let ppi = DEFAULT_PIXELS_PER_INCH;
let convert = |value: i64, from: &str, into: &str| unit(from).conversion(unit(into)).unwrap().apply(Number::Integer(value), ppi).unwrap().canonical();
assert_eq!(convert(3, "ft", "in"), Number::Integer(36));
assert_eq!(convert(1, "in", "px"), Number::Integer(96));
assert_eq!(convert(72, "pt", "in"), Number::Integer(1));
assert_eq!(convert(1, "turn", "deg"), Number::Integer(360));
assert_eq!(convert(1, "h", "s"), Number::Integer(3600));
assert_eq!(convert(254, "mm", "in").as_real(), Some(10.));
assert!(unit("mm").conversion(unit("s")).is_err());
}
#[test]
fn units_display_as_written() {
assert_eq!(unit("km").product(unit("h").inverse(), 96.).unwrap().0.to_string(), "km/h");
assert_eq!(unit("m").product(unit("s").power(-2.).unwrap(), 96.).unwrap().0.to_string(), "m/s^2");
assert_eq!(unit("s").inverse().to_string(), "1/s");
assert_eq!(unit("deg").to_string(), "°");
assert!(unit("deg").attaches_without_space());
assert!(!unit("mm").attaches_without_space());
}
}
+392
View File
@@ -0,0 +1,392 @@
use crate::ast::Node;
use crate::context::{EvalContext, NothingMap, ValueProvider};
use crate::object::Object;
use crate::quantity::Quantity;
use crate::units::{Dimension, Unit};
use crate::value::Value;
const EPSILON: f64 = 1e-9;
fn evaluate_with(source: &str, pixels_per_inch: f64) -> Result<Object, String> {
let node = Node::try_parse_from_str(source).map_err(|error| error.to_string())?;
node.eval(&EvalContext::new(NothingMap, NothingMap).with_pixels_per_inch(pixels_per_inch))
.map_err(|error| error.to_string())
}
fn quantity(source: &str) -> Quantity {
match evaluate_with(source, 96.) {
Ok(Object::Value(quantity)) => quantity,
result => panic!("`{source}` should be a value, not {result:?}"),
}
}
fn shown(source: &str) -> String {
quantity(source).to_string()
}
fn error(source: &str) -> String {
match evaluate_with(source, 96.) {
Err(error) => error,
Ok(result) => panic!("`{source}` should fail, not give {result}"),
}
}
fn unit(name: &str) -> Unit {
Unit::named(name).unwrap_or_else(|| panic!("`{name}` should name a unit"))
}
/// The value read in the given unit.
fn read(source: &str, unit_name: &str) -> f64 {
let quantity = quantity(source);
quantity
.convert(unit(unit_name), 96.)
.unwrap_or_else(|error| panic!("`{source}` should convert to `{unit_name}`: {error:?}"))
.as_real()
.unwrap()
}
fn assert_close(actual: f64, expected: f64, source: &str) {
assert!((actual - expected).abs() <= EPSILON * expected.abs().max(1.), "`{source}` gave {actual}, expected {expected}");
}
#[test]
fn a_number_before_a_unit_measures_in_it() {
assert_eq!(shown("5mm"), "5 mm");
assert_eq!(shown("5 mm"), "5 mm");
assert_eq!(shown("2.5 inches"), "2.5 in");
assert_eq!(shown("3 feet"), "3 ft");
assert_eq!(shown("90 degrees"), "90°");
assert_eq!(shown("45deg"), "45°");
assert_eq!(shown("45°"), "45°");
assert_eq!(shown("50%"), "50%");
assert_eq!(shown("12.5 %"), "12.5%");
assert_eq!(shown("5Hz"), "5 Hz");
assert_eq!(shown("2 kHz"), "2 kHz");
assert_eq!(shown("1000um"), "1000 µm");
assert_eq!(shown("1000µm"), "1000 µm");
assert_eq!(shown("9.8m/s^2"), "9.8 m/s^2");
assert_eq!(shown("-5mm"), "-5 mm");
}
#[test]
fn sums_take_the_unit_that_converts_exactly() {
assert_eq!(shown("5m + 3m"), "8 m");
assert_eq!(shown("5ft + 3ft"), "8 ft");
assert_eq!(shown("1m + 1mm"), "1001 mm");
assert_eq!(shown("1ft + 1in"), "13 in");
assert_eq!(shown("90deg + 0.25turn"), "180°");
assert_eq!(shown("1in + 1px"), "97 px");
assert_close(read("5m + 3ft", "m"), 5.9144, "5m + 3ft");
assert_eq!(quantity("5m + 3ft").unit, unit("m"));
assert_close(read("1in + 1mm", "mm"), 26.4, "1in + 1mm");
assert_eq!(quantity("1in + 1mm").unit, unit("mm"));
// Radians are coherent, so a mix with them keeps them
assert_eq!(quantity("asin(0.5) + 30deg").unit, unit("rad"));
assert_close(read("asin(0.5) + 30deg", "rad"), std::f64::consts::PI / 3., "asin(0.5) + 30deg");
}
#[test]
fn a_plain_number_only_adds_to_a_unit_when_it_is_zero() {
assert!(error("1in + 5").contains("A plain number can't be added to a value in `in`"));
assert!(error("5 - 1in").contains("A plain number can't be subtracted from a value in `in`"));
assert!(error("1 + 50%").contains("plain number"));
assert!(error("asin(0.5) + 1").contains("A plain number can't be added to a value in `rad`"));
assert_eq!(shown("0 + 5mm"), "5 mm");
assert_eq!(shown("5mm - 0"), "5 mm");
assert_eq!(read("max(0, 3mm - 5mm)", "mm"), 0.);
assert_eq!(evaluate_with("0 < 1mm", 96.).unwrap().as_bool(), Some(true));
}
#[test]
fn different_dimensions_never_mix() {
assert!(error("1mm + 1s").contains("measure different things"));
assert!(error("1mm < 1s").contains("measure different things"));
assert!(error("max(1mm, 1kg)").contains("measure different things"));
assert!(error("1mm == 1s").contains("measure different things"));
}
#[test]
fn a_number_and_unit_after_a_value_with_a_unit_is_the_divisor() {
assert_eq!(quantity("10mm/2mm").value, Value::from_i64(5));
assert!(quantity("10mm/2mm").is_plain());
assert_eq!(shown("100km/2h"), "50 km/h");
assert_eq!(shown("10mm / 2 mm"), "5");
assert_eq!(shown("1in/2.54cm"), "1");
assert_eq!(quantity("10mm/2mm^2").unit, unit("mm").inverse());
assert_eq!(shown("3mm * 2 / 4mm"), "1.5");
// The dividend's value decides, however its name is spelled
assert_eq!(shown("a / 2mm where a = 10mm"), "5");
assert_eq!(shown("x / 2mm where x = 3"), "1.5 mm");
// Without a unit in the dividend, a unit after the number applies to the whole quotient
assert_eq!(shown("3/4in"), "0.75 in");
assert_close(read("pi/2 rad", "rad"), std::f64::consts::FRAC_PI_2, "pi/2 rad");
assert_close(quantity("1/2pi").value.as_real().unwrap(), std::f64::consts::FRAC_PI_2, "1/2pi");
assert_eq!(shown("50% / 2mm"), "0.25 mm");
// A name defined as a variable is no unit, so it multiplies left to right like any other factor
assert_eq!(shown("s/2m where s = 12, m = 3"), "18");
assert_eq!(shown("a/2m where a = 12mm, m = 3"), "18 mm");
let node = Node::try_parse_from_str("10mm / 2m").unwrap();
let host = crate::context::ValueMap([("m".to_string(), Value::from_i64(3))].into_iter().collect());
assert_eq!(node.eval(&EvalContext::new(host, NothingMap)).unwrap().to_string(), "15 mm");
// Only juxtaposition joins the divisor
assert_eq!(shown("10mm/2*mm"), "5 mm^2");
// A matrix's units are known only once evaluated, so it divides by the whole measure, unless one of its names is a variable
assert_eq!(shown("(0mm..10mm) / 2mm"), "5");
assert_eq!(shown("(0..12) / 2m where m = 3"), "18");
}
#[test]
fn feet_then_inches_sum() {
assert_eq!(shown("5'6\""), "66 in");
assert_eq!(shown("5'"), "5 ft");
assert_eq!(shown("6\""), "6 in");
}
#[test]
fn percentages_scale_and_stay_percentages_beside_plain_numbers() {
assert_eq!(shown("50% + 10%"), "60%");
assert_eq!(shown("50% / 2"), "25%");
assert_eq!(shown("2 * 50%"), "100%");
assert_eq!(shown("50% * 50%"), "25%");
assert_eq!(shown("50% * 10mm"), "5 mm");
assert_eq!(quantity("100 / (50%)").value, Value::from_i64(200));
assert_eq!(quantity("x / 50% where x = 3").value, Value::from_i64(6));
assert_eq!(quantity("50% / 25%").value, Value::from_i64(2));
assert_eq!(evaluate_with("50%", 96.).unwrap().as_real(), Some(0.5));
assert!(evaluate_with("7 % 3", 96.).is_err());
}
#[test]
fn products_merge_units_of_one_dimension() {
assert_eq!(shown("3mm * 2mm"), "6 mm^2");
assert_eq!(quantity("3mm * 2in").unit, unit("mm").power(2.).unwrap());
assert_close(quantity("3mm * 2in").value.as_real().unwrap(), 152.4, "3mm * 2in");
}
#[test]
fn powers_and_roots_raise_units() {
assert_eq!(shown("(2mm)^2"), "4 mm^2");
assert_eq!(shown("sqrt(9mm^2)"), "3 mm");
assert_eq!(shown("cbrt(8mm^3)"), "2 mm");
assert_eq!(shown("root(16mm^4, 4)"), "2 mm");
assert_eq!(shown("(4mm^2)^0.5"), "2 mm");
assert_eq!(shown("(2mm)^0"), "1");
assert!(error("sqrt(1mm)").contains("fractional exponent"));
assert!(error("2^(1mm)").contains("An exponent can't be in `mm`"));
}
#[test]
fn circular_functions_take_angles_or_radians() {
assert_close(quantity("sin(30deg)").value.as_real().unwrap(), 0.5, "sin(30deg)");
assert_close(quantity("sin(pi/6)").value.as_real().unwrap(), 0.5, "sin(pi/6)");
assert_close(quantity("cos(0.5turn)").value.as_real().unwrap(), -1., "cos(0.5turn)");
assert!(error("sin(1mm)").contains("`sin` takes an angle or a plain number"));
// The inverse functions give angles in radians, which the circular functions read back
assert_eq!(quantity("asin(1)").unit, unit("rad"));
assert_close(read("asin(1)", "deg"), 90., "asin(1)");
assert_close(quantity("sin(asin(0.5))").value.as_real().unwrap(), 0.5, "sin(asin(0.5))");
assert_close(read("atan2(1, 1)", "deg"), 45., "atan2(1, 1)");
assert_close(quantity("atan2(1, 1) / turn + 0.5").value.as_real().unwrap(), 0.625, "atan2(1, 1) / turn + 0.5");
assert!(error("atan2(1, 1) / (2pi) + 0.5").contains("A plain number can't be added to a value in `rad`"));
assert_eq!(quantity("atan2(3mm, 4mm)").unit, unit("rad"));
assert_close(read("atan2(3mm, 4cm)", "rad"), (3_f64).atan2(40.), "atan2(3mm, 4cm)");
assert_eq!(quantity("angle(i, j)").unit, unit("rad"));
assert_close(read("angle(1mm i, 1mm j)", "deg"), 90., "angle(1mm i, 1mm j)");
// Dividing by `rad` reads an angle as plain radians
assert_close(quantity("asin(1)/rad + 1").value.as_real().unwrap(), std::f64::consts::FRAC_PI_2 + 1., "asin(1)/rad + 1");
// An exponent with no plain part rotates, read in radians
let rotation = quantity("e^(i 90deg)").number().to_quaternion();
assert!(rotation.w.abs() < EPSILON && (rotation.x - 1.).abs() < EPSILON);
assert!(evaluate_with("e^(2 + i 90deg)", 96.).is_err());
assert!(evaluate_with("exp(i 90deg)", 96.).is_ok());
}
#[test]
fn rounding_takes_plain_numbers_and_snap_rounds_in_a_unit() {
assert!(error("floor(1.5mm)").contains("snap(x, 1 mm)"));
assert!(error("round(2.5in)").contains("snap(x, 1 in)"));
assert_eq!(shown("snap(13mm, 5mm)"), "15 mm");
assert_eq!(shown("mod(13mm, 5mm)"), "3 mm");
assert_eq!(shown("floor(150%)"), "1");
}
#[test]
fn builtins_carry_units_by_their_rules() {
assert_eq!(shown("max(1mm, 1in)"), "25.4 mm");
assert_eq!(shown("min(1cm, 1mm)"), "1 mm");
assert_eq!(shown("abs(-3mm)"), "3 mm");
assert_eq!(shown("sign(-3mm)"), "-1");
assert_eq!(shown("hypot(3mm, 4mm)"), "5 mm");
assert_eq!(shown("mean(1mm, 3mm)"), "2 mm");
assert_eq!(quantity("variance(1mm, 3mm)").unit, unit("mm").power(2.).unwrap());
assert_eq!(shown("lerp(0mm, 10mm, 50%)"), "5 mm");
assert_eq!(shown("count(1mm, 2s)"), "2");
assert_eq!(shown("|3mm i + 4mm j|"), "5 mm");
assert!(quantity("normalize(3mm i + 4mm j)").is_plain());
assert_eq!(shown("dot(1mm i, 2mm i)"), "2 mm^2");
assert_eq!(quantity("distance(1mm i, 4mm i)").unit, unit("mm"));
let rotated = quantity("rotate(1mm i, 90deg)");
assert_eq!(rotated.unit, unit("mm"));
assert!((rotated.number().to_quaternion().y - 1.).abs() < EPSILON);
assert!(error("ln(2mm)").contains("`ln` takes plain numbers"));
assert!(error("5mm!").contains("`!` takes plain numbers"));
assert!(evaluate_with("1mm && 1", 96.).is_err());
}
#[test]
fn angles_and_cycles_divide_out_explicitly() {
assert_eq!(quantity("720deg / turn").value, Value::from_i64(2));
assert_eq!(quantity("720deg / deg").value, Value::from_i64(720));
assert_close(quantity("720deg / rad").value.as_real().unwrap(), 4. * std::f64::consts::PI, "720deg / rad");
assert_eq!(quantity("60rpm / turn").dimension(), quantity("1Hz").dimension());
assert_close(read("60rpm / turn", "Hz"), 1., "60rpm / turn");
assert_close(read("1rpm * 1s", "turn"), 1. / 60., "1rpm * 1s");
assert_eq!(quantity("1Hz * 1min").value, Value::from_i64(60));
assert_eq!(quantity("2px * 3deg").dimension(), Dimension([1, 0, 0, 1]));
}
#[test]
fn pixels_are_sized_by_the_pixels_per_inch() {
assert_eq!(read("1in", "px"), 96.);
assert_close(read("10mm", "px"), 10. / 25.4 * 96., "10mm");
assert_eq!(read("72pt", "px"), 96.);
let at_300 = match evaluate_with("1in", 300.).unwrap() {
Object::Value(quantity) => quantity.convert(unit("px"), 300.).unwrap().as_real().unwrap(),
_ => unreachable!(),
};
assert_eq!(at_300, 300.);
assert_eq!(shown("1in + 1px"), "97 px");
}
#[test]
fn a_field_reads_a_plain_result_in_its_own_unit() {
let px = unit("px");
assert_eq!(quantity("5").read_in(px, 96.).unwrap().as_real(), Some(5.));
assert_eq!(quantity("1in").read_in(px, 96.).unwrap().as_real(), Some(96.));
assert!(quantity("1s").read_in(px, 96.).is_err());
}
#[test]
fn hosts_read_angles_as_radians_and_lengths_not_at_all() {
assert_close(evaluate_with("90deg", 96.).unwrap().as_real().unwrap(), std::f64::consts::FRAC_PI_2, "90deg");
assert_eq!(evaluate_with("5mm", 96.).unwrap().as_real(), None);
assert_eq!(evaluate_with("5", 96.).unwrap().as_real(), Some(5.));
}
struct Bindings;
impl ValueProvider for Bindings {
fn get_value(&self, name: &str) -> Option<Value> {
(name == "m").then(|| Value::from_i64(3))
}
fn get_quantity(&self, name: &str) -> Option<Quantity> {
match name {
"x" => Some(Quantity::new(Value::from_i64(10), Unit::named("px")?)),
_ => self.get_value(name).map(Quantity::plain),
}
}
}
#[test]
fn bindings_shadow_units_and_carry_their_own() {
let evaluate = |source: &str| Node::try_parse_from_str(source).unwrap().eval(&EvalContext::new(Bindings, NothingMap)).unwrap();
assert_eq!(evaluate("2m").as_real(), Some(6.));
assert_eq!(evaluate("2\\m").as_quantity().unwrap().unit, unit("m"));
assert_eq!(evaluate("x + 1in").to_string(), "106 px");
assert_eq!(evaluate("x * 2").to_string(), "20 px");
assert_eq!(evaluate("a where a = 5mm").to_string(), "5 mm");
assert_eq!(evaluate("f(2mm) where f(t) = t * 2").to_string(), "4 mm");
assert_eq!(evaluate("{1mm if 1 > 0, 2mm otherwise}").to_string(), "1 mm");
}
#[test]
fn ranges_and_matrices_carry_units() {
assert_eq!(shown("clamp(15mm, 0..10mm)"), "10 mm");
assert_close(read("clamp(5mm, 0..1cm)", "mm"), 5., "clamp(5mm, 0..1cm)");
assert_eq!(shown("remap(5mm, 0..10mm, 0..1)"), "0.5");
assert_eq!(shown("remap(0.5, 0..1, 0..10mm)"), "5 mm");
assert_eq!(evaluate_with("within(5mm, 0..1cm)", 96.).unwrap().as_bool(), Some(true));
assert_eq!(shown("(0..10mm) 0.5"), "5 mm");
assert_eq!(shown("(0..10mm)^-1 (5mm)"), "0.5");
assert_eq!(shown("(I + 5mm i) (1mm i)"), "(6i) mm");
assert_eq!(quantity("det(0..(2mm i + 3mm j))").unit, unit("mm").power(2.).unwrap());
assert!(error("clamp(5, 0..10mm)").contains("plain number"));
let rotated = quantity("rotation(90deg) (1mm i)");
assert_eq!(rotated.unit, unit("mm"));
assert!((rotated.number().to_quaternion().y - 1.).abs() < EPSILON);
}
#[test]
fn exponents_stay_in_range() {
assert_eq!(quantity("1 / (1m^-127)").unit, unit("m").power(127.).unwrap());
assert!(evaluate_with("1m^-128", 96.).is_err());
assert!(evaluate_with("1m^200", 96.).is_err());
assert_eq!(shown("root(1m^49, 49)"), "1 m");
}
#[test]
fn exact_conversions_survive_large_operands() {
assert_eq!(quantity("2540000000000000127mm / in").value, Value::from_i64(100_000_000_000_000_005));
assert_close(quantity("1e308m / (1e308cm)").value.as_real().unwrap(), 100., "1e308m / (1e308cm)");
assert_close(read("50% * (1e308mm)", "mm"), 5e307, "50% * (1e308mm)");
}
#[test]
fn matrices_with_units_apply_compose_and_compare() {
assert_eq!(shown("(1mm I + 1) 0"), "1");
assert_eq!(shown("((1mm..2mm)^1) 0.5"), "1.5 mm");
assert_eq!(evaluate_with("within(i, (0..10mm)^0)", 96.).unwrap().as_bool(), Some(false));
assert_eq!(evaluate_with("[1m] != [2m] != [1001mm]", 96.).unwrap().as_bool(), Some(true));
assert_eq!(evaluate_with("[1m] == [1000mm]", 96.).unwrap().as_bool(), Some(true));
assert_eq!(shown("shear(1m i, 1m j, 1) j"), shown("shear(100cm i, 100cm j, 1) j"));
assert_eq!(shown("scale(50%) 1"), shown("scale(0.5) 1"));
}
#[test]
fn a_sign_before_feet_and_inches_applies_to_both() {
assert_eq!(shown("-5'6\""), "-66 in");
assert_eq!(shown("1ft - 5'6\""), "-54 in");
}
#[test]
fn equal_ranges_in_different_units_compare_equal() {
assert_eq!(evaluate_with("(0..1cm) == (0..10mm)", 96.).unwrap().as_bool(), Some(true));
assert_eq!(evaluate_with("(0..1in) != (0..1cm) != (0..10mm)", 96.).unwrap().as_bool(), Some(false));
// A part outside a range's axes passes through untouched
assert_eq!(quantity("((0..1in) (0..1cm)) (0.5 + 2j)").number().to_quaternion().y, 2.);
}
#[test]
fn percentages_stand_for_their_fraction_where_plain_numbers_go() {
assert_eq!(shown("clamp(150%, 0..1)"), "1");
assert_eq!(shown("remap(50%, 0..1, 0..10mm)"), "5 mm");
assert_eq!(evaluate_with("within(50%, 0..1)", 96.).unwrap().as_bool(), Some(true));
assert_eq!(quantity("100 / 50%").value, Value::from_i64(200));
}
#[test]
fn inches_convert_to_pixels_exactly_at_any_whole_resolution() {
for pixels_per_inch in 1..=4000 {
let pixels_per_inch = pixels_per_inch as f64;
let pixels = match evaluate_with("1in", pixels_per_inch).unwrap() {
Object::Value(quantity) => quantity.convert(unit("px"), pixels_per_inch).unwrap().as_real().unwrap(),
_ => unreachable!(),
};
assert_eq!(pixels, pixels_per_inch);
}
}
#[test]
fn plain_matrices_are_named_plainly_in_errors() {
assert!(error("I + (0..10mm)").contains("A plain number can't be added to a value in `mm`"));
}
+123 -4
View File
@@ -6,6 +6,7 @@ use core_types::color::SRGBA8;
use core_types::list::{Item, List, NodeIdPath};
use core_types::transfer_curve::TransferCurve;
use core_types::transform::Footprint;
use core_types::units::{Angle, AngleUnit, DEFAULT_PIXELS_PER_INCH, Length, LengthUnit, TypedAngle, TypedLength};
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
pub use dyn_any::StaticType;
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
@@ -83,6 +84,11 @@ macro_rules! tagged_value {
BoxCorners(Vec<f64>),
/// Stored compactly as a `Vec<DVec2>` of control points, materializes as an `Item<TransferCurve>` at runtime via `to_dynany`/`to_any`.
TransferCurve(Vec<DVec2>),
/// A length in the unit it was typed in, materializing as an `Item<Length>` in pixels. A physical unit needs the document's resolution,
/// so the preprocessor replaces it with a conversion node reading that from the scope.
Length(TypedLength),
/// An angle in the unit it was typed in, materializing as an `Item<Angle>`.
Angle(TypedAngle),
/// Stored as the `GradientRamp` exchange struct (nested `{ stops: { color, position?, midpoint? } }`), materializing as an `Item<Gradient>` at runtime. Aliases recover legacy on-disk shapes.
/// (Old documents stored flat stops, a tuple list, or the ancient full `Gradient` struct under the legacy `"Gradient"` tag, all routed by `deserialize_tagged_value_with_legacy_migration`.)
#[serde(alias = "Gradient", alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
@@ -132,6 +138,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => lengths.cache_hash(state),
Self::BoxCorners(values) => values.cache_hash(state),
Self::TransferCurve(points) => points.cache_hash(state),
Self::Length(length) => length.cache_hash(state),
Self::Angle(angle) => angle.cache_hash(state),
Self::GradientRamp(ramp) => ramp.cache_hash(state),
Self::Strokes(strokes) => strokes.cache_hash(state),
Self::BrushCache(cache) => cache.cache_hash(state),
@@ -189,6 +197,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => Box::new(Item::new_from_element(DashPattern::from(lengths))),
Self::BoxCorners(values) => Box::new(Item::new_from_element(BoxCorners::from(values))),
Self::TransferCurve(points) => Box::new(Item::new_from_element(TransferCurve::from(points))),
Self::Length(length) => Box::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
Self::Angle(angle) => Box::new(Item::new_from_element(angle.to_angle())),
Self::GradientRamp(ramp) => Box::new(Item::<Gradient>::from(ramp)),
Self::Strokes(strokes) => {
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
@@ -249,6 +259,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => Arc::new(Item::new_from_element(DashPattern::from(lengths))),
Self::BoxCorners(values) => Arc::new(Item::new_from_element(BoxCorners::from(values))),
Self::TransferCurve(points) => Arc::new(Item::new_from_element(TransferCurve::from(points))),
Self::Length(length) => Arc::new(Item::new_from_element(length.to_length(DEFAULT_PIXELS_PER_INCH))),
Self::Angle(angle) => Arc::new(Item::new_from_element(angle.to_angle())),
Self::GradientRamp(ramp) => Arc::new(Item::<Gradient>::from(ramp)),
Self::Strokes(strokes) => {
let list: List<Stroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
@@ -284,6 +296,8 @@ macro_rules! tagged_value {
Self::DashPattern(_) => item!(DashPattern),
Self::BoxCorners(_) => item!(BoxCorners),
Self::TransferCurve(_) => item!(TransferCurve),
Self::Length(_) => item!(Length),
Self::Angle(_) => item!(Angle),
Self::GradientRamp(_) => item!(Gradient),
Self::Strokes(_) => list!(Stroke),
Self::BrushCache(_) => item!(BrushCache),
@@ -325,6 +339,10 @@ macro_rules! tagged_value {
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast::<Item<BoxCorners>>().unwrap().into_element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<TransferCurve>() => Ok(TaggedValue::TransferCurve(input.downcast::<TransferCurve>().unwrap().points().to_vec())),
x if x == TypeId::of::<Item<TransferCurve>>() => Ok(TaggedValue::TransferCurve(input.downcast::<Item<TransferCurve>>().unwrap().into_element().points().to_vec())),
x if x == TypeId::of::<Length>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Length>().unwrap().pixels()))),
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast::<Item<Length>>().unwrap().into_element().pixels()))),
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Angle>().unwrap().degrees()))),
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast::<Item<Angle>>().unwrap().into_element().degrees()))),
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(*input.downcast::<Gradient>().unwrap()))),
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(&*input.downcast::<Item<Gradient>>().unwrap()))),
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast::<List<Stroke>>().unwrap().into_iter().map(Item::into_element).collect())),
@@ -361,6 +379,10 @@ macro_rules! tagged_value {
x if x == TypeId::of::<Item<BoxCorners>>() => Ok(TaggedValue::BoxCorners(input.downcast_ref::<Item<BoxCorners>>().unwrap().element().0.iter_element_values().copied().collect())),
x if x == TypeId::of::<TransferCurve>() => Ok(TaggedValue::TransferCurve(input.downcast_ref::<TransferCurve>().unwrap().points().to_vec())),
x if x == TypeId::of::<Item<TransferCurve>>() => Ok(TaggedValue::TransferCurve(input.downcast_ref::<Item<TransferCurve>>().unwrap().element().points().to_vec())),
x if x == TypeId::of::<Length>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Length>().unwrap().pixels()))),
x if x == TypeId::of::<Item<Length>>() => Ok(TaggedValue::Length(TypedLength::pixels(input.downcast_ref::<Item<Length>>().unwrap().element().pixels()))),
x if x == TypeId::of::<Angle>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Angle>().unwrap().degrees()))),
x if x == TypeId::of::<Item<Angle>>() => Ok(TaggedValue::Angle(TypedAngle::degrees(input.downcast_ref::<Item<Angle>>().unwrap().element().degrees()))),
x if x == TypeId::of::<Gradient>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Gradient>().unwrap()))),
x if x == TypeId::of::<Item<Gradient>>() => Ok(TaggedValue::GradientRamp(GradientRamp::from(input.downcast_ref::<Item<Gradient>>().unwrap()))),
x if x == TypeId::of::<List<Stroke>>() => Ok(TaggedValue::Strokes(input.downcast_ref::<List<Stroke>>().unwrap().iter_element_values().cloned().collect())),
@@ -392,6 +414,8 @@ macro_rules! tagged_value {
if name == std::any::type_name::<DashPattern>() { return Some(TaggedValue::DashPattern(Vec::new())) }
if name == std::any::type_name::<BoxCorners>() { return Some(TaggedValue::BoxCorners(Vec::new())) }
if name == std::any::type_name::<TransferCurve>() { return Some(TaggedValue::TransferCurve(TransferCurve::default().points().to_vec())) }
if name == std::any::type_name::<Length>() { return Some(TaggedValue::Length(TypedLength::default())) }
if name == std::any::type_name::<Angle>() { return Some(TaggedValue::Angle(TypedAngle::default())) }
$( if name == std::any::type_name::<$ty>() { return Some(TaggedValue::$identifier(Default::default())) } )*
if name == std::any::type_name::<List<Stroke>>() { return Some(TaggedValue::Strokes(Vec::new())) }
if name == std::any::type_name::<BrushCache>() { return Some(TaggedValue::BrushCache(Default::default())) }
@@ -442,6 +466,8 @@ macro_rules! tagged_value {
Self::DashPattern(lengths) => format!("DashPattern({lengths:?})"),
Self::BoxCorners(values) => format!("BoxCorners({values:?})"),
Self::TransferCurve(points) => format!("TransferCurve({points:?})"),
Self::Length(length) => format!("Length({} {})", length.value, length.unit.symbol()),
Self::Angle(angle) => format!("Angle({} {})", angle.value, angle.unit.symbol()),
Self::GradientRamp(ramp) => format!("GradientRamp({ramp:?})"),
Self::Strokes(strokes) => format!("Strokes({strokes:?})"),
Self::BrushCache(cache) => format!("{cache:?}"),
@@ -540,6 +566,11 @@ tagged_value! {
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
GlowTechnique(graphic_types::GlowTechnique),
GlowSource(graphic_types::GlowSource),
MaskMode(graphic_types::MaskMode),
BevelStyle(graphic_types::BevelStyle),
BevelDirection(graphic_types::BevelDirection),
BevelTechnique(graphic_types::BevelTechnique),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
@@ -569,6 +600,8 @@ tagged_value! {
TextAlign(text_nodes::TextAlign),
TextDenomination(text_nodes::TextDenomination),
ScaleType(core_types::transform::ScaleType),
LengthUnit(LengthUnit),
AngleUnit(AngleUnit),
// Legacy
PaintOrder(vector::style::PaintOrder), // TODO: Eventually remove this document upgrade code
#[serde(alias = "Fill")]
@@ -578,6 +611,48 @@ tagged_value! {
}
impl TaggedValue {
/// A length input's value in pixels, whether stored as a typed length or as a plain number of pixels.
pub fn as_length_pixels(&self, pixels_per_inch: f64) -> Option<f64> {
match self {
Self::Length(length) => Some(length.to_length(pixels_per_inch).pixels()),
Self::Number(pixels) => Some(*pixels),
_ => None,
}
}
/// A length in pixels as a value for a length input, kept in the unit `self` was typed in, like a dragged radius that stays in millimeters.
pub fn length_in_same_unit(&self, pixels: f64, pixels_per_inch: f64) -> Self {
let unit = match self {
Self::Length(length) => length.unit,
_ => LengthUnit::Pixel,
};
Self::Length(TypedLength {
value: LengthUnit::Pixel.convert(pixels, unit, pixels_per_inch),
unit,
})
}
/// An angle input's value in degrees, whether stored as a typed angle or as a plain number of degrees.
pub fn as_angle_degrees(&self) -> Option<f64> {
match self {
Self::Angle(angle) => Some(angle.to_angle().degrees()),
Self::Number(degrees) => Some(*degrees),
_ => None,
}
}
/// An angle in degrees as a value for an angle input, kept in the unit `self` was typed in.
pub fn angle_in_same_unit(&self, degrees: f64) -> Self {
let unit = match self {
Self::Angle(angle) => angle.unit,
_ => AngleUnit::Degree,
};
Self::Angle(TypedAngle {
value: unit.from_angle(Angle::from_degrees(degrees)),
unit,
})
}
pub fn to_primitive_string(&self) -> String {
match self {
TaggedValue::None => "()".to_string(),
@@ -690,6 +765,46 @@ impl TaggedValue {
})
}
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
let mut choices = input.split("::");
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
if first == "StrokeAlign" {
return Some(match second {
"Center" => vector::style::StrokeAlign::Center,
"Inside" => vector::style::StrokeAlign::Inside,
"Outside" => vector::style::StrokeAlign::Outside,
_ => {
log::error!("Invalid StrokeAlign default type variant: {input}");
return None;
}
});
}
log::error!("Invalid StrokeAlign default type: {input}");
None
}
fn to_blend_mode(input: &str) -> Option<core_types::blending::BlendMode> {
use core_types::blending::BlendMode;
let Some(("BlendMode", variant)) = input.split_once("::").map(|(first, second)| (first.trim(), second.trim())) else {
log::error!("Invalid BlendMode default type: {input}");
return None;
};
// The variants hidden from the standard list are valid defaults too
let blend_mode = BlendMode::list()
.into_iter()
.flatten()
.chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha])
.find(|blend_mode| format!("{blend_mode:?}") == variant)
.copied();
if blend_mode.is_none() {
log::error!("Invalid BlendMode default type variant: {input}");
}
blend_mode
}
match ty {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
@@ -709,9 +824,16 @@ impl TaggedValue {
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
_ => return None,
() if ty == TypeId::of::<Length>() => to_number(string).map(|pixels| TaggedValue::Length(TypedLength::pixels(pixels)))?,
() if ty == TypeId::of::<Angle>() => to_number(string).map(|degrees| TaggedValue::Angle(TypedAngle::degrees(degrees)))?,
_ => {
log::error!("No parser for a default value of type `{}`: {string}", concrete_type.name);
return None;
}
};
Some(ty)
}
@@ -924,8 +1046,6 @@ pub enum RenderOutputType {
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
image_data: Vec<(u64, CanvasImage)>,
},
/// A PDF document's file contents.
Pdf { data: Vec<u8> },
#[cfg(target_family = "wasm")]
CanvasFrame { canvas_id: u64, resolution: DVec2 },
}
@@ -944,7 +1064,6 @@ impl CacheHash for RenderOutputType {
svg.cache_hash(state);
image_data.cache_hash(state);
}
Self::Pdf { data } => data.cache_hash(state),
#[cfg(target_family = "wasm")]
Self::CanvasFrame { canvas_id, resolution } => {
canvas_id.cache_hash(state);
+1 -10
View File
@@ -602,10 +602,6 @@ pub enum GraphErrorType {
NonConstantInput {
index: usize,
},
/// The input's value refers to a resource the document can't resolve to its data.
MissingResource {
index: usize,
},
}
impl Debug for GraphErrorType {
// TODO: format with the document graph context so the input index is the same as in the graph UI.
@@ -654,11 +650,6 @@ impl Debug for GraphErrorType {
"Warning: an upstream node adapts to the visible canvas area, so this node's output changes when the view is panned or zoomed"
),
GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1),
GraphErrorType::MissingResource { index } => write!(
f,
"Warning: input {} needs a font, image, or other resource that can't be found, so a fallback is used in its place",
index + 1
),
}
}
}
@@ -1129,7 +1120,7 @@ mod test {
// If this assert fails: These NodeIds seem to be changing when you modify TaggedValue, just update them.
assert_eq!(
ids,
vec![NodeId(7074930193456627328), NodeId(651950451264872860), NodeId(15983493604836528424), NodeId(2458326405488235061)]
vec![NodeId(7958315323958235311), NodeId(7951824047151403135), NodeId(16894780098949252642), NodeId(8854475046694858618)]
);
}
+29 -28
View File
@@ -1,6 +1,5 @@
use crate::TokioSpawner;
use graph_craft::document::value::{DAffine2, DVec2, RenderOutputType, TaggedValue, UVec2};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::core_types::ops::ConvertAsync;
use graphene_std::core_types::transform::Footprint;
@@ -9,7 +8,7 @@ use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::{no_paths, paths_from_item_attributes};
use graphene_std::{NodeError, Poll};
use image::ImageFormat;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::error::Error;
use std::io::Cursor;
use std::path::{Path, PathBuf};
@@ -18,7 +17,6 @@ use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileType {
Svg,
Pdf,
Png,
Jpg,
Webp,
@@ -30,7 +28,7 @@ pub enum FileType {
}
impl FileType {
/// The image format of a file type encoded from a single image, which excludes SVG, PDF, and GIF.
/// The image format of a file type encoded from a single image, which excludes SVG and GIF.
fn raster_format(self) -> Option<ImageFormat> {
match self {
FileType::Png => Some(ImageFormat::Png),
@@ -40,7 +38,7 @@ impl FileType {
FileType::Bmp => Some(ImageFormat::Bmp),
FileType::Tga => Some(ImageFormat::Tga),
FileType::Ico => Some(ImageFormat::Ico),
FileType::Svg | FileType::Pdf | FileType::Gif => None,
FileType::Svg | FileType::Gif => None,
}
}
}
@@ -48,7 +46,6 @@ impl FileType {
pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
match path.extension().and_then(|s| s.to_str()) {
Some("svg") => Ok(FileType::Svg),
Some("pdf") => Ok(FileType::Pdf),
Some("png") => Ok(FileType::Png),
Some("jpg" | "jpeg") => Ok(FileType::Jpg),
Some("webp") => Ok(FileType::Webp),
@@ -57,14 +54,13 @@ pub fn detect_file_type(path: &Path) -> Result<FileType, String> {
Some("tga") => Ok(FileType::Tga),
Some("ico") => Ok(FileType::Ico),
Some("gif") => Ok(FileType::Gif),
_ => Err("Unsupported file extension. Supported formats: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
_ => Err("Unsupported file extension. Supported formats: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif".to_string()),
}
}
/// One rendered frame of the document, as SVG text, a PDF document, or 8-bit RGBA pixels with straight alpha.
/// One rendered frame of the document, as SVG text or as 8-bit RGBA pixels with straight alpha.
pub enum RenderedFrame {
Svg(String),
Pdf(Vec<u8>),
Raster { data: Vec<u8>, width: u32, height: u32 },
}
@@ -91,12 +87,12 @@ pub struct Framing {
impl ExportSettings {
/// Frame the artwork as it is at time zero, unless a size was given.
/// Every frame of an animation shares this framing, so they all have one size.
pub async fn framed(mut self, executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
pub async fn framed(mut self, executor: &DynamicExecutor, output: &OutputHandle, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Self, Box<dyn Error>> {
if self.size.0.is_some() && self.size.1.is_some() {
return Ok(self);
}
let [min, max] = artwork_bounds(executor, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
let [min, max] = artwork_bounds(executor, output, runtime, spawner).await?.ok_or("The document has no artwork to export")?;
let resolution = ((max - min) * self.scale).round().max(DVec2::ONE).as_uvec2();
self.framing = Some(Framing {
transform: DAffine2::from_translation(min).inverse(),
@@ -108,7 +104,7 @@ impl ExportSettings {
/// The document-space bounds of every layer including its stroke, artboards included, from the metadata of an SVG render.
/// Content an artboard clips away still counts, since this has no layer tree to tell which artboard holds it.
async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
async fn artwork_bounds(executor: &DynamicExecutor, output: &OutputHandle, runtime: &AsyncRuntime, spawner: &TokioSpawner) -> Result<Option<[DVec2; 2]>, Box<dyn Error>> {
// An identity viewport, since the default one is degenerate and its transforms come out NaN
let render_config = RenderConfig {
viewport: Footprint {
@@ -121,7 +117,7 @@ async fn artwork_bounds(executor: &DynamicExecutor, runtime: &AsyncRuntime, spaw
for_export: true,
..Default::default()
};
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, runtime, spawner, render_config).await? else {
let TaggedValue::RenderOutput(output) = execute_until_settled(executor, output, runtime, spawner, render_config).await? else {
return Err("The document did not render".into());
};
@@ -156,6 +152,7 @@ fn combine_bounds([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DV
/// Renders the document at the given animation time, as SVG text for an SVG export and as pixels for every other file type.
pub(crate) async fn render_frame(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
settings: ExportSettings,
animation_time: Duration,
@@ -168,11 +165,7 @@ pub(crate) async fn render_frame(
size: (width, height),
..
} = settings;
let export_format = match file_type {
FileType::Svg => ExportFormat::Svg,
FileType::Pdf => ExportFormat::Pdf { artboards_as_pages: false },
_ => ExportFormat::Raster,
};
let export_format = if file_type == FileType::Svg { ExportFormat::Svg } else { ExportFormat::Raster };
// Create render config with export settings and the animation time
let mut render_config = RenderConfig {
@@ -194,10 +187,9 @@ pub(crate) async fn render_frame(
}
// Execute the graph and extract its output
match execute_until_settled(executor, runtime, spawner, render_config).await? {
match execute_until_settled(executor, output, runtime, spawner, render_config).await? {
TaggedValue::RenderOutput(output) => match output.data {
RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)),
RenderOutputType::Pdf { data } => Ok(RenderedFrame::Pdf(data)),
RenderOutputType::Texture(texture) => {
// Convert GPU texture to CPU buffer
let gpu_raster = Raster::<GPU>::new_gpu(texture);
@@ -207,7 +199,7 @@ pub(crate) async fn render_frame(
}
RenderOutputType::Buffer { data, width, height } => Ok(RenderedFrame::Raster { data, width, height }),
#[cfg(target_family = "wasm")]
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture or Buffer for raster export, Svg for SVG export, or Pdf for PDF export.").into()),
other => Err(format!("Unexpected render output type: {other:?}. Expected Texture, Buffer for raster export or Svg for SVG export.").into()),
},
other => Err(format!("Expected RenderOutput, got: {other:?}").into()),
}
@@ -217,7 +209,6 @@ pub(crate) async fn render_frame(
fn write_frame(path: &Path, settings: ExportSettings, frame: RenderedFrame) -> Result<(), Box<dyn Error>> {
let contents = match frame {
RenderedFrame::Svg(svg) => svg.into_bytes(),
RenderedFrame::Pdf(pdf) => pdf,
RenderedFrame::Raster { data, width, height } => encode_raster(settings.file_type, data, width, height, settings.transparent)?,
};
std::fs::write(path, contents)?;
@@ -272,13 +263,14 @@ fn encode_raster(file_type: FileType, data: Vec<u8>, width: u32, height: u32, tr
pub async fn export_document(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
output_path: PathBuf,
settings: ExportSettings,
runtime: &AsyncRuntime,
spawner: &TokioSpawner,
) -> Result<(), Box<dyn Error>> {
let frame = render_frame(executor, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?;
let frame = render_frame(executor, output, wgpu_executor, settings, Duration::ZERO, runtime, spawner).await?;
write_frame(&output_path, settings, frame)?;
log::info!("Exported to: {}", output_path.display());
@@ -314,8 +306,10 @@ impl AnimationParams {
}
/// Export an animated GIF by rendering multiple frames at different animation times
#[allow(clippy::too_many_arguments)]
pub async fn export_gif(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
output_path: PathBuf,
settings: ExportSettings,
@@ -343,7 +337,7 @@ pub async fn export_gif(
log::debug!("Rendering frame {}/{} at time {:?}", frame_idx + 1, animation.frames, animation_time);
let RenderedFrame::Raster { data, width, height } = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await? else {
let RenderedFrame::Raster { data, width, height } = render_frame(executor, output, wgpu_executor, settings, animation_time, runtime, spawner).await? else {
return Err("A GIF frame must render as pixels".into());
};
@@ -364,8 +358,10 @@ pub async fn export_gif(
}
/// Export an animation as one numbered file per frame beside the output path (`name_000.png`, `name_001.png`, ..., zero-padded to fit the frame count).
#[allow(clippy::too_many_arguments)]
pub async fn export_image_sequence(
executor: &DynamicExecutor,
output: &OutputHandle,
wgpu_executor: &wgpu_executor::WgpuExecutor,
output_path: PathBuf,
settings: ExportSettings,
@@ -387,7 +383,7 @@ pub async fn export_image_sequence(
// Print progress to stderr (overwrites previous line)
eprint!("\rRendering frame {}/{}...", frame_idx + 1, animation.frames);
let frame = render_frame(executor, wgpu_executor, settings, animation_time, runtime, spawner).await?;
let frame = render_frame(executor, output, wgpu_executor, settings, animation_time, runtime, spawner).await?;
let frame_path = directory.join(format!("{stem}_{frame_idx:0digits$}.{extension}"));
write_frame(&frame_path, settings, frame)?;
}
@@ -399,8 +395,14 @@ pub async fn export_image_sequence(
Ok(())
}
pub async fn execute_until_settled(executor: &DynamicExecutor, runtime: &AsyncRuntime, spawner: &TokioSpawner, render_config: RenderConfig) -> Result<TaggedValue, Box<dyn Error>> {
let execute = || executor.execute(render_config.clone().into_context_with_generations(runtime.snapshot()));
pub async fn execute_until_settled(
executor: &DynamicExecutor,
output: &OutputHandle,
runtime: &AsyncRuntime,
spawner: &TokioSpawner,
render_config: RenderConfig,
) -> Result<TaggedValue, Box<dyn Error>> {
let execute = || executor.execute(output, render_config.into_context_with_generations(runtime.snapshot()));
let mut frame = execute()?;
while spawner.join().await {
frame = execute()?;
@@ -478,7 +480,6 @@ mod tests {
assert_eq!(detect_file_type(Path::new("frame.tif")), Ok(FileType::Tiff));
assert_eq!(detect_file_type(Path::new("frame.jpeg")), Ok(FileType::Jpg));
assert_eq!(detect_file_type(Path::new("frame.webp")), Ok(FileType::Webp));
assert_eq!(detect_file_type(Path::new("frame.pdf")), Ok(FileType::Pdf));
assert!(detect_file_type(Path::new("frame.exr")).is_err());
assert!(detect_file_type(Path::new("frame")).is_err());
}
+11 -12
View File
@@ -12,7 +12,7 @@ use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork;
use graphene_std::application_io::ApplicationIo;
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_in_scope;
use std::collections::HashMap;
@@ -95,7 +95,7 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
write_layer_paths(&mut network, layers);
let mut network = wrap_network_in_scope(network, editor_api, runtime);
let mut network = wrap_network_in_scope(network, editor_api, runtime, graphene_std::units::DEFAULT_PIXELS_PER_INCH);
let preprocessor = preprocessor::Preprocessor::new();
let preprocessed = match gdd {
@@ -111,13 +111,6 @@ pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_ap
Ok(compiled_network.network)
}
pub fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
DynamicExecutor::new(proto_network).map_err(|errors| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n").into()
})
}
pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocument, Box<dyn Error>> {
let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await;
let spawner = Arc::new(TokioSpawner::default());
@@ -134,7 +127,11 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
impl CompiledDocument {
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
let executor = create_executor(self.proto_network)?;
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n")
})?;
self.runtime.update_sources(executor.sources());
let device = self.application_io.gpu_executor().ok_or("No GPU executor is available")?.context().device.clone();
@@ -151,6 +148,7 @@ impl CompiledDocument {
Ok(Renderer {
executor,
output,
application_io: self.application_io,
runtime: self.runtime,
spawner: self.spawner,
@@ -162,6 +160,7 @@ impl CompiledDocument {
/// Executes a compiled document, polling its GPU device until dropped.
pub struct Renderer {
pub executor: DynamicExecutor,
pub output: OutputHandle,
pub runtime: AsyncRuntime,
pub spawner: Arc<TokioSpawner>,
application_io: Arc<PlatformApplicationIo>,
@@ -175,12 +174,12 @@ impl Renderer {
/// Fit `settings` to the artwork, unless they give a size.
pub async fn frame(&self, settings: export::ExportSettings) -> Result<export::ExportSettings, Box<dyn Error>> {
settings.framed(&self.executor, &self.runtime, &self.spawner).await
settings.framed(&self.executor, &self.output, &self.runtime, &self.spawner).await
}
/// Render one frame at `animation_time`.
pub async fn render(&self, settings: export::ExportSettings, animation_time: std::time::Duration) -> Result<export::RenderedFrame, Box<dyn Error>> {
export::render_frame(&self.executor, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
export::render_frame(&self.executor, &self.output, self.wgpu_executor(), settings, animation_time, &self.runtime, &self.spawner).await
}
}
+4 -4
View File
@@ -49,7 +49,7 @@ enum Command {
/// Path to the .graphite document
document: PathBuf,
/// Output file path (extension determines format: .svg, .pdf, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
/// Output file path (extension determines format: .svg, .png, .jpg, .webp, .tiff, .bmp, .tga, .ico, .gif)
#[clap(long, short = 'o')]
output: PathBuf,
@@ -198,14 +198,14 @@ async fn main() -> Result<(), Box<dyn Error>> {
let settings = renderer.frame(settings).await?;
let animation = export::AnimationParams::new(fps, frames, duration);
if file_type == export::FileType::Gif {
export::export_gif(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
export::export_gif(executor, &renderer.output, wgpu_executor, output, settings, animation, runtime, spawner).await?;
} else if animation.frames > 1 {
if file_type == export::FileType::Ico {
return Err("ICO can't be exported as an image sequence".into());
}
export::export_image_sequence(executor, wgpu_executor, output, settings, animation, runtime, spawner).await?;
export::export_image_sequence(executor, &renderer.output, wgpu_executor, output, settings, animation, runtime, spawner).await?;
} else {
export::export_document(executor, wgpu_executor, output, settings, runtime, spawner).await?;
export::export_document(executor, &renderer.output, wgpu_executor, output, settings, runtime, spawner).await?;
}
}
Command::ListNodeIdentifiers | Command::ExtractLegacyDoc { .. } | Command::Host { .. } | Command::Join { .. } | Command::Watch { .. } => unreachable!("Handled before compiling"),
+14 -9
View File
@@ -2,10 +2,10 @@ use document_live::{Event, LiveDocument};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue, UVec2};
use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export};
use graphene_cli::{TokioSpawner, compile_graph, editor_api, export};
use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig};
use graphene_std::runtime::AsyncRuntime;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::error::Error;
use std::sync::Arc;
use std::time::{Duration, Instant};
@@ -56,7 +56,7 @@ struct Viewer {
window: Option<Arc<dyn Window>>,
surface: Option<(WgpuSurface, wgpu::SurfaceConfiguration)>,
blitter: Option<TextureBlitter>,
executor: Option<DynamicExecutor>,
executor: Option<(DynamicExecutor, OutputHandle)>,
dirty: bool,
waiting: Vec<ResourceHash>,
}
@@ -132,13 +132,17 @@ impl Viewer {
Ok(proto) => proto,
Err(error) => return log::error!("Compile failed: {error}"),
};
match create_executor(proto) {
Ok(executor) => {
let mut executor = DynamicExecutor::default();
match executor.update(proto) {
Ok((output, _)) => {
self.graph_runtime.update_sources(executor.sources());
log::info!("Document compiled");
self.executor = Some(executor);
self.executor = Some((executor, output));
}
Err((_, errors)) => {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
log::error!("Executor creation failed: {}", messages.join("\n"));
}
Err(error) => log::error!("Executor creation failed: {error}"),
}
}
@@ -149,14 +153,15 @@ impl Viewer {
// Present even without a frame, since Wayland never shows a surface with no committed buffer
let frame = match &self.executor {
Some(executor) => {
Some((executor, output)) => {
let mut render_config = RenderConfig {
export_format: ExportFormat::Raster,
scale: 1.,
..Default::default()
};
render_config.viewport.resolution = UVec2::new(config.width, config.height);
match self.runtime.block_on(export::execute_until_settled(executor, &self.graph_runtime, &self.spawner, render_config))? {
let settled = export::execute_until_settled(executor, output, &self.graph_runtime, &self.spawner, render_config);
match self.runtime.block_on(settled)? {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(texture),
..
@@ -4,21 +4,27 @@ use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile};
use graphene_std::application_io::EditorApi;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::util::wrap_network_in_scope;
use std::path::Path;
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
let network = futures::executor::block_on(document_loader::open_document(Path::new(&format!("../../demo-artwork/{name}.graphite"))))
.unwrap()
.network;
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
let mut network = wrap_network_in_scope(
network,
editor_api,
AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle(),
graphene_std::units::DEFAULT_PIXELS_PER_INCH,
);
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
(executor, proto_network)
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network.clone()).unwrap();
(executor, output, proto_network)
}
#[allow(dead_code, reason = "shared by the bench targets, only some of which call it, and each compiles this module separately")]
@@ -20,7 +20,7 @@ use graphene_std::uuid::NodeId;
use graphene_std::{Color, Context};
use gungraun::prelude::*;
use gungraun::{Callgrind, EntryPoint};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use interpreted_executor::util::wrap_network_in_scope;
use std::hint::black_box;
use std::sync::Arc;
@@ -43,6 +43,7 @@ pub struct Session {
runtime: AsyncRuntime,
preprocessor: preprocessor::Preprocessor,
executor: DynamicExecutor,
output: OutputHandle,
/// The document graph for the measured update.
document: NodeNetwork,
}
@@ -60,6 +61,7 @@ impl Session {
runtime: AsyncRuntime::new(Arc::new(BlockingSpawner)),
preprocessor: preprocessor::Preprocessor::new(),
executor: DynamicExecutor::default(),
output: OutputHandle::default(),
document: NodeNetwork::default(),
};
session.update(brush_layer(&BrushCache::default(), after));
@@ -68,10 +70,10 @@ impl Session {
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
fn update(&mut self, document: NodeNetwork) {
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle(), graphene_std::units::DEFAULT_PIXELS_PER_INCH);
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
self.executor.update(proto_network).expect("Failed to update the executor");
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig {
viewport: Footprint {
@@ -82,7 +84,7 @@ impl Session {
scale: 1.,
..Default::default()
};
let output = self.executor.tree().eval_tagged_value(self.executor.output(), &render_config.into_context());
let output = self.executor.tree().eval_tagged_value(self.output.node(), &render_config.into_context());
assert!(matches!(output, Ok(graphene_std::Poll::Final(_))), "Failed to render the document: {output:?}");
// Waiting for the device puts its rasterization inside the measurement, rather than only the encoding of its commands
let _ = self.gpu.context().device.poll(wgpu::PollType::wait_indefinitely());
@@ -8,9 +8,9 @@ fn subsequent_evaluations(c: &mut Criterion) {
let mut group = c.benchmark_group("Subsequent Evaluations");
let context = RenderConfig::default().into_context();
bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name);
let (executor, output, _) = setup_network(name);
let context = context.clone();
g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap()));
g.bench_function(name, |b| b.iter(|| executor.tree().eval_tagged_value(output.node(), std::hint::black_box(&context)).unwrap()));
});
group.finish();
}
@@ -3,27 +3,28 @@ mod benchmark_util;
use benchmark_util::setup_network;
use graphene_std::application_io::RenderConfig;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use std::hint::black_box;
fn setup_run_cached(name: &str) -> DynamicExecutor {
let (executor, _) = setup_network(name);
fn setup_run_cached(name: &str) -> (DynamicExecutor, OutputHandle) {
let (executor, output, _) = setup_network(name);
// Warm up the cache by running once
let context = RenderConfig::default().into_context();
let _ = executor.tree().eval_tagged_value(executor.output(), &context);
let _ = executor.tree().eval_tagged_value(output.node(), &context);
executor
(executor, output)
}
#[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
pub fn run_cached(setup: (DynamicExecutor, OutputHandle)) -> (DynamicExecutor, OutputHandle) {
let (executor, output) = setup;
let context = RenderConfig::default().into_context();
black_box(executor.tree().eval_tagged_value(executor.output(), black_box(&context)).unwrap());
black_box(executor.tree().eval_tagged_value(output.node(), black_box(&context)).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
(executor, output)
}
library_benchmark_group!(name = run_cached_group; benchmarks = run_cached);
@@ -1,7 +1,5 @@
use criterion::measurement::Measurement;
use criterion::{BenchmarkGroup, Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile};
use graphene_std::transform::Footprint;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -12,9 +10,8 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
.unwrap()
.network;
let proto_network = compile(network);
let empty = ProtoNetwork::default();
let executor = DynamicExecutor::new(empty).unwrap();
let executor = DynamicExecutor::default();
c.bench_function(name, |b| {
b.iter_batched(
@@ -38,10 +35,11 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
.network;
let proto_network = compile(network);
let executor = DynamicExecutor::new(proto_network).unwrap();
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap();
let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
}
fn run_once_demo(c: &mut Criterion) {
let mut g = c.benchmark_group("Run Once no render");
@@ -12,7 +12,7 @@ fn run_once(c: &mut Criterion) {
g.bench_function(name, |b| {
b.iter_batched(
|| setup_network(name),
|(executor, _)| executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(&context)).unwrap(),
|(executor, output, _)| executor.tree().eval_tagged_value(output.node(), std::hint::black_box(&context)).unwrap(),
criterion::BatchSize::SmallInput,
)
});
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more