Compare commits

..
Author SHA1 Message Date
TimonandDennis Kobert 33dd5e545a Move the node graph's hit testing and bounds to the layout (#5049)
* Cache the measured width of a layer's name along with the layer's width

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

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

---------

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

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

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

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

* Draw no viewport overlays while the node graph is open

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

* Allow wrapping a network in scope without the render node

* Implement CacheHash for BTreeMap

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

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

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

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

* Follow the wire's route with its center line

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

No files matched your search

+7 -2
View File
@@ -7,6 +7,8 @@ on:
push: push:
branches: branches:
- master - master
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
workflow_dispatch: {}
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other) # Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
concurrency: concurrency:
@@ -245,7 +247,8 @@ jobs:
permissions: permissions:
contents: read contents: read
env: env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }} # A manual run has no base commit of its own, so it compares against master
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
steps: steps:
- name: 📥 Clone repository - name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -259,7 +262,9 @@ jobs:
rustflags: "" rustflags: ""
- name: 📥 Fetch the base commit - name: 📥 Fetch the base commit
run: git fetch --depth=1 origin "$BASE_SHA" run: |
git fetch --depth=1 origin "$BASE_REF"
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
- name: 🔬 Check migrations against the base commit - name: 🔬 Check migrations against the base commit
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA" run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
Generated
+2 -1
View File
@@ -590,6 +590,7 @@ dependencies = [
"node-macro", "node-macro",
"raster-kernels", "raster-kernels",
"serde", "serde",
"text-nodes",
"vector-types", "vector-types",
] ]
@@ -1226,7 +1227,6 @@ dependencies = [
"kurbo", "kurbo",
"log", "log",
"lyon_geom", "lyon_geom",
"math-parser",
"node-macro", "node-macro",
"num-derive", "num-derive",
"num-traits", "num-traits",
@@ -5746,6 +5746,7 @@ dependencies = [
"glam", "glam",
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
"half",
"log", "log",
"raster-types", "raster-types",
"thiserror 2.0.21", "thiserror 2.0.21",
@@ -57,10 +57,6 @@ pub mod network {
pub const IMPORT_METADATA: &str = "ui::import_metadata"; pub const IMPORT_METADATA: &str = "ui::import_metadata";
pub const EXPORT_NAMES: &str = "ui::export_names"; pub const EXPORT_NAMES: &str = "ui::export_names";
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions"; pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
/// is the default, CSS's 96. Only the root network's applies.
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
} }
pub mod delta { pub mod delta {
@@ -473,12 +473,6 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
.map_err(map_serialization_error(network::PINNED_ORDER))?; .map_err(map_serialization_error(network::PINNED_ORDER))?;
} }
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
attributes
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
}
Ok(()) Ok(())
} }
@@ -38,8 +38,6 @@ pub struct NetworkMetadataEntry {
pub import_metadata: Vec<InputMetadataEntry>, pub import_metadata: Vec<InputMetadataEntry>,
pub export_names: Vec<String>, pub export_names: Vec<String>,
pub export_descriptions: Vec<String>, pub export_descriptions: Vec<String>,
/// The document's pixels per inch, where it differs from the default.
pub pixels_per_inch: Option<f64>,
} }
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so /// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
@@ -80,11 +78,6 @@ pub trait NodeMetadataSource {
Vec::new() Vec::new()
} }
/// The network's pixels per inch, where it differs from the default.
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
None
}
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> { fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
Vec::new() Vec::new()
} }
@@ -12,25 +12,9 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
/// Note: This only works for complete networks with all inputs resolved. /// Note: This only works for complete networks with all inputs resolved.
/// Test networks with Import inputs will fail compilation (which is expected). /// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> { fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
use graph_craft::document::value::TaggedValue;
let mut network = network.clone(); let mut network = network.clone();
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?; network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
let resolution_node = NodeId(u64::MAX);
network.nodes.insert(
resolution_node,
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
..Default::default()
},
);
network
.scope_injections
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
let compiler = Compiler {}; let compiler = Compiler {};
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?; compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(()) Ok(())
-1
View File
@@ -417,7 +417,6 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
import_metadata: attributes.get_or_default(network::IMPORT_METADATA), import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
export_names: attributes.get_or_default(network::EXPORT_NAMES), export_names: attributes.get_or_default(network::EXPORT_NAMES),
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS), export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
} }
} }
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BevelAndEmbossV2, &contract());
check_undo(&BevelAndEmbossV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BevelAndEmbossV2);
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
assert_eq!(fixture.inputs(&migrated, bevel), expected);
}
}
@@ -0,0 +1,69 @@
use migration_core::{Inputs, NodeInput, encode, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
TypeDefault(Type),
}
/// Frozen mirror of the `Type` an empty list of graphics stores.
#[derive(Serialize, Deserialize)]
enum Type {
Concrete(TypeDescriptor),
List(Box<Type>),
}
#[derive(Serialize, Deserialize)]
struct TypeDescriptor {
name: String,
}
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
pub fn blur_v2(inputs: &mut Inputs) {
inputs.insert(2, empty_radius_mask());
}
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
fn empty_radius_mask() -> NodeInput {
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
name: "graphic_types::graphic::Graphic".to_string(),
}))));
NodeInput::Value {
value: encode(&no_graphics),
exposed: false,
}
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
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(&BlurV2, &contract());
check_undo(&BlurV2, &contract());
}
#[test]
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&BlurV2);
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
let migrated = fixture.migrate(&BlurV2).unwrap();
let mut expected = inputs;
expected.insert(2, empty_radius_mask());
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
assert_eq!(fixture.inputs(&migrated, blur), expected);
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
}
}
@@ -0,0 +1,43 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
}
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Bool(false)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ConvolutionKernelV1, &contract());
check_undo(&ConvolutionKernelV1, &contract());
}
#[test]
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&ConvolutionKernelV1);
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
}
}
@@ -1,6 +1,9 @@
//! Migrations of the nodes in `blending_nodes`. //! Migrations of the nodes in `blending_nodes`.
mod bevel_and_emboss_v1; mod bevel_and_emboss_v1;
mod bevel_and_emboss_v2;
mod blur_v2;
mod convolution_kernel_v1;
mod drop_shadow_v1; mod drop_shadow_v1;
mod inner_glow_v1; mod inner_glow_v1;
mod inner_shadow_v1; mod inner_shadow_v1;
@@ -8,6 +11,8 @@ mod mask_by_any_graphic;
mod outer_glow_v1; mod outer_glow_v1;
mod outline_v1; mod outline_v1;
mod outline_v2; mod outline_v2;
mod outline_v3;
mod paint_overlay_from_color_overlay; mod paint_overlay_from_color_overlay;
mod paint_overlay_v2;
mod renames; mod renames;
mod satin_v1; mod satin_v1;
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Outline' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
pub fn outline_v3(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&OutlineV3, &contract());
check_undo(&OutlineV3, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&OutlineV3);
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
let migrated = fixture.migrate(&OutlineV3).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
assert_eq!(fixture.inputs(&migrated, outline), expected);
}
}
@@ -0,0 +1,53 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Bool(bool),
DAffine2([f64; 6]),
}
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
pub fn paint_overlay_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PaintOverlayV2, &contract());
check_undo(&PaintOverlayV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_an_unset_placement() {
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&PaintOverlayV2);
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
assert_eq!(fixture.inputs(&migrated, overlay), expected);
}
}
@@ -1,47 +0,0 @@
use migration_core::{Inputs, NodeInput, migration};
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
pub fn math_function_v2(inputs: &mut Inputs) {
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
String(String),
}
fn contract() -> SourceContract {
SourceContract::new(3, |random, slot| match slot {
1 => literal(Tagged::String("x".to_string())),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&MathFunctionV2, &contract());
check_undo(&MathFunctionV2, &contract());
}
#[test]
fn the_resolution_is_read_from_the_scope() {
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
let mut fixture = Fixture::new(&MathFunctionV2);
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
assert_eq!(fixture.inputs(&migrated, function), expected);
}
}
@@ -1,5 +1,4 @@
//! Migrations of the nodes in `math_nodes`. //! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f; mod math_formula_from_math_f;
mod math_function_v2;
mod renames; mod renames;
@@ -1,65 +0,0 @@
use migration_core::{Inputs, Node, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const RADIUS: usize = 1;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
None,
Number(f64),
Length(TypedLength),
}
#[derive(Serialize, Deserialize)]
struct TypedLength {
value: f64,
unit: LengthUnit,
}
#[derive(Serialize, Deserialize)]
enum LengthUnit {
Pixel,
}
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
let Some(slot) = node.inputs().get(RADIUS) else { return };
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
inputs.set(
RADIUS as u32,
literal(Tagged::Length(TypedLength {
value: pixels,
unit: LengthUnit::Pixel,
})),
);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
}
#[test]
fn rewrites_history() {
check_commutation(&CircleV1, &contract());
check_undo(&CircleV1, &contract());
}
#[test]
fn a_number_of_pixels_becomes_a_length_in_pixels() {
let mut fixture = Fixture::new(&CircleV1);
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
let migrated = fixture.migrate(&CircleV1).unwrap();
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
}
}
@@ -1,5 +1,4 @@
//! Migrations of the nodes in `vector_nodes`. //! Migrations of the nodes in `vector_nodes`.
mod circle_v1;
mod path_from_path_network; mod path_from_path_network;
mod renames; mod renames;
@@ -6,8 +6,6 @@ use crate::messages::prelude::*;
pub enum DialogMessage { pub enum DialogMessage {
// Sub-messages // Sub-messages
#[child] #[child]
DocumentSetupDialog(DocumentSetupDialogMessage),
#[child]
ExportDialog(ExportDialogMessage), ExportDialog(ExportDialogMessage),
#[child] #[child]
NewDocumentDialog(NewDocumentDialogMessage), NewDocumentDialog(NewDocumentDialogMessage),
@@ -36,7 +34,6 @@ pub enum DialogMessage {
localized_commit_year: String, localized_commit_year: String,
}, },
RequestDemoArtworkDialog, RequestDemoArtworkDialog,
RequestDocumentSetupDialog,
RequestExportDialog, RequestExportDialog,
RequestLicensesDialogWithLocalizedCommitDate { RequestLicensesDialogWithLocalizedCommitDate {
localized_commit_year: String, localized_commit_year: String,
@@ -4,7 +4,6 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
use crate::messages::frontend::utility_types::ExportBounds; use crate::messages::frontend::utility_types::ExportBounds;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
#[derive(ExtractField)] #[derive(ExtractField)]
pub struct DialogMessageContext<'a> { pub struct DialogMessageContext<'a> {
@@ -17,7 +16,6 @@ pub struct DialogMessageContext<'a> {
pub struct DialogMessageHandler { pub struct DialogMessageHandler {
on_dismiss: Option<Message>, on_dismiss: Option<Message>,
redisplay: Option<Message>, redisplay: Option<Message>,
document_setup_dialog: DocumentSetupDialogMessageHandler,
export_dialog: ExportDialogMessageHandler, export_dialog: ExportDialogMessageHandler,
new_document_dialog: NewDocumentDialogMessageHandler, new_document_dialog: NewDocumentDialogMessageHandler,
preferences_dialog: PreferencesDialogMessageHandler, preferences_dialog: PreferencesDialogMessageHandler,
@@ -29,7 +27,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let DialogMessageContext { portfolio, preferences } = context; let DialogMessageContext { portfolio, preferences } = context;
match message { match message {
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }), DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()), DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }), DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
@@ -103,15 +100,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
let dialog = DemoArtworkDialog; let dialog = DemoArtworkDialog;
dialog.send_dialog_to_frontend(responses); dialog.send_dialog_to_frontend(responses);
} }
DialogMessage::RequestDocumentSetupDialog => {
self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() {
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
pixels_per_inch: document.network_interface.pixels_per_inch(),
};
self.document_setup_dialog.send_dialog_to_frontend(responses);
}
}
DialogMessage::RequestExportDialog => { DialogMessage::RequestExportDialog => {
self.on_dismiss = Some(DialogMessage::Close.into()); self.on_dismiss = Some(DialogMessage::Close.into());
if let Some(document) = portfolio.active_document() { if let Some(document) = portfolio.active_document() {
@@ -157,9 +145,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
self.new_document_dialog = NewDocumentDialogMessageHandler { self.new_document_dialog = NewDocumentDialogMessageHandler {
name: portfolio.generate_new_document_name(None), name: portfolio.generate_new_document_name(None),
infinite: false, infinite: false,
width: TypedLength::pixels(1920.), dimensions: glam::UVec2::new(1920, 1080),
height: TypedLength::pixels(1080.),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}; };
self.new_document_dialog.send_dialog_to_frontend(responses); self.new_document_dialog.send_dialog_to_frontend(responses);
} }
@@ -1,9 +0,0 @@
use crate::messages::prelude::*;
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum DocumentSetupDialogMessage {
Resolution { pixels_per_inch: f64 },
Submit,
}
@@ -1,158 +0,0 @@
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*;
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
/// A dialog to allow users to change the settings of the active document.
#[derive(Debug, Clone, ExtractField)]
pub struct DocumentSetupDialogMessageHandler {
pub pixels_per_inch: f64,
}
impl Default for DocumentSetupDialogMessageHandler {
fn default() -> Self {
Self {
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
}
#[message_handler_data]
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
match message {
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
DocumentSetupDialogMessage::Submit => {
// The settings apply as one undo step, which ending the transaction drops if nothing changed
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
responses.add(DocumentMessage::EndTransaction);
}
}
self.send_dialog_to_frontend(responses);
}
advertise_actions!(DocumentSetupDialogUpdate;
);
}
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
const ICON: &'static str = "File";
const TITLE: &'static str = "Document Setup";
fn layout_buttons(&self) -> Layout {
let widgets = vec![
TextButton::new("OK")
.emphasized(true)
.on_update(|_| {
DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
}
.into()
})
.widget_instance(),
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
];
Layout(vec![LayoutGroup::row(widgets)])
}
}
impl LayoutHolder for DocumentSetupDialogMessageHandler {
fn layout(&self) -> Layout {
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
Layout(vec![LayoutGroup::row(resolution)])
}
}
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
vec![
TextLabel::new("Resolution")
.table_align(true)
.sizing(WidgetSizing::fixed(90))
.tooltip_label("Resolution")
.tooltip_description(description)
.widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(pixels_per_inch))
.unit(" PPI")
.min(1.)
.max(100_000.)
.tooltip_label("Resolution")
.tooltip_description(description)
// Matches the width of the New Document dialog's Name field
.sizing(WidgetSizing::default().min_width(204))
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
.widget_instance(),
]
}
#[cfg(test)]
mod tests {
use crate::test_utils::test_prelude::*;
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
editor.active_document().network_interface.pixels_per_inch()
}
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
}
async fn confirm(editor: &mut EditorTestUtils) {
editor
.handle_message(DialogMessage::CloseAndThen {
followups: vec![DocumentSetupDialogMessage::Submit.into()],
})
.await;
}
#[tokio::test]
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
let layer_count = editor.active_document().metadata().all_layers().count();
open_and_set_resolution(&mut editor, 300.).await;
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
// Undoing reverts only the resolution, leaving the rectangle drawn before it
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96.);
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(pixels_per_inch(&editor), 300.);
}
#[tokio::test]
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
open_and_set_resolution(&mut editor, 300.).await;
confirm(&mut editor).await;
open_and_set_resolution(&mut editor, 150.).await;
editor.handle_message(DialogMessage::Close).await;
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
confirm(&mut editor).await;
assert_eq!(pixels_per_inch(&editor), 300.);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
}
}
@@ -1,7 +0,0 @@
mod document_setup_dialog_message;
mod document_setup_dialog_message_handler;
#[doc(inline)]
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
#[doc(inline)]
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
-1
View File
@@ -8,7 +8,6 @@
mod dialog_message; mod dialog_message;
mod dialog_message_handler; mod dialog_message_handler;
pub mod document_setup_dialog;
pub mod export_dialog; pub mod export_dialog;
pub mod new_document_dialog; pub mod new_document_dialog;
pub mod preferences_dialog; pub mod preferences_dialog;
@@ -1,14 +1,12 @@
use crate::messages::prelude::*; use crate::messages::prelude::*;
use graphene_std::units::TypedLength;
#[impl_message(Message, DialogMessage, NewDocumentDialog)] #[impl_message(Message, DialogMessage, NewDocumentDialog)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)] #[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum NewDocumentDialogMessage { pub enum NewDocumentDialogMessage {
Name { name: String }, Name { name: String },
Infinite { infinite: bool }, Infinite { infinite: bool },
DimensionsX { width: TypedLength }, DimensionsX { width: f64 },
DimensionsY { height: TypedLength }, DimensionsY { height: f64 },
Resolution { pixels_per_inch: f64 },
Submit, Submit,
} }
@@ -1,33 +1,16 @@
use crate::messages::dialog::document_setup_dialog::resolution_row;
use crate::messages::layout::layout_message_handler::unit_suffix;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::prelude::*; use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils; use crate::messages::tool::common_functionality::graph_modification_utils;
use glam::DVec2; use glam::UVec2;
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::Color; use graphene_std::Color;
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength};
/// A dialog to allow users to set some initial options about a new document. /// A dialog to allow users to set some initial options about a new document.
#[derive(Debug, Clone, ExtractField)] #[derive(Debug, Clone, Default, ExtractField)]
pub struct NewDocumentDialogMessageHandler { pub struct NewDocumentDialogMessageHandler {
pub name: String, pub name: String,
pub infinite: bool, pub infinite: bool,
pub width: TypedLength, pub dimensions: UVec2,
pub height: TypedLength,
pub pixels_per_inch: f64,
}
impl Default for NewDocumentDialogMessageHandler {
fn default() -> Self {
Self {
name: String::new(),
infinite: false,
width: TypedLength::default(),
height: TypedLength::default(),
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
}
}
} }
#[message_handler_data] #[message_handler_data]
@@ -36,37 +19,24 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
match message { match message {
NewDocumentDialogMessage::Name { name } => self.name = name, NewDocumentDialogMessage::Name { name } => self.name = name,
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite, NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
NewDocumentDialogMessage::DimensionsX { width } => { NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
self.width = whole_pixels(width); NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
self.height = self.in_unit(self.height, self.width.unit);
}
NewDocumentDialogMessage::DimensionsY { height } => {
self.height = whole_pixels(height);
self.width = self.in_unit(self.width, self.height.unit);
}
NewDocumentDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
NewDocumentDialogMessage::Submit => { NewDocumentDialogMessage::Submit => {
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() }); responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
// Like the artboard, the resolution is part of the document's starting state rather than an undo step
responses.add(DocumentMessage::SetPixelsPerInch {
pixels_per_inch: self.pixels_per_inch,
});
let dimensions = self.artboard_dimensions();
if self.infinite { if self.infinite {
// Infinite canvas: add a locked white background layer // Infinite canvas: add a locked white background layer
graph_modification_utils::new_background_layer(0, responses); graph_modification_utils::new_background_layer(0, responses);
} else if dimensions.x > 0. && dimensions.y > 0. { } else if self.dimensions.x > 0 && self.dimensions.y > 0 {
// Finite canvas: create an artboard with the specified dimensions // Finite canvas: create an artboard with the specified dimensions
responses.add(GraphOperationMessage::NewArtboard { responses.add(GraphOperationMessage::NewArtboard {
id: NodeId::new(), id: NodeId::new(),
location: DVec2::ZERO, location: glam::DVec2::ZERO,
dimensions, dimensions: self.dimensions.as_dvec2(),
background: Color::WHITE, background: Color::WHITE,
clip: true, clip: true,
}); });
responses.add(NavigationMessage::CanvasPan { delta: dimensions }); responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
} }
responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::RunDocumentGraph);
@@ -137,150 +107,32 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
.widget_instance(), .widget_instance(),
]; ];
// Each dimension shows the unit it was typed in and keeps any length unit typed into it let scale = vec![
let dimension_field = |length: TypedLength, label: &str| {
NumberInput::new(Some(length.value))
.label(label)
.unit(unit_suffix(length.unit.symbol()))
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
.pixels_per_inch(self.pixels_per_inch)
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
};
let dimensions = vec![
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(), TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance(),
dimension_field(self.width, "W") NumberInput::new(Some(self.dimensions.x as f64))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into()) .label("W")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
.widget_instance(), .widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(), Separator::new(SeparatorStyle::Related).widget_instance(),
dimension_field(self.height, "H") NumberInput::new(Some(self.dimensions.y as f64))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into()) .label("H")
.unit(" px")
.min(0.)
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(true)
.disabled(self.infinite)
.sizing(WidgetSizing::default().min_width(100))
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
.widget_instance(), .widget_instance(),
]; ];
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into()); Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(dimensions), LayoutGroup::row(resolution)])
}
}
impl NewDocumentDialogMessageHandler {
/// A dimension converted into `unit` at the chosen resolution, keeping its size.
fn in_unit(&self, length: TypedLength, unit: LengthUnit) -> TypedLength {
whole_pixels(TypedLength {
value: length.unit.convert(length.value, unit, self.pixels_per_inch),
unit,
})
}
/// The artboard's size in 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.)));
} }
} }
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions; use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{ use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
}; };
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry}; use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate}; use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -196,10 +196,6 @@ pub enum FrontendMessage {
#[serde(rename = "contextMenuInformation")] #[serde(rename = "contextMenuInformation")]
context_menu_information: Option<ContextMenuInformation>, context_menu_information: Option<ContextMenuInformation>,
}, },
UpdateClickTargets {
#[serde(rename = "clickTargets")]
click_targets: Option<FrontendClickTargets>,
},
UpdateGraphViewOverlay { UpdateGraphViewOverlay {
open: bool, open: bool,
}, },
@@ -87,9 +87,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility), entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked), entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes), entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes), entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }), entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }), entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }), entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
@@ -417,20 +417,16 @@ impl LayoutMessageHandler {
} }
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate. // A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
Value::String(expression) => { Value::String(expression) => {
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else { let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
return;
};
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway. // Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
if number_input.value == Some(evaluated) && number_input.unit == unit { if number_input.value == Some(evaluated) {
return; return;
} }
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`. // Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
responses.add((number_input.on_commit.callback)(&())); responses.add((number_input.on_commit.callback)(&()));
number_input.value = Some(evaluated); number_input.value = Some(evaluated);
number_input.unit = unit;
responses.add((number_input.on_update.callback)(number_input)); responses.add((number_input.on_update.callback)(number_input));
} }
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback. // The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
@@ -708,41 +704,21 @@ fn populate_computed_display_fields(layout: &mut Layout) {
} }
} }
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`. /// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
pub fn unit_suffix(symbol: &str) -> String { /// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() } fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
} let value = math_parser::evaluate(expression)
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
let value = math_parser::ast::Node::try_parse_from_str(expression)
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}")) .inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
.ok()? .ok()?
.eval(&context)
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}")) .inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
.ok()?; .ok()?;
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it let real = value.as_real()?;
let field_unit = math_parser::units::Unit::named(number_input.unit.trim()); if real.is_nan() {
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
(Some(quantity), Some(unit)) => {
let read = quantity
.read_in(unit, number_input.pixels_per_inch)
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
.ok()?
.as_real()?;
(read, Some(*quantity))
}
_ => (value.as_real()?, None),
};
if in_field_unit.is_nan() {
return None; return None;
} }
let mut validated = in_field_unit; let mut validated = real;
if let Some(min) = number_input.min { if let Some(min) = number_input.min {
validated = validated.max(min); validated = validated.max(min);
} }
@@ -753,17 +729,5 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
validated = validated.round(); validated = validated.round();
} }
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it Some(validated)
let kept_unit = quantity.and_then(|quantity| {
let symbol = quantity.unit.single()?.definition().symbol;
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
});
if let Some((quantity, symbol)) = kept_unit
&& validated == in_field_unit
&& let Some(kept_value) = quantity.value.as_real()
{
return Some((kept_value, Some(symbol.to_string())));
}
Some((validated, None))
} }
@@ -247,14 +247,6 @@ pub struct NumberInput {
#[serde(rename = "unitIsHiddenWhenEditing")] #[serde(rename = "unitIsHiddenWhenEditing")]
#[derivative(Default(value = "true"))] #[derivative(Default(value = "true"))]
pub unit_is_hidden_when_editing: bool, pub unit_is_hidden_when_editing: bool,
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
#[serde(skip)]
pub kept_units: Vec<String>,
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
#[serde(skip)]
#[derivative(Default(value = "96."))]
pub pixels_per_inch: f64,
// Tooltips // Tooltips
#[serde(rename = "tooltipLabel")] #[serde(rename = "tooltipLabel")]
@@ -615,7 +607,6 @@ pub enum MathExpressionRole {
Function, Function,
Keyword, Keyword,
Operator, Operator,
Unit,
Bracket, Bracket,
MatrixLiteral, MatrixLiteral,
Error, Error,
@@ -632,7 +623,6 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
Role::Function => Self::Function, Role::Function => Self::Function,
Role::Keyword => Self::Keyword, Role::Keyword => Self::Keyword,
Role::Operator => Self::Operator, Role::Operator => Self::Operator,
Role::Unit => Self::Unit,
Role::Bracket => Self::Bracket, Role::Bracket => Self::Bracket,
Role::MatrixLiteral => Self::MatrixLiteral, Role::MatrixLiteral => Self::MatrixLiteral,
Role::Error => Self::Error, Role::Error => Self::Error,
@@ -181,13 +181,6 @@ impl LayoutHolder for MenuBarMessageHandler {
.on_commit(|_| DialogMessage::RequestExportDialog.into()) .on_commit(|_| DialogMessage::RequestExportDialog.into())
.disabled(no_active_document), .disabled(no_active_document),
], ],
vec![
MenuListEntry::new("Document Setup…")
.label("Document Setup…")
.icon("Settings")
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
.disabled(no_active_document),
],
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
vec![preferences], vec![preferences],
]) ])
@@ -0,0 +1,153 @@
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::test_utils::gpu_executor;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, UVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
use graphene_std::graphic::{IntoGraphicList, extend};
use graphene_std::list::{Item, List};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
#[derive(Clone, Copy, Debug)]
enum Base {
VectorLayer,
ImageLayer,
/// A group holding a vector layer, with the effect on the group.
Group,
}
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
if effect == blur::IDENTIFIER {
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
.upstream_node_id_from_protonode(effect)
.expect("the layer has its blur");
let value = Box::new(TaggedValue::Number(10.));
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id,
input_index: blur::RadiusInput::INDEX,
value,
})
.await;
}
}
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
match base {
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
Base::VectorLayer | Base::Group => {
editor.select_primary_color(blue).await;
editor.select_secondary_color(blue).await;
editor.draw_rect(50., 50., 130., 130.).await;
}
}
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
if !matches!(base, Base::Group) {
add_effect(&mut editor, base_layer, effect.clone()).await;
}
editor.select_tool(ToolType::Select).await;
editor.select_primary_color(red).await;
editor.select_secondary_color(red).await;
editor.draw_rect(20., 20., 200., 200.).await;
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
editor
.handle_message(GraphOperationMessage::FillColorSet {
layer: clipped_layer,
color: Some(red),
})
.await;
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
// Grouped once the red is clipped, the group takes the base's place beneath it
if let Base::Group = base {
let nodes = vec![base_layer.to_node()];
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
let group_folder_type = GroupFolderType::Layer;
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
let group = editor.get_selected_layer().await.expect("the group is selected");
add_effect(&mut editor, group, effect).await;
}
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
stack.push(clipped);
stack
}
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
// The clip's def in SVG carries out the blur but not the shadow
let mut render = SvgRender::new();
graphic.render_svg(
&mut render,
&RenderParams {
for_export: true,
..Default::default()
},
);
let body = render.svg.to_svg_string();
let reference = body.rfind("url(#mask-").expect("the red is clipped");
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
let defs = &render.svg_defs;
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
let def_end = ["</mask>", "</clipPath>"]
.iter()
.filter_map(|closing| defs[def_start..].find(closing))
.min()
.expect("the clip's def is closed");
let clip = &defs[def_start..def_start + def_end];
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
let size = UVec2::new(256, 256);
let executor = gpu_executor();
let texture = executor
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
.expect("the clip renders");
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
let pixel = |x: u32, y: u32| -> [u8; 4] {
let index = (y * size.x + x) as usize * 4;
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
};
let within = pixel(90, 90);
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
}
#[tokio::test]
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
let stack = clipped_stack(base, effect.clone()).await;
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
// Flattened into one list of vectors, the base clips its sibling by the same rule
if let Base::VectorLayer = base {
let flattened: List<Vector> = stack.into_flattened_list();
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
}
}
}
}
@@ -7,6 +7,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use crate::node_graph_executor::InspectedContext; use crate::node_graph_executor::InspectedContext;
use glam::{Affine2, DAffine2, Vec2}; use glam::{Affine2, DAffine2, Vec2};
use graph_craft::document::NodeId; use graph_craft::document::NodeId;
use graphene_std::RadialBlurMethod;
use graphene_std::animation::RealTimeMode; use graphene_std::animation::RealTimeMode;
use graphene_std::blending::BlendMode; use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
@@ -25,7 +26,6 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve; use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::transform::{ReferencePoint, ScaleType}; use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::units::{Angle, Length};
use graphene_std::vector::misc::{ use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod, WeldMethod,
@@ -36,7 +36,7 @@ use graphene_std::vector::style::{
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector}; use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{ use graphene_std::{
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic, Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
MaskMode, MaskMode, MinimumMaximumMode, NoiseDistribution,
}; };
use kurbo::BezPath; use kurbo::BezPath;
use std::any::Any; use std::any::Any;
@@ -402,8 +402,6 @@ macro_rules! inspectable_types {
List<Generator>, List<Generator>,
List<String>, List<String>,
List<f64>, List<f64>,
List<Length>,
List<Angle>,
List<i64>, List<i64>,
List<bool>, List<bool>,
List<DVec2>, List<DVec2>,
@@ -464,8 +462,6 @@ macro_rules! inspectable_types {
Item<Generator>, Item<Generator>,
Item<String>, Item<String>,
Item<f64>, Item<f64>,
Item<Length>,
Item<Angle>,
Item<i64>, Item<i64>,
Item<bool>, Item<bool>,
Item<DVec2>, Item<DVec2>,
@@ -1105,30 +1101,6 @@ impl TableItemLayout for f64 {
} }
} }
impl TableItemLayout for Length {
fn type_name() -> &'static str {
"Length"
}
fn identifier(&self) -> String {
format!("{} px", format_f64(round_away_float_noise(self.pixels())))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for Angle {
fn type_name() -> &'static str {
"Angle"
}
fn identifier(&self) -> String {
format!("{}°", format_f64(round_away_float_noise(self.degrees())))
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
impl TableItemLayout for u8 { impl TableItemLayout for u8 {
fn type_name() -> &'static str { fn type_name() -> &'static str {
"Byte" "Byte"
@@ -1300,16 +1272,19 @@ impl_table_item_layout_for_choice_enum!(
BevelDirection, BevelDirection,
BevelTechnique, BevelTechnique,
BevelStyle, BevelStyle,
RadialBlurMethod,
EffectKind, EffectKind,
Generator, Generator,
GlowSource, GlowSource,
MaskMode, MaskMode,
MinimumMaximumMode,
GradientForm, GradientForm,
GradientSpread, GradientSpread,
GradientSpace, GradientSpace,
GradientHueDirection, GradientHueDirection,
GradientInterpolation, GradientInterpolation,
GlowTechnique, GlowTechnique,
NoiseDistribution,
StrokeJoin, StrokeJoin,
StrokeAlign, StrokeAlign,
StrokeCap, StrokeCap,
@@ -1485,9 +1460,11 @@ macro_rules! known_item_types {
EffectKind, EffectKind,
GlowSource, GlowSource,
MaskMode, MaskMode,
MinimumMaximumMode,
BevelStyle, BevelStyle,
BevelDirection, BevelDirection,
BevelTechnique, BevelTechnique,
RadialBlurMethod,
DashPattern, DashPattern,
BoxCorners, BoxCorners,
TransferCurve, TransferCurve,
@@ -1498,6 +1475,7 @@ macro_rules! known_item_types {
GradientHueDirection, GradientHueDirection,
GradientInterpolation, GradientInterpolation,
GlowTechnique, GlowTechnique,
NoiseDistribution,
StrokeJoin, StrokeJoin,
StrokeAlign, StrokeAlign,
StrokeCap, StrokeCap,
@@ -266,11 +266,6 @@ pub enum DocumentMessage {
SetRenderMode { SetRenderMode {
render_mode: RenderMode, 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 { ShowNodeInGraph {
node_id: NodeId, node_id: NodeId,
}, },
@@ -53,7 +53,6 @@ use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::{GradientStops, RenderMode}; use graphene_std::vector::style::{GradientStops, RenderMode};
use kurbo::{Affine, BezPath, Line, PathSeg, Shape}; use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
use std::collections::HashSet; use std::collections::HashSet;
use std::hash::{Hash, Hasher};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@@ -305,8 +304,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let visibility_settings = self.overlays_visibility_settings; let visibility_settings = self.overlays_visibility_settings;
// Send the overlays message to the overlays message handler // Send the overlays message to the overlays message handler
self.overlays_message_handler self.overlays_message_handler.process_message(
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport }); message,
responses,
OverlaysMessageContext {
visibility_settings,
viewport,
graph_open: self.graph_view_overlay_open,
},
);
} }
DocumentMessage::Inspector(message) => { DocumentMessage::Inspector(message) => {
let context = InspectorMessageContext { let context = InspectorMessageContext {
@@ -1695,16 +1701,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.render_mode = render_mode; self.render_mode = render_mode;
responses.add_front(NodeGraphMessage::RunDocumentGraph); 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 } => { DocumentMessage::ShowNodeInGraph { node_id } => {
// The node is in the document network, so the graph first leaves any nested network it's showing // 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() { if !self.breadcrumb_network_path.is_empty() {
@@ -2691,7 +2687,6 @@ impl DocumentMessageHandler {
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) { fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
for path in self.network_interface.paths_reaching(&reconciled.networks) { for path in self.network_interface.paths_reaching(&reconciled.networks) {
self.network_interface.unload_import_export_ports(&path); self.network_interface.unload_import_export_ports(&path);
self.network_interface.unload_all_nodes_bounding_box(&path);
self.network_interface.unload_outward_wires(&path); self.network_interface.unload_outward_wires(&path);
} }
self.network_interface.load_structure(); self.network_interface.load_structure();
@@ -3241,10 +3236,7 @@ impl DocumentMessageHandler {
} }
pub fn current_hash(&self) -> u64 { pub fn current_hash(&self) -> u64 {
// The resolution lives in the network's metadata rather than the network, but changing it changes the document self.network_interface.document_network().current_hash()
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 { pub fn is_auto_saved(&self) -> bool {
@@ -807,9 +807,6 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
// Set positions for all imported descendants in a single O(n) pass // Set positions for all imported descendants in a single O(n) pass
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO); let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map); set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
// Invalidate caches once after all positions are set
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
} }
usvg::Node::Path(path) => { usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info); import_usvg_path(modify_inputs, node, path, layer, gradient_info);
@@ -1,4 +1,6 @@
#[cfg(test)] #[cfg(test)]
mod clipping_tests;
#[cfg(test)]
pub(crate) mod document_diff; pub(crate) mod document_diff;
mod document_history; mod document_history;
mod document_message; mod document_message;
@@ -139,18 +139,6 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA /// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> { fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![ let custom = vec![
DocumentNodeDefinition {
identifier: "Custom Node",
version: 1,
category: "Routing",
icon: Some("NodeCustomNode"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
},
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
inspector: None,
},
DocumentNodeDefinition { DocumentNodeDefinition {
identifier: "Merge", identifier: "Merge",
version: 1, version: 1,
@@ -701,6 +689,7 @@ fn static_node_inspector() -> NodeInspector {
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector)); map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector)); map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector)); map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
map map
} }
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
xy: Option<(i32, i32)>, xy: Option<(i32, i32)>,
add_transaction: bool, add_transaction: bool,
}, },
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
CreateEmptySubgraph {
node_id: Option<NodeId>,
xy: Option<(i32, i32)>,
},
CreateWire { CreateWire {
output_connector: OutputConnector, output_connector: OutputConnector,
input_connector: InputConnector, input_connector: InputConnector,
@@ -202,8 +207,6 @@ pub enum NodeGraphMessage {
SelectedNodesSet { SelectedNodesSet {
nodes: Vec<NodeId>, nodes: Vec<NodeId>,
}, },
SendClickTargets,
EndSendClickTargets,
UnloadWires, UnloadWires,
SendWires, SendWires,
UpdateVisibleNodes, UpdateVisibleNodes,
@@ -383,6 +386,7 @@ impl NodeGraphMessage {
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path), | Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
Self::AddNodes { .. } Self::AddNodes { .. }
| Self::CreateNodeFromContextMenu { .. } | Self::CreateNodeFromContextMenu { .. }
| Self::CreateEmptySubgraph { .. }
| Self::CreateWire { .. } | Self::CreateWire { .. }
| Self::CreateWires { .. } | Self::CreateWires { .. }
| Self::ConnectUpstreamOutputToInput { .. } | Self::ConnectUpstreamOutputToInput { .. }
@@ -442,8 +446,6 @@ impl NodeGraphMessage {
| Self::SelectedNodesAdd { .. } | Self::SelectedNodesAdd { .. }
| Self::SelectedNodesRemove { .. } | Self::SelectedNodesRemove { .. }
| Self::SelectedNodesSet { .. } | Self::SelectedNodesSet { .. }
| Self::SendClickTargets
| Self::EndSendClickTargets
| Self::UnloadWires | Self::UnloadWires
| Self::SendWires | Self::SendWires
| Self::UpdateVisibleNodes | Self::UpdateVisibleNodes
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls; use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext; use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic}; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView; use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{ use crate::messages::portfolio::document::utility_types::network_interface::{
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus, self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
TransactionStatus,
}; };
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry}; use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire}; use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
@@ -23,14 +24,12 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion}; use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo}; use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position; use crate::messages::viewport::Position;
use glam::{DAffine2, DVec2, IVec2}; use glam::{DVec2, IVec2};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath; use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
use graphene_std::*; use graphene_std::*;
use kurbo::{DEFAULT_ACCURACY, Shape}; use kurbo::{DEFAULT_ACCURACY, Shape};
use renderer::Quad;
#[derive(Debug, ExtractField)] #[derive(Debug, ExtractField)]
pub struct NodeGraphMessageContext<'a> { pub struct NodeGraphMessageContext<'a> {
@@ -422,6 +421,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}); });
responses.add(NodeGraphMessage::SendGraph); responses.add(NodeGraphMessage::SendGraph);
} }
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
let node_id = node_id.unwrap_or_else(NodeId::new);
let (x, y) = xy.unwrap_or_else(|| {
network_interface
.node_graph_ptz(breadcrumb_network_path)
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
});
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode {
node_id,
node_template: Box::new(NodeTemplate::empty_subgraph()),
});
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
responses.add(NodeGraphMessage::SendGraph);
}
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => { NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else { let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
log::error!("Failed to find upstream node for downstream_input"); log::error!("Failed to find upstream node for downstream_input");
@@ -769,24 +785,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
} }
} }
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports // Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
let encapsulating_node_id = NodeId::new(); let encapsulating_node_id = NodeId::new();
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template(); let mut subgraph_template = NodeTemplate::empty_subgraph();
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else { let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
log::error!("Could not get center of selected_nodes"); log::error!("Could not get center of selected_nodes");
return; return;
}; };
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32); let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1)); subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
responses.add(DocumentMessage::AddTransaction); responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::InsertNode { responses.add(NodeGraphMessage::InsertNode {
node_id: encapsulating_node_id, node_id: encapsulating_node_id,
node_template: Box::new(default_node_template), node_template: Box::new(subgraph_template),
});
responses.add(NodeGraphMessage::SetDisplayNameImpl {
node_id: encapsulating_node_id,
network_path: selection_network_path.to_vec(),
alias: "Untitled Node".to_string(),
}); });
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id }); responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
@@ -2012,10 +2023,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
selected_nodes.set_selected_nodes(nodes); selected_nodes.set_selected_nodes(nodes);
responses.add(EventMessage::SelectionChanged); responses.add(EventMessage::SelectionChanged);
} }
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
}),
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
NodeGraphMessage::UnloadWires => { NodeGraphMessage::UnloadWires => {
self.frontend_wires.clear(); self.frontend_wires.clear();
responses.add(FrontendMessage::ClearAllNodeGraphWires); responses.add(FrontendMessage::ClearAllNodeGraphWires);
@@ -2530,13 +2537,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
HashSet::new() HashSet::new()
}; };
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>(); let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
for node_id in all_nodes { for node_id in all_nodes {
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else { let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
log::error!("Could not get transient metadata for node {node_id}"); log::error!("Could not get the body of node {node_id}");
continue; continue;
}; };
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]); if body.overlaps(selection_min, selection_max) {
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
if alt { if alt {
nodes.remove(&node_id); nodes.remove(&node_id);
} else { } else {
@@ -3198,11 +3205,6 @@ impl NodeGraphMessageHandler {
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList { pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp); let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
// Only development builds draw the click targets, so users don't come across the overlay by accident
if cfg!(debug_assertions) {
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
}
if self.has_selection { if self.has_selection {
common.extend(actions!(NodeGraphMessageDiscriminant; common.extend(actions!(NodeGraphMessageDiscriminant;
Copy, Copy,
@@ -3426,6 +3428,13 @@ impl NodeGraphMessageHandler {
}) })
.disabled(read_only) .disabled(read_only)
.widget_instance(), .widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("New Custom Node")
.tooltip_label("New Custom Node")
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
.disabled(read_only)
.widget_instance(),
// //
Separator::new(SeparatorStyle::Unrelated).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance(),
// //
@@ -2,7 +2,6 @@
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext}; use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
use super::utility_types::FrontendGraphDataType; 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::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::tooltip_markdown::{escape_markdown, markdown_code_span};
use crate::messages::layout::utility_types::widget_prelude::*; use crate::messages::layout::utility_types::widget_prelude::*;
@@ -21,6 +20,7 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput}; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
use graph_craft::{Type, concrete, item}; use graph_craft::{Type, concrete, item};
use graphene_std::RadialBlurMethod;
use graphene_std::animation::RealTimeMode; use graphene_std::animation::RealTimeMode;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::raster::{ use graphene_std::raster::{
@@ -32,7 +32,6 @@ use graphene_std::text::{Font, TextAlign};
use graphene_std::text_nodes::{StringCapitalization, TextDenomination}; use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve; use graphene_std::transfer_curve::TransferCurve;
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform}; 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::BooleanOperation;
use graphene_std::vector::misc::{ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod, ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
@@ -42,7 +41,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation, build_transform_with_y_preservation,
}; };
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector}; use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
use graphene_std::{NodeParameter, ParameterRef}; use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError}; use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf; use std::path::PathBuf;
@@ -307,7 +306,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
step, step,
} = options; } = options;
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch()); let mut number_input = NumberInput::default();
if slider { if slider {
number_input = number_input.mode_range(); number_input = number_input.mode_range();
} }
@@ -389,8 +388,6 @@ 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)), 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::<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::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
Some(x) if id_is::<String>(x) => match multiline { Some(x) if id_is::<String>(x) => match multiline {
true => text_area_widget(default_info).into(), true => text_area_widget(default_info).into(),
@@ -457,9 +454,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(), Some(x) if id_is::<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::<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::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(), Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(), Some(x) if id_is::<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::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(), Some(x) if id_is::<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::<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(), Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -900,7 +900,6 @@ 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 { 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 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 { let Some(input) = parameter_widgets_info.input() else {
log::warn!("A widget failed to be built because its node's input index is invalid."); log::warn!("A widget failed to be built because its node's input index is invalid.");
@@ -917,7 +916,6 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .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_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
.on_commit(commit_value) .on_commit(commit_value)
.widget_instance(), .widget_instance(),
@@ -929,7 +927,6 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .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_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
.on_commit(commit_value) .on_commit(commit_value)
.widget_instance(), .widget_instance(),
@@ -945,7 +942,6 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .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_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
.on_commit(commit_value) .on_commit(commit_value)
.widget_instance(), .widget_instance(),
@@ -957,7 +953,6 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.max((1_u64 << f64::MANTISSA_DIGITS) as f64) .max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.is_integer(is_integer) .is_integer(is_integer)
.disabled(disabled) .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_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
.on_commit(commit_value) .on_commit(commit_value)
.widget_instance(), .widget_instance(),
@@ -1326,92 +1321,6 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
widgets 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 // TODO: Auto-generate this enum dropdown menu widget
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup { pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info); let mut widgets = start_widgets(&parameter_widgets_info);
@@ -1512,7 +1421,6 @@ fn wire_element(ty: &Type) -> Type {
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> { fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
let vocabulary = [ let vocabulary = [
vec![concrete!(bool), concrete!(i64), concrete!(f64)], vec![concrete!(bool), concrete!(i64), concrete!(f64)],
vec![concrete!(Length), concrete!(Angle)],
vec![concrete!(DVec2)], vec![concrete!(DVec2)],
vec![concrete!(DAffine2)], vec![concrete!(DAffine2)],
vec![concrete!(Artboard)], vec![concrete!(Artboard)],
@@ -3864,6 +3772,29 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)] vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
} }
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::blending_nodes::filters::sharpen::*;
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
let edges_only = get_document_node(node_id, context)
.ok()
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
}
pub struct ParameterWidgetsInfo<'a> { pub struct ParameterWidgetsInfo<'a> {
document_id: DocumentId, document_id: DocumentId,
network_interface: &'a NodeNetworkInterface, network_interface: &'a NodeNetworkInterface,
@@ -4152,10 +4083,7 @@ mod tests {
fn math_expression_errors_quote_the_expression_safely() { 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 // 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("`abc").as_deref(), Some("`` `abc `` is not recognized"));
assert_eq!( assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
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 // A quoted token like `*` is a code span, so it can't pair with another into italics
let error = description("2 * * 3").unwrap(); let error = description("2 * * 3").unwrap();
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
"Color" => Self::Color, "Color" => Self::Color,
"Gradient" => Self::Gradient, "Gradient" => Self::Gradient,
"String" => Self::Typography, "String" => Self::Typography,
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number, "f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
// A generator draws pixels like an image, at whatever resolution is needed // A generator draws pixels like an image, at whatever resolution is needed
"Generator" => Self::Raster, "Generator" => Self::Raster,
raster if raster.starts_with("Raster") => Self::Raster, raster if raster.starts_with("Raster") => Self::Raster,
@@ -212,23 +212,6 @@ pub struct NodeEvaluationError {
pub message: String, pub message: String,
} }
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
pub struct FrontendClickTargets {
#[serde(rename = "nodeClickTargets")]
pub node_click_targets: Vec<String>,
#[serde(rename = "layerClickTargets")]
pub layer_click_targets: Vec<String>,
#[serde(rename = "connectorClickTargets")]
pub connector_click_targets: Vec<String>,
#[serde(rename = "iconClickTargets")]
pub icon_click_targets: Vec<String>,
#[serde(rename = "allNodesBoundingBox")]
pub all_nodes_bounding_box: String,
#[serde(rename = "importExportNames")]
pub import_export_names: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Direction { pub enum Direction {
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
pub struct OverlaysMessageContext<'a> { pub struct OverlaysMessageContext<'a> {
pub visibility_settings: OverlaysVisibilitySettings, pub visibility_settings: OverlaysVisibilitySettings,
pub viewport: &'a ViewportMessageHandler, pub viewport: &'a ViewportMessageHandler,
pub graph_open: bool,
} }
#[derive(Debug, Clone, Default, ExtractField)] #[derive(Debug, Clone, Default, ExtractField)]
@@ -25,7 +26,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
let overlay_context = OverlayContext::new(*viewport, visibility_settings); let overlay_context = OverlayContext::new(*viewport, visibility_settings);
if visibility_settings.all() { if visibility_settings.all() && !context.graph_open {
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() }); responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() }); responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
@@ -1,7 +1,7 @@
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand. //! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
use super::test_support::open_demo; use super::test_support::open_demo;
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector}; use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle; use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use glam::DVec2; use glam::DVec2;
use graphene_std::uuid::NodeId; use graphene_std::uuid::NodeId;
@@ -20,20 +20,32 @@ const DEMOS: [&str; 8] = [
const REPETITIONS: u32 = 200; const REPETITIONS: u32 = 200;
#[test] #[test]
fn wire_anchors_match_the_ports_of_every_demo_node() { fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
for demo in DEMOS { for demo in DEMOS {
let document = open_demo(demo); let document = open_demo(demo);
let interface = &document.network_interface; let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() { for node_id in interface.document_network().nodes.keys() {
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports"); // A redirect dot's wires attach at its center, between the gutters they're grabbed from
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
let on_port = |wanted: Part, anchor: Option<DVec2>| {
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
match (port, anchor) {
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
(Some(port), Some(anchor)) => port.contains(anchor),
(None, None) => true,
_ => false,
}
};
for index in 0..interface.number_of_inputs(node_id, &[]) { for index in 0..interface.number_of_inputs(node_id, &[]) {
let input = InputConnector::node_at_index(*node_id, index); let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}"); assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
} }
for index in 0..interface.number_of_outputs(node_id, &[]) { for index in 0..interface.number_of_outputs(node_id, &[]) {
let output = OutputConnector::node(*node_id, index); let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}"); assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
} }
} }
} }
@@ -60,7 +72,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now(); let start = Instant::now();
for _ in 0..REPETITIONS { for _ in 0..REPETITIONS {
for node_id in &node_ids { for node_id in &node_ids {
std::hint::black_box(interface.node_click_targets(node_id, &[])); std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
} }
} }
let all_click_targets = start.elapsed() / REPETITIONS; let all_click_targets = start.elapsed() / REPETITIONS;
@@ -296,29 +296,6 @@ 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 /// 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. /// the view map, then apply it onto a fresh handler and confirm each field matches.
#[test] #[test]
@@ -35,7 +35,6 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) { if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_absolute_position(*position); node.set_absolute_position(*position);
} }
interface.invalidate_positions(network_path);
} }
} }
@@ -172,14 +171,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
interface.finish_drag(&[]); interface.finish_drag(&[]);
let kept = interface.positions(node_ids.iter().copied(), &[]); let kept = interface.positions(node_ids.iter().copied(), &[]);
let Some((_, indices, graph)) = interface.layout_graph(&[]) else { let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
panic!("the root network is laid out") panic!("the root network is laid out")
}; };
let fresh = graph_layout::Layout::new(&graph); let fresh = graph_layout::Layout::new(&graph);
for (other, position) in kept { for (other, position) in kept {
assert_eq!( assert_eq!(
Some(position), Some(position),
indices.get(&other).map(|index| fresh.node(*index).position), laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it" "After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
); );
} }
@@ -22,6 +22,7 @@ mod layout;
mod layout_pass; mod layout_pass;
mod memo_network; mod memo_network;
mod mutations; mod mutations;
mod node_parts;
mod queries; mod queries;
mod reconcile; mod reconcile;
mod resolved_types; mod resolved_types;
@@ -36,6 +37,7 @@ mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange}; pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use layout_pass::NetworkLayout; pub use layout_pass::NetworkLayout;
pub use node_parts::{Part, PartTarget};
pub use reconcile::{ReconcileError, Reconciled}; pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded; use store::Guarded;
pub use store::NodeLocator; pub use store::NodeLocator;
@@ -52,7 +54,7 @@ use crate::consts::{
STACK_VERTICAL_GAP, STACK_VERTICAL_GAP,
}; };
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput}; use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes; use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
use crate::messages::portfolio::document::utility_types::text_metrics::text_width; use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire}; use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
EditorDelta::NodeMetadata { network, node_id, change } => { EditorDelta::NodeMetadata { network, node_id, change } => {
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return }; let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
match change { match change {
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()), NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()), NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
NodeMetadataChange::Locked(locked) => node.set_locked(*locked), NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned), NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
@@ -105,7 +105,6 @@ impl NodeNetworkInterface {
match change { match change {
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()), NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.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::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()), NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()), NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
@@ -88,34 +88,15 @@ impl NodeNetworkInterface {
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets; *network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
} }
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> { /// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
self.load_import_export_ports(network_path);
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
}
/// Reads the import/export ports through &self, loading them first if needed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> { pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
self.network_metadata(network_path)? let generation = self.with_layout(network_path, NetworkLayout::generation)?;
.transient_metadata let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
.import_export_ports if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
.with_loaded_or(|| self.compute_import_export_ports(network_path), read) cache.unload();
} }
pub fn load_import_export_ports(&self, network_path: &[NodeId]) { cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
} }
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) { pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
@@ -126,78 +107,13 @@ impl NodeNetworkInterface {
transient.import_export_ports.unload(); transient.import_export_ports.unload();
} }
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
return None;
};
let bounding_box = network_metadata
.transient_metadata
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
/// The combined bounds of every node in the network, in node graph space. /// The combined bounds of every node in the network, in node graph space.
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> { pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let network_metadata = self.network_metadata(network_path)?; self.with_layout(network_path, NetworkLayout::bounds)
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
Some(
nodes
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
)
}
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
return;
};
transient.all_nodes_bounding_box.unload();
transient.import_export_clearance.unload();
self.unload_import_export_ports(network_path);
} }
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> { pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let Some(network_metadata) = self.network_metadata(network_path) else { self.with_layout(network_path, NetworkLayout::clearance)
log::error!("Could not get nested network_metadata in import_export_clearance");
return None;
};
network_metadata
.transient_metadata
.import_export_clearance
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
}
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let network_metadata = self.network_metadata(network_path)?;
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut clearance = ImportExportClearance::default();
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
continue;
};
if self.is_redirect_dot(node_id, network_path) {
let center = (top_left.x + bottom_right.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
}
}
Some(clearance)
} }
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> { pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
@@ -364,6 +280,10 @@ impl NodeNetworkInterface {
} }
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> { pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
}
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else { let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in layer_width"); log::error!("Could not get nested node_metadata in layer_width");
return None; return None;
@@ -376,7 +296,7 @@ impl NodeNetworkInterface {
node_metadata node_metadata
.transient_metadata .transient_metadata
.layer_width .layer_width
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width) .with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
} }
/// Unloads layer width if the node is a layer. /// Unloads layer width if the node is a layer.
@@ -475,7 +395,7 @@ impl NodeNetworkInterface {
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path)); let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start; let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style); let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end); let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
let path_string = vector_wire.to_svg(); let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg(); let center_path_string = center_line.to_svg();
@@ -523,7 +443,7 @@ impl NodeNetworkInterface {
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path)); let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
let thick = vertical_end && vertical_start; let thick = vertical_end && vertical_start;
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style); let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end); let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
Some((vector_wire, center_line, thick)) Some((vector_wire, center_line, thick))
} }
@@ -549,17 +469,10 @@ impl NodeNetworkInterface {
} }
/// The node's body, ports, and handles, built where it is drawn now. /// The node's body, ports, and handles, built where it is drawn now.
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> { /// The box around the node's body where it sits in its grid cell, in node graph space.
self.compute_node_click_targets(node_id, network_path)
}
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> { pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box()) let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
.flatten() Some([body.min, body.max])
} }
} }
@@ -1,4 +1,4 @@
use super::template::NodeTemplateImplementation; use super::template::{NodeTemplate, NodeTemplateImplementation};
use super::{InputConnector, OutputConnector, catalog}; use super::{InputConnector, OutputConnector, catalog};
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type}; use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd; use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() { async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await; editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]); assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
let custom = NodeId::new(); let custom = NodeId::new();
let blend = NodeId::new(); let blend = NodeId::new();
let interface = &mut editor.active_document_mut().network_interface; let interface = &mut editor.active_document_mut().network_interface;
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]); interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]); interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else { let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
panic!("the Blend should name a table entry") panic!("the Blend should name a table entry")
@@ -2,7 +2,7 @@ use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
}; };
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS}; use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState; use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type; use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction}; use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
@@ -330,7 +330,6 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
} }
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3)))); let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative); network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
network_interface.invalidate_positions(&[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7))); assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
@@ -3119,7 +3118,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let path = [subgraph]; let path = [subgraph];
editor.enter_editable_network(subgraph).await; editor.enter_editable_network(subgraph).await;
@@ -3506,7 +3505,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export. /// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) { async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
editor.enter_editable_network(subgraph).await; editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddImport).await; editor.handle_message(NodeGraphMessage::AddImport).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await; editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
@@ -4041,18 +4040,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
); );
} }
#[tokio::test]
async fn a_new_subgraph_is_its_own_definition() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &editor.active_document().network_interface;
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
}
#[tokio::test] #[tokio::test]
async fn cannot_preview_node_without_outputs() { async fn cannot_preview_node_without_outputs() {
let mut editor = EditorTestUtils::create(); let mut editor = EditorTestUtils::create();
editor.new_document().await; editor.new_document().await;
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await; let subgraph = editor.create_empty_subgraph_at(0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface; let network_interface = &mut editor.active_document_mut().network_interface;
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0); assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
// Attempting to toggle preview on a node without outputs should not enable previewing // Attempting to toggle preview on a node without outputs should not enable previewing
network_interface.toggle_preview(custom_node, &[]); network_interface.toggle_preview(subgraph, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No); assert_eq!(network_interface.previewing(&[]), Previewing::No);
} }
@@ -4216,3 +4227,73 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
assert_eq!(overlapping_layers(&editor), Vec::new()); assert_eq!(overlapping_layers(&editor), Vec::new());
assert_invariants(&editor, "after grouping a group"); assert_invariants(&editor, "after grouping a group");
} }
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
let interface = &editor.active_document().network_interface;
let parent = layer.parent(interface.document_metadata())?;
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
}
#[tokio::test]
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
for x in [0., 50., 100.] {
editor.draw_rect(x, 0., x + 40., 40.).await;
}
let artboard = LayerNodeIdentifier::ROOT_PARENT
.children(editor.active_document().metadata())
.next()
.expect("the artboard should be a layer");
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
group_selected_layers(&mut editor).await;
let group = artboard
.children(editor.active_document().metadata())
.next()
.expect("the group should be the top layer of the artboard");
for insert_index in [0, 2] {
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
for layer in group.children(editor.active_document().metadata()).chain([group]) {
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
}
}
assert_eq!(overlapping_layers(&editor), Vec::new());
}
#[tokio::test]
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(new_artboard_message(NodeId::new())).await;
for x in [0., 50., 100., 150.] {
editor.draw_rect(x, 0., x + 40., 40.).await;
}
let artboard = LayerNodeIdentifier::ROOT_PARENT
.children(editor.active_document().metadata())
.next()
.expect("the artboard should be a layer");
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
let interface = &mut editor.active_document_mut().network_interface;
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
for keep_upstream in [false, true] {
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
let before = interface.positions(layers.iter().copied(), &[]);
interface.drag_selected_nodes(offset, keep_upstream, &[]);
let dragging = interface.positions(layers.iter().copied(), &[]);
interface.finish_drag(&[]);
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
}
}
}
@@ -62,11 +62,21 @@ pub enum NodeMetadataChange {
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which /// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
/// merge independently, so a concurrent move and a concurrent layer toggle both survive. /// merge independently, so a concurrent move and a concurrent layer toggle both survive.
NodeType(NodeTypePersistentMetadata), NodeType(NodeTypePersistentMetadata),
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
Position(NodeTypePersistentMetadata),
DisplayName(String), DisplayName(String),
Locked(bool), Locked(bool),
Pinned(bool), Pinned(bool),
} }
impl NodeMetadataChange {
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
}
}
/// One field of a network's persistent metadata. The navigation transform and width are absent /// One field of a network's persistent metadata. The navigation transform and width are absent
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry. /// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@@ -75,7 +85,6 @@ pub enum NetworkMetadataChange {
Reference(Option<String>), Reference(Option<String>),
/// The whole order, since the encoding is one array-valued attribute rather than a slot each. /// The whole order, since the encoding is one array-valued attribute rather than a slot each.
PinnedOrder(Vec<NodeId>), PinnedOrder(Vec<NodeId>),
PixelsPerInch(Option<f64>),
ImportMetadata(Vec<InputMetadata>), ImportMetadata(Vec<InputMetadata>),
ExportNames(Vec<String>), ExportNames(Vec<String>),
ExportDescriptions(Vec<String>), ExportDescriptions(Vec<String>),
@@ -257,12 +266,6 @@ impl EditorDelta {
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?, 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::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?, NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?, NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
@@ -326,6 +329,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))), node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
] ]
} }
NodeMetadataChange::Position(node_type) => vec![node_attribute(
node_attr::ui::POSITION,
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
)],
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))], NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))], NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))], NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
@@ -3,6 +3,7 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
use super::storage_metadata::StorageMetadataView; use super::storage_metadata::StorageMetadataView;
use super::{InputConnector, NodeTemplate}; use super::{InputConnector, NodeTemplate};
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::delta::compute_deltas; use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session}; use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
@@ -184,7 +185,7 @@ async fn per_field_metadata_edits_match_the_diff() {
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())), metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)), metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)), metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())), metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
EditorDelta::Graph(RuntimeDelta::SetVisibility { EditorDelta::Graph(RuntimeDelta::SetVisibility {
network: None, network: None,
node_id: node, node_id: node,
@@ -283,6 +284,32 @@ async fn unchanged_writes_emit_nothing() {
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}"); assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
} }
#[tokio::test]
async fn moving_a_layer_writes_only_its_position() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 40., 40.).await;
let layer = LayerNodeIdentifier::ROOT_PARENT
.children(editor.active_document().metadata())
.next()
.expect("the rectangle should be a layer")
.to_node();
let working = convert(&editor);
editor.active_document_mut().network_interface.discard_deltas();
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
let emitted = committed_deltas(&mut editor);
let written: Vec<String> = construct(&editor, &emitted, &working)
.into_iter()
.filter_map(|op| match op {
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
_ => None,
})
.collect();
assert_eq!(written, [node_attr::ui::POSITION]);
}
/// Structural writes go through the store too, so inserting and deleting a node must be recorded /// Structural writes go through the store too, so inserting and deleting a node must be recorded
/// without the caller saying anything about it. /// without the caller saying anything about it.
#[tokio::test] #[tokio::test]
@@ -46,193 +46,6 @@ impl NodeNetworkInterface {
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.))) (!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
} }
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_ports for node {node_id}");
return None;
};
let document_node = self.document_node(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut ports = Ports::new();
if self.is_redirect_dot(node_id, network_path) {
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
} else if !self.is_layer(node_id, network_path) {
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
ports.insert_node_input(input_index, input_row_count, node_top_left);
}
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
ports.insert_node_output(output_index, node_top_left);
}
} else {
ports.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
ports.insert_layer_input(1, node_top_left);
}
ports.insert_layer_output(node_top_left);
}
Some(ports)
}
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
return None;
};
let node_metadata = self.node_metadata(node_id, network_path)?;
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
if self.is_redirect_dot(node_id, network_path) {
const DOT_HALF_WIDTH: f64 = 15.;
const DOT_HALF_HEIGHT: f64 = 8.;
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
let path = rounded_rectangle_path(
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
[DOT_HALF_HEIGHT; 4],
);
return Some(DocumentNodeClickTargets {
node_click_target: ClickTarget::new_with_path(path, 0.),
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
});
}
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
Some(document_node_click_targets)
}
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu. /// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
/// Laid out as the frontend draws them, just past the connector. /// Laid out as the frontend draws them, just past the connector.
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> { pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
@@ -339,9 +152,9 @@ impl NodeNetworkInterface {
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count)) Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
} }
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached /// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
/// because measuring the name's text is slow. /// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 { pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
const GAP_WIDTH: f64 = 8.; const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.; const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.; let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
@@ -356,7 +169,7 @@ impl NodeNetworkInterface {
let icon_overhang_width = GRID_SIZE as f64 / 2.; let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width; let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
((layer_width_pixels / 24.).ceil() as u32).max(8) (((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
} }
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> { pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else { let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
@@ -24,81 +24,6 @@ impl NodeNetworkInterface {
all_selected_nodes all_selected_nodes
} }
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
let mut all_node_click_targets = Vec::new();
let mut connector_click_targets = Vec::new();
let mut icon_click_targets = Vec::new();
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
return FrontendClickTargets::default();
};
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
self.with_import_export_ports(network_path, |import_export_click_targets| {
for port in import_export_click_targets.click_targets() {
if let ClickTargetType::Path(path) = port.target_type() {
connector_click_targets.push(path.to_svg());
}
}
});
nodes.into_iter().for_each(|node_id| {
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
let mut node_path = String::new();
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
node_path.push_str(path.to_svg().as_str())
}
all_node_click_targets.push((node_id, node_path));
for port in node_click_targets.port_click_targets.click_targets() {
if let ClickTargetType::Path(path) = port.target_type() {
connector_click_targets.push(path.to_svg());
}
}
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
// Visibility button (eye icon)
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
icon_click_targets.push(path.to_svg());
}
// Lock button (padlock icon), only when the layer is locked
if let Some(lock_click_target) = &layer_metadata.lock_click_target
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
{
icon_click_targets.push(path.to_svg());
}
// Drag grip (dotted symbol)
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
icon_click_targets.push(path.to_svg());
}
}
});
});
let mut layer_click_targets = Vec::new();
let mut node_click_targets = Vec::new();
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
if self.is_layer(&node_id, network_path) {
layer_click_targets.push(path);
} else {
node_click_targets.push(path);
}
});
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
let import_export_names = self
.import_export_name_bounds(network_path)
.into_iter()
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
.collect();
FrontendClickTargets {
node_click_targets,
layer_click_targets,
connector_click_targets,
icon_click_targets,
all_nodes_bounding_box,
import_export_names,
}
}
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) { pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
self.document_metadata.document_to_viewport = transform; self.document_metadata.document_to_viewport = transform;
} }
@@ -123,6 +48,24 @@ impl NodeNetworkInterface {
Some(&mut navigation.node_graph_ptz) Some(&mut navigation.node_graph_ptz)
} }
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
/// grid cell, and an input by its index rather than the row a node draws it in.
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
self.with_layout(network_path, |layout| {
layout.find_part(node_id, |target| {
let part = match target.part {
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
part => part,
};
find(part, target)
})
})
.flatten()
}
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets. /// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> { pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
let Some(network_metadata) = self.network_metadata(network_path) else { let Some(network_metadata) = self.network_metadata(network_path) else {
@@ -133,16 +76,13 @@ impl NodeNetworkInterface {
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
// Each node is pressed where it's drawn, even while gliding into its grid cell // Each node is pressed where it's drawn, even while gliding into its grid cell
let glide_offsets = self.glide_offsets(network_path); let glide_offsets = self.glide_offsets(network_path);
let clicked_nodes = self let reaching = self.nodes_reaching(point, network_path);
.nodes_reaching(point, network_path) let clicked_nodes = self.with_layout(network_path, |layout| {
.iter() reaching
.filter(|node_id| { .into_iter()
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { .filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id)) .collect::<Vec<_>>()
}) == Some(true) })?;
})
.cloned()
.collect::<Vec<_>>();
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order // Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
let drawing_layer = |node_id: &NodeId| { let drawing_layer = |node_id: &NodeId| {
if self.is_redirect_dot(node_id, network_path) { if self.is_redirect_dot(node_id, network_path) {
@@ -165,25 +105,18 @@ impl NodeNetworkInterface {
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click); let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path); let glide_offsets = self.glide_offsets(network_path);
self.nodes_reaching(point, network_path) let wanted = match click_target_type {
.iter() LayerClickTargetTypes::Visibility => Part::Visibility,
.filter_map(|node_id| { LayerClickTargetTypes::Lock => Part::Lock,
let point = point - glide_offsets.node(node_id); LayerClickTargetTypes::Grip => Part::Grip,
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { LayerClickTargetTypes::Name => Part::Name,
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata { };
match click_target_type {
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id), self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)), let point = point - glide_offsets.node(node_id);
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id), self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)), .is_some()
} })
} else {
None
}
})
.flatten()
})
.next()
} }
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center. /// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
@@ -269,13 +202,11 @@ impl NodeNetworkInterface {
.iter() .iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id)) .filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| { .filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { let point = point - glide_offsets.node(node_id);
transient_node_metadata self.find_node_part(node_id, network_path, |part, target| match part {
.port_click_targets Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
.clicked_input_port_from_point(point - glide_offsets.node(node_id)) _ => None,
.map(|port| InputConnector::node_at_index(*node_id, port))
}) })
.flatten()
}) })
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path)) .find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
.or_else(|| { .or_else(|| {
@@ -302,13 +233,11 @@ impl NodeNetworkInterface {
.iter() .iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id)) .filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| { .filter_map(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| { let point = point - glide_offsets.node(node_id);
transient_node_metadata self.find_node_part(node_id, network_path, |part, target| match part {
.port_click_targets Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
.clicked_output_port_from_point(point - glide_offsets.node(node_id)) _ => None,
.map(|output_index| OutputConnector::node(*node_id, output_index))
}) })
.flatten()
}) })
.next() .next()
.or_else(|| { .or_else(|| {
@@ -426,3 +355,17 @@ impl NodeNetworkInterface {
(layer_widths, chain_widths, has_left_input_wire) (layer_widths, chain_widths, has_left_input_wire)
} }
} }
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
let mut current_row = 0;
for (index, input) in inputs.iter().enumerate() {
if input.is_exposed() && current_row == row {
return Some(index);
}
if index == 0 || input.is_exposed() {
current_row += 1;
}
}
None
}
@@ -6,10 +6,6 @@
use super::*; use super::*;
impl NodeNetworkInterface { impl NodeNetworkInterface {
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
self.unload_all_nodes_bounding_box(network_path);
}
/// Unloads the network's import and export ports. /// Unloads the network's import and export ports.
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) { pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
self.unload_import_export_ports(network_path); self.unload_import_export_ports(network_path);
@@ -17,6 +13,5 @@ impl NodeNetworkInterface {
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) { pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path); self.try_unload_layer_width(node_id, network_path);
self.unload_all_nodes_bounding_box(network_path);
} }
} }
@@ -52,7 +52,6 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest. /// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
@@ -145,7 +144,6 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
/// Sets the position of a layer to a stack position /// Sets the position of a layer to a stack position
@@ -159,8 +157,6 @@ impl NodeNetworkInterface {
} else if node.set_stack_position(y_offset) { } else if node.set_stack_position(y_offset) {
self.transaction_modified(); self.transaction_modified();
} }
self.invalidate_positions(network_path);
} }
/// Sets the position of a node to a stack position without changing its y offset /// Sets the position of a node to a stack position without changing its y offset
@@ -371,7 +367,6 @@ impl NodeNetworkInterface {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return }; let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
if node.shift_absolute_position(position - current_position) { if node.shift_absolute_position(position - current_position) {
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
} }
@@ -1,7 +1,9 @@
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
use super::*; use super::*;
use glam::UVec2; use glam::UVec2;
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire}; use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
use std::cell::RefCell; use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
const REACH_MARGIN: f64 = 16.; const REACH_MARGIN: f64 = 16.;
@@ -9,13 +11,53 @@ const REACH_MARGIN: f64 = 16.;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct NetworkLayout { pub struct NetworkLayout {
revision: u64, revision: u64,
generation: u64,
node_ids: Vec<NodeId>, node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>, indices: HashMap<NodeId, NodeIndex>,
graph: Graph, graph: Graph,
shapes: Vec<NodeShape>,
layout: Layout, layout: Layout,
bounds: [DVec2; 2],
clearance: ImportExportClearance,
} }
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
impl NetworkLayout { impl NetworkLayout {
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let mut network_layout = Self {
revision,
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
node_ids,
indices,
graph,
shapes,
layout,
bounds: [DVec2::ZERO; 2],
clearance: ImportExportClearance::default(),
};
network_layout.measure_bounds_and_clearance();
network_layout
}
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
let Self {
node_ids,
indices,
shapes,
graph,
layout,
..
} = self;
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
}
pub fn generation(&self) -> u64 {
self.generation
}
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> { pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
Some(self.node(node_id)?.position) Some(self.node(node_id)?.position)
} }
@@ -53,6 +95,33 @@ impl NetworkLayout {
self.node(layer).map_or(0, |node| node.chain_length) self.node(layer).map_or(0, |node| node.chain_length)
} }
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
pub fn bounds(&self) -> [DVec2; 2] {
self.bounds
}
/// What the imports and exports keep their distance from horizontally.
pub(crate) fn clearance(&self) -> ImportExportClearance {
self.clearance
}
/// The node's body where it sits in its grid cell, in node graph space.
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
Some(self.placed(*self.indices.get(node_id)?).body())
}
/// The first of the node's parts, its body last, that `find` picks something from.
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
let placed = self.placed(*self.indices.get(node_id)?);
let mut found = None;
placed.parts(|target| {
if found.is_none() {
found = find(&target);
}
});
found
}
/// Whether `point`, in node graph space, lies within the box around everything the node draws. /// Whether `point`, in node graph space, lies within the box around everything the node draws.
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool { pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
let Some(index) = self.indices.get(node_id) else { return false }; let Some(index) = self.indices.get(node_id) else { return false };
@@ -62,6 +131,38 @@ impl NetworkLayout {
point.cmpge(min).all() && point.cmplt(max).all() point.cmpge(min).all() && point.cmplt(max).all()
} }
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
let node_layout = self.layout.node(index);
PlacedNode {
node: &self.graph[index],
shape: &self.shapes[index.index()],
position: node_layout.position,
chain_length: node_layout.chain_length,
}
}
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
fn measure_bounds_and_clearance(&mut self) {
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut bounds: Option<[DVec2; 2]> = None;
let mut clearance = ImportExportClearance::default();
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
let body = self.placed(index).body();
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
if self.graph[index].kind == NodeKind::Waypoint {
let center = (body.min.x + body.max.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
}
}
self.bounds = bounds.unwrap_or_default();
self.clearance = clearance;
}
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> { fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
Some(self.layout.node(*self.indices.get(node_id)?)) Some(self.layout.node(*self.indices.get(node_id)?))
} }
@@ -86,12 +187,14 @@ struct DragOrigin {
keep_upstream: bool, keep_upstream: bool,
node_ids: Vec<NodeId>, node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>, indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
start: Graph, start: Graph,
drag: Drag, drag: Drag,
} }
impl DragOrigin { impl DragOrigin {
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self { fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect(); let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
Self { Self {
revision, revision,
@@ -99,6 +202,7 @@ impl DragOrigin {
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream), drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
node_ids, node_ids,
indices, indices,
shapes,
start, start,
} }
} }
@@ -154,7 +258,6 @@ impl NodeNetworkInterface {
} }
} }
transient.layout.unload(); transient.layout.unload();
self.invalidate_positions(network_path);
} }
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag. /// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
@@ -178,9 +281,14 @@ impl NodeNetworkInterface {
.filter(|((before, after), _)| before.placement != after.placement) .filter(|((before, after), _)| before.placement != after.placement)
.map(|((_, after), node_id)| (*node_id, after.placement)) .map(|((_, after), node_id)| (*node_id, after.placement))
.collect(); .collect();
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved) let laid_out = LaidOutNodes {
node_ids: std::mem::take(&mut origin.node_ids),
indices: std::mem::take(&mut origin.indices),
shapes: std::mem::take(&mut origin.shapes),
};
(moved_placements, laid_out, moved)
}); });
let Some((moved_placements, node_ids, indices, graph)) = finished else { return }; let Some((moved_placements, laid_out, graph)) = finished else { return };
let mut stored_all = true; let mut stored_all = true;
for (node_id, placement) in moved_placements { for (node_id, placement) in moved_placements {
@@ -189,13 +297,7 @@ impl NodeNetworkInterface {
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) { if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
let layout = Layout::new(&graph); let layout = Layout::new(&graph);
network_metadata.transient_metadata.layout.store(NetworkLayout { network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
revision: store::revision(),
layout,
graph,
node_ids,
indices,
});
} }
} }
@@ -208,16 +310,15 @@ impl NodeNetworkInterface {
let transient = self.network_transient_mut(network_path)?; let transient = self.network_transient_mut(network_path)?;
let drag = transient.drag.take()?; let drag = transient.drag.take()?;
transient.layout.unload(); transient.layout.unload();
self.invalidate_positions(network_path);
Some(drag) Some(drag)
} }
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> { fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
let mut origin = drag.origin.borrow_mut(); let mut origin = drag.origin.borrow_mut();
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) { if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
let (node_ids, indices, start) = self.layout_graph(network_path)?; let (laid_out, start) = self.layout_graph(network_path)?;
let start_layout = Layout::new(&start); let start_layout = Layout::new(&start);
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision)); *origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
} }
origin.as_mut().map(read) origin.as_mut().map(read)
} }
@@ -227,8 +328,8 @@ impl NodeNetworkInterface {
let cache = &self.network_metadata(network_path)?.transient_metadata.layout; let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?; let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached; let (laid_out, graph, layout) = cached.into_parts();
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision)) Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
} }
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool { fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
@@ -246,40 +347,38 @@ impl NodeNetworkInterface {
}; };
if node.set_node_type(node_type) { if node.set_node_type(node_type) {
self.transaction_modified(); self.transaction_modified();
self.invalidate_positions(network_path);
} }
true true
} }
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> { fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag { let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| { Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
let (graph, mut layout) = origin.drag.moved(drag.offset); let (graph, mut layout) = origin.drag.moved(drag.offset);
layout.snap_chains(&graph); layout.snap_chains(&graph);
(origin.node_ids.clone(), origin.indices.clone(), graph, layout) let laid_out = LaidOutNodes {
node_ids: origin.node_ids.clone(),
indices: origin.indices.clone(),
shapes: origin.shapes.clone(),
};
(laid_out, graph, layout)
})?, })?,
None => { None => {
let (node_ids, indices, graph) = self.layout_graph(network_path)?; let (laid_out, graph) = self.layout_graph(network_path)?;
let layout = Layout::new(&graph); let layout = Layout::new(&graph);
(node_ids, indices, graph, layout) (laid_out, graph, layout)
} }
}; };
Some(NetworkLayout { Some(NetworkLayout::new(revision, laid_out, graph, layout))
revision,
layout,
graph,
node_ids,
indices,
})
} }
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> { pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
let network = self.nested_network(network_path)?; let network = self.nested_network(network_path)?;
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect(); let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect(); let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?; let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
let wires = node_ids let wires = node_ids
.iter() .iter()
.enumerate() .enumerate()
@@ -297,10 +396,10 @@ impl NodeNetworkInterface {
}) })
.collect(); .collect();
Some((node_ids, indices, Graph { nodes, wires })) Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
} }
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> { fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
let metadata = self.node_metadata(node_id, network_path)?; let metadata = self.node_metadata(node_id, network_path)?;
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata { let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => match layer.position { NodeTypePersistentMetadata::Layer(layer) => match layer.position {
@@ -314,17 +413,40 @@ impl NodeNetworkInterface {
}; };
let is_redirect_dot = self.is_redirect_dot(node_id, network_path); let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
let (layer_width, name_width) = if is_layer {
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
} else {
(0, 0.)
};
let (kind, size) = match (is_layer, is_redirect_dot) { let (kind, size) = match (is_layer, is_redirect_dot) {
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)), (true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))), (false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))), (false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
}; };
Some(Node {
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
let node = Node {
placement, placement,
kind, kind,
size: size.as_ivec2(), size: size.as_ivec2(),
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path), chainable: !is_redirect_dot && !primary_output_hidden,
held: false, held: false,
}) };
let shape = NodeShape {
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
outputs: self.number_of_outputs(node_id, network_path) as u32,
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
primary_output_hidden,
name_width,
locked: self.is_locked(node_id, network_path),
};
Some((node, shape))
} }
} }
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
pub(crate) struct LaidOutNodes {
pub(crate) node_ids: Vec<NodeId>,
pub(crate) indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
}
@@ -94,11 +94,9 @@ impl NodeNetworkInterface {
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false); self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
} }
// Update the outward wires and bounding box for all nodes in the encapsulating network // Update the outward wires for all nodes in the encapsulating network
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) { if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
encapsulating_transient.outward_wires.unload(); encapsulating_transient.outward_wires.unload();
encapsulating_transient.all_nodes_bounding_box.unload();
encapsulating_transient.import_export_clearance.unload();
} }
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure // An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
@@ -141,7 +139,6 @@ impl NodeNetworkInterface {
// Update the metadata for the encapsulating node // Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path); self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1; affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
} }
if affects_document_structure { if affects_document_structure {
@@ -179,7 +176,6 @@ impl NodeNetworkInterface {
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) { fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
// Update the metadata for the encapsulating node // Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path); self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) { if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false); self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
} }
@@ -572,8 +568,7 @@ impl NodeNetworkInterface {
/// Lightweight version of `set_input` for bulk import operations. /// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions, /// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and /// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) { pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) { if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762"); log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
@@ -673,8 +668,6 @@ impl NodeNetworkInterface {
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector { (NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
// Exposing or hiding a value input changes the node's port count // Exposing or hiding a value input changes the node's port count
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => { InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
self.unload_all_nodes_bounding_box(network_path);
// A nested network draws its interior ports from the encapsulating node's inputs // A nested network draws its interior ports from the encapsulating node's inputs
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) { if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
let nested_path = [network_path, &[*node_id]].concat(); let nested_path = [network_path, &[*node_id]].concat();
@@ -904,7 +897,6 @@ impl NodeNetworkInterface {
self.transaction_modified(); self.transaction_modified();
} }
self.unload_all_nodes_bounding_box(network_path);
self.unload_outward_wires(network_path); self.unload_outward_wires(network_path);
} }
@@ -927,7 +919,6 @@ impl NodeNetworkInterface {
} }
self.transaction_modified(); self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
previous_entry previous_entry
} }
@@ -1092,7 +1083,6 @@ impl NodeNetworkInterface {
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id))); outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
} }
self.unload_all_nodes_bounding_box(network_path);
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else { let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes"); log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
return; return;
@@ -1126,10 +1116,10 @@ impl NodeNetworkInterface {
} }
} }
let reconnected_offset = reconnect_to_input let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
.as_ref() let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
.and_then(NodeInput::as_node) Some((reconnected, offset))
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?))); });
let mut exports_fed_by_import = Vec::new(); let mut exports_fed_by_import = Vec::new();
@@ -1254,19 +1244,6 @@ impl NodeNetworkInterface {
self.transaction_modified(); 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) { 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 { 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"); log::error!("Could not get node {node_id} in set_visibility");
@@ -1378,7 +1355,6 @@ impl NodeNetworkInterface {
transient.layer_width.unload(); transient.layer_width.unload();
self.transaction_modified(); self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
self.invalidate_import_export(network_path); self.invalidate_import_export(network_path);
self.load_structure(); self.load_structure();
} }
@@ -0,0 +1,231 @@
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
use glam::{DVec2, IVec2};
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
const GRID: f64 = GRID_SIZE as f64;
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
const SIDE_PORT_INWARD_REACH: f64 = 8.;
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
const GRIP_WIDTH: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
/// What a node draws beyond the size the layout gives it.
#[derive(Clone, Copy, Debug, Default)]
pub struct NodeShape {
/// How many inputs have a port, which doesn't count a hidden primary input.
pub inputs: u32,
pub outputs: u32,
/// Whether a node's primary input has no port, though its row is still drawn.
pub primary_input_hidden: bool,
pub primary_output_hidden: bool,
/// The width of a layer's name in pixels.
pub name_width: f64,
pub locked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
/// A rounded rectangle of a node that reacts to the pointer.
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
/// A port on the left side of a node, reaching further out than over the node.
fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Input(input),
}
}
/// A port on the right side of a node, reaching further out than over the node.
fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Output(output),
}
}
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
/// Whether `point` is inside the rounded rectangle.
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
#[derive(Clone, Copy, Debug)]
pub struct PlacedNode<'a> {
pub node: &'a Node,
pub shape: &'a NodeShape,
pub position: IVec2,
pub chain_length: u32,
}
impl PlacedNode<'_> {
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
pub fn body(&self) -> PartTarget {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
match self.node.kind {
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: top_left - DVec2::new(self.chain_width(), 0.),
max: top_left + size,
corner_radius: 10.,
part: Part::Body,
},
NodeKind::Node => {
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
PartTarget {
min: body_top_left,
max: body_top_left + size - DVec2::new(0., GRID),
corner_radius: 3.,
part: Part::Body,
}
}
}
}
/// Calls `visit` with each part, the body last.
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.node.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.top_left() + DVec2::new(0., GRID);
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let width = self.node.size.x as f64 * GRID;
let row_center = |row: u32| GRID * (row as f64 + 1.);
let first_input_row = u32::from(self.shape.primary_input_hidden);
for row in first_input_row..first_input_row + self.shape.inputs {
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
}
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
}
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
let icon_half_size = DVec2::splat(HALF_GRID);
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
if self.shape.locked {
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
}
let icons_width = if self.shape.locked { GRID } else { 0. };
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
let handle_top = top_left.y + HALF_GRID;
let handle_bottom = top_left.y + GRID + HALF_GRID;
visit(PartTarget {
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
max: DVec2::new(grip_right, handle_bottom),
corner_radius: 0.,
part: Part::Grip,
});
let name_left = top_left.x + NAME_LEFT_OFFSET;
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, handle_top),
max: DVec2::new(name_right, handle_bottom),
corner_radius: 3.,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.position.as_dvec2() * GRID
}
fn has_side_input(&self) -> bool {
self.shape.inputs > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
}
}
@@ -128,18 +128,10 @@ impl NodeNetworkInterface {
}); });
let mut hasher = std::hash::DefaultHasher::new(); let mut hasher = std::hash::DefaultHasher::new();
(self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher); (self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
hasher.finish() 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 /// 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> { pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
self.query(network_path, "document_node", |view| view.node(node_id)) self.query(network_path, "document_node", |view| view.node(node_id))
@@ -810,7 +802,7 @@ impl NodeNetworkInterface {
self.query(network_path, "reference", |view| view.reference(node_id)).flatten() self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
} }
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found. /// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str { pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
self.reference(node_id, network_path) self.reference(node_id, network_path)
.and_then(|reference| resolve_document_node_type(&reference)?.icon) .and_then(|reference| resolve_document_node_type(&reference)?.icon)
@@ -883,16 +875,16 @@ impl NodeNetworkInterface {
node.set_widget_override(index, widget_override); node.set_widget_override(index, widget_override);
} }
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type. /// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String { pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id))) self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string()) .unwrap_or_else(|| "Subgraph".to_string())
} }
/// The uneditable name in the Inspector which represents the function name of the node implementation. /// The uneditable name in the Inspector which represents the function name of the node implementation.
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String { pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id))) self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
.unwrap_or_else(|| "Custom Node".to_string()) .unwrap_or_else(|| "Subgraph".to_string())
} }
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool { pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
@@ -143,9 +143,6 @@ impl NodeNetworkInterface {
if current_metadata.pinned_node_order != target.metadata.pinned_order { if current_metadata.pinned_node_order != target.metadata.pinned_order {
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone()))); 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 // 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(); 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 { if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
@@ -331,7 +328,10 @@ fn field_deltas(
} }
if current_metadata.node_type_metadata != target_metadata.node_type_metadata { if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone()))); deltas.push(metadata(NodeMetadataChange::placement(
&current_metadata.node_type_metadata,
target_metadata.node_type_metadata.clone(),
)));
} }
if current_metadata.display_name != target_metadata.display_name { if current_metadata.display_name != target_metadata.display_name {
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone()))); deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
@@ -111,10 +111,6 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> { fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default() 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<'_> { impl DocumentSettings<'_> {
@@ -311,7 +307,6 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
network_metadata.persistent_metadata.reference = Some(reference); network_metadata.persistent_metadata.reference = Some(reference);
} }
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order; 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.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_names = entry.export_names;
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions; network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
@@ -229,13 +229,14 @@ impl NodeMut<'_> {
/// Whether the node is displayed as a layer or a node, together with its position. /// Whether the node is displayed as a layer or a node, together with its position.
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool { pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
let changed = self.metadata.node_type_metadata != node_type; if self.metadata.node_type_metadata == node_type {
self.metadata.node_type_metadata = node_type; return false;
if changed {
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
self.deltas.metadata(change);
} }
changed
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
self.metadata.node_type_metadata = node_type;
self.deltas.metadata(change);
true
} }
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface. /// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
@@ -538,16 +539,6 @@ impl NetworkMut<'_> {
changed 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. /// The display order of pinned nodes in the Inspector.
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool { pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
let changed = self.metadata.pinned_node_order != pinned_node_order; let changed = self.metadata.pinned_node_order != pinned_node_order;
@@ -511,7 +511,6 @@ impl NodeNetworkInterface {
.into_iter() .into_iter()
.chain([ .chain([
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()), NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch),
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()), NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()), NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()), NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
} }
impl NodeTemplate { impl NodeTemplate {
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
pub fn empty_subgraph() -> Self {
Self {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
..Default::default()
}
}
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`]. /// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> { pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
self.inputs.get(P::INDEX) self.inputs.get(P::INDEX)
@@ -291,7 +299,6 @@ impl NodeTemplateImplementation {
reference, reference,
node_metadata, node_metadata,
pinned_node_order, pinned_node_order,
pixels_per_inch: None,
previewing, previewing,
navigation_metadata, navigation_metadata,
selection_undo_history: Default::default(), selection_undo_history: Default::default(),
@@ -3,12 +3,7 @@ use graphene_std::ParameterRef;
use graphene_std::vector::misc::dvec2_to_point; use graphene_std::vector::misc::dvec2_to_point;
use kurbo::{DEFAULT_ACCURACY, Shape}; use kurbo::{DEFAULT_ACCURACY, Shape};
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets. /// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
}
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath { pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)); let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
if radii.iter().all(|radius| *radius == 0.) { if radii.iter().all(|radius| *radius == 0.) {
@@ -19,16 +14,6 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY) kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
} }
/// Ellipse inscribed in the box spanning the two opposite corners.
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
path.close_path();
path
}
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document. /// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ChainNodeCopy { pub struct ChainNodeCopy {
@@ -292,13 +277,6 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)] [center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
} }
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
[center - HALF_SIZE, center + HALF_SIZE]
}
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget { pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
const CORNER_RADIUS: f64 = 4.; const CORNER_RADIUS: f64 = 4.;
@@ -332,13 +310,6 @@ impl Ports {
} }
} }
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
self.input_ports
.iter()
.map(|(_, click_target)| click_target)
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
}
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> { pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
self.input_ports.iter() self.input_ports.iter()
} }
@@ -348,51 +319,15 @@ impl Ports {
} }
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) { pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true))); self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
self.input_anchors.push((input_index, center)); self.input_anchors.push((input_index, center));
} }
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
self.input_ports.push((input_index, click_target));
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) { pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false))); self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
self.output_anchors.push((output_index, center)); self.output_anchors.push((output_index, center));
} }
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
self.output_ports.push((output_index, click_target));
}
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
self.insert_input_port_at_center(input_index, center);
}
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
self.insert_output_port_at_center(output_index, center);
}
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
if input_index == 0 {
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
} else {
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
}
}
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
// The center of the click target is 8 px above the layer, over its thumbnail
let center = node_top_left + DVec2::new(2. * 24., -8.);
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
}
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> { pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port)) self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
} }
@@ -401,37 +336,12 @@ impl Ports {
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port)) self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
} }
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
const GUTTER_OFFSET: f64 = 10.;
const GUTTER_RADIUS: f64 = 5.;
let gutter = |x_offset: f64| {
let gutter_center = center + DVec2::new(x_offset, 0.);
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
};
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
self.input_anchors.push((0, center));
self.output_anchors.push((0, center));
}
pub fn input_port_position(&self, index: usize) -> Option<DVec2> { pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) { self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
return Some(*anchor);
}
self.input_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
} }
pub fn output_port_position(&self, index: usize) -> Option<DVec2> { pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) { self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
return Some(*anchor);
}
self.output_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
} }
} }
@@ -674,9 +584,6 @@ pub struct NodeNetworkPersistentMetadata {
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID. /// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
#[serde(default)] #[serde(default)]
pub pinned_node_order: Vec<NodeId>, 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 /// 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. /// 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, pub previewing: Previewing,
@@ -750,16 +657,12 @@ impl<T> TransientCache<T> {
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct NodeNetworkTransientMetadata { pub struct NodeNetworkTransientMetadata {
pub selected_nodes: SelectedNodes, pub selected_nodes: SelectedNodes,
/// Cache for the bounding box around all nodes in node graph space.
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
/// Cache for all outward wire connections /// Cache for all outward wire connections
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>, pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
pub(crate) layout: TransientCache<NetworkLayout>, pub(crate) layout: TransientCache<NetworkLayout>,
pub(crate) drag: Option<super::layout_pass::DragPreview>, pub(crate) drag: Option<super::layout_pass::DragPreview>,
/// All export connector click targets /// The import and export connector click targets, with the generation of the layout they were placed by.
pub(crate) import_export_ports: TransientCache<Ports>, pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for. /// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>, pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
@@ -1176,40 +1079,8 @@ impl From<LegacyNodePosition> for NodePosition {
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields. /// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
pub struct DocumentNodeTransientMetadata { pub struct DocumentNodeTransientMetadata {
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers. /// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<u32>, pub(crate) layer_width: TransientCache<(u32, f64)>,
}
#[derive(Debug, Clone)]
pub struct DocumentNodeClickTargets {
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
pub node_click_target: ClickTarget,
/// Stores all port click targets in node graph space.
pub port_click_targets: Ports,
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
pub node_type_metadata: NodeTypeClickTargets,
}
#[derive(Debug, Clone)]
pub enum NodeTypeClickTargets {
Layer(Box<LayerClickTargets>),
Node, // No transient click targets are stored exclusively for nodes
}
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone)]
pub struct LayerClickTargets {
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
pub visibility_click_target: ClickTarget,
/// Cache for the lock icon button, only present when the layer is locked.
pub lock_click_target: Option<ClickTarget>,
/// Cache for the grip icon, which is next to the visibility button.
pub grip_click_target: ClickTarget,
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
/// `None` for layers whose display name is empty.
pub name_click_target: Option<ClickTarget>,
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
.ok() .ok()
.flatten() .flatten()
.map(|identifier| identifier.implementation_name_from_identifier()) .map(|identifier| identifier.implementation_name_from_identifier())
.unwrap_or("Custom Node".to_string()) .unwrap_or("Subgraph".to_string())
} }
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed. /// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
@@ -1,7 +1,7 @@
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType; use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
use glam::{DVec2, IVec2}; use glam::{DVec2, IVec2};
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point}; use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape}; use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -125,23 +125,27 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing (output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
} }
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output /// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires. /// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath { pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) { if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new(); return BezPath::new();
} }
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
let sign = (input_position.y - output_position.y).signum(); let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
let output_trim = 1.5; return BezPath::new();
let input_trim = 1.; };
let start = output_position + DVec2::new(0., output_trim * sign);
let end = input_position - DVec2::new(0., input_trim * sign);
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
let sign = (input_position.y - output_position.y).signum();
let mut center_line = BezPath::new(); let mut center_line = BezPath::new();
center_line.move_to(dvec2_to_point(start)); center_line.move_to(start - Vec2::new(0., 1.5 * sign));
center_line.line_to(dvec2_to_point(end)); center_line.line_to(start);
for element in wire.elements().iter().skip(1) {
center_line.push(*element);
}
center_line.line_to(end + Vec2::new(0., 2. * sign));
center_line center_line
} }
@@ -580,7 +584,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use kurbo::{Affine, Vec2}; use kurbo::{Affine, ParamCurveNearest};
#[test] #[test]
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() { fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
@@ -603,4 +607,30 @@ mod tests {
} }
} }
} }
#[test]
fn the_center_line_of_a_stack_wire_runs_inside_it() {
let ends = [
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
];
let half_wire_width = 4.;
for (output, input) in ends {
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
let wire = build_vector_wire(output, input, true, true, style);
let center_line = build_thick_wire_center_line(output, input, true, true, style);
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
for sample in samples {
let distance = wire
.segments()
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
.fold(f64::INFINITY, f64::min);
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
}
}
}
}
} }
@@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
} }
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present. // The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way. // Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths. // Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
.network_interface .network_interface
@@ -1468,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` // Lex a static expression once, learning both whether it lexes at all and whether it references `B`
let static_expression = match expression.as_value() { let static_expression = match expression.as_value() {
Some(TaggedValue::String(expression)) => Some(read_old_inverse_functions_as_radians(expression)), Some(TaggedValue::String(expression)) => Some(expression.clone()),
_ => None, _ => None,
}; };
let mut references_b = false; let mut references_b = false;
@@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}) })
.collect(); .collect();
migrate_custom_node_subgraphs(document);
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs // Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
let nodes = document let nodes = document
.network_interface .network_interface
@@ -4045,86 +4047,23 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(()) Some(())
} }
/// The old "Math" node's inverse trigonometric functions, each with the builtin that replaced it. /// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
const OLD_INVERSE_FUNCTIONS: [(&str, &str); 6] = [("invsin", "asin"), ("invcos", "acos"), ("invtan", "atan"), ("invcsc", "acsc"), ("invsec", "asec"), ("invcot", "acot")]; /// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
.map(|(node_id, _, path)| (*node_id, path))
.collect();
/// The old "Math" node's expression with each inverse trigonometric call, like `invsin(A)`, spelled as the builtin that replaced it for (node_id, network_path) in subgraphs {
/// and divided by `rad` as `(asin(A)/rad)`, since the builtin gives an angle where the old function gave plain radians. reset_default_display_name(document, &node_id, &network_path, "Custom Node");
fn read_old_inverse_functions_as_radians(expression: &str) -> String { reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
rewrite_old_inverse_calls(expression, 0) document.network_interface.set_reference(&node_id, &network_path, None);
}
/// 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. /// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
@@ -4679,6 +4618,45 @@ mod tests {
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}"); assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
} }
#[tokio::test]
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
let document = editor.active_document_mut();
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
panic!("the subgraph should name a definitions table entry")
};
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
let from_merging = NodeId::new();
let instance = NodeTemplate {
implementation: NodeTemplateImplementation::Definition(shared),
..Default::default()
};
document.network_interface.insert_node(from_merging, instance, &[]);
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
for node_id in [from_catalog, from_merging] {
assert!(
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
"the subgraph should still exist"
);
assert_eq!(interface.reference(&node_id, &[]), None);
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
}
}
#[tokio::test] #[tokio::test]
async fn a_rasterize_node_on_the_export_compiles() { async fn a_rasterize_node_on_the_export_compiles() {
use crate::test_utils::test_prelude::*; use crate::test_utils::test_prelude::*;
@@ -4935,11 +4913,10 @@ mod tests {
// The old inputs stay in place and the witness defaults to Number, the output type every such node had // 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 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(); let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(node.inputs.len(), 4); assert_eq!(node.inputs.len(), 3);
assert_eq!(value_at(0), Some(TaggedValue::Number(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(1), Some(TaggedValue::String("x^2".into())));
assert_eq!(value_at(2), Some(TaggedValue::Number(0.))); 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 // The same upgrade on a node whose value comes from upstream, where restoring the inputs has to preserve the wire
@@ -4971,7 +4948,7 @@ mod tests {
migrate(&mut document); migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id]; let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.inputs.len(), 4); assert_eq!(node.inputs.len(), 3);
assert!( assert!(
matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id), matches!(node.inputs.first(), Some(NodeInput::Node { node_id: upstream, .. }) if *upstream == source_id),
"the upstream wire was dropped by the upgrade, leaving {:?}", "the upstream wire was dropped by the upgrade, leaving {:?}",
@@ -5019,48 +4996,6 @@ mod tests {
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER); 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", // 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" // while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
#[test] #[test]
@@ -5127,8 +5062,8 @@ mod tests {
let node = &document.network_interface.document_network().nodes[&math_id]; let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!( assert_eq!(
node.inputs.len(), node.inputs.len(),
4, 3,
"the old `B` input should be dropped, leaving the value, the expression, the output-type witness, and the resolution" "the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
); );
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0))); 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()))); assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
-1
View File
@@ -11,7 +11,6 @@ pub use crate::messages::clipboard::{ClipboardMessage, ClipboardMessageContext,
pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler}; pub use crate::messages::color_picker::{ColorPickerMessage, ColorPickerMessageDiscriminant, ColorPickerMessageHandler};
pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler}; pub use crate::messages::debug::{DebugMessage, DebugMessageDiscriminant, DebugMessageHandler};
pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMessageHandler}; 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::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler}; pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler}; pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
@@ -194,15 +194,9 @@ impl RadiusHandle {
// The size is snapped, which keeps whichever sign the radius has come to // 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(); 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 { responses.add(NodeGraphMessage::SetInput {
input_connector, input_connector: InputConnector::node(node_id, radius_parameter),
input: NodeInput::value(radius, false), input: NodeInput::value(TaggedValue::Number(snapped_radius), false),
}); });
responses.add(NodeGraphMessage::RunDocumentGraph); responses.add(NodeGraphMessage::RunDocumentGraph);
} }
@@ -12,7 +12,6 @@ use crate::messages::tool::tool_messages::shape_tool::ShapeToolData;
use crate::messages::tool::tool_messages::tool_prelude::*; use crate::messages::tool::tool_messages::tool_prelude::*;
use graph_craft::document::NodeInput; use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue; use graph_craft::document::value::TaggedValue;
use graphene_std::units::TypedLength;
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
pub struct CircleGizmoHandler { pub struct CircleGizmoHandler {
@@ -109,7 +108,7 @@ impl Circle {
responses.add(NodeGraphMessage::SetInput { responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput), input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput),
input: NodeInput::value(TaggedValue::Length(TypedLength::pixels(radius)), false), input: NodeInput::value(TaggedValue::Number(radius), false),
}); });
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE)); responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
@@ -421,7 +421,11 @@ pub fn pointer_travel_per_radian(layer_to_viewport: DAffine2, pointer: DVec2) ->
pub fn extract_circle_radius(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<f64> { 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 node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER))?;
node_inputs.get(1)?.as_value()?.as_length_pixels(document.network_interface.pixels_per_inch()) let Some(&TaggedValue::Number(radius)) = node_inputs.get(1)?.as_value() else {
return None;
};
Some(radius)
} }
/// Calculate the viewport position of as a star vertex given its index /// Calculate the viewport position of as a star vertex given its index
+69 -59
View File
@@ -27,7 +27,7 @@ mod recompile_tests;
mod runtime; mod runtime;
pub use runtime::*; pub use runtime::*;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)] #[derive(Debug, Clone, Copy)]
pub struct ExecutionRequest { pub struct ExecutionRequest {
execution_id: u64, execution_id: u64,
render_config: RenderConfig, render_config: RenderConfig,
@@ -41,6 +41,15 @@ pub struct ExecutionResponse {
dropped_thumbnails: Vec<NodeId>, dropped_thumbnails: Vec<NodeId>,
/// The latest result of each observation. /// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>, observations: HashMap<ObservationKey, InspectResult>,
/// The canvas the frame was presented to
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info: Option<ViewportCanvasInfo>,
}
#[cfg(all(target_family = "wasm", feature = "wasm"))]
struct ViewportCanvasInfo {
id: u64,
resolution: DVec2,
} }
/// Names an observation so it can be changed or stopped without touching the others. /// Names an observation so it can be changed or stopped without touching the others.
@@ -192,18 +201,6 @@ impl NodeGraphExecutor {
self.canvas_images_sent.clear(); self.canvas_images_sent.clear();
} }
/// Allows the test runner to see if any more executions have been queued.
#[cfg(test)]
pub fn current_execution_id(&self) -> u64 {
self.current_execution_id
}
/// Allows the test runner to access last executions evaluation errors.
#[cfg(test)]
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
self.evaluation_errors.take()
}
/// Execute the network by flattening it and creating a borrow stack. /// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 { fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
let execution_id = self.current_execution_id; let execution_id = self.current_execution_id;
@@ -253,30 +250,6 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view"); .expect("Failed to send the thumbnails in view");
} }
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
#[cfg(test)]
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network);
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
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)
}
/// Update the cached network if necessary. /// Update the cached network if necessary.
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> { fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect; let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
@@ -302,7 +275,6 @@ impl NodeGraphExecutor {
previewed, previewed,
layers, layers,
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
} else if inspected_node_changed { } else if inspected_node_changed {
@@ -357,7 +329,6 @@ impl NodeGraphExecutor {
render_mode: document.render_mode, render_mode: document.render_mode,
for_export: false, for_export: false,
for_eyedropper: false, for_eyedropper: false,
pixels_per_inch: None,
}; };
// Execute the node graph // Execute the node graph
@@ -425,7 +396,6 @@ impl NodeGraphExecutor {
render_mode, render_mode,
for_export: false, for_export: false,
for_eyedropper: true, for_eyedropper: true,
pixels_per_inch: None,
}; };
// Execute the node graph // Execute the node graph
@@ -486,8 +456,6 @@ impl NodeGraphExecutor {
render_mode: graphene_std::vector::style::RenderMode::Normal, render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true, for_export: true,
for_eyedropper: false, for_eyedropper: false,
// 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 // Execute the node graph
@@ -498,7 +466,6 @@ impl NodeGraphExecutor {
previewed, previewed,
layers: document.network_interface.layer_paths(), layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
pixels_per_inch: document.network_interface.pixels_per_inch(),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config); let execution_id = self.queue_execution(render_config);
@@ -534,6 +501,8 @@ impl NodeGraphExecutor {
responses: existing_responses, responses: existing_responses,
dropped_thumbnails, dropped_thumbnails,
mut observations, mut observations,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info,
} = *execution_response; } = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -576,6 +545,29 @@ impl NodeGraphExecutor {
continue; continue;
} }
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let mut result = result;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
if let Some(canvas) = viewport_canvas_info {
let placeholder = format!(
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
canvas.resolution.x, canvas.resolution.y, canvas.id,
);
match result.render_output() {
Some(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => {
let end = svg.rfind("</svg>").unwrap_or(svg.len());
svg.insert_str(end, &placeholder);
}
_ => {
let svg = format!("<svg>{placeholder}</svg>");
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
}
}
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
// A pending graph keeps the last frame, and the errors shown with it // A pending graph keeps the last frame, and the errors shown with it
@@ -898,7 +890,6 @@ impl NodeGraphExecutor {
previewed: Vec::new(), previewed: Vec::new(),
layers: document.network_interface.layer_paths(), layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]), observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
pixels_per_inch: document.network_interface.pixels_per_inch(),
})) }))
.is_err() .is_err()
{ {
@@ -924,7 +915,6 @@ impl NodeGraphExecutor {
render_mode: document.render_mode, render_mode: document.render_mode,
for_export: false, for_export: false,
for_eyedropper: false, for_eyedropper: false,
pixels_per_inch: None,
}; };
let execution_id = self.queue_execution(render_config); let execution_id = self.queue_execution(render_config);
self.futures.push_back(( self.futures.push_back((
@@ -1045,11 +1035,6 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use }); responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
responses.add(FrontendMessage::UpdateDocumentArtwork { svg }); responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
} }
#[cfg(target_family = "wasm")]
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
let svg = format!("<svg>{}</svg>", viewport_canvas_placeholder(canvas_id, resolution));
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
RenderOutputType::Texture { .. } => {} RenderOutputType::Texture { .. } => {}
RenderOutputType::Buffer { width, height, .. } => { RenderOutputType::Buffer { width, height, .. } => {
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer"); log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
@@ -1214,15 +1199,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None None
} }
/// The SVG element the frontend replaces with the viewport canvas, covering the viewport at its logical `resolution`.
#[cfg(target_family = "wasm")]
fn viewport_canvas_placeholder(canvas_id: u64, resolution: DVec2) -> String {
format!(
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
resolution.x, resolution.y, canvas_id,
)
}
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile. /// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage { fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError { DialogMessage::DisplayDialogError {
@@ -1277,6 +1253,40 @@ mod test {
use graphene_std::list::Item; use graphene_std::list::Item;
use test_prelude::LayerNodeIdentifier; use test_prelude::LayerNodeIdentifier;
impl NodeGraphExecutor {
/// Allows the test runner to see if any more executions have been queued.
pub fn current_execution_id(&self) -> u64 {
self.current_execution_id
}
/// Allows the test runner to access last executions evaluation errors.
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
self.evaluation_errors.take()
}
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
// We should always invalidate the cache.
self.node_graph_hash = crate::application::generate_uuid();
let mut network = document.network_interface.document_network().clone();
network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network);
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
}
}
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received. /// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
#[derive(Default)] #[derive(Default)]
pub struct Instrumented { pub struct Instrumented {
+49 -67
View File
@@ -20,7 +20,7 @@ use graphene_std::vector::style::RenderMode;
use graphene_std::{Context, NodeError, Poll}; use graphene_std::{Context, NodeError, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta}; use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::layer_paths::write_layer_paths; use interpreted_executor::layer_paths::write_layer_paths;
use interpreted_executor::util::wrap_network_in_scope; use interpreted_executor::util::wrap_network_with_render_node_in_scope;
use observer::Observer; use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue}; pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
use std::sync::Arc; use std::sync::Arc;
@@ -94,7 +94,7 @@ enum ViewportArtwork {
} }
/// Messages passed from the editor thread to the node runtime thread. /// Messages passed from the editor thread to the node runtime thread.
#[derive(Debug, serde::Serialize, serde::Deserialize)] #[derive(Debug)]
pub enum GraphRuntimeRequest { pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate), GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest), ExecutionRequest(ExecutionRequest),
@@ -114,7 +114,7 @@ pub enum GraphRuntimeRequest {
RenderOverlays(OverlayContext), RenderOverlays(OverlayContext),
} }
#[derive(Debug, serde::Serialize, serde::Deserialize)] #[derive(Debug)]
pub struct GraphUpdate { pub struct GraphUpdate {
pub(super) network: NodeNetwork, pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry, pub(super) resources: ResourceRegistry,
@@ -124,8 +124,6 @@ pub struct GraphUpdate {
pub(super) layers: Vec<Vec<NodeId>>, pub(super) layers: Vec<Vec<NodeId>>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before. /// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>, 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. /// Replaces each network's primary export with its previewed node.
@@ -242,7 +240,6 @@ impl NodeRuntime {
previewed, previewed,
layers, layers,
observations, observations,
pixels_per_inch,
}) = graph }) = graph
else { else {
return; return;
@@ -255,7 +252,7 @@ impl NodeRuntime {
self.node_graph_errors.clear(); self.node_graph_errors.clear();
self.node_graph_warnings.clear(); self.node_graph_warnings.clear();
let result = self.update_network(network.clone(), pixels_per_inch); let result = self.update_network(network.clone());
self.compile_failed = result.is_err(); self.compile_failed = result.is_err();
if result.is_ok() { if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor); self.thumbnails.update_sources(&layers, &network, &self.executor);
@@ -305,7 +302,7 @@ impl NodeRuntime {
} }
if let Some(viewport) = viewport { if let Some(viewport) = viewport {
texture = self.run_viewport(viewport).await; self.run_viewport(viewport).await;
} }
// Overlays that changed without new artwork are drawn over the artwork already shown // Overlays that changed without new artwork are drawn over the artwork already shown
@@ -318,63 +315,27 @@ impl NodeRuntime {
texture texture
} }
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> { async fn run_viewport(&mut self, request: ExecutionRequest) {
self.thumbnails.set_scale(request.render_config.scale); self.thumbnails.set_scale(request.render_config.scale);
let mut result = self.evaluate(request)?; let Some(mut result) = self.evaluate(request) else { return };
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
#[cfg(all(target_family = "wasm", feature = "wasm"))] if let Some(RenderOutput { data, metadata }) = result.render_output() {
let resolution = request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale; let content = match data {
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
let texture = if let Some(RenderOutput { data, metadata }) = result.render_output() RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
&& let RenderOutputType::Texture(texture) = data _ => None,
{ };
self.viewport_artwork = Some(ViewportArtwork::Texture(texture.clone())); if content.is_some() {
let path_contents = path_contents(&observations); self.viewport_artwork = content;
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref()); let path_contents = path_contents(&observations);
self.overlays_stale = true; self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
let frame = self.composite_viewport_frame(); self.overlays_stale = true;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
{
*data = RenderOutputType::CanvasFrame {
canvas_id: self.wasm_canvas_cache.id(),
resolution,
};
} }
}
frame self.respond(request, result, observations).await;
} else if request.render_config.export_format == ExportFormat::Raster
&& let Some(RenderOutput {
data: RenderOutputType::Svg { .. },
metadata,
}) = result.render_output()
{
// The viewport was rendered as SVG in place of the requested raster, so the frontend draws it beneath the overlays
self.viewport_artwork = Some(ViewportArtwork::Svg);
let path_contents = path_contents(&observations);
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
self.overlays_stale = true;
let frame = self.composite_viewport_frame();
#[cfg(all(target_family = "wasm", feature = "wasm"))]
if let Some(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) = result.render_output()
{
let end = svg.rfind("</svg>").unwrap_or(svg.len());
svg.insert_str(end, &viewport_canvas_placeholder(self.wasm_canvas_cache.id(), resolution));
}
frame
} else {
None
};
self.respond(request.execution_id, result, observations).await;
texture
} }
/// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web. /// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web.
@@ -434,7 +395,7 @@ impl NodeRuntime {
*data = RenderOutputType::Buffer { data: buffer, width, height }; *data = RenderOutputType::Buffer { data: buffer, width, height };
} }
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.respond(request.execution_id, result, observations).await; self.respond(request, result, observations).await;
} }
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) { async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
@@ -468,7 +429,7 @@ impl NodeRuntime {
} }
let context = render_config.into_context_with_generations(self.async_runtime().snapshot()); 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.output.node(), &context))) { let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.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::Partial(value))) => ExecutionResult::Partial(value),
@@ -478,7 +439,7 @@ impl NodeRuntime {
ExecutionResult::Fallback(value, self.resolve_errors(&error)) ExecutionResult::Fallback(value, self.resolve_errors(&error))
} }
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)), Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))), Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
Err(payload) => { Err(payload) => {
let response = ExecutionResponse { let response = ExecutionResponse {
execution_id, execution_id,
@@ -486,6 +447,8 @@ impl NodeRuntime {
responses: VecDeque::new(), responses: VecDeque::new(),
dropped_thumbnails: Vec::new(), dropped_thumbnails: Vec::new(),
observations: HashMap::new(), observations: HashMap::new(),
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info: None,
}; };
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None; return None;
@@ -494,18 +457,37 @@ impl NodeRuntime {
Some(result) Some(result)
} }
async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) { async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
let mut responses = VecDeque::new(); let mut responses = VecDeque::new();
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did // While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await }; let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let mut result = result;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
let viewport_canvas_info = (!request.render_config.for_export
&& match result.render_output() {
Some(RenderOutput { data, .. }) => match data {
RenderOutputType::Texture(_) => true,
RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster,
RenderOutputType::Buffer { .. } => false,
},
None => false,
})
.then(|| ViewportCanvasInfo {
id: self.wasm_canvas_cache.id(),
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
});
let response = ExecutionResponse { let response = ExecutionResponse {
execution_id, execution_id: request.execution_id,
result, result,
responses, responses,
dropped_thumbnails, dropped_thumbnails,
observations, observations,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
viewport_canvas_info,
}; };
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
} }
@@ -524,8 +506,8 @@ impl NodeRuntime {
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
} }
fn update_network(&mut self, graph: NodeNetwork, pixels_per_inch: f64) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> { fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle(), pixels_per_inch); let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string())); return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
@@ -589,7 +571,7 @@ impl NodeRuntime {
} }
impl ExecutionResult { impl ExecutionResult {
fn render_output(&mut self) -> Option<&mut RenderOutput> { pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> {
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else { let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
return None; return None;
}; };
+20 -5
View File
@@ -423,6 +423,17 @@ impl EditorTestUtils {
self.create_node(node_type, Some((x, y))).await self.create_node(node_type, Some((x, y))).await
} }
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
node_id: Some(node_id),
xy: Some((x, y)),
})
.await;
node_id
}
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId { async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
let node_id = NodeId::new(); let node_id = NodeId::new();
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu { self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
@@ -509,14 +520,18 @@ fn init_test_logger() {
}); });
} }
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow. /// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
/// Panics if no adapter is found, since tests render on the GPU like the app does. /// Panics if no adapter is found, since tests render on the GPU like the app does.
fn gpu_application_io() -> PlatformApplicationIo { pub fn gpu_executor() -> <PlatformApplicationIo as ApplicationIo>::Executor {
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned()); static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
let executor = GPU_EXECUTOR.clone().expect( GPU_EXECUTOR.clone().expect(
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).", "Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
); )
PlatformApplicationIo::new_with_executor(executor) }
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
fn gpu_application_io() -> PlatformApplicationIo {
PlatformApplicationIo::new_with_executor(gpu_executor())
} }
/// Runs `operation`, returning its result along with the errors it logged. /// Runs `operation`, returning its result along with the errors it logged.
@@ -538,30 +538,6 @@
</div> </div>
{/if} {/if}
<!-- Click target debug visualizations -->
{#if $nodeGraph.clickTargets}
<div class="click-targets" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
<svg>
{#each $nodeGraph.clickTargets.nodeClickTargets as pathString}
<path class="node" d={pathString} />
{/each}
{#each $nodeGraph.clickTargets.layerClickTargets as pathString}
<path class="layer" d={pathString} />
{/each}
{#each $nodeGraph.clickTargets.connectorClickTargets as pathString}
<path class="connector" d={pathString} />
{/each}
{#each $nodeGraph.clickTargets.iconClickTargets as pathString}
<path class="visibility" d={pathString} />
{/each}
<path class="all-nodes-bounding-box" d={$nodeGraph.clickTargets.allNodesBoundingBox} />
{#each $nodeGraph.clickTargets.importExportNames as pathString}
<path class="import-export-name" d={pathString} />
{/each}
</svg>
</div>
{/if}
<!-- Thick vertical layer connection wires --> <!-- Thick vertical layer connection wires -->
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}> <div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
<svg> <svg>
@@ -1311,46 +1287,6 @@
} }
} }
.click-targets {
position: absolute;
pointer-events: none;
width: 100%;
height: 100%;
z-index: 10;
svg {
overflow: visible;
width: 100%;
height: 100%;
stroke-width: 1;
fill: none;
.layer {
stroke: yellow;
}
.node {
stroke: blue;
}
.connector {
stroke: green;
}
.visibility {
stroke: red;
}
.all-nodes-bounding-box {
stroke: purple;
}
.import-export-name {
stroke: orange;
}
}
}
.wires { .wires {
pointer-events: none; pointer-events: none;
position: absolute; position: absolute;
@@ -1151,7 +1151,6 @@
--math-basis-j: #66c14a; --math-basis-j: #66c14a;
--math-basis-k: #76b6ff; --math-basis-k: #76b6ff;
--math-variable: #fff9a8; --math-variable: #fff9a8;
--math-unit: #eeeeee;
--math-function: #c9c2ff; --math-function: #c9c2ff;
--math-operator: #ffffff; --math-operator: #ffffff;
--math-bracket: #f2b532; --math-bracket: #f2b532;
@@ -1203,11 +1202,6 @@
color: var(--math-function); 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 // A keyword is an operator spelled as a word
.operator, .operator,
.keyword { .keyword {
@@ -75,9 +75,6 @@
let inputRangeElement: HTMLInputElement | undefined; let inputRangeElement: HTMLInputElement | undefined;
let text = exact ?? displayText(value, unit); let text = exact ?? displayText(value, unit);
let editing = false; 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 isDragging = false;
let pressingArrow = false; let pressingArrow = false;
let repeatTimeout: ReturnType<typeof setTimeout> | undefined = undefined; let repeatTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
@@ -121,7 +118,7 @@
let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined; let sliderAbortTimeout1: ReturnType<typeof setTimeout> | undefined;
let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined; let sliderAbortTimeout2: ReturnType<typeof setTimeout> | undefined;
$: watchValue(value, unit, min, max); $: watchValue(value, unit);
$: if (exact !== undefined && !editing) text = exact; $: if (exact !== undefined && !editing) text = exact;
$: present = exact !== undefined || value !== undefined; $: 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 // A number of only one digit, like `0` or `-1`, has no other digit to move the underline to, so it isn't shown
@@ -179,8 +176,8 @@
// TRACKING AND UPDATING THE VALUE // TRACKING AND UPDATING THE VALUE
// =============================== // ===============================
// Called only when `value`, its unit, or its bounds are changed from outside this component. // Called only when `value` is changed from outside this component.
function watchValue(value: number | undefined, unit: string, min: number | undefined, max: number | undefined) { function watchValue(value: number | undefined, unit: string) {
// Don't update if the slider is currently being dragged (we don't want the backend fighting with the user's drag) // 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; if (rangeSliderClickDragState === "Dragging") return;
@@ -384,11 +381,6 @@
return `${number}`; 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. // Removes the trailing "s" from a unit if the quantity is 1.
function unPluralize(unit: string, quantity: number): string { function unPluralize(unit: string, quantity: number): string {
if (quantity !== 1 || !unit.endsWith("s")) return unit; if (quantity !== 1 || !unit.endsWith("s")) return unit;
@@ -1010,9 +1002,6 @@
>{text.slice(markedDigit + 1)}</span >{text.slice(markedDigit + 1)}</span
> >
{/if} {/if}
{#if ghostUnit}
<span class="ghost-unit">{text}<span class="unit">{ghostUnit}</span></span>
{/if}
{#if present} {#if present}
{#if mode === "Increment" && incrementBehavior !== "None"} {#if mode === "Increment" && incrementBehavior !== "None"}
<button <button
@@ -1114,24 +1103,6 @@
display: none; 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 // A disabled field's underline only marks the stepped digit, with no press target to hover or drag
&.disabled .digit-mark .marked::after { &.disabled .digit-mark .marked::after {
pointer-events: none; pointer-events: none;
+1 -11
View File
@@ -3,7 +3,7 @@ import type { Writable } from "svelte/store";
import type { IconName } from "/src/icons"; import type { IconName } from "/src/icons";
import type { SubscriptionsRouter } from "/src/subscriptions-router"; import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageBody } from "/src/subscriptions-router"; import type { MessageBody } from "/src/subscriptions-router";
import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper"; import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>; export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
@@ -13,7 +13,6 @@ export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId
type NodeGraphStoreState = { type NodeGraphStoreState = {
box: BoxSelection | undefined; box: BoxSelection | undefined;
clickTargets: FrontendClickTargets | undefined;
contextMenuInformation: ContextMenuInformation | undefined; contextMenuInformation: ContextMenuInformation | undefined;
errors: NodeGraphErrorDiagnostic[]; errors: NodeGraphErrorDiagnostic[];
layerWidths: Map<bigint, number>; layerWidths: Map<bigint, number>;
@@ -36,7 +35,6 @@ type NodeGraphStoreState = {
}; };
const initialState: NodeGraphStoreState = { const initialState: NodeGraphStoreState = {
box: undefined, box: undefined,
clickTargets: undefined,
contextMenuInformation: undefined, contextMenuInformation: undefined,
errors: [], errors: [],
layerWidths: new Map(), layerWidths: new Map(),
@@ -136,13 +134,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
}); });
}); });
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
update((state) => {
state.clickTargets = data.clickTargets;
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => { subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
update((state) => { update((state) => {
state.contextMenuInformation = data.contextMenuInformation; state.contextMenuInformation = data.contextMenuInformation;
@@ -330,7 +321,6 @@ export function destroyNodeGraphStore() {
subscriptions.unsubscribeFrontendMessage("SendUIMetadata"); subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
subscriptions.unsubscribeFrontendMessage("UpdateBox"); subscriptions.unsubscribeFrontendMessage("UpdateBox");
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation"); subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex"); subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex"); subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
+63 -16
View File
@@ -1,8 +1,8 @@
use super::mover::Mover; use super::mover::Mover;
use crate::graph::LAYER_BOTTOM_GAP;
use crate::per_node::PerNode; use crate::per_node::PerNode;
use crate::{NodeIndex, Placement}; use crate::{NodeIndex, Placement};
use glam::IVec2; use glam::IVec2;
use std::mem;
pub(super) struct Snapshot { pub(super) struct Snapshot {
placements: PerNode<Placement>, placements: PerNode<Placement>,
@@ -16,38 +16,85 @@ impl Mover {
Snapshot { placements, positions } Snapshot { placements, positions }
} }
pub(super) fn restore_followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) { pub(super) fn restore_followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) {
let followers = self.followers(before, moved); let followers = self.followers(before, kept);
let mut restored = PerNode::filled(&self.graph, false); let mut pushed = PerNode::filled(&self.graph, None);
followers for node in followers.indices().filter(|node| followers[*node]) {
.indices() self.restore_follower(node, &followers, &before.positions, &mut pushed);
.filter(|node| followers[*node]) }
.for_each(|node| self.restore_follower(node, &followers, &before.positions, &mut restored));
} }
fn followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) -> PerNode<bool> { fn followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) -> PerNode<bool> {
let (graph, layout) = self.graph_and_layout(); let (graph, layout) = self.graph_and_layout();
PerNode::from_fn(graph, |node| { PerNode::from_fn(graph, |node| {
let placement = graph[node].placement; let placement = graph[node].placement;
let unchanged = placement == before.placements[node]; let unchanged = placement == before.placements[node];
let was_relative = matches!(before.placements[node], Placement::Relative(_)); let was_relative = matches!(before.placements[node], Placement::Relative(_));
let is_relative = matches!(placement, Placement::Relative(_)); let is_relative = matches!(placement, Placement::Relative(_));
!moved.contains(&node) && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node] kept[node] && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
}) })
} }
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, restored: &mut PerNode<bool>) { fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, pushed: &mut PerNode<Option<IVec2>>) -> IVec2 {
if mem::replace(&mut restored[node], true) { if let Some(push) = pushed[node] {
return; return push;
} }
pushed[node] = Some(IVec2::ZERO);
let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect(); let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect();
for reader in following_readers { let pushed_by_readers = following_readers
self.restore_follower(reader, followers, positions_before, restored); .into_iter()
.map(|reader| self.restore_follower(reader, followers, positions_before, pushed))
.fold(IVec2::ZERO, IVec2::max);
let shift = positions_before[node] + pushed_by_readers - self.position(node);
let shifted = self.graph[node].placement.shifted(shift);
let clear = self.clear_of_the_layer_above(node, shifted);
self.set_placement(node, clear);
let push = pushed_by_readers + clear.stored_offset() - shifted.stored_offset();
pushed[node] = Some(push);
push
}
pub(super) fn carry_along(&mut self, before: &Snapshot, carried: &PerNode<bool>) {
let mut shifts = PerNode::filled(&self.graph, None);
for node in carried.indices().filter(|node| carried[*node]) {
self.carry(node, carried, &before.positions, &mut shifts);
}
}
fn carry(&mut self, node: NodeIndex, carried: &PerNode<bool>, positions_before: &PerNode<IVec2>, shifts: &mut PerNode<Option<IVec2>>) -> IVec2 {
if let Some(shift) = shifts[node] {
return shift;
}
shifts[node] = Some(IVec2::ZERO);
let readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).collect();
let mut shift = IVec2::ZERO;
for reader in readers {
shift = if carried[reader] {
self.carry(reader, carried, positions_before, shifts)
} else {
self.position(reader) - positions_before[reader]
};
if shift != IVec2::ZERO {
break;
}
} }
let shift = positions_before[node] - self.position(node);
let shifted = self.graph[node].placement.shifted(shift); let shifted = self.graph[node].placement.shifted(shift);
self.set_placement(node, shifted); self.set_placement(node, shifted);
shifts[node] = Some(shift);
shift
}
fn clear_of_the_layer_above(&self, node: NodeIndex, placement: Placement) -> Placement {
let Placement::Relative(offset) = placement else { return placement };
let layer_above = self.readers.of(&self.graph, node).find(|wire| self.graph.feeds_stack(wire)).map(|wire| wire.target);
let Some(layer_above) = layer_above.filter(|_| offset.x == 0) else { return placement };
let lowest_free_row = self.graph[layer_above].size.y + LAYER_BOTTOM_GAP;
Placement::Relative(IVec2::new(0, offset.y.max(lowest_free_row)))
} }
} }
+60
View File
@@ -0,0 +1,60 @@
use crate::connections::WiresByNode;
use crate::per_node::PerNode;
use crate::{Graph, NodeIndex, Placement, Wire};
use glam::IVec2;
use std::mem;
#[derive(Clone, Debug)]
pub(super) struct UpstreamOfDragged {
moving_up_or_down: Upstream,
moving_sideways: Upstream,
}
#[derive(Clone, Debug)]
pub(super) struct Upstream {
pub(super) kept: PerNode<bool>,
pub(super) carried: PerNode<bool>,
}
impl UpstreamOfDragged {
pub(super) fn new(graph: &Graph, dragged: &[NodeIndex]) -> Self {
let inputs = WiresByNode::inputs(graph);
let everything = upstream_through(graph, &inputs, dragged, |_| true);
let into_a_node = |wire: &Wire| !graph[wire.target].is_layer();
let split = |kept: PerNode<bool>| {
let carried = PerNode::from_fn(graph, |node| everything[node] && !kept[node] && matches!(graph[node].placement, Placement::Absolute(_)));
Upstream { kept, carried }
};
Self {
moving_up_or_down: split(upstream_through(graph, &inputs, dragged, |wire| into_a_node(wire) || graph.feeds_stack(wire))),
moving_sideways: split(upstream_through(graph, &inputs, dragged, into_a_node)),
}
}
pub(super) fn moving_by(&self, shift: IVec2) -> &Upstream {
if shift.x == 0 { &self.moving_up_or_down } else { &self.moving_sideways }
}
}
fn upstream_through(graph: &Graph, inputs: &WiresByNode, dragged: &[NodeIndex], followed: impl Fn(&Wire) -> bool) -> PerNode<bool> {
let mut upstream = PerNode::filled(graph, false);
for node in dragged {
upstream[*node] = true;
}
dragged
.iter()
.flat_map(|node| inputs.of(graph, *node))
.filter(|wire| followed(wire))
.for_each(|wire| mark_upstream(graph, inputs, wire.source, &mut upstream));
for node in dragged {
upstream[*node] = false;
}
upstream
}
fn mark_upstream(graph: &Graph, inputs: &WiresByNode, node: NodeIndex, upstream: &mut PerNode<bool>) {
if mem::replace(&mut upstream[node], true) {
return;
}
inputs.of(graph, node).for_each(|wire| mark_upstream(graph, inputs, wire.source, upstream));
}
+9 -4
View File
@@ -1,10 +1,12 @@
mod followers; mod followers;
mod kept;
mod mover; mod mover;
mod shift; mod shift;
mod stack; mod stack;
use crate::{Graph, Layout, NodeIndex, Placement}; use crate::{Graph, Layout, NodeIndex, Placement};
use glam::IVec2; use glam::IVec2;
use kept::UpstreamOfDragged;
use mover::Mover; use mover::Mover;
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone. /// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
@@ -12,7 +14,7 @@ use mover::Mover;
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Drag { pub struct Drag {
dragged: Vec<NodeIndex>, dragged: Vec<NodeIndex>,
keep_upstream: bool, upstream: Option<UpstreamOfDragged>,
rows_up: Vec<Graph>, rows_up: Vec<Graph>,
held_in_place: Vec<HeldInPlace>, held_in_place: Vec<HeldInPlace>,
} }
@@ -26,8 +28,11 @@ struct HeldInPlace {
impl Drag { impl Drag {
/// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn. /// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn.
/// Dragged layers still carry their content and chain, and carry the stacks below them when moved sideways.
/// Nodes starting a tree of their own upstream of what moves follow the nodes reading them.
#[must_use] #[must_use]
pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self { pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self {
let upstream = keep_upstream.then(|| UpstreamOfDragged::new(&start, &dragged));
let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect(); let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect();
let mut mover = Mover::new(start, Some(start_layout)); let mut mover = Mover::new(start, Some(start_layout));
mover.hold(&dragged); mover.hold(&dragged);
@@ -45,7 +50,7 @@ impl Drag {
.collect(); .collect();
Self { Self {
dragged, dragged,
keep_upstream, upstream,
rows_up: vec![held], rows_up: vec![held],
held_in_place, held_in_place,
} }
@@ -74,7 +79,7 @@ impl Drag {
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)] [IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
.into_iter() .into_iter()
.filter(|shift| *shift != IVec2::ZERO) .filter(|shift| *shift != IVec2::ZERO)
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.keep_upstream)); .for_each(|shift| mover.shift_step(&self.dragged, shift, self.upstream.as_ref().map(|upstream| upstream.moving_by(shift))));
mover.into_graph_and_layout() mover.into_graph_and_layout()
} }
@@ -89,7 +94,7 @@ impl Drag {
fn one_row_further_up(&self) -> Graph { fn one_row_further_up(&self) -> Graph {
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default(); let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
let mut mover = Mover::new(highest_so_far, None); let mut mover = Mover::new(highest_so_far, None);
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.keep_upstream); mover.shift_step(&self.dragged, IVec2::NEG_Y, self.upstream.as_ref().map(|upstream| upstream.moving_by(IVec2::NEG_Y)));
mover.into_graph() mover.into_graph()
} }
} }
+12 -12
View File
@@ -1,27 +1,27 @@
use super::kept::Upstream;
use super::mover::Mover; use super::mover::Mover;
use crate::NodeIndex; use crate::NodeIndex;
use glam::IVec2; use glam::IVec2;
impl Mover { impl Mover {
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, keep_upstream: bool) { pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, upstream: Option<&Upstream>) {
let before = keep_upstream.then(|| self.snapshot()); let before = upstream.map(|upstream| (self.snapshot(), upstream));
let shifted = self.shift_nodes(dragged, shift); self.shift_nodes(dragged, shift);
if let Some(before) = before { if let Some((before, upstream)) = before {
let moved: Vec<NodeIndex> = dragged.iter().chain(&shifted).copied().collect(); self.restore_followers(&before, &upstream.kept);
self.restore_followers(&before, &moved); self.carry_along(&before, &upstream.carried);
} }
} }
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) -> Vec<NodeIndex> { fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) {
let mut shifted = Vec::new(); let mut shifted = Vec::new();
for node in self.moving_on_their_own(nodes) { for node in self.moving_on_their_own(nodes) {
self.shift_node(node, shift, &mut shifted); self.shift_node(node, shift, &mut shifted);
} }
shifted
} }
fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) { fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) {
let moving = self.node_moving_for(node, shift); let Some(moving) = self.node_moving_for(node, shift) else { return };
if shifted.contains(&moving) { if shifted.contains(&moving) {
return; return;
} }
@@ -34,12 +34,12 @@ impl Mover {
self.place_at(moving, position + shift); self.place_at(moving, position + shift);
} }
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> NodeIndex { fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> Option<NodeIndex> {
let (stack, layout) = self.stack_and_layout(); let (stack, layout) = self.stack_and_layout();
match shift { match shift {
IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node), IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node),
IVec2 { x: 0, .. } => node, IVec2 { x: 0, .. } => Some(node),
_ => stack.top(node), _ => Some(stack.top(node)),
} }
} }
+12 -2
View File
@@ -14,8 +14,18 @@ impl Stack<'_> {
self.climb(node, |layer| self.layer_above(layer)) self.climb(node, |layer| self.layer_above(layer))
} }
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> NodeIndex { pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> Option<NodeIndex> {
self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above))) let top_of_closed_up_run = self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)));
(!self.closed_up_under_its_parent(layout, top_of_closed_up_run)).then_some(top_of_closed_up_run)
}
fn closed_up_under_its_parent(&self, layout: &Layout, layer: NodeIndex) -> bool {
let parent = self
.readers
.of(self.graph, layer)
.find(|wire| wire.is_primary() && self.graph[wire.target].is_layer() && !self.graph.feeds_stack(wire))
.map(|wire| wire.target);
self.graph[layer].is_layer() && parent.is_some_and(|parent| self.closed_up(layout, layer, parent))
} }
fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool { fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool {
+146 -1
View File
@@ -1,6 +1,6 @@
mod common; mod common;
use common::{at, layer, stacked, wire}; use common::{CHAINED, at, layer, node, stacked, wire};
use glam::IVec2; use glam::IVec2;
use graph_layout::{Drag, Graph, Layout, Placement}; use graph_layout::{Drag, Graph, Layout, Placement};
@@ -73,3 +73,148 @@ fn a_layer_pushed_up_with_its_upstream_kept_carries_the_layer_above_from_the_fir
assert_eq!(layout.node(at(2)).position, before.node(at(2)).position + IVec2::new(0, -2)); assert_eq!(layout.node(at(2)).position, before.node(at(2)).position + IVec2::new(0, -2));
assert_eq!(layout.node(at(1)).position, before.node(at(1)).position + IVec2::new(0, -2)); assert_eq!(layout.node(at(1)).position, before.node(at(1)).position + IVec2::new(0, -2));
} }
#[test]
fn a_layer_dragged_up_with_its_upstream_kept_carries_its_chain_and_leaves_its_stack() {
let start = Graph {
nodes: vec![
layer(Placement::Absolute(IVec2::new(30, 10))),
node(CHAINED),
node(Placement::Relative(IVec2::new(-8, 0))),
layer(stacked(0)),
],
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 0, 0)],
};
let before = Layout::new(&start);
let offset = IVec2::new(0, -4);
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(0)], true).moved(offset);
for carried in [0, 1, 2] {
assert_eq!(layout.node(at(carried)).position, before.node(at(carried)).position + offset);
}
assert_eq!(layout.node(at(3)).position, before.node(at(3)).position);
}
fn stack_of_layers_with_chains() -> Graph {
let layers = [layer(Placement::Absolute(IVec2::new(30, 10))), layer(stacked(0)), layer(stacked(0))];
let chains = [node(CHAINED), node(CHAINED), node(CHAINED)];
let stack_wires = [wire(1, 0, 0), wire(2, 1, 0)];
let chain_wires = [wire(3, 0, 1), wire(4, 1, 1), wire(5, 2, 1)];
Graph {
nodes: layers.into_iter().chain(chains).collect(),
wires: stack_wires.into_iter().chain(chain_wires).collect(),
}
}
fn moved_by_dragging(graph: &Graph, dragged: &[u32], offset: IVec2) -> Vec<u32> {
let before = Layout::new(graph);
let (_, layout) = Drag::new(graph.clone(), Layout::new(graph), dragged.iter().copied().map(at).collect(), true).moved(offset);
let node_count = u32::try_from(graph.nodes.len()).unwrap();
(0..node_count).filter(|index| layout.node(at(*index)).position != before.node(at(*index)).position).collect()
}
#[test]
fn a_layer_in_the_middle_of_a_stack_dragged_sideways_with_its_upstream_kept_moves_its_whole_stack() {
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1], IVec2::new(10, 0)), vec![0, 1, 2, 3, 4, 5]);
}
#[test]
fn a_chain_node_dragged_with_its_upstream_kept_moves_alone() {
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[4], IVec2::new(0, 10)), vec![4]);
}
#[test]
fn a_layer_pushed_up_with_its_upstream_kept_carries_the_closed_up_layers_above_with_their_chains() {
let graph = stack_of_layers_with_chains();
let mut stack_with_one_more_below = graph.clone();
stack_with_one_more_below.nodes.push(layer(stacked(0)));
stack_with_one_more_below.wires.push(wire(6, 2, 0));
assert_eq!(moved_by_dragging(&stack_with_one_more_below, &[2], IVec2::new(0, -1)), vec![0, 1, 2, 3, 4, 5]);
}
#[test]
fn layers_of_one_stack_dragged_down_together_with_their_upstream_kept_carry_their_chains() {
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1, 2], IVec2::new(0, 4)), vec![1, 2, 4, 5]);
}
fn artboard_holding_a_stack_of_layers_with_chains() -> Graph {
let artboard = layer(Placement::Absolute(IVec2::new(30, 10)));
let layers = [layer(Placement::Relative(IVec2::new(-8, 3))), layer(stacked(0)), layer(stacked(0)), layer(stacked(0))];
let chains = (0..4).flat_map(|_| [node(CHAINED), node(CHAINED), node(CHAINED)]);
let stack_wires = [wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 0), wire(4, 3, 0)];
let chain_wires = (0..4).flat_map(|layer| {
let first = 5 + layer * 3;
[wire(first, layer + 1, 1), wire(first + 1, first, 0), wire(first + 2, first + 1, 0)]
});
Graph {
nodes: [artboard].into_iter().chain(layers).chain(chains).collect(),
wires: stack_wires.into_iter().chain(chain_wires).collect(),
}
}
#[test]
fn releasing_a_drag_draws_every_node_where_the_drag_drew_it() {
let stack = artboard_holding_a_stack_of_layers_with_chains();
let reading_a_tree = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
let drags = [
(&stack, vec![1, 2], IVec2::new(5, 0), true),
(&stack, vec![1, 2], IVec2::new(5, 0), false),
(&stack, vec![2], IVec2::new(5, 0), false),
(&stack, vec![3], IVec2::new(0, -2), true),
(&stack, vec![3], IVec2::new(0, 3), true),
(&stack, vec![3], IVec2::new(0, -2), false),
(&stack, vec![3], IVec2::new(0, 3), false),
(&reading_a_tree, vec![2], IVec2::new(0, 3), true),
(&reading_a_tree, vec![2], IVec2::new(5, 0), true),
];
for (start, dragged, offset, keep_upstream) in drags {
let mut drag = Drag::new(start.clone(), Layout::new(start), dragged.iter().copied().map(at).collect(), keep_upstream);
let (_, dragging) = drag.moved(offset);
let released = Layout::new(&drag.released(offset));
let node_count = u32::try_from(start.nodes.len()).unwrap();
let drawn = |layout: &Layout| (0..node_count).map(|index| layout.node(at(index)).position).collect::<Vec<_>>();
assert_eq!(drawn(&released), drawn(&dragging), "dragging {dragged:?} by {offset} keeping upstream: {keep_upstream}");
}
}
#[test]
fn layers_closed_up_under_the_layer_holding_them_cannot_be_pushed_up_into_it() {
let start = artboard_holding_a_stack_of_layers_with_chains();
for keep_upstream in [false, true] {
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(3)], keep_upstream).moved(IVec2::new(0, -2));
assert_eq!(layout.node(at(1)).position, Layout::new(&start).node(at(1)).position, "keeping upstream: {keep_upstream}");
}
}
fn artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own() -> Graph {
Graph {
nodes: vec![
layer(Placement::Absolute(IVec2::new(30, 10))),
layer(Placement::Relative(IVec2::new(-8, 3))),
layer(stacked(0)),
node(CHAINED),
node(Placement::Absolute(IVec2::new(0, 30))),
node(CHAINED),
],
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 1), wire(4, 3, 0), wire(5, 4, 0)],
}
}
#[test]
fn a_layer_dragged_with_its_upstream_kept_carries_the_trees_its_chain_reads() {
let graph = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(0, 3)), vec![2, 3, 4, 5]);
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(5, 0)), vec![1, 2, 3, 4, 5]);
}
#[test]
fn the_trees_a_blocked_layer_reads_stay_with_it() {
assert_eq!(
moved_by_dragging(&artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own(), &[2], IVec2::new(0, -2)),
Vec::<u32>::new()
);
}
-4
View File
@@ -37,10 +37,6 @@ macro_rules! generate_benchmarks {
} }
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 "(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 "((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 "log(100, 10) + (5 * sin(pi/4) + sqrt(81)) / (2 * phi)", // Logarithmic and trigonometric functions
+2 -47
View File
@@ -1,6 +1,4 @@
use crate::constants::{BuiltinFunction, MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix}; use crate::constants::{MatrixToMatrix, MatrixToValue, ValueOfRegions, ValuesToMatrix};
use crate::quantity::{BuilderUnits, MatrixValueUnit, RegionResult, UnitRule};
use crate::units::UnitId;
use crate::value::Value; use crate::value::Value;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@@ -98,11 +96,6 @@ pub enum Syntax<'src> {
first: Box<Syntax<'src>>, first: Box<Syntax<'src>>,
rest: Vec<(BinaryOp, 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. /// 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 { Piecewise {
cases: Vec<Case<'src>>, cases: Vec<Case<'src>>,
@@ -164,17 +157,10 @@ pub enum Node {
pub enum ValueNode { pub enum ValueNode {
Lit(Literal), Lit(Literal),
Var(String), 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 { FnCall {
name: String, name: String,
expr: Vec<ValueNode>, 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 { BinOp {
lhs: Box<ValueNode>, lhs: Box<ValueNode>,
op: BinaryOp, op: BinaryOp,
@@ -197,24 +183,16 @@ pub enum ValueNode {
matrix: Box<MatrixNode>, matrix: Box<MatrixNode>,
value: Box<ValueNode>, 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)`. /// A function of a matrix with a value result, like `det(A)`.
OfMatrix { OfMatrix {
function: MatrixToValue, function: MatrixToValue,
unit: MatrixValueUnit,
matrix: Box<MatrixNode>, matrix: Box<MatrixNode>,
}, },
/// A function of a value and regions with a value result, like `within(p, R)`. /// A function of a value and regions with a value result, like `within(p, R)`.
OfValueAndRegions { OfValueAndRegions {
function: ValueOfRegions, function: ValueOfRegions,
result: RegionResult,
value: Box<ValueNode>, value: Box<ValueNode>,
regions: Box<[MatrixNode]>, regions: Vec<MatrixNode>,
/// The value after the regions, where the builtin takes one, like `smoothstep`'s continuity. /// The value after the regions, where the builtin takes one, like `smoothstep`'s continuity.
trailing: Option<Box<ValueNode>>, trailing: Option<Box<ValueNode>>,
}, },
@@ -237,28 +215,6 @@ 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. /// A subexpression evaluating to a matrix.
#[derive(Debug)] #[derive(Debug)]
pub enum MatrixNode { pub enum MatrixNode {
@@ -270,7 +226,6 @@ pub enum MatrixNode {
/// A function building a matrix from values, like `rotation(angle)`. /// A function building a matrix from values, like `rotation(angle)`.
FromValues { FromValues {
function: ValuesToMatrix, function: ValuesToMatrix,
units: BuilderUnits,
arguments: Vec<ValueNode>, arguments: Vec<ValueNode>,
}, },
/// The range `a..b`. /// The range `a..b`.
+3 -57
View File
@@ -1,11 +1,10 @@
//! The names an editor offers to finish the one being typed. //! The names an editor offers to finish the one being typed.
use crate::constants::{BUILTIN_FUNCTION_ALIASES, SUFFIXED_FORMS}; use crate::constants::{BUILTIN_FUNCTION_ALIASES, SUFFIXED_FORMS};
use crate::documentation::{BUILTIN_FUNCTIONS, Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, unit_tooltip}; use crate::documentation::{BUILTIN_FUNCTIONS, Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip};
use crate::lexer::{CONSTANT_SPELLINGS, Constant, KEYWORDS, Lexer, Token, offset_in, operand_ended}; use crate::lexer::{CONSTANT_SPELLINGS, Constant, KEYWORDS, Lexer, Token, offset_in, operand_ended};
use crate::parser::{keywords_accepted_after, parse_quietly}; use crate::parser::{keywords_accepted_after, parse_quietly};
use crate::sort::names_in_scope; use crate::sort::names_in_scope;
use crate::units::{UNITS, unit_named};
use std::borrow::Cow; use std::borrow::Cow;
/// What an offered name is, by which the offers are grouped. /// What an offered name is, by which the offers are grouped.
@@ -15,8 +14,6 @@ pub enum CompletionKind {
Local, Local,
Function, Function,
Constant, Constant,
/// A unit of measure, like `mm`.
Unit,
Keyword, Keyword,
/// The typeset alias of an operator typed in ASCII, like `≤` for `<=`. /// The typeset alias of an operator typed in ASCII, like `≤` for `<=`.
Operator, Operator,
@@ -237,42 +234,6 @@ pub fn completions(source: &str, caret: usize, asked: bool) -> Completions<'_> {
}); });
let constants = identity.into_iter().chain(constants).collect::<Vec<_>>(); 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 // 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)| { let keywords = KEYWORDS.into_iter().filter(|_| !builtins_only).filter_map(|(keyword, token)| {
Some(Candidate { Some(Candidate {
@@ -299,7 +260,6 @@ pub fn completions(source: &str, caret: usize, asked: bool) -> Completions<'_> {
(locals, CompletionKind::Local), (locals, CompletionKind::Local),
(functions, CompletionKind::Function), (functions, CompletionKind::Function),
(constants, CompletionKind::Constant), (constants, CompletionKind::Constant),
(units, CompletionKind::Unit),
(keywords, CompletionKind::Keyword), (keywords, CompletionKind::Keyword),
] ]
.into_iter() .into_iter()
@@ -556,12 +516,12 @@ mod tests {
#[test] #[test]
fn definitions_are_offered_where_they_can_be_read() { fn definitions_are_offered_where_they_can_be_read() {
assert_eq!(names("2 rad‸ where radius = 2"), ["radius", "rad", "radian"]); assert_eq!(names("2 rad‸ where radius = 2"), ["radius"]);
assert_eq!(names("ea‸(2) where ease(t) = t^2"), ["ease"]); assert_eq!(names("ea‸(2) where ease(t) = t^2"), ["ease"]);
assert_eq!(names("sig‸ where sigma = 1"), ["sigma", "sign"]); 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 // 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", "rad", "radian"]); assert_eq!(names("f(1) where f(radius) = 2 rad‸"), ["radius"]);
assert!(names("(f(1) where f(radius) = 2 radius) + rad‸").is_empty()); assert!(names("(f(1) where f(radius) = 2 radius) + rad‸").is_empty());
assert!(names("(2 where radius = 1) + rad‸").is_empty()); assert!(names("(2 where radius = 1) + rad‸").is_empty());
assert!(!names("fo‸(2 where foo = 1)").contains(&"foo".to_string())); assert!(!names("fo‸(2 where foo = 1)").contains(&"foo".to_string()));
@@ -712,18 +672,4 @@ mod tests {
assert_eq!(crate::evaluate(ascii).unwrap().unwrap(), crate::evaluate(typeset).unwrap().unwrap(), "`{typeset}`"); 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()));
}
} }
+5 -52
View File
@@ -1,6 +1,4 @@
use crate::matrix::Matrix; use crate::matrix::Matrix;
use crate::quantity::{MatrixQuantity, Quantity};
use crate::units::DEFAULT_PIXELS_PER_INCH;
use crate::value::Value; use crate::value::Value;
use std::collections::HashMap; use std::collections::HashMap;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
@@ -13,16 +11,6 @@ pub trait ValueProvider {
fn get_matrix(&self, _name: &str) -> Option<Matrix> { fn get_matrix(&self, _name: &str) -> Option<Matrix> {
None 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 { pub trait FunctionProvider {
@@ -46,14 +34,6 @@ impl<V: ValueProvider> ValueProvider for &V {
fn get_matrix(&self, name: &str) -> Option<Matrix> { fn get_matrix(&self, name: &str) -> Option<Matrix> {
(**self).get_matrix(name) (**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 { impl ValueProvider for NothingMap {
@@ -93,47 +73,20 @@ impl FunctionProvider for NothingMap {
pub struct EvalContext<V: ValueProvider, F: FunctionProvider> { pub struct EvalContext<V: ValueProvider, F: FunctionProvider> {
values: V, values: V,
functions: F, 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> { impl Default for EvalContext<NothingMap, NothingMap> {
fn default() -> Self { fn default() -> Self {
Self::new(NothingMap, NothingMap) Self {
values: NothingMap,
functions: NothingMap,
}
} }
} }
impl<V: ValueProvider, F: FunctionProvider> EvalContext<V, F> { impl<V: ValueProvider, F: FunctionProvider> EvalContext<V, F> {
pub fn new(values: V, functions: F) -> Self { pub fn new(values: V, functions: F) -> Self {
Self { Self { values, functions }
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> { pub fn get_value(&self, name: &str) -> Option<Value> {
+12 -41
View File
@@ -8,7 +8,6 @@ use crate::lexer::{Constant, Token};
use crate::matrix::Matrix; use crate::matrix::Matrix;
use crate::quaternion::Quaternion; use crate::quaternion::Quaternion;
use crate::reducer::{Reducer, classify_reducer}; use crate::reducer::{Reducer, classify_reducer};
use crate::units::UnitId;
use crate::value::Value; use crate::value::Value;
/// Hover text, as the tooltip Markdown subset: code spans, fenced code blocks, bold, and italic. /// Hover text, as the tooltip Markdown subset: code spans, fenced code blocks, bold, and italic.
@@ -190,7 +189,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[−π/2, π/2]", "[−π/2, π/2]",
doc( doc(
"The angle whose sine is `x`. Outside its domain, the result climbs into the complex plane.", "The angle whose sine is `x`. Outside its domain, the result climbs into the complex plane.",
&[("asin(1)", "π/2 rad"), ("asin(2)", "(π/2 - 1.317i) rad")], &[("asin(1)", "π/2"), ("asin(2)", "π/2 - 1.317i")],
), ),
), ),
function( function(
@@ -201,7 +200,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[0, π]", "[0, π]",
doc( doc(
"The angle whose cosine is `x`. Outside its domain, the result climbs into the complex plane.", "The angle whose cosine is `x`. Outside its domain, the result climbs into the complex plane.",
&[("acos(-1)", "π rad"), ("acos(2)", "1.317i rad")], &[("acos(-1)", "π"), ("acos(2)", "1.317i")],
), ),
), ),
function( function(
@@ -210,7 +209,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
Treatment::InPlane, Treatment::InPlane,
&[parameter("x", "[−∞, ∞]", "the tangent")], &[parameter("x", "[−∞, ∞]", "the tangent")],
"[−π/2, π/2]", "[−π/2, π/2]",
doc("The angle whose tangent is `x`.", &[("atan(1)", "π/4 rad"), ("atan(∞)", "π/2 rad")]), doc("The angle whose tangent is `x`.", &[("atan(1)", "π/4"), ("atan(∞)", "π/2")]),
), ),
function( function(
"atan2", "atan2",
@@ -218,7 +217,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
Treatment::RealOnly, Treatment::RealOnly,
&[parameter("y", "[−∞, ∞]", "the point's `y` coordinate"), parameter("x", "[−∞, ∞]", "the point's `x` coordinate")], &[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 rad"), ("atan2(0, -1)", "π rad")]), doc("The angle from the positive `x` axis to the point `(x, y)`.", &[("atan2(1, 1)", "π/4"), ("atan2(0, -1)", "π")]),
), ),
function( function(
"acsc", "acsc",
@@ -228,7 +227,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[−π/2, π/2]", "[−π/2, π/2]",
doc( 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.", "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 rad")], &[("acsc(2)", "π/6")],
), ),
), ),
function( function(
@@ -239,7 +238,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[0, π]", "[0, π]",
doc( 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.", "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 rad")], &[("asec(2)", "π/3")],
), ),
), ),
function( function(
@@ -248,7 +247,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
Treatment::InPlane, Treatment::InPlane,
&[parameter("x", "[−∞, ∞]", "the cotangent")], &[parameter("x", "[−∞, ∞]", "the cotangent")],
"[−π/2, π/2]", "[−π/2, π/2]",
doc("The angle whose cotangent is `x`, `atan(1/x)`.", &[("acot(1)", "π/4 rad")]), doc("The angle whose cotangent is `x`, `atan(1/x)`.", &[("acot(1)", "π/4")]),
), ),
// Hyperbolic functions // Hyperbolic functions
function( function(
@@ -737,7 +736,7 @@ pub static BUILTIN_FUNCTIONS: &[DocumentedFunction] = &[
"[−π, π]", "[−π, π]",
doc( 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`.", "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 rad"), ("angle(j, i)", "-π/2 rad")], &[("angle(i, j)", "π/2"), ("angle(j, i)", "-π/2")],
), ),
), ),
function( function(
@@ -1091,28 +1090,6 @@ const IDENTITY: Doc = doc(
&[("I (3i + 4j)", "3i + 4j")], &[("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`. /// The hover text for the identity matrix `I`.
pub fn identity_tooltip() -> Tooltip { pub fn identity_tooltip() -> Tooltip {
documented("Identity Matrix", "I".to_string(), &IDENTITY, Treatment::Whole, "") documented("Identity Matrix", "I".to_string(), &IDENTITY, Treatment::Whole, "")
@@ -1735,17 +1712,11 @@ mod tests {
use super::*; use super::*;
use crate::object::Object; use crate::object::Object;
/// Whether two results agree to the few digits the documentation rounds them to, matrices entry by entry, and values in their units. /// Whether two results agree to the few digits the documentation rounds them to, matrices entry by entry.
fn agree(actual: &Object, expected: &Object) -> bool { 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 { let parts = |object: &Object| match object {
Object::Value(quantity) => quantity.number().to_quaternion().parts().to_vec(), Object::Value(Value::Number(number)) => number.to_quaternion().parts().to_vec(),
Object::Matrix(matrix) => matrix.matrix.rows.iter().chain([&matrix.matrix.translation]).flat_map(|row| row.parts()).collect(), Object::Matrix(matrix) => matrix.rows.iter().chain([&matrix.translation]).flat_map(|row| row.parts()).collect(),
}; };
let close = |actual: f64, expected: f64| { let close = |actual: f64, expected: f64| {
if expected.is_infinite() { if expected.is_infinite() {
@@ -1781,7 +1752,7 @@ mod tests {
fn every_treatment_matches_how_the_function_evaluates() { fn every_treatment_matches_how_the_function_evaluates() {
let evaluate = |expression: &str| crate::evaluate(expression).ok()?.ok(); let evaluate = |expression: &str| crate::evaluate(expression).ok()?.ok();
let number = |expression: &str| match evaluate(expression) { let number = |expression: &str| match evaluate(expression) {
Some(Object::Value(quantity)) => quantity.number().to_quaternion(), Some(Object::Value(Value::Number(number))) => number.to_quaternion(),
result => panic!("`{expression}` should be a number, not {result:?}"), 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); let close = |actual: Quaternion, expected: Quaternion| actual.parts().iter().zip(expected.parts()).all(|(actual, expected)| (actual - expected).abs() <= 1e-9);
+168 -448
View File
@@ -1,12 +1,10 @@
use crate::ast::{BinaryOp, BuiltinCall, Clause, Literal, Local, MatrixNode, Measure, Node, SortedCase, UnaryOp, ValueNode}; use crate::ast::{BinaryOp, Clause, Literal, Local, MatrixNode, Node, SortedCase, UnaryOp, ValueNode};
use crate::constants::{Builtin, MatrixToValue, SuffixedFunction, ValueOfRegions, builtin_function, suffixed_function}; use crate::constants::{Builtin, MatrixToValue, SuffixedFunction, ValueOfRegions, builtin_function, suffixed_function};
use crate::context::{EvalContext, FunctionProvider, ValueProvider}; use crate::context::{EvalContext, FunctionProvider, ValueProvider};
use crate::lexer::Constant; use crate::lexer::Constant;
use crate::matrix::{Matrix, Region}; use crate::matrix::{Matrix, Region};
use crate::object::Object; use crate::object::Object;
use crate::quantity::{self, MatrixQuantity, MatrixValueUnit, Quantity, RegionResult, UnitRule, unit_rule};
use crate::quaternion::Quaternion; use crate::quaternion::Quaternion;
use crate::units::{Unit, unit_named};
use crate::value::{Number, Value}; use crate::value::{Number, Value};
use std::cell::OnceCell; use std::cell::OnceCell;
use thiserror::Error; use thiserror::Error;
@@ -60,58 +58,18 @@ pub enum EvalError {
#[error("Value of {0} is not a number")] #[error("Value of {0} is not a number")]
NotANumber(String), 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 /// 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. /// 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 // 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)] #[inline(always)]
fn settle(quantity: Quantity) -> Result<Quantity, EvalError> { fn settle(value: Value) -> Result<Value, EvalError> {
let number = quantity.number(); let Value::Number(number) = value;
if number.is_nan() { if number.is_nan() {
return Err(EvalError::Indeterminate); return Err(EvalError::Indeterminate);
} }
Ok(Quantity::new(Value::Number(number.canonical()), quantity.unit)) Ok(Value::Number(number.canonical()))
} }
/// Settles a matrix result like [`settle`] does a value, with signed zeros made plain zero. /// Settles a matrix result like [`settle`] does a value, with signed zeros made plain zero.
@@ -122,90 +80,35 @@ pub(crate) fn settle_matrix(matrix: Matrix) -> Result<Matrix, EvalError> {
Ok(matrix.map(|entry| if entry == 0. { 0. } else { entry })) 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 /// 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. /// supply) is an error naming its source.
#[inline(always)] #[inline(always)]
fn canonical_host_value(name: &str, quantity: Quantity) -> Result<Quantity, EvalError> { fn canonical_host_value(name: &str, value: Value) -> Result<Value, EvalError> {
let number = quantity.number(); let Value::Number(number) = value;
if number.is_nan() { if number.is_nan() {
return Err(EvalError::NotANumber(name.to_string())); return Err(EvalError::NotANumber(name.to_string()));
} }
Ok(Quantity::new(Value::Number(number.canonical()), quantity.unit)) Ok(Value::Number(number.canonical()))
} }
/// Resolves a name against the environment before the builtin constants and units, so a binding of exactly that spelling shadows /// Resolves a name against the environment before the builtin constants, so a binding of exactly that spelling shadows the builtin.
/// the builtin. The `\` prefix skips the environment. /// The `\` prefix skips the environment.
fn resolve_value<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Quantity> { fn resolve_value<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Value> {
let builtin = |name: &str| { let constant = |name: &str| Constant::from_name(name).map(|constant| Value::Number(constant.value()));
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('\\') { match name.strip_prefix('\\') {
Some(builtin_name) => builtin(builtin_name), Some(builtin_name) => constant(builtin_name),
None => context.get_quantity(name).or_else(|| builtin(name)), None => context.get_value(name).or_else(|| constant(name)),
} }
} }
/// Resolves a matrix's name like [`resolve_value`], with `I` the one builtin. /// 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<MatrixQuantity> { fn resolve_matrix<V: ValueProvider, F: FunctionProvider>(context: &EvalContext<V, F>, name: &str) -> Option<Matrix> {
let constant = |name: &str| (name == "I").then_some(MatrixQuantity::plain(Matrix::IDENTITY)); let constant = |name: &str| (name == "I").then_some(Matrix::IDENTITY);
match name.strip_prefix('\\') { match name.strip_prefix('\\') {
Some(builtin_name) => constant(builtin_name), Some(builtin_name) => constant(builtin_name),
None => context.get_matrix_quantity(name).or_else(|| constant(name)), None => context.get_matrix(name).or_else(|| constant(name)),
} }
} }
@@ -228,10 +131,6 @@ impl<'a, V: ValueProvider, F: FunctionProvider> Scope<'a, V, F> {
} }
frame.ok_or(EvalError::OperatorTypeError) 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. /// The definitions of one `where` clause, or the arguments of one call, each evaluated on its first read and at most once.
@@ -260,9 +159,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 // 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 // called from several sites since wasm-opt inlines a function with one call site
#[inline(never)] #[inline(never)]
fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<ValueNode>) -> Result<Quantity, EvalError> { fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<ValueNode>) -> Result<Value, EvalError> {
match bound { match bound {
Bound::Local(local) => read(scope, local)?.as_quantity().copied().ok_or(EvalError::OperatorTypeError), Bound::Local(local) => read(scope, local)?.as_value().copied().ok_or(EvalError::OperatorTypeError),
Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body { Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body {
Node::Value(body) => body.eval_in(scope), Node::Value(body) => body.eval_in(scope),
Node::Matrix(_) => Err(EvalError::OperatorTypeError), Node::Matrix(_) => Err(EvalError::OperatorTypeError),
@@ -272,9 +171,9 @@ fn bound_value<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, b
} }
#[inline(never)] #[inline(never)]
fn bound_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<MatrixNode>) -> Result<MatrixQuantity, EvalError> { fn bound_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, bound: Bound<MatrixNode>) -> Result<Matrix, EvalError> {
match bound { match bound {
Bound::Local(local) => read(scope, local)?.as_matrix_quantity().copied().ok_or(EvalError::OperatorTypeError), Bound::Local(local) => read(scope, local)?.as_matrix().copied().ok_or(EvalError::OperatorTypeError),
Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body { Bound::Call(function, arguments) => call(scope, function, arguments, |body, scope| match body {
Node::Matrix(body) => body.eval_in(scope), Node::Matrix(body) => body.eval_in(scope),
Node::Value(_) => Err(EvalError::OperatorTypeError), Node::Value(_) => Err(EvalError::OperatorTypeError),
@@ -353,11 +252,8 @@ fn holding_case<'a, T, V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_,
let mut holding = None; let mut holding = None;
let mut overlapping = false; let mut overlapping = false;
for case in cases { for case in cases {
let condition = case.condition.eval_in(scope)?; let Value::Number(condition) = case.condition.eval_in(scope)?;
if !condition.is_plain() { match condition.as_bool() {
return Err(EvalError::NotATruthValue);
}
match condition.number().as_bool() {
Some(false) => {} Some(false) => {}
Some(true) if holding.is_none() => holding = Some(&case.value), Some(true) if holding.is_none() => holding = Some(&case.value),
Some(true) => overlapping = true, Some(true) => overlapping = true,
@@ -372,8 +268,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. /// An operand of a matrix operation, holding a matrix on the stack since the operation consumes it at once.
enum Operand { enum Operand {
Value(Quantity), Value(Value),
Matrix(MatrixQuantity), Matrix(Matrix),
} }
impl Node { impl Node {
@@ -387,40 +283,30 @@ 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 /// 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. /// value as translation, division is times-inverse, and powers are whole.
fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand, pixels_per_inch: f64) -> Result<MatrixQuantity, EvalError> { fn matrix_binary_op(lhs: Operand, op: BinaryOp, rhs: Operand) -> Result<Matrix, EvalError> {
use BinaryOp as Op; use BinaryOp as Op;
let result = match (lhs, op, rhs) { match (lhs, op, rhs) {
(Operand::Value(q), Op::Mul, Operand::Matrix(b)) => { (Operand::Value(Value::Number(q)), Op::Mul, Operand::Matrix(b)) => settle_matrix(Matrix::left_multiplication(q.to_quaternion()).compose(b)),
let left_multiplication = MatrixQuantity { (Operand::Matrix(a), Op::Mul, Operand::Matrix(b)) => settle_matrix(a.compose(b)),
matrix: Matrix::left_multiplication(q.number().to_quaternion()), (lhs, Op::Div, Operand::Matrix(b)) => matrix_binary_op(lhs, Op::Mul, Operand::Matrix(b.inverse().ok_or(EvalError::SingularMatrix)?)),
linear: q.unit, (Operand::Matrix(a), Op::Add, Operand::Matrix(b)) => settle_matrix(a + b),
translation: Unit::NONE, (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())),
left_multiplication.compose(&b, pixels_per_inch)? (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::Mul, Operand::Matrix(b)) => a.compose(&b, pixels_per_inch)?, (Operand::Matrix(a), Op::Pow, Operand::Value(Value::Number(exponent))) => {
(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 // 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.number() { let whole = match exponent {
Number::Integer(integer) => integer, Number::Integer(integer) => integer,
real => real real => real
.as_real() .as_real()
.filter(|real| real.fract() == 0. && real.abs() < i64::MAX as f64) .filter(|real| real.fract() == 0. && real.abs() < i64::MAX as f64)
.ok_or(EvalError::FractionalMatrixPower)? as i64, .ok_or(EvalError::FractionalMatrixPower)? as i64,
}; };
a.power(whole, pixels_per_inch)? settle_matrix(a.power(whole).ok_or(EvalError::SingularMatrix)?)
} }
_ => return Err(EvalError::OperatorTypeError), _ => Err(EvalError::OperatorTypeError),
}; }
settle_matrix_quantity(result)
} }
impl Node { impl Node {
@@ -441,43 +327,98 @@ impl Node {
} }
impl ValueNode { impl ValueNode {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Quantity, EvalError> { pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Value, EvalError> {
self.eval_in(&Scope::root(context)) self.eval_in(&Scope::root(context))
} }
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Quantity, EvalError> { fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Value, EvalError> {
match self { match self {
ValueNode::Lit(lit) => match lit { ValueNode::Lit(lit) => match lit {
Literal::Integer(integer) => Ok(Quantity::plain(Value::from_i64(*integer))), Literal::Integer(integer) => Ok(Value::from_i64(*integer)),
Literal::Float(float) => Ok(Quantity::plain(Value::from_f64(*float))), Literal::Float(float) => Ok(Value::from_f64(*float)),
}, },
ValueNode::BinOp { lhs, op, rhs } => binary(lhs.eval_in(scope)?, *op, rhs.eval_in(scope)?, scope.pixels_per_inch()), ValueNode::BinOp { lhs, op, rhs } => match (lhs.eval_in(scope)?, rhs.eval_in(scope)?) {
ValueNode::MeasureQuotient { dividend, measure } => measure_quotient(scope, dividend, measure), (Value::Number(lhs), Value::Number(rhs)) => {
ValueNode::UnaryOp { expr, op } => { // Logic rejects operands that aren't truth values, while the other operators reject operand types they don't support
let operand = expr.eval_in(scope)?; let rejected = if matches!(op, BinaryOp::And | BinaryOp::Or) {
if !operand.is_plain() { EvalError::NotATruthValue
return settle(quantity::unary_op(operand, *op)?); } else {
EvalError::OperatorTypeError
};
settle(Value::Number(lhs.binary_op(*op, rhs).ok_or(rejected)?))
} }
},
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>>()?;
let rejected = if *op == UnaryOp::Not { EvalError::NotATruthValue } else { EvalError::OperatorTypeError }; // 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
settle(Quantity::of_number(operand.number().unary_op(*op).ok_or(rejected)?, Unit::NONE)) 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))
} }
ValueNode::Comparison { first, rest } => comparison_chain(scope, first, rest),
ValueNode::Var(name) => { ValueNode::Var(name) => {
let value = resolve_value(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?; let value = resolve_value(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?;
canonical_host_value(name, value) canonical_host_value(name, value)
} }
ValueNode::Unit { name, unit } => { ValueNode::FnCall { name, expr } => {
// A host's binding of the spelling shadows the unit, unless the `\` prefix asks for the unit // Arguments land in a stack buffer when they fit (builtins take at most 5), avoiding a heap allocation per call
let bound = (!name.starts_with('\\')).then(|| scope.context.get_quantity(name)).flatten(); let mut stack_values = [Value::from_i64(0); 5];
match bound { let heap_values: Vec<Value>;
Some(value) => canonical_host_value(name, value), let values: &[Value] = if expr.len() <= stack_values.len() {
None => Ok(Quantity::new(Value::from_i64(1), Unit::of(*unit))), 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::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 // 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) { ValueNode::Piecewise { cases, otherwise } => match (holding_case(scope, cases)?, otherwise) {
(Some(value), _) => value.eval_in(scope), (Some(value), _) => value.eval_in(scope),
@@ -485,14 +426,8 @@ impl ValueNode {
(None, None) => Err(EvalError::NoCaseHolds), (None, None) => Err(EvalError::NoCaseHolds),
}, },
ValueNode::Apply { matrix, value } => value_of_matrix(scope, MatrixValueCase::Apply(matrix, value)), ValueNode::Apply { matrix, value } => value_of_matrix(scope, MatrixValueCase::Apply(matrix, value)),
ValueNode::OfMatrix { function, unit, matrix } => value_of_matrix(scope, MatrixValueCase::OfMatrix(*function, *unit, matrix)), ValueNode::OfMatrix { function, matrix } => value_of_matrix(scope, MatrixValueCase::OfMatrix(*function, matrix)),
ValueNode::OfValueAndRegions { ValueNode::OfValueAndRegions { function, value, regions, trailing } => value_of_matrix(scope, MatrixValueCase::OfValueAndRegions(*function, value, regions, trailing.as_deref())),
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::MatrixComparison { matrices, distinct } => value_of_matrix(scope, MatrixValueCase::Comparison(matrices, *distinct)),
ValueNode::Local(local) => bound_value(scope, Bound::Local(*local)), ValueNode::Local(local) => bound_value(scope, Bound::Local(*local)),
ValueNode::Call { function, arguments } => bound_value(scope, Bound::Call(*function, arguments)), ValueNode::Call { function, arguments } => bound_value(scope, Bound::Call(*function, arguments)),
@@ -501,349 +436,134 @@ 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. /// A value computed from matrices.
enum MatrixValueCase<'a> { enum MatrixValueCase<'a> {
Apply(&'a MatrixNode, &'a ValueNode), Apply(&'a MatrixNode, &'a ValueNode),
OfMatrix(MatrixToValue, MatrixValueUnit, &'a MatrixNode), OfMatrix(MatrixToValue, &'a MatrixNode),
OfValueAndRegions(ValueOfRegions, RegionResult, &'a ValueNode, &'a [MatrixNode], Option<&'a ValueNode>), OfValueAndRegions(ValueOfRegions, &'a ValueNode, &'a [MatrixNode], Option<&'a ValueNode>),
Comparison(&'a [MatrixNode], bool), 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 // 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] #[cold]
#[inline(never)] #[inline(never)]
fn value_of_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, case: MatrixValueCase) -> Result<Quantity, EvalError> { fn value_of_matrix<V: ValueProvider, F: FunctionProvider>(scope: &Scope<'_, V, F>, case: MatrixValueCase) -> Result<Value, EvalError> {
let pixels_per_inch = scope.pixels_per_inch();
match case { match case {
MatrixValueCase::Apply(matrix, value) => { MatrixValueCase::Apply(matrix, value) => {
let matrix = matrix.eval_in(scope)?; let matrix = matrix.eval_in(scope)?;
let value = value.eval_in(scope)?; let Value::Number(value) = value.eval_in(scope)?;
settle(matrix.apply(value, pixels_per_inch)?) settle(Value::from(matrix.apply(value.to_quaternion())))
} }
MatrixValueCase::OfMatrix(function, unit, matrix) => { MatrixValueCase::OfMatrix(function, matrix) => settle(function(matrix.eval_in(scope)?)),
let matrix = matrix.eval_in(scope)?; MatrixValueCase::OfValueAndRegions(function, value, regions, trailing) => {
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)?; let value = value.eval_in(scope)?;
// A range literal is kept by its corners, which may be infinite where no matrix can hold them // A range literal is kept by its corners, which may be infinite where no matrix can hold them
let region_of = |region: &MatrixNode| -> Result<UnitRegion, EvalError> { let region_of = |region: &MatrixNode| -> Result<Region, EvalError> {
match region { match region {
MatrixNode::Range { from, to } => { MatrixNode::Range { from, to } => {
let (from, to, unit) = quantity::range_corners(from.eval_in(scope)?, to.eval_in(scope)?, pixels_per_inch)?; let (Value::Number(from), Value::Number(to)) = (from.eval_in(scope)?, to.eval_in(scope)?);
Ok(UnitRegion { Ok(Region::Range(from, to))
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 // 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 placeholder = UnitRegion { let mut stack_regions = [Region::Range(Number::Integer(0), Number::Integer(0)); 2];
region: Region::Range(Number::Integer(0), Number::Integer(0)), let heap_regions: Vec<Region>;
unit: Unit::NONE, let regions: &[Region] = if regions.len() <= stack_regions.len() {
};
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) { for (slot, region) in stack_regions.iter_mut().zip(regions) {
*slot = region_of(region)?; *slot = region_of(region)?;
} }
&stack_regions[..regions.len()] &stack_regions[..regions.len()]
} else { } else {
heap_regions = regions.iter().map(region_of).collect::<Result<Vec<UnitRegion>, EvalError>>()?; heap_regions = regions.iter().map(region_of).collect::<Result<Vec<Region>, EvalError>>()?;
&heap_regions &heap_regions
}; };
// The value is measured in the first region's unit, and a remap's result in the last's let trailing = trailing.map(|trailing| trailing.eval_in(scope)).transpose()?;
let Some(first) = unit_regions.first() else { return Err(EvalError::TypeError) }; settle(function(value, regions, trailing)?)
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) => { MatrixValueCase::Comparison(matrices, distinct) => {
// A chain lands in a stack buffer when it fits, the usual case // A chain lands in a stack buffer when it fits, the usual case
let mut stack_matrices = [MatrixQuantity::plain(Matrix::ZERO); 4]; let mut stack_matrices = [Matrix::ZERO; 4];
let heap_matrices: Vec<MatrixQuantity>; let heap_matrices: Vec<Matrix>;
let matrices: &[MatrixQuantity] = if matrices.len() <= stack_matrices.len() { let matrices: &[Matrix] = if matrices.len() <= stack_matrices.len() {
for (slot, matrix) in stack_matrices.iter_mut().zip(matrices) { for (slot, matrix) in stack_matrices.iter_mut().zip(matrices) {
*slot = matrix.eval_in(scope)?; *slot = matrix.eval_in(scope)?;
} }
&stack_matrices[..matrices.len()] &stack_matrices[..matrices.len()]
} else { } else {
heap_matrices = matrices.iter().map(|matrix| matrix.eval_in(scope)).collect::<Result<Vec<MatrixQuantity>, EvalError>>()?; heap_matrices = matrices.iter().map(|matrix| matrix.eval_in(scope)).collect::<Result<Vec<Matrix>, EvalError>>()?;
&heap_matrices &heap_matrices
}; };
// 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)
};
let plain = matrices.iter().map(in_first_units).collect::<Result<Vec<Matrix>, EvalError>>()?;
let holds = if distinct { let holds = if distinct {
plain.iter().enumerate().all(|(index, a)| plain[index + 1..].iter().all(|b| !a.same_entries(*b))) matrices.iter().enumerate().all(|(index, a)| matrices[index + 1..].iter().all(|b| !a.same_entries(*b)))
} else { } else {
plain.windows(2).all(|pair| pair[0].same_entries(pair[1])) matrices.windows(2).all(|pair| pair[0].same_entries(pair[1]))
}; };
Ok(Quantity::plain(Value::from_bool(holds))) Ok(Value::from_bool(holds))
} }
} }
} }
impl MatrixNode { impl MatrixNode {
pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<MatrixQuantity, EvalError> { pub fn eval<V: ValueProvider, F: FunctionProvider>(&self, context: &EvalContext<V, F>) -> Result<Matrix, EvalError> {
self.eval_in(&Scope::root(context)) self.eval_in(&Scope::root(context))
} }
fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<MatrixQuantity, EvalError> { fn eval_in<V: ValueProvider, F: FunctionProvider>(&self, scope: &Scope<'_, V, F>) -> Result<Matrix, EvalError> {
let pixels_per_inch = scope.pixels_per_inch();
match self { match self {
MatrixNode::Var(name) => { MatrixNode::Var(name) => {
let matrix = resolve_matrix(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?; let matrix = resolve_matrix(scope.context, name).ok_or_else(|| EvalError::MissingValue(name.clone()))?;
if matrix.matrix.is_nan() { if matrix.is_nan() {
return Err(EvalError::NotANumber(name.clone())); return Err(EvalError::NotANumber(name.clone()));
} }
settle_matrix_quantity(matrix) settle_matrix(matrix)
} }
MatrixNode::Literal { entries, by_rows } => { MatrixNode::Literal { entries, by_rows } => {
if entries.len() > 4 { let mut quaternions = [Quaternion::ZERO; 4];
if entries.len() > quaternions.len() {
return Err(EvalError::TypeError); return Err(EvalError::TypeError);
} }
let quantities = entries.iter().map(|entry| entry.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?; for (slot, entry) in quaternions.iter_mut().zip(entries) {
let (quaternions, unit) = quantity::literal_entries(&quantities, pixels_per_inch)?; let Value::Number(number) = entry.eval_in(scope)?;
*slot = number.to_quaternion();
}
let matrix = if *by_rows { Matrix::from_rows(&quaternions) } else { Matrix::from_columns(&quaternions) }; let entries = &quaternions[..entries.len()];
settle_matrix_quantity(MatrixQuantity { let matrix = if *by_rows { Matrix::from_rows(entries) } else { Matrix::from_columns(entries) };
matrix: matrix.ok_or(EvalError::TypeError)?, settle_matrix(matrix.ok_or(EvalError::TypeError)?)
linear: unit,
translation: Unit::NONE,
})
} }
MatrixNode::FromValues { function, units, arguments } => { MatrixNode::FromValues { function, 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 // 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 = [Quantity::plain(Value::from_i64(0)); 3]; let mut stack_values = [Value::from_i64(0); 3];
let heap_values: Vec<Quantity>; let heap_values: Vec<Value>;
let quantities: &[Quantity] = if arguments.len() <= stack_values.len() { let values: &[Value] = if arguments.len() <= stack_values.len() {
for (slot, argument) in stack_values.iter_mut().zip(arguments) { for (slot, argument) in stack_values.iter_mut().zip(arguments) {
*slot = argument.eval_in(scope)?; *slot = argument.eval_in(scope)?;
} }
&stack_values[..arguments.len()] &stack_values[..arguments.len()]
} else { } else {
heap_values = arguments.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Quantity>, EvalError>>()?; heap_values = arguments.iter().map(|argument| argument.eval_in(scope)).collect::<Result<Vec<Value>, EvalError>>()?;
&heap_values &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 } => { MatrixNode::Range { from, to } => {
let (from, to, unit) = quantity::range_corners(from.eval_in(scope)?, to.eval_in(scope)?, pixels_per_inch)?; let (Value::Number(from), Value::Number(to)) = (from.eval_in(scope)?, to.eval_in(scope)?);
let matrix = Matrix::range(from.to_quaternion(), to.to_quaternion()); settle_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 } => { MatrixNode::OfMatrix { function, matrix } => settle_matrix(function(matrix.eval_in(scope)?)),
let matrix = matrix.eval_in(scope)?; MatrixNode::BinOp { lhs, op, rhs } => matrix_binary_op(lhs.operand(scope)?, *op, rhs.operand(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 } => { MatrixNode::UnaryOp { expr, op } => {
let matrix = expr.eval_in(scope)?; let matrix = expr.eval_in(scope)?;
match op { match op {
UnaryOp::Pos => Ok(matrix), UnaryOp::Pos => Ok(matrix),
UnaryOp::Neg => settle_matrix_quantity(matrix.negated()), UnaryOp::Neg => settle_matrix(-matrix),
UnaryOp::Transpose if matrix.matrix.is_linear() => settle_matrix_quantity(MatrixQuantity { UnaryOp::Transpose if matrix.is_linear() => settle_matrix(matrix.transposed()),
matrix: matrix.matrix.transposed(),
..matrix
}),
UnaryOp::Transpose => Err(EvalError::AffineTranspose), UnaryOp::Transpose => Err(EvalError::AffineTranspose),
UnaryOp::Not | UnaryOp::Fac | UnaryOp::Magnitude => Err(EvalError::OperatorTypeError), UnaryOp::Not | UnaryOp::Fac | UnaryOp::Magnitude => Err(EvalError::OperatorTypeError),
} }
@@ -881,7 +601,7 @@ mod tests {
expr: vec![ValueNode::Lit(Literal::Float(2.))], expr: vec![ValueNode::Lit(Literal::Float(2.))],
}; };
let result = call.eval(&EvalContext::new(SingleValue(5.), NothingMap)).unwrap(); let result = call.eval(&EvalContext::new(SingleValue(5.), NothingMap)).unwrap();
assert_eq!(result.value, Value::from_f64(10.)); assert_eq!(result, Value::from_f64(10.));
} }
#[test] #[test]
@@ -899,7 +619,7 @@ mod tests {
#[test] #[test]
fn $name() { fn $name() {
let result = $expr.eval(&EvalContext::default()).unwrap(); let result = $expr.eval(&EvalContext::default()).unwrap();
assert_eq!(result.value, $expected); assert_eq!(result, $expected);
} }
)* )*
}; };
+3 -47
View File
@@ -1,11 +1,10 @@
//! The roles the lexer and grammar give each stretch of source, for an editor to color and typeset an expression as it is typed. //! 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::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, unit_tooltip}; use crate::documentation::{Operator, Tooltip, constant_tooltip, function_tooltip, identity_tooltip, keyword_tooltip, matrix_literal_tooltip, range_tooltip, reducer_tooltip};
use crate::lexer::{Constant, Lexer, Token, names_matrix, operand_ended}; use crate::lexer::{Constant, Lexer, Token, names_matrix, operand_ended};
use crate::parser::parse_quietly; use crate::parser::parse_quietly;
use crate::sort::{NameUse, name_uses}; use crate::sort::{NameUse, name_uses};
use crate::units::unit_named;
use std::collections::HashMap; use std::collections::HashMap;
/// What a stretch of source is, as far as its spelling and its neighbors say. /// What a stretch of source is, as far as its spelling and its neighbors say.
@@ -21,8 +20,6 @@ pub enum Role {
Function, Function,
Keyword, Keyword,
Operator, 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. /// A grouping delimiter: a parenthesis, a brace, or a magnitude bar.
Bracket, Bracket,
/// A matrix literal's brackets and separators, and a range's `..`. /// A matrix literal's brackets and separators, and a range's `..`.
@@ -137,8 +134,6 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
Role::Function Role::Function
} else if matches!(bare, "i" | "j" | "k") { } else if matches!(bare, "i" | "j" | "k") {
Role::Basis Role::Basis
} else if unit_named(bare).is_some() && !called {
Role::Unit
} else { } else {
Role::Variable Role::Variable
} }
@@ -150,7 +145,6 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
(Some(NameUse::Local | NameUse::LocalFunction), _) => None, (Some(NameUse::Local | NameUse::LocalFunction), _) => None,
(_, Role::Function) => function_tooltip(bare), (_, Role::Function) => function_tooltip(bare),
(_, Role::Matrix) => (bare == "I").then(identity_tooltip), (_, Role::Matrix) => (bare == "I").then(identity_tooltip),
(_, Role::Unit) => unit_named(bare).map(unit_tooltip),
_ => Constant::from_name(bare).map(constant_tooltip), _ => Constant::from_name(bare).map(constant_tooltip),
}; };
highlights.push(Highlight { highlights.push(Highlight {
@@ -211,10 +205,6 @@ pub fn highlight(source: &str, accepts_reducers: bool) -> Vec<Highlight> {
}); });
} }
Token::DotDot => highlights.push(plain(start, end, Role::MatrixLiteral)), 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)), Token::Error(_) => highlights.push(plain(start, end, Role::Error)),
_ => highlights.push(Highlight { _ => highlights.push(Highlight {
tooltip: operator, tooltip: operator,
@@ -438,7 +428,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 // 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!( assert_eq!(
read("[a, b; c] max(a, b) M(v) 1..5 \\pi θ Δx q@"), read("[a, b; c] max(a, b) M(v) 1..5 \\pi θ Δx m@"),
[ [
("[", MatrixLiteral, 0, None), ("[", MatrixLiteral, 0, None),
("a", Variable, 0, None), ("a", Variable, 0, None),
@@ -463,7 +453,7 @@ mod tests {
("\\pi", Variable, 0, None), ("\\pi", Variable, 0, None),
("θ", Variable, 0, None), ("θ", Variable, 0, None),
("Δx", Matrix, 0, None), ("Δx", Matrix, 0, None),
("q", Variable, 0, None), ("m", Variable, 0, None),
("@", Error, 0, None), ("@", Error, 0, None),
] ]
); );
@@ -740,38 +730,4 @@ 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`.");
}
} }
+6 -18
View File
@@ -1,5 +1,4 @@
use crate::quaternion::Quaternion; use crate::quaternion::Quaternion;
use crate::units::unit_named;
use crate::value::{Complex, Number}; use crate::value::{Complex, Number};
use chumsky::input::{Input, ValueInput}; use chumsky::input::{Input, ValueInput};
use chumsky::span::SimpleSpan; use chumsky::span::SimpleSpan;
@@ -34,7 +33,7 @@ pub enum Token<'src> {
DotDot, DotDot,
Plus, Plus,
Minus, Minus,
/// The percent unit, which only follows the number it is a percentage of. /// Reserved for percentages, so the parser never matches it and its error points a C-style remainder to `mod(a, b)`.
Percent, Percent,
Star, Star,
Slash, Slash,
@@ -222,16 +221,14 @@ fn keyword(word: &str) -> Option<Token<'static>> {
KEYWORDS.into_iter().find_map(|(spelling, token)| (word == spelling).then_some(token)) 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, other than the /// Whether a name is a matrix's by the case rule: an uppercase-initial identifier, read after the `\` prefix.
/// spelling of a unit like `Hz`.
#[inline] #[inline]
pub fn names_matrix(name: &str) -> bool { pub fn names_matrix(name: &str) -> bool {
let name = name.strip_prefix('\\').unwrap_or(name); let name = name.strip_prefix('\\').unwrap_or(name);
let uppercase = match name.as_bytes().first() { match name.as_bytes().first() {
Some(byte) if byte.is_ascii() => byte.is_ascii_uppercase(), Some(byte) if byte.is_ascii() => byte.is_ascii_uppercase(),
_ => name.starts_with(char::is_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 /// Whether an operand has just ended after the token, given whether one had before it. A `!` leaves that as it was, since a factorial
@@ -245,15 +242,9 @@ 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, the `∞` literal, or a /// Whether a character ends an operand: a name, a number, a closing parenthesis, brace, or bracket, or the `∞` literal.
/// unit symbol that isn't a letter.
fn ends_operand(c: char) -> bool { fn ends_operand(c: char) -> bool {
c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(c, '.' | ')' | '}' | ']' | '∞') || is_unit_symbol(c) c.is_alphanumeric() || unicode_ident::is_xid_continue(c) || matches!(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 /// Reads every `|` in the source up front, since each depends on what precedes it: a bar opens a magnitude where an operand
@@ -548,9 +539,6 @@ impl<'a> Lexer<'a> {
// A symbol can't be a name, so unlike `inf`, no binding can shadow `∞` // A symbol can't be a name, so unlike `inf`, no binding can shadow `∞`
'∞' => Float(f64::INFINITY), '∞' => 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 // Typeset math symbol aliases
'∧' => AndAnd, '∧' => AndAnd,
'∨' => OrOr, '∨' => OrOr,
+7 -17
View File
@@ -9,16 +9,11 @@ pub mod lexer;
pub mod matrix; pub mod matrix;
pub mod object; pub mod object;
pub mod parser; pub mod parser;
pub mod quantity;
pub mod quaternion; pub mod quaternion;
pub mod reducer; pub mod reducer;
pub mod sort; pub mod sort;
pub mod units;
pub mod value; pub mod value;
#[cfg(test)]
mod units_tests;
use context::EvalContext; use context::EvalContext;
use executer::EvalError; use executer::EvalError;
use object::Object; use object::Object;
@@ -73,7 +68,7 @@ mod tests {
#[test] #[test]
fn percent_is_not_the_remainder() { 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 // `%` 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% 2", "5 + %"] { for input in ["5 % 3", "x % 2", "%", "50%"] {
let error = evaluate(input).unwrap_err().to_string(); let error = evaluate(input).unwrap_err().to_string();
assert!(error.contains("`mod(a, b)`"), "`{input}` gave the error `{error}`"); assert!(error.contains("`mod(a, b)`"), "`{input}` gave the error `{error}`");
} }
@@ -95,7 +90,7 @@ mod tests {
#[test] #[test]
fn error_spans_begin_at_the_token() { fn error_spans_begin_at_the_token() {
for (input, expected) in [("7 % 3", "at 2..3"), ("x if 1", "at 3..5")] { for (input, expected) in [("2 %", "at 2..3"), ("x if 1", "at 3..5")] {
let error = evaluate(input).unwrap_err().to_string(); let error = evaluate(input).unwrap_err().to_string();
assert!(error.ends_with(expected), "`{input}` gave the error `{error}`"); assert!(error.ends_with(expected), "`{input}` gave the error `{error}`");
} }
@@ -125,11 +120,7 @@ mod tests {
assert_eq!(message("`abc").span(), Some(0..4)); assert_eq!(message("`abc").span(), Some(0..4));
assert_eq!( assert_eq!(
message("7 % 3").parts(), 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("7 % 3").span(), Some(2..3));
assert_eq!(message("sin(I)").parts(), [Text("A matrix stands where a value is needed".into())]); assert_eq!(message("sin(I)").parts(), [Text("A matrix stands where a value is needed".into())]);
@@ -177,11 +168,10 @@ mod tests {
let negations = format!("{}1", "-".repeat(127)); 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 // 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 product = format!("{}1", "I ".repeat(127));
let measures = format!("1mm{}", " / 2mm".repeat(42));
let nested = format!("{}1{}", "(".repeat(32), ")".repeat(32)); 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 = (0..99).map(|n| format!("a{n} = I a{}", n + 1)).collect::<Vec<_>>().join(", ");
let bindings = format!("a0 where {bindings}, a99 = 1"); let bindings = format!("a0 where {bindings}, a99 = 1");
for source in [&sum, &negations, &product, &measures, &nested, &bindings] { for source in [&sum, &negations, &product, &nested, &bindings] {
assert!(evaluate(source).is_ok(), "`{source}` should be read"); assert!(evaluate(source).is_ok(), "`{source}` should be read");
highlight::highlight(source, false); highlight::highlight(source, false);
completion::completions(source, source.len(), true); completion::completions(source, source.len(), true);
@@ -999,8 +989,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 // 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 { let entries = |object: &Object| match object {
Object::Value(quantity) => quantity.number().to_quaternion().parts().to_vec(), Object::Value(Value::Number(number)) => 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>>(), Object::Matrix(matrix) => matrix.rows.iter().chain([&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}"); 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()) { if let (Some(actual), Some(expected)) = (actual.as_matrix(), expected.as_matrix()) {
@@ -1840,7 +1830,7 @@ mod tests {
#[test] #[test]
fn smoothstep_eases_along_a_rotated_box() { 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 // 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.]) { 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}"); assert!((part - expected).abs() < 1e-12, "{part} against {expected}");
} }
+19 -40
View File
@@ -1,21 +1,20 @@
use crate::matrix::Matrix; use crate::matrix::Matrix;
use crate::quantity::{MatrixQuantity, Quantity};
use crate::value::Value; use crate::value::Value;
use std::fmt; use std::fmt;
/// 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. /// What an expression evaluates to, one of the language's two sorts: a value or a matrix. The matrix is boxed so that a
/// The matrix is boxed so that a value, the common case, stays small. /// value, the common case, stays small.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub enum Object { pub enum Object {
Value(Quantity), Value(Value),
Matrix(Box<MatrixQuantity>), Matrix(Box<Matrix>),
} }
/// Generates readers that see a value's parts read as a plain number and nothing of a matrix. /// Generates readers that see a value's parts and nothing of a matrix.
macro_rules! value_readers { macro_rules! value_readers {
($($fn_name:ident: $type:ty),* $(,)?) => { ($($fn_name:ident: $type:ty),* $(,)?) => {
$( $(
#[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.")] #[doc = concat!("Reads the object as [`Value::", stringify!($fn_name), "`] does, or `None` for a matrix.")]
pub fn $fn_name(&self) -> Option<$type> { pub fn $fn_name(&self) -> Option<$type> {
self.as_value()?.$fn_name() self.as_value()?.$fn_name()
} }
@@ -24,44 +23,36 @@ macro_rules! value_readers {
} }
impl Object { impl Object {
/// The value with its unit, or `None` for a matrix.
#[inline] #[inline]
pub fn as_quantity(&self) -> Option<&Quantity> { pub fn as_value(&self) -> Option<&Value> {
match self { match self {
Self::Value(quantity) => Some(quantity), Self::Value(value) => Some(value),
Self::Matrix(_) => None, Self::Matrix(_) => None,
} }
} }
/// The value read as a plain number, as [`Quantity::as_plain`] reads it, or `None` for a matrix.
#[inline] #[inline]
pub fn as_value(&self) -> Option<Value> { pub fn as_matrix(&self) -> Option<&Matrix> {
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 { match self {
Self::Value(_) => None, Self::Value(_) => None,
Self::Matrix(matrix) => Some(matrix), 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] #[inline]
pub fn into_value(self) -> Option<Value> { pub fn into_value(self) -> Option<Value> {
self.as_value() match self {
Self::Value(value) => Some(value),
Self::Matrix(_) => None,
}
} }
#[inline] #[inline]
pub fn into_matrix(self) -> Option<Matrix> { pub fn into_matrix(self) -> Option<Matrix> {
self.as_matrix() match self {
Self::Value(_) => None,
Self::Matrix(matrix) => Some(*matrix),
}
} }
value_readers! { value_readers! {
@@ -83,24 +74,12 @@ impl Object {
impl<T: Into<Value>> From<T> for Object { impl<T: Into<Value>> From<T> for Object {
fn from(value: T) -> Self { fn from(value: T) -> Self {
Self::Value(Quantity::plain(value.into())) Self::Value(value.into())
}
}
impl From<Quantity> for Object {
fn from(quantity: Quantity) -> Self {
Self::Value(quantity)
} }
} }
impl From<Matrix> for Object { impl From<Matrix> for Object {
fn from(matrix: Matrix) -> Self { 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)) Self::Matrix(Box::new(matrix))
} }
} }
@@ -108,7 +87,7 @@ impl From<MatrixQuantity> for Object {
impl fmt::Display for Object { impl fmt::Display for Object {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Self::Value(quantity) => quantity.fmt(f), Self::Value(value) => value.fmt(f),
Self::Matrix(matrix) => matrix.fmt(f), Self::Matrix(matrix) => matrix.fmt(f),
} }
} }
+4 -137
View File
@@ -2,7 +2,6 @@ use crate::ast::{BinaryOp, Binding, CallWhere, Case, Literal, Node, Syntax, Unar
use crate::context::{FunctionProvider, NothingMap}; use crate::context::{FunctionProvider, NothingMap};
use crate::lexer::{LexError, Lexer, Span, Token}; use crate::lexer::{LexError, Lexer, Span, Token};
use crate::sort::sorted; use crate::sort::sorted;
use crate::units::unit_named;
use chumsky::cache::{Cache, Cached}; use chumsky::cache::{Cache, Cached};
use chumsky::error::{EmptyErr, LabelError, RichPattern, RichReason}; use chumsky::error::{EmptyErr, LabelError, RichPattern, RichReason};
use chumsky::input::ValueInput; use chumsky::input::ValueInput;
@@ -298,7 +297,7 @@ fn parse(src: &str) -> Result<Syntax<'_>, ParseError> {
let after_operand = e.expected().any(|pattern| matches!(pattern, RichPattern::Token(token) if **token == Token::EqEq)); let after_operand = e.expected().any(|pattern| matches!(pattern, RichPattern::Token(token) if **token == Token::EqEq));
match e.found() { match e.found() {
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::Percent) => ErrorMessage::from_prose("`%` is reserved for percentages, 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::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::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()), Some(Token::Equals) if after_operand => ErrorMessage::from_prose("`=` names a value in a `where` clause, so equality is written `==`").at(e.span()),
@@ -369,128 +368,6 @@ where
} }
/// The expression, within the names its `where` clause defines if it has one. /// 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> { fn with_bindings<'src>((body, bindings): (Syntax<'src>, Option<Vec<Binding<'src>>>)) -> Syntax<'src> {
match bindings { match bindings {
Some(bindings) => Syntax::Where { body: Box::new(body), bindings }, Some(bindings) => Syntax::Where { body: Box::new(body), bindings },
@@ -618,21 +495,11 @@ where
// Juxtaposed factors like `2pi` or `2sqrt(4)` multiply implicitly at the same precedence as `*` and `/`. // 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`). // 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, true)); let implicit_mul = pow.map(|rhs| (BinaryOp::Mul, rhs));
// 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 let product = unary
.clone() .clone()
.then(link.repeated().collect::<Vec<_>>()) .then(choice((mul_op.then(unary), implicit_mul)).repeated().collect::<Vec<_>>())
.validate(|(first, links): (Syntax<'src>, Vec<ProductLink<'src>>), _, emitter| { .map(|(first, mut rest): (Syntax<'src>, Vec<(BinaryOp, Syntax<'src>)>)| {
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 // Two factors group only one way, while a longer chain is grouped by the sort pass, which knows the matrices
if rest.len() <= 1 { if rest.len() <= 1 {
return match rest.pop() { return match rest.pop() {
-913
View File
@@ -1,913 +0,0 @@
//! 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)
}
}
}
+2 -161
View File
@@ -1,13 +1,11 @@
use crate::ast::BinaryOp; use crate::ast::BinaryOp;
use crate::constants::{Builtin, BuiltinFunction, builtin_function}; use crate::constants::{Builtin, BuiltinFunction, builtin_function};
use crate::context::{NothingMap, ValueProvider}; use crate::context::{NothingMap, ValueProvider};
use crate::documentation::BUILTIN_FUNCTIONS; use crate::executer::settle_matrix;
use crate::executer::{EvalError, settle_matrix};
use crate::lexer::{Lexer, Token}; use crate::lexer::{Lexer, Token};
use crate::matrix::Matrix; use crate::matrix::Matrix;
use crate::object::Object; use crate::object::Object;
use crate::parser::ParseError; use crate::parser::ParseError;
use crate::quantity::{self, Quantity, UnitRule, unit_rule};
use crate::value::{Number, Value}; use crate::value::{Number, Value};
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::HashSet; use std::collections::HashSet;
@@ -28,12 +26,7 @@ pub enum Reducer {
/// A single n-ary predicate asserting that every pair of items is distinct, like `a != b != c`. /// A single n-ary predicate asserting that every pair of items is distinct, like `a != b != c`.
ChainDistinct, ChainDistinct,
/// A single call of a variadic function over all items, like `min(a, b, c)`. /// A single call of a variadic function over all items, like `min(a, b, c)`.
Function { Function { function: BuiltinFunction, over_matrices: Option<MatrixFunction> },
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 /// The action of a variadic function across matrices: the mean is pointwise and the count counts, while the others need an
@@ -79,7 +72,6 @@ pub fn classify_reducer(source: &str, bindings: impl ValueProvider) -> Option<Re
match builtin_function(bare_name)? { match builtin_function(bare_name)? {
Builtin::Values { function, variadic: true } => Reducer::Function { Builtin::Values { function, variadic: true } => Reducer::Function {
function, function,
name: BUILTIN_FUNCTIONS.iter().find(|documented| documented.name == bare_name)?.name,
over_matrices: matrix_function(bare_name), over_matrices: matrix_function(bare_name),
}, },
_ => return None, _ => return None,
@@ -273,107 +265,6 @@ impl Reducer {
results.resize(items.len(), None); results.resize(items.len(), None);
results 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. /// A reducer's result in canonical form, or `None` for an indeterminate result, since no operation produces NaN.
@@ -469,7 +360,6 @@ mod tests {
use crate::ast; use crate::ast;
use crate::context::{EvalContext, NothingMap, ValueMap}; use crate::context::{EvalContext, NothingMap, ValueMap};
use crate::quaternion::Quaternion; use crate::quaternion::Quaternion;
use crate::units::Unit;
use crate::value::Complex; use crate::value::Complex;
use std::collections::HashMap; use std::collections::HashMap;
@@ -692,53 +582,4 @@ 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:?}");
}
}
}
} }
+5 -88
View File
@@ -1,10 +1,7 @@
use crate::ast::{BinaryOp, Binding, BuiltinCall, CallWhere, Case, Clause, Literal, Local, MatrixNode, Measure, Node, SortedCase, Syntax, UnaryOp, ValueNode}; use crate::ast::{BinaryOp, Binding, CallWhere, Case, Clause, Literal, Local, MatrixNode, Node, SortedCase, Syntax, UnaryOp, ValueNode};
use crate::constants::{Builtin, SuffixedFunction, builtin_function, suffixed_function}; use crate::constants::{Builtin, builtin_function, suffixed_function};
use crate::context::{FunctionProvider, NothingMap}; use crate::context::{FunctionProvider, NothingMap};
use crate::lexer::{names_matrix, offset_in}; 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::borrow::Cow;
use std::fmt; use std::fmt;
use std::ops::Range; use std::ops::Range;
@@ -305,10 +302,6 @@ impl<'src> Sorter<'_, 'src> {
Syntax::Lit(literal) => Node::Value(ValueNode::Lit(literal)), Syntax::Lit(literal) => Node::Value(ValueNode::Lit(literal)),
Syntax::Var(name) => self.name(name, 0), Syntax::Var(name) => self.name(name, 0),
Syntax::FnCall { name, expr } => self.call(name, expr, 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 } => { Syntax::BinOp { lhs, op, rhs } => {
let lhs = self.sort(*lhs); let lhs = self.sort(*lhs);
let rhs = self.sort(*rhs); let rhs = self.sort(*rhs);
@@ -401,10 +394,7 @@ impl<'src> Sorter<'_, 'src> {
match local { match local {
Some(local) => local, Some(local) => local,
None if names_matrix(name) => Node::Matrix(MatrixNode::Var(name.to_string())), None if names_matrix(name) => Node::Matrix(MatrixNode::Var(name.to_string())),
None => match unit_named(name) { None => Node::Value(ValueNode::Var(name.to_string())),
Some(unit) => Node::Value(ValueNode::Unit { name: name.to_string(), unit }),
None => Node::Value(ValueNode::Var(name.to_string())),
},
} }
} }
@@ -518,7 +508,6 @@ impl<'src> Sorter<'_, 'src> {
Ok(match builtin { Ok(match builtin {
Some(Builtin::OfMatrix(function)) => Node::Value(ValueNode::OfMatrix { Some(Builtin::OfMatrix(function)) => Node::Value(ValueNode::OfMatrix {
function, function,
unit: matrix_value_unit(bare_name),
matrix: Box::new(self.matrix(one(arguments).ok_or(invalid_arguments)?, VALUE_AS_MATRIX)?), matrix: Box::new(self.matrix(one(arguments).ok_or(invalid_arguments)?, VALUE_AS_MATRIX)?),
}), }),
Some(Builtin::MatrixOfMatrix(function)) => Node::Matrix(MatrixNode::OfMatrix { Some(Builtin::MatrixOfMatrix(function)) => Node::Matrix(MatrixNode::OfMatrix {
@@ -531,7 +520,6 @@ impl<'src> Sorter<'_, 'src> {
} }
Node::Matrix(MatrixNode::FromValues { Node::Matrix(MatrixNode::FromValues {
function, function,
units: builder_units(bare_name),
arguments: self.values(arguments)?, arguments: self.values(arguments)?,
}) })
} }
@@ -549,32 +537,10 @@ impl<'src> Sorter<'_, 'src> {
.by_ref() .by_ref()
.take(region_count) .take(region_count)
.map(|region| self.matrix(region, VALUE_AS_MATRIX)) .map(|region| self.matrix(region, VALUE_AS_MATRIX))
.collect::<Result<Box<[MatrixNode]>, SortError>>()?; .collect::<Result<Vec<MatrixNode>, SortError>>()?;
let trailing = arguments.next().map(|trailing| self.value(trailing, MATRIX_AS_VALUE).map(Box::new)).transpose()?; let trailing = arguments.next().map(|trailing| self.value(trailing, MATRIX_AS_VALUE).map(Box::new)).transpose()?;
Node::Value(ValueNode::OfValueAndRegions { Node::Value(ValueNode::OfValueAndRegions { function, value, regions, trailing })
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 { _ => Node::Value(ValueNode::FnCall {
name: name.to_string(), name: name.to_string(),
expr: self.values(arguments)?, expr: self.values(arguments)?,
@@ -655,22 +621,6 @@ impl<'src> Sorter<'_, 'src> {
let mut accumulated = first; let mut accumulated = first;
while let Some((op, factor)) = rest.next() { 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)?) { accumulated = match (accumulated, self.sort(factor)?) {
(Node::Matrix(matrix), Node::Value(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)` // Dividing by a value applies the matrix to its reciprocal times the rest, so `M / v w` is `M (v⁻¹ w)`
@@ -686,39 +636,6 @@ impl<'src> Sorter<'_, 'src> {
Ok(accumulated) 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. /// 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> { fn piecewise(&mut self, cases: Vec<Case<'src>>, otherwise: Option<Box<Syntax<'src>>>) -> Result<Node, SortError> {
let cases = cases let cases = cases
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff. Show more