Compare commits

..
30 changed files with 707 additions and 506 deletions

No files matched your search

Generated
-1
View File
@@ -2846,7 +2846,6 @@ dependencies = [
"bitflags 2.13.2",
"blake3",
"color",
"convert_case 0.12.0",
"core-types",
"derivative",
"document-container",
+55 -12
View File
@@ -104,7 +104,7 @@ impl<L: Layout> Gdd<L> {
Ok(rewritten) => rewritten,
Err(error) => {
log::warn!("Migrating this document's history failed, so undo can't reach before this point: {error}");
(self.session_with_truncated_history(migrated)?, remap_metadata(&self.metadata, |_| None))
(session_with_truncated_history(&self.session, migrated)?, remap_metadata(&self.metadata, |_| None))
}
};
self.keep_blobs_durably(blobs.into_added()).await?;
@@ -189,19 +189,24 @@ impl<L: Layout> Gdd<L> {
session.absorb_retired_marks(previous.retired_marks());
Ok((session, remap_metadata(&self.metadata, remap)))
}
}
/// A session whose history restarts from `migrated`.
fn session_with_truncated_history(&self, migrated: Registry) -> Result<Session, Error> {
let previous = &self.session;
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated.clone())?;
/// A session continuing `previous` whose history restarts from `migrated`.
fn session_with_truncated_history(previous: &Session, migrated: Registry) -> Result<Session, Error> {
let peer_users = migrated.peer_users.clone();
let restarted = Session::bootstrap_from_registry(previous.peer(), previous.user(), migrated)?;
let history: Vec<Delta> = restarted.history().cloned().collect();
let mut session = Session::load(previous.peer(), previous.user(), migrated, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
session.absorb_retired_marks(previous.retired_marks());
Ok(session)
}
// The bootstrap re-stamps every value, so its registry is the one matching its history. Its deltas leave out
// which user each device belongs to, so those registrations carry over directly.
let mut registry = restarted.retired_registry().clone();
registry.peer_users = peer_users;
let history: Vec<Delta> = restarted.history().cloned().collect();
let mut session = Session::load(previous.peer(), previous.user(), registry, history, restarted.head_rev(), Vec::new(), previous.next_node_counter());
session.restore_hot_sequence(previous.last_hot_sequence());
session.restore_clock_counter(previous.clock_counter().max(restarted.clock_counter()));
session.absorb_retired_marks(previous.retired_marks());
Ok(session)
}
/// Resolves declaration resources to the declarations migrations name. A declaration's resource derives from its identifier and version
@@ -269,3 +274,41 @@ impl DeclarationResolver for DocumentDeclarations {
Some(self.encoded.get(self.known.get(&resource)?)?.proto.clone())
}
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{AttributeDelta, RegistryDelta, Value};
#[test]
fn a_truncated_history_matches_its_registry_and_keeps_device_registrations() {
let other_device = PeerId(2);
let mut previous = Session::with_peer(PeerId(1));
previous
.stage_computed_ops(vec![RegistryDelta::RegisterPeer {
peer: other_device,
user: previous.user(),
}])
.unwrap();
previous.retire_all().unwrap();
// Each edit stamps the value later than a fresh bootstrap would
for edit in 0..10 {
let delta = AttributeDelta {
key: "edit".to_string(),
value: Some(Value::Str(edit.to_string())),
};
previous.stage_computed_ops(vec![RegistryDelta::ChangeDocumentAttribute { delta }]).unwrap();
previous.retire_all().unwrap();
}
let session = session_with_truncated_history(&previous, previous.retired_registry().clone()).unwrap();
assert_eq!(session.user_of(other_device), Some(previous.user()));
// Device registrations carry over apart from the history, so everything else must match its replay
let replayed = Session::replay_from_history(session.peer(), session.user(), session.history().cloned(), session.next_node_counter()).unwrap();
let mut registry = session.retired_registry().clone();
registry.peer_users = replayed.retired_registry().peer_users.clone();
assert_eq!(&registry, replayed.retired_registry());
}
}
+9
View File
@@ -7,6 +7,15 @@ use std::collections::{BTreeMap, btree_map};
/// keys live on `Node.inputs_attributes[i]`; per-network keys live on `Network.attributes`.
pub mod attr;
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
}
impl AttributeValue {
pub fn new(value: Value, timestamp: TimeStamp) -> Self {
Self { value, timestamp, deleted: false }
+1 -1
View File
@@ -44,7 +44,7 @@ pub use from_runtime::{
encode_node_ui_attributes, node_value_resource_refs, storage_location_id, storage_node_id, value_resource_ref,
};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
+1 -10
View File
@@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap};
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::document::NetworkLocation;
use crate::{NetworkReference, Value};
use crate::{NetworkReference, Position, Value};
/// One node's editor-side metadata, produced by `Registry::to_runtime_with_metadata`. One entry per
/// node, since every node carries an identity to restore even when it carries no `ui::*` attribute.
@@ -124,12 +124,3 @@ pub trait NodeMetadataSource {
pub struct NoMetadata;
impl NodeMetadataSource for NoMetadata {}
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
}
+3
View File
@@ -22,6 +22,9 @@ impl Node {
pub fn inputs_mut(&mut self) -> &mut Vec<InputSlot> {
&mut self.inputs
}
pub fn attributes_mut(&mut self) -> &mut Attributes {
&mut self.attributes
}
/// True if both nodes agree on every value-bearing field, ignoring slot/attribute timestamps.
pub fn value_equal(&self, other: &Self) -> bool {
@@ -1,9 +1,10 @@
use document_graph_storage::attr::node::VISIBLE;
use document_graph_storage::attr::node::ui::DISPLAY_NAME;
use graphene_std::Color;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::Gradient;
use migration_core::{Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use migration_core::{Attributes, Compiler, Inputs, MigrationError, NewNode, Node, NodeInput, Target, Upstream, decl, literal, literal_of, migration};
use serde::{Deserialize, Serialize};
const CONTENT: usize = 1;
@@ -29,11 +30,23 @@ fn number(input: &NodeInput) -> Option<f64> {
/// Repeat on Points overwrites. Content that doesn't compile takes Flatten Graphic, which can't make that state any worse. A hidden node only passes
/// its points through, so it needs nothing past the repeat, and its unused scale and rotation are dropped.
#[migration("core_types::vector::CopyToPointsNode"@1 => "transform_nodes::transform_nodes::VaryRotationsNode"@2)]
pub fn vary_nodes_from_copy_to_points(node: &Node, compiler: Option<&dyn Compiler>, inputs: &mut Inputs, upstream: &mut Upstream, target: &mut Target) -> Result<(), MigrationError> {
pub fn vary_nodes_from_copy_to_points(
node: &Node,
compiler: Option<&dyn Compiler>,
inputs: &mut Inputs,
upstream: &mut Upstream,
target: &mut Target,
attributes: &mut Attributes,
) -> Result<(), MigrationError> {
let slots: Vec<NodeInput> = node.inputs().iter().map(|slot| slot.input.clone()).collect();
let [points, content, scale_min, scale_max, scale_bias, scale_seed, rotation, rotation_seed] =
<[NodeInput; 8]>::try_from(slots).map_err(|_| MigrationError::invariant("Copy to Points has eight inputs"))?;
// A stored default name would misname the new node
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Copy to Points") {
attributes.remove(node.id(), DISPLAY_NAME);
}
let repeat = decl!("repeat_nodes::repeat_nodes::RepeatOnPointsNode"@1);
let unset = || literal(Tagged::Bool(false));
@@ -170,6 +183,8 @@ fn bias_keeping_average_scale(bias: f64) -> f64 {
mod tests {
use super::*;
use crate::CompilerHost;
use document_graph_storage::attr::node::ui::POSITION;
use document_graph_storage::{NodeId, Position, TimeStamp, Value, to_value};
use migration_core::Declaration;
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
@@ -184,10 +199,13 @@ mod tests {
}
fn contract() -> SourceContract {
SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
SourceContract {
display_names: &["Copy to Points"],
..SourceContract::new(8, |random: &mut Random, slot| match slot {
2 | 3 | 4 | 6 => literal(Tagged::Number(random.below(3) as f64)),
_ => literal(Tagged::Integer(random.below(3) as i64)),
})
}
}
fn star_inputs() -> Vec<NodeInput> {
@@ -262,6 +280,48 @@ mod tests {
assert_eq!(number(&fixture.inputs(&migrated, rotations)[2]), Some(45.));
}
#[test]
fn the_default_name_is_cleared() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
let name = Value::Str("Copy to Points".to_string());
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(DISPLAY_NAME, name, TimeStamp::ORIGIN);
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
assert!(migrated.node_instances[&copies].attributes().get_typed::<String>(DISPLAY_NAME).is_none());
}
/// Matches the layout the legacy migration gives a star copied at a scale of 2 with random rotations spanning 90°.
#[test]
fn stages_lead_up_to_a_placed_node_in_a_row() {
let mut fixture = Fixture::new(&VaryNodesFromCopyToPoints);
let star = fixture.add(STAR, star_inputs());
let copies = fixture.add(COPY_TO_POINTS, inputs(NodeInput::Node { id: star, index: 0 }, 2., 90.));
let position = to_value(&Position::Absolute([20, 10])).unwrap();
fixture.registry.node_instances.get_mut(&copies).unwrap().attributes_mut().set(POSITION, position, TimeStamp::ORIGIN);
let migrated = fixture.migrate_with(&VaryNodesFromCopyToPoints, Some(&host())).unwrap();
let position_of = |node: NodeId| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION);
// Walk back from the anchor through each stage's points
let mut stages = Vec::new();
let mut stage = copies;
while let NodeInput::Node { id, .. } = fixture.inputs(&migrated, stage)[0]
&& id != star
{
stages.insert(0, position_of(id));
stage = id;
}
let NodeInput::Node { id: group, .. } = fixture.inputs(&migrated, stage)[1] else {
panic!("the repeat reads the group")
};
assert_eq!(stages, [-1, 6, 13].map(|x| Some(Position::Absolute([x, 10]))));
assert_eq!(position_of(group), Some(Position::Absolute([-8, 13])));
}
#[test]
fn bias_keeps_its_average() {
assert_eq!(bias_keeping_average_scale(0.), 0.5);
+2 -2
View File
@@ -29,7 +29,7 @@ pub use connector::{InputConnector, NewNode, OutputConnector};
#[cfg(feature = "typed")]
pub use declaration::{Declaration, DeclarationKind, DeclarationResolver};
#[cfg(feature = "typed")]
pub use document_graph_storage::NodeInput;
pub use document_graph_storage::{NodeInput, Position, attr};
pub use error::MigrationError;
pub use format::{DocumentPayloads, FormatMigration, HistoryPolicy, Upgrade};
#[cfg(feature = "typed")]
@@ -44,7 +44,7 @@ pub use registry::{register_migration, registered_migrations};
#[cfg(feature = "typed")]
pub use value::{encode, literal, literal_of};
#[cfg(feature = "typed")]
pub use view::{AddedNode, AnchorContext, Downstream, Edits, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
pub use view::{AddedNode, AnchorContext, AttributeWrite, Attributes, CHAIN_WIDTH, Downstream, Edits, FEEDER_ROW_HEIGHT, Graph, Inputs, InputsEdit, Node, Region, Target, Upstream, View, implements};
// For the registration `#[migration]`, `rename!`, and `format_migration!` generate
#[doc(hidden)]
+63 -2
View File
@@ -1,7 +1,13 @@
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector};
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode};
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp, Value};
use serde::Serialize;
use std::ops::Deref;
/// How many grid cells the editor's layout steps left for each node of a layer's chain.
pub const CHAIN_WIDTH: i32 = 7;
/// How many grid cells apart the rows of nodes feeding a node from below are.
pub const FEEDER_ROW_HEIGHT: i32 = 3;
/// Which part of the registry around an anchor a view reads or edits. A migration's footprint is the union of its views' regions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Region(u8);
@@ -14,6 +20,8 @@ impl Region {
pub const DOWNSTREAM: Self = Self(1 << 3);
/// The anchor's whole network, as read through [`Graph`].
pub const NETWORK: Self = Self(1 << 4);
/// Attributes of the anchor and of the nodes the run adds, such as their positions and display names.
pub const ATTRIBUTES: Self = Self(1 << 5);
pub const fn union(self, other: Self) -> Self {
Self(self.0 | other.0)
@@ -223,6 +231,8 @@ pub struct Edits {
pub connections: Vec<(OutputConnector, InputConnector)>,
/// The declaration this anchor switches to, when not the migration's target.
pub target: Option<Declaration>,
/// Attribute writes to the anchor and the nodes this run adds.
pub attributes: Vec<AttributeWrite>,
}
impl Edits {
@@ -234,6 +244,57 @@ impl Edits {
self.removed_nodes.extend(other.removed_nodes);
self.connections.extend(other.connections);
self.target = other.target.or(self.target);
self.attributes.extend(other.attributes);
}
}
/// One attribute of the anchor or of a node the run adds. A run's writes apply in the order it recorded them.
#[derive(Debug)]
pub struct AttributeWrite {
pub node: NodeId,
pub key: String,
/// `None` deletes the key.
pub value: Option<Value>,
}
/// Attributes of the anchor and of the nodes this run adds, such as where they sit and what they're named.
#[derive(Default)]
pub struct Attributes {
writes: Vec<AttributeWrite>,
}
impl Attributes {
/// Write `value` under `key` on the anchor or on a node this run adds.
pub fn set<T: Serialize>(&mut self, node: NodeId, key: &str, value: &T) {
self.writes.push(AttributeWrite {
node,
key: key.to_string(),
value: Some(encode(value)),
});
}
/// Delete `key` from the anchor or from a node this run adds.
pub fn remove(&mut self, node: NodeId, key: &str) {
self.writes.push(AttributeWrite {
node,
key: key.to_string(),
value: None,
});
}
}
impl<'a> View<'a> for Attributes {
const REGION: Region = Region::ATTRIBUTES;
fn extract(_context: &AnchorContext<'a>) -> Self {
Self::default()
}
fn into_edits(self) -> Result<Edits, MigrationError> {
Ok(Edits {
attributes: self.writes,
..Default::default()
})
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ use syn::{Error, FnArg, Ident, ItemFn, ReturnType, Type, parse_macro_input};
/// A `network` prefix names a built-in network definition, as in `#[migration(network "Merge"@1 => "module::merge"@2)]`.
///
/// Parameters state what the migration reads and writes: `&Node` and `&Graph` read the source state, `Option<&dyn Compiler>` asks what only the
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
/// compiler can tell about it, and each `&mut` parameter is a view (`Inputs`, `Upstream`, `Downstream`, `Target`, `Attributes`) recording edits to its region. The function may return `()` or `Result<(), MigrationError>`.
///
/// Generates a unit struct named after the function in Pascal case implementing `NodeMigration`, and registers it.
#[proc_macro_attribute]
+2
View File
@@ -40,6 +40,8 @@ pub enum RunnerError {
DuplicateAddedNode { anchor: NodeId, declaration: Declaration, key: String },
#[error("added node {0:?} already exists")]
AddedNodeExists(NodeId),
#[error("node {anchor:?} writes attributes of {node:?}, which is neither it nor a node it adds")]
AttributesOutsideRegion { anchor: NodeId, node: NodeId },
#[error("{0:?} is rewired by one anchor while its own migration replaces or removes it")]
ConflictingSlot(InputConnector),
#[error("{0:?} does not exist in the migrated state")]
+93 -3
View File
@@ -2,10 +2,12 @@
use crate::{MigrationBlobs, RunnerError};
use document_graph_storage::TimeStamp;
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::attributes::attr::node::ui::{IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{AnchorContext, Compiler, Declaration, DeclarationResolver, Edits, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, implements};
use document_graph_storage::{Delta, Implementation, NetworkId, Node, NodeId, NodeInput, Position, ProtoNode, Registry, RegistryDelta, ResourceHash, ResourceId, Rev, apply_retired_op};
use migration_core::{
AnchorContext, CHAIN_WIDTH, Compiler, Declaration, DeclarationResolver, Edits, FEEDER_ROW_HEIGHT, InputConnector, InputsEdit, MigrationHost, NodeMigration, OutputConnector, encode, implements,
};
use std::collections::{HashMap, HashSet};
/// A [`DeclarationResolver`] over a fixed set of declarations for tests, whose resource IDs derive from `identifier@version` rather than the encoded declarations documents store.
@@ -173,6 +175,10 @@ fn apply_runs(migration: &dyn NodeMigration, source: &Registry, anchors: &[NodeI
}
add_nodes(&mut target, &runs, resolver)?;
for (anchor, edits) in &runs {
place_added_nodes(&mut target, *anchor, edits);
write_attributes(&mut target, *anchor, edits)?;
}
let input_edits: HashMap<NodeId, &InputsEdit> = runs.iter().filter_map(|(anchor, edits)| Some((*anchor, edits.inputs.as_ref()?))).collect();
for (anchor, inputs) in &input_edits {
@@ -328,6 +334,90 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec
Ok(())
}
/// Default positions for the nodes one run adds, read from the anchor's own position only. The nodes leading up to the anchor's
/// chain input form a row, or join the chain of a chained or layer anchor. Each other node sits below the first one reading it,
/// or on the anchor when none does. Without absolute coordinates for the anchor, only the chain is placed.
fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
let Some(anchor_node) = target.node_instances.get(&anchor) else { return };
let stored = anchor_node.attributes().get_typed::<Position>(POSITION);
let is_layer = anchor_node.attributes().get_or(IS_LAYER, false);
let anchor_inputs: Vec<NodeInput> = match &edits.inputs {
Some(inputs) => inputs.slots.iter().map(|slot| slot.input.clone()).collect(),
None => anchor_node.inputs().iter().map(|slot| slot.input.clone()).collect(),
};
let added_inputs: HashMap<NodeId, &[NodeInput]> = edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())).collect();
let reads = |inputs: &[NodeInput], node: NodeId| inputs.iter().any(|input| matches!(input, NodeInput::Node { id, .. } if *id == node));
let chain_input = if is_layer { 1 } else { 0 };
let mut chain = Vec::new();
let mut next = anchor_inputs.get(chain_input);
while let Some(NodeInput::Node { id, .. }) = next
&& let Some(inputs) = added_inputs.get(id)
&& !chain.contains(id)
{
chain.push(*id);
next = inputs.first();
}
let joins_chain = is_layer || stored == Some(Position::Chain);
let coordinates = match stored {
Some(Position::Absolute(coordinates)) => Some(coordinates),
_ => None,
};
let mut positions = Vec::new();
for (step, id) in chain.iter().enumerate() {
match coordinates {
_ if joins_chain => positions.push((*id, Position::Chain)),
Some([x, y]) => positions.push((*id, Position::Absolute([x - CHAIN_WIDTH * (step as i32 + 1), y]))),
None => {}
}
}
if let Some([x, y]) = coordinates {
let readers: Vec<(&[NodeInput], i32)> = std::iter::once((anchor_inputs.as_slice(), x))
.chain(chain.iter().enumerate().map(|(step, id)| (added_inputs[id], x - CHAIN_WIDTH * (step as i32 + 1))))
.collect();
let mut feeders_below = vec![0; readers.len()];
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
let position = match readers.iter().position(|(inputs, _)| reads(inputs, added.id)) {
Some(reader) => {
feeders_below[reader] += 1;
[readers[reader].1 - CHAIN_WIDTH, y + FEEDER_ROW_HEIGHT * feeders_below[reader]]
}
None => [x, y],
};
positions.push((added.id, Position::Absolute(position)));
}
}
for (id, position) in positions {
if let Some(node) = target.node_instances.get_mut(&id) {
node.attributes_mut().set(POSITION, encode(&position), TimeStamp::ORIGIN);
}
}
}
/// Apply one run's attribute writes, which may only name its anchor and the nodes it adds.
fn write_attributes(target: &mut Registry, anchor: NodeId, edits: &Edits) -> Result<(), RunnerError> {
for write in &edits.attributes {
let in_region = write.node == anchor || edits.added_nodes.iter().any(|added| added.id == write.node);
let node = target.node_instances.get_mut(&write.node).filter(|_| in_region);
let node = node.ok_or(RunnerError::AttributesOutsideRegion { anchor, node: write.node })?;
match &write.value {
Some(value) => node.attributes_mut().set(&write.key, value.clone(), TimeStamp::ORIGIN),
None => {
node.attributes_mut().remove(&write.key);
}
}
}
Ok(())
}
/// Make `consumer`, named in the source layout, read `output` in the target layout. Fails when the consumer's own migration replaced or
/// removed that slot, since two runs then disagree on what it should read.
fn connect(target: &mut Registry, output: OutputConnector, consumer: InputConnector, input_edits: &HashMap<NodeId, &InputsEdit>) -> Result<(), RunnerError> {
+37 -3
View File
@@ -3,9 +3,10 @@
use crate::node::{apply_migration, needs_whole_states, rewrite_history};
use crate::{DeclarationTable, MigrationBlobs, RunnerError, references, registry_at};
use document_graph_storage::attributes::attr::node::ui::REFERENCE;
use document_graph_storage::attributes::attr::node::ui::{DISPLAY_NAME, IS_LAYER, POSITION, REFERENCE};
use document_graph_storage::{
Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, apply_retired_op,
AttributeDelta, Delta, ExportSlot, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, Position, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp, UserId, Value,
apply_retired_op, to_value,
};
use migration_core::{Declaration, DeclarationResolver, MigrationHost, NodeMigration, decl, implements, literal, registered_migrations};
use std::collections::HashSet;
@@ -138,6 +139,8 @@ pub struct SourceContract {
pub literal: fn(&mut Random, usize) -> NodeInput,
/// Whether a slot may read an output of another node of the source declaration.
pub reads_own_output: fn(usize) -> bool,
/// Display names, besides a custom one, that generated histories give nodes, such as a default the migration clears.
pub display_names: &'static [&'static str],
}
impl SourceContract {
@@ -146,6 +149,7 @@ impl SourceContract {
input_count,
literal,
reads_own_output: |_| true,
display_names: &[],
}
}
}
@@ -276,11 +280,36 @@ impl Generator<'_> {
self.commit_interaction(ops);
}
/// A name, position, or layer flag, written or deleted.
fn attribute(&mut self) -> AttributeDelta {
let (key, value) = match self.random.below(3) {
0 => {
let names = self.contract.display_names;
let name = match self.random.below(names.len() + 2) {
index if index < names.len() => Some(names[index]),
index if index == names.len() => Some("Renamed"),
_ => None,
};
(DISPLAY_NAME, name.map(|name| Value::Str(name.to_string())))
}
1 => {
let position = match self.random.below(3) {
0 => Position::Chain,
_ => Position::Absolute([self.random.below(20) as i32, self.random.below(20) as i32]),
};
(POSITION, Some(to_value(&position).expect("positions serialize")))
}
_ => (IS_LAYER, (self.random.below(2) == 0).then_some(Value::Bool(true))),
};
AttributeDelta { key: key.to_string(), value }
}
fn step(&mut self) {
let nodes = self.live_nodes();
let root_nodes = self.live_nodes_in(ROOT_NETWORK);
match self.random.below(11) {
match self.random.below(13) {
0..=3 => {
let (declaration, input_count) = if self.random.below(3) == 0 {
(self.source, self.contract.input_count)
@@ -335,6 +364,11 @@ impl Generator<'_> {
self.session.undo().expect("an interaction is left to undo");
self.undoable -= 1;
}
11 | 12 if !nodes.is_empty() => {
let id = self.random.pick(&nodes);
let delta = self.attribute();
self.commit(RegistryDelta::ChangeNodeAttribute { id, delta });
}
_ => {}
}
}
@@ -0,0 +1,137 @@
//! Attribute writes on the anchor and the nodes it adds, and the positions added nodes get by default.
use document_graph_storage::attr::node::ui::{DISPLAY_NAME, POSITION};
use document_graph_storage::{NodeId, NodeInput, Position, Value, to_value};
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, FEEDER_ROW_HEIGHT, Inputs, NewNode, Node, Upstream, decl, migration};
use migration_runner::RunnerError;
use migration_runner::testing::Fixture;
/// Clears the anchor's old default name and places a node it adds.
#[migration("attributes::renamed"@1 => @2)]
pub fn renamed(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Old name") {
attributes.remove(node.id(), DISPLAY_NAME);
}
let added = downstream.add_node(NewNode {
declaration: decl!("math_nodes::add"@1),
inputs: vec![],
});
attributes.set(added, POSITION, &Position::Absolute([3, 4]));
}
/// Renames the node its first input reads, which it neither is nor adds.
#[migration("attributes::outside"@1 => @2)]
pub fn outside(node: &Node, attributes: &mut Attributes) {
if let Some(NodeInput::Node { id, .. }) = node.inputs().first().map(|slot| &slot.input) {
attributes.set(*id, DISPLAY_NAME, &"Renamed");
}
}
/// Adds two nodes leading up to the anchor's first input, and one feeding the nearer of them from below.
#[migration("attributes::placed"@1 => @2)]
pub fn placed(node: &Node, inputs: &mut Inputs, upstream: &mut Upstream) {
let add = decl!("math_nodes::add"@1);
let source = node.inputs().first().map_or(NodeInput::Import { index: 0 }, |slot| slot.input.clone());
let far = upstream.add_node_keyed(
NewNode {
declaration: add,
inputs: vec![source],
},
"far",
);
let below = upstream.add_node_keyed(NewNode { declaration: add, inputs: vec![] }, "below");
let near = upstream.add_node_keyed(
NewNode {
declaration: add,
inputs: vec![wire(far), wire(below)],
},
"near",
);
inputs.set(0, wire(near));
}
fn set_name(fixture: &mut Fixture, node: NodeId, name: &str) {
let name = Value::Str(name.to_string());
fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut().set(DISPLAY_NAME, name, Default::default());
}
/// The positions of the far, near, and below nodes `Placed` adds for an anchor stored at `position`.
fn placed_around(position: Position) -> [Option<Position>; 3] {
let migration = &Placed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::placed"@1), vec![NodeInput::Import { index: 0 }]);
let position = to_value(&position).unwrap();
fixture.registry.node_instances.get_mut(&anchor).unwrap().attributes_mut().set(POSITION, position, Default::default());
let migrated = fixture.migrate(migration).unwrap();
let position_of = |id: NodeId| migrated.node_instances[&id].attributes().get_typed::<Position>(POSITION);
let NodeInput::Node { id: near, .. } = fixture.inputs(&migrated, anchor)[0] else {
panic!("the anchor reads the near node")
};
let [NodeInput::Node { id: far, .. }, NodeInput::Node { id: below, .. }] = fixture.inputs(&migrated, near)[..] else {
panic!("the near node reads the far and below nodes")
};
[position_of(far), position_of(near), position_of(below)]
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn a_run_writes_its_anchor_and_the_nodes_it_adds() {
let migration = &Renamed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
set_name(&mut fixture, anchor, "Old name");
fixture.export(wire(anchor));
let migrated = fixture.migrate(migration).unwrap();
assert!(migrated.node_instances[&anchor].attributes().get(DISPLAY_NAME).is_none());
let added = migrated.node_instances.iter().find(|(id, _)| **id != anchor).map(|(_, node)| node).expect("the run adds a node");
assert_eq!(added.attributes().get_typed::<Position>(POSITION), Some(Position::Absolute([3, 4])));
}
#[test]
fn a_name_given_by_the_user_is_kept() {
let migration = &Renamed;
let mut fixture = Fixture::new(migration);
let anchor = fixture.add(decl!("attributes::renamed"@1), vec![]);
set_name(&mut fixture, anchor, "Mine");
let migrated = fixture.migrate(migration).unwrap();
assert_eq!(migrated.node_instances[&anchor].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), Some("Mine"));
}
#[test]
fn added_nodes_lead_up_to_a_placed_anchor() {
let [far, near, below] = placed_around(Position::Absolute([20, 10]));
assert_eq!(far, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10])));
assert_eq!(near, Some(Position::Absolute([20 - CHAIN_WIDTH, 10])));
assert_eq!(below, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10 + FEEDER_ROW_HEIGHT])));
}
#[test]
fn added_nodes_join_a_chained_anchors_chain() {
let [far, near, below] = placed_around(Position::Chain);
assert_eq!([far, near], [Some(Position::Chain); 2]);
assert_eq!(below, None);
}
#[test]
fn writing_another_nodes_attributes_fails() {
let migration = &Outside;
let mut fixture = Fixture::new(migration);
let other = fixture.add(decl!("math_nodes::add"@1), vec![]);
fixture.add(decl!("attributes::outside"@1), vec![wire(other)]);
let error = fixture.migrate(migration).unwrap_err();
assert!(matches!(error, RunnerError::AttributesOutsideRegion { node, .. } if node == other), "{error}");
}
@@ -1,3 +1,4 @@
mod attributes;
mod blobs;
mod compiler;
mod examples;
@@ -13,6 +13,9 @@ fn every_migration_registers_once() {
sources.sort();
let mut expected = vec![
decl!("attributes::outside"@1),
decl!("attributes::placed"@1),
decl!("attributes::renamed"@1),
decl!("blending_nodes::opacity"@1),
decl!("blob_nodes::text"@1),
decl!("compiler::anchor"@1),
+1 -1
View File
@@ -168,7 +168,7 @@ fn write_step(migrations: &Path, node: &NodeSource, name: &str, step: &str, from
/// Describe what changed from version {from}.\n\
#[migration({step})]\n\
pub fn {name}(inputs: &mut Inputs) {{\n\
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, or `&mut Downstream`\");\n\
\tcompile_error!(\"Migrate from version {from} here. Read the source state with `&Node` or `&Graph`, and edit it through `&mut Inputs`, `&mut Upstream`, `&mut Downstream`, or `&mut Attributes`\");\n\
}}\n\n\
#[cfg(test)]\n\
mod tests {{\n\
+1 -2
View File
@@ -26,7 +26,6 @@ document-format = { workspace = true, features = ["migrations", "network"] }
migration-formats = { workspace = true }
migration-compiled = { workspace = true }
migration-nodes = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
document-graph-storage = { workspace = true, features = ["conversion"] }
document-container = { workspace = true }
peer-transport = { workspace = true }
@@ -50,7 +49,6 @@ kurbo = { workspace = true }
futures = { workspace = true }
glam = { workspace = true }
derivative = { workspace = true }
convert_case = { workspace = true }
tsify = { workspace = true }
dyn-any = { workspace = true }
num_enum = { workspace = true }
@@ -82,3 +80,4 @@ env_logger = { workspace = true }
futures = { workspace = true }
node-macro = { workspace = true }
core-types = { workspace = true }
migration-core = { workspace = true, features = ["typed"] }
@@ -65,9 +65,9 @@ const DEFAULT_ROWS_IN_VIEW: Range<usize> = 0..100;
impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanelMessageHandler {
fn process_message(&mut self, message: DataPanelMessage, responses: &mut VecDeque<Message>, context: DataPanelMessageContext) {
match message {
DataPanelMessage::UpdateLayout { inspect_result } => {
self.introspected_data = inspect_result.data;
self.introspected_node_path = inspect_result.node_path;
DataPanelMessage::UpdateLayout { mut inspect_result } => {
self.introspected_data = inspect_result.take_data();
self.introspected_node_path = inspect_result.inspect_node_path;
self.context = inspect_result.context;
self.update_layout(responses, context);
}
@@ -618,7 +618,7 @@ impl<T: TableItemLayout> TableItemLayout for Item<T> {
}
}
let attribute_keys: Vec<String> = self.attributes().keys().map(str::to_string).collect();
let attribute_keys: Vec<String> = self.attributes().keys().filter(|key| !key.starts_with(INTERNAL_ATTRIBUTE_PREFIX)).map(str::to_string).collect();
// A single element, so no leading ID column, unlike the `List` table
let saved_gradient_settings = data.gradient_settings;
@@ -8,11 +8,9 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::document_migration::legacy_aliases;
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
use crate::node_graph_executor::NodeGraphExecutor;
use convert_case::{Boundary, Case, Casing};
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::value::*;
@@ -23,7 +21,6 @@ use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color,
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::*;
use migration_core::{DeclarationKind, NodeMigration};
use std::collections::{HashMap, VecDeque};
pub struct NodeInspectorContext<'a> {
@@ -1623,8 +1620,6 @@ impl InputTypeConstraint {
/// The node catalog's entries, ordered by category and then by name.
pub fn collect_node_types() -> Vec<FrontendNodeType> {
let migrations = migration_core::registered_migrations();
let mut node_types: Vec<FrontendNodeType> = DOCUMENT_NODE_TYPES
.iter()
// A Passthrough is placed as a redirect dot on a wire, so it isn't offered as a node
@@ -1638,7 +1633,6 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
FrontendNodeType {
identifier: identifier.serialized(),
input_types: InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, &name),
search_aliases: former_names(identifier, &name, &migrations),
name,
category: definition.category.to_string(),
}
@@ -1653,51 +1647,6 @@ pub fn collect_node_types() -> Vec<FrontendNodeType> {
node_types
}
/// The display names of every declaration that migrates, directly or through others, to the node of `identifier`, and of its legacy aliases.
fn former_names(identifier: &DefinitionIdentifier, current_name: &str, migrations: &[&'static dyn NodeMigration]) -> Vec<String> {
let (current, legacy_aliases): (_, Vec<&str>) = match identifier {
DefinitionIdentifier::ProtoNode(proto_node_identifier) => ((proto_node_identifier.as_str(), DeclarationKind::Proto), legacy_aliases(proto_node_identifier).collect()),
DefinitionIdentifier::Network(name) => ((name.as_str(), DeclarationKind::Network), Vec::new()),
};
let mut visited = vec![current];
let mut pending = vec![current];
while let Some((identifier, kind)) = pending.pop() {
for migration in migrations {
let (source, target) = (migration.source(), migration.target());
let predecessor = (source.identifier, source.kind);
if target.identifier == identifier && target.kind == kind && !visited.contains(&predecessor) {
visited.push(predecessor);
pending.push(predecessor);
}
}
}
let mut names: Vec<String> = visited
.into_iter()
.skip(1)
.chain(legacy_aliases.into_iter().map(|alias| (alias, DeclarationKind::Proto)))
.map(|(identifier, kind)| declaration_display_name(identifier, kind))
.filter(|name| !name.eq_ignore_ascii_case(current_name))
.collect();
names.sort();
names.dedup();
names
}
/// A network definition's identifier is its display name, and a proto node's is approximated from its type name, like `MathFxNode` becoming "Math Fx".
fn declaration_display_name(identifier: &str, kind: DeclarationKind) -> String {
match kind {
DeclarationKind::Network => identifier.to_string(),
DeclarationKind::Proto => {
let type_name = identifier.rsplit("::").next().unwrap_or(identifier);
let name = type_name.strip_suffix("Node").unwrap_or(type_name);
name.set_boundaries(&[Boundary::LowerUpper, Boundary::DigitUpper, Boundary::Acronym]).to_case(Case::Title)
}
}
}
pub fn collect_node_descriptions() -> Vec<(String, String)> {
DOCUMENT_NODE_TYPES
.iter()
@@ -120,9 +120,6 @@ pub struct FrontendNodeType {
pub category: String,
#[serde(rename = "inputTypes")]
pub input_types: Vec<InputTypeConstraint>,
/// Names the node went by before migrations replaced it, which the catalog search also matches.
#[serde(rename = "searchAliases")]
pub search_aliases: Vec<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -55,14 +55,6 @@ fn into_group_aliases() -> impl Iterator<Item = &'static &'static str> {
.flat_map(|replacement| replacement.aliases)
}
/// The identifiers and display names that legacy documents use for `node`.
pub fn legacy_aliases(node: &ProtoNodeIdentifier) -> impl Iterator<Item = &'static str> + '_ {
NODE_REPLACEMENTS
.iter()
.filter(move |replacement| replacement.node == *node)
.flat_map(|replacement| replacement.aliases.iter().copied())
}
/// Clears a migrated node's stored display name if it was only the replaced node's default name, so it shows its new node's name instead.
fn reset_default_display_name(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], old_default_name: &str) {
if document.network_interface.display_name(node_id, network_path) == old_default_name {
@@ -361,8 +353,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_and::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalAndNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_math_nodes::LogicalAndNode",
],
},
@@ -370,8 +362,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_not::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalNotNode",
"graphene_core::ops::LogicNotNode",
"graphene_core::logic::LogicNotNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_math_nodes::LogicalNotNode",
],
},
@@ -379,8 +371,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::logical_or::IDENTIFIER,
aliases: &[
"graphene_core::ops::LogicalOrNode",
"graphene_core::ops::LogicOrNode",
"graphene_core::logic::LogicOrNode",
"graphene_core::ops::LogicAndNode",
"graphene_core::logic::LogicAndNode",
"graphene_math_nodes::LogicalOrNode",
],
},
@@ -1941,7 +1933,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
&& inner.nodes.values().any(|n| {
matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::floor::IDENTIFIER)
&& n.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. }))
}) && let Some(node_definition) = resolve_network_node_type("Blend")
})
&& let Some(node_definition) = resolve_network_node_type("Blend")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
@@ -1953,7 +1946,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
n.inputs
.iter()
.any(|input| matches!(input, NodeInput::Import { import_type, import_index: 2 } if *import_type == item!(f64)))
}) && let Some(node_definition) = resolve_network_node_type("Regex Find")
})
&& let Some(node_definition) = resolve_network_node_type("Regex Find")
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
+25 -86
View File
@@ -15,7 +15,7 @@ use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic};
use graphene_std::{ATTR_TRANSFORM, Graphic};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -39,18 +39,8 @@ pub struct ExecutionResponse {
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
dropped_thumbnails: Vec<NodeId>,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The latest result of each observation.
observations: HashMap<ObservationKey, InspectResult>,
}
/// Names an observation so it can be changed or stopped without touching the others.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ObservationKey {
/// The node the Data panel inspects.
DataPanel,
// TODO: Eventually remove this document upgrade code
/// The "Fill" node whose geometry a gradient migration measures.
FillMeasurement,
/// The resulting value from the temporary inspected during execution
inspect_result: Option<InspectResult>,
}
#[derive(Debug)]
@@ -91,16 +81,9 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
Thumbnails {
responses: VecDeque<FrontendMessage>,
document_id: DocumentId,
},
/// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg {
id: u64,
svg: Option<String>,
},
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
InspectResult(Box<InspectResult>),
ClipboardSvg { id: u64, svg: Option<String> },
}
#[derive(Debug)]
@@ -115,8 +98,6 @@ pub struct NodeGraphExecutor {
node_graph_document: Option<DocumentId>,
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
previous_node_to_inspect: Vec<NodeId>,
/// The context overrides the Data panel evaluates its inspected node with, reset when another node is inspected.
inspect_context_overrides: ContextOverrides,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
/// Evaluation errors of the last evaluation, used in tests
@@ -171,7 +152,6 @@ impl NodeGraphExecutor {
node_graph_hash: 0,
node_graph_document: None,
previous_node_to_inspect: Vec::new(),
inspect_context_overrides: ContextOverrides::default(),
canvas_images_sent: HashSet::new(),
#[cfg(test)]
evaluation_errors: None,
@@ -208,16 +188,8 @@ impl NodeGraphExecutor {
execution_id
}
pub fn submit_inspect_context_overrides(&mut self, overrides: ContextOverrides) {
self.inspect_context_overrides = overrides;
let Some(observation) = self.data_panel_observation() else { return };
self.sender
.send(GraphRuntimeRequest::Observe {
key: ObservationKey::DataPanel,
observation: Some(observation),
})
.expect("Failed to send the context overrides");
pub fn submit_inspect_context_overrides(&self, overrides: graphene_std::ContextOverrides) {
self.sender.send(GraphRuntimeRequest::InspectContextOverrides(overrides)).expect("Failed to send the context overrides");
}
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
@@ -256,9 +228,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::new(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -266,17 +238,12 @@ impl NodeGraphExecutor {
/// 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> {
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
if inspected_node_changed {
self.previous_node_to_inspect = node_to_inspect;
self.inspect_context_overrides = ContextOverrides::default();
}
let network_hash = document.network_interface.network_hash();
if network_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths();
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.node_graph_hash = network_hash;
self.node_graph_document = Some(document_id);
@@ -286,38 +253,19 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect,
previewed,
layers,
observations: self.observations(),
}))
.map_err(|e| e.to_string())?;
} else if inspected_node_changed {
let observation = self.data_panel_observation();
self.sender
.send(GraphRuntimeRequest::Observe {
key: ObservationKey::DataPanel,
observation,
})
.map_err(|e| e.to_string())?;
} else if self.previous_node_to_inspect != node_to_inspect {
self.previous_node_to_inspect.clone_from(&node_to_inspect);
self.sender.send(GraphRuntimeRequest::Inspect(node_to_inspect)).map_err(|e| e.to_string())?;
}
Ok(())
}
/// What the Data panel reads back, if it inspects a node.
fn data_panel_observation(&self) -> Option<Observation> {
(!self.previous_node_to_inspect.is_empty()).then(|| Observation {
node_path: self.previous_node_to_inspect.clone(),
connector: ObservedConnector::Output,
overrides: self.inspect_context_overrides.clone(),
})
}
/// Every observation a graph update of the document starts with.
fn observations(&self) -> HashMap<ObservationKey, Observation> {
self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation)).into_iter().collect()
}
/// Adds an evaluate request for whatever current network is cached.
pub(crate) fn submit_current_node_graph_evaluation(
&mut self,
@@ -481,9 +429,9 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: Vec::new(),
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -519,7 +467,7 @@ impl NodeGraphExecutor {
responses: existing_responses,
dropped_thumbnails,
vector_modify,
mut observations,
inspect_result,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -555,8 +503,7 @@ impl NodeGraphExecutor {
// Apply only to the active document's in-progress migration, dropping responses left over from a document switch.
if let Some(bake_target) = execution_context.measure_fill {
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
let measured = observations.remove(&ObservationKey::FillMeasurement);
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten();
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
}
continue;
@@ -658,7 +605,6 @@ impl NodeGraphExecutor {
});
// Update the Data panel on the frontend using the value of the inspect result.
let inspect_result = observations.remove(&ObservationKey::DataPanel);
if let Some(inspect_result) = (!self.previous_node_to_inspect.is_empty()).then_some(inspect_result).flatten() {
responses.add(DataPanelMessage::UpdateLayout {
inspect_result: Box::new(inspect_result),
@@ -715,13 +661,9 @@ impl NodeGraphExecutor {
let (data, width, height) = raster.to_flat_u8();
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
}
NodeGraphUpdate::Observations(mut observations) => {
if let Some(inspect_result) = observations.remove(&ObservationKey::DataPanel)
&& inspect_result.node_path == self.previous_node_to_inspect
{
responses.add(DataPanelMessage::UpdateLayout {
inspect_result: Box::new(inspect_result),
});
NodeGraphUpdate::InspectResult(inspect_result) => {
if inspect_result.inspect_node_path == self.previous_node_to_inspect {
responses.add(DataPanelMessage::UpdateLayout { inspect_result });
}
}
NodeGraphUpdate::Thumbnails {
@@ -847,19 +789,14 @@ impl NodeGraphExecutor {
}
let resources = document.resources.registry.clone();
let fill_measurement = Observation {
node_path: full_path,
connector: ObservedConnector::Output,
overrides: ContextOverrides::default(),
};
if self
.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect: full_path.clone(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
}))
.is_err()
{
@@ -870,6 +807,7 @@ impl NodeGraphExecutor {
// Force the next normal render to recompile and re-send the real, non-redirected network
self.node_graph_hash = 0;
self.previous_node_to_inspect = full_path;
let viewport = Footprint {
transform: document.metadata().document_to_viewport,
@@ -920,7 +858,7 @@ impl NodeGraphExecutor {
return;
}
match inspect_result.and_then(|result| result.data).and_then(|data| measure_fill_geometry(&data)) {
match inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data)) {
Some((bounding_box, item_transform)) => {
// Skip the bake if the user already placed this gradient themselves, but drop the now-superseded entry either way
if fill_transform_unbaked(document, &network_path, fill_node_id) {
@@ -966,9 +904,10 @@ impl NodeGraphExecutor {
}
// TODO: Eventually remove this document upgrade code
/// Tear down the in-progress migration and clear the hash so the next normal render recompiles the real network.
/// Tear down the in-progress migration and clear the stale inspect target and hash so the next normal render recompiles the real network.
fn cancel_gradient_migration(&mut self) {
self.gradient_migration = None;
self.previous_node_to_inspect = Vec::new();
self.node_graph_hash = 0;
}
+157 -42
View File
@@ -2,7 +2,7 @@ use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task};
use glam::UVec2;
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
@@ -20,17 +20,14 @@ use graphene_std::raster_types::Raster;
use graphene_std::runtime::AsyncRuntime;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Context, NodeError, Poll};
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use observer::Observer;
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use thumbnails::Thumbnails;
mod observer;
mod thumbnails;
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
@@ -59,9 +56,9 @@ pub struct NodeRuntime {
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
thumbnails: Thumbnails,
observer: Observer<ObservationKey>,
/// Whether an observation changed since its results were last sent.
observations_changed: bool,
/// The node the Data panel inspects.
inspect_state: Option<InspectState>,
preprocessor: preprocessor::Preprocessor,
@@ -81,31 +78,22 @@ pub struct NodeRuntime {
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
ThumbnailsInView {
layers: HashSet<NodeId>,
document_id: DocumentId,
},
/// Starts, changes, or with `None` stops one observation without a graph update.
Observe {
key: ObservationKey,
observation: Option<Observation>,
},
ClipboardSvg {
id: u64,
layers: Vec<NodeId>,
},
ThumbnailsInView { layers: HashSet<NodeId>, document_id: DocumentId },
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
ClipboardSvg { id: u64, layers: Vec<NodeId> },
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct GraphUpdate {
pub(super) network: NodeNetwork,
pub(super) resources: ResourceRegistry,
/// Full path from the root network to the node the Data panel inspects.
pub(super) node_to_inspect: Vec<NodeId>,
/// The node each network renders in place of its export, paired with that network's path.
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
/// Full path from the root network to every layer, which are the nodes with thumbnails.
pub(super) layers: Vec<Vec<NodeId>>,
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
pub(super) observations: HashMap<ObservationKey, Observation>,
}
/// Replaces each network's primary export with its previewed node.
@@ -157,13 +145,12 @@ impl NodeRuntime {
node_graph_warnings: Vec::new(),
monitor_nodes: Vec::new(),
thumbnails: Thumbnails::new(),
observer: Observer::default(),
observations_changed: false,
preprocessor: preprocessor::Preprocessor::new(),
vector_modify: Default::default(),
vector_evaluations: Default::default(),
inspect_state: None,
#[cfg(all(target_family = "wasm", feature = "gpu"))]
wasm_canvas_cache: CanvasSurfaceHandle::new(),
#[cfg(all(target_family = "wasm", feature = "gpu"))]
@@ -194,15 +181,17 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
// A graph update applied after this loop would otherwise replace this with what it observed before
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
(Some(update), None) => _ = update.observations.remove(&key),
(None, observation) => {
self.observer.set(key, observation);
self.observations_changed = true;
}
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
Some(update) => update.node_to_inspect = node_to_inspect,
None => self.inspect_state = InspectState::new(node_to_inspect),
},
GraphRuntimeRequest::InspectContextOverrides(overrides) => {
if let Some(inspect_state) = &mut self.inspect_state {
inspect_state.overrides = overrides;
inspect_state.overrides_changed = true;
}
}
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
@@ -213,16 +202,21 @@ impl NodeRuntime {
let Some(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
observations,
}) = graph
else {
return;
};
apply_previews(&mut network, &previewed);
self.observer.replace_all(observations);
match &mut self.inspect_state {
Some(inspect_state) if inspect_state.inspect_node_path == node_to_inspect => inspect_state.last_evaluation = None,
_ => self.inspect_state = InspectState::new(node_to_inspect),
}
self.resources = resources;
self.node_graph_errors.clear();
@@ -265,9 +259,12 @@ impl NodeRuntime {
}
}
if std::mem::take(&mut self.observations_changed) && viewport.is_none() {
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response");
if let Some(inspect_state) = &mut self.inspect_state
&& std::mem::take(&mut inspect_state.overrides_changed)
&& viewport.is_none()
{
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
}
if let Some(eyedropper) = self.pending_eyedropper.take() {
@@ -377,7 +374,7 @@ impl NodeRuntime {
responses: VecDeque::new(),
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
observations: HashMap::new(),
inspect_result: None,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -389,7 +386,7 @@ impl NodeRuntime {
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
let mut responses = VecDeque::new();
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let response = ExecutionResponse {
execution_id,
@@ -397,7 +394,7 @@ impl NodeRuntime {
responses,
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
observations,
inspect_result,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
@@ -526,6 +523,23 @@ fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> b
.is_ok_and(|data| data.is::<IORecord<Context, List<Vector>>>() || data.is::<IORecord<Context, Item<Vector>>>())
}
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
InspectedContext {
features: ContextOverrides {
footprint: context.try_footprint().copied(),
real_time: context.try_real_time(),
animation_time: context.try_animation_time(),
pointer_position: context.try_pointer_position(),
index: context.try_index().map(|index| index.collect()),
},
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
variables: context.varargs_len().unwrap_or_default(),
..Default::default()
}
}
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
match poll {
Poll::Final(output) | Poll::Partial(output) => Some(output),
@@ -580,11 +594,112 @@ impl Spawn for NodeTaskExecutor {
}
}
/// The node the Data panel inspects, which is evaluated again from the context it was last evaluated with.
struct InspectState {
inspect_node_path: Vec<NodeId>,
overrides: ContextOverrides,
last_evaluation: Option<(NodeId, u64, Option<InspectedData>)>,
overrides_changed: bool,
}
type InspectedData = Arc<dyn std::any::Any + Send + Sync + 'static>;
/// The resulting value from the temporary inspected during execution
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
introspected_data: Option<Arc<dyn std::any::Any + Send + Sync + 'static>>,
/// Full path from the root network to the inspected node, with the node itself as the last element.
/// The parent slice (`split_last().1`) is the network the node lives in, which downstream consumers
/// (e.g. the Data panel) need when looking the node up via `network_interface.is_layer(...)` etc.
pub inspect_node_path: Vec<NodeId>,
pub context: InspectedContext,
}
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectedContext {
pub features: ContextOverrides,
/// The positions the context carries, from the outermost level in.
pub positions: Vec<DVec2>,
pub variables: usize,
pub overrides: ContextOverrides,
pub dependencies: ContextFeatures,
}
impl InspectResult {
pub fn take_data(&mut self) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
self.introspected_data.clone()
}
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.inspect_node_path == other.inspect_node_path
}
}
impl InspectState {
fn new(inspect_node_path: Vec<NodeId>) -> Option<Self> {
(!inspect_node_path.is_empty()).then_some(Self {
inspect_node_path,
overrides: ContextOverrides::default(),
last_evaluation: None,
overrides_changed: false,
})
}
fn access(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> InspectResult {
let node = network.and_then(|network| executor.tree().output_node(network, &self.inspect_node_path));
let context = node.and_then(|node| executor.tree().last_context(node).ok().flatten()).map(|context| self.with_overrides(context));
let introspected_data = node.zip(context.clone()).and_then(|(node, context)| self.evaluate(executor, node, context));
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
let context = InspectedContext {
overrides: self.overrides.clone(),
dependencies: node.map(|node| executor.tree().context_features(node)).unwrap_or_default(),
..features
};
InspectResult {
introspected_data,
inspect_node_path: self.inspect_node_path.clone(),
context,
}
}
fn with_overrides(&self, context: Context<'static>) -> Context<'static> {
if self.overrides.is_empty() {
return context;
}
let context = context
.as_deref()
.map(|context| context.with_overrides(&self.overrides))
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(&self.overrides));
Some(Arc::new(context))
}
/// Evaluates the node with the context, reusing the last result if neither changed.
fn evaluate(&mut self, executor: &DynamicExecutor, node: NodeId, context: Context<'static>) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
let context_hash = context_hash(&context);
if let Some((last_node, last_context_hash, data)) = &self.last_evaluation
&& (*last_node, *last_context_hash) == (node, context_hash)
{
return data.clone();
}
let output = evaluated_output(executor.tree().evaluate(node, &context).ok()?)?;
// Output the Data panel can't show is remembered too, so it isn't evaluated again for nothing
let data = crate::messages::portfolio::document::data_panel::shareable_inspect_output(output);
self.last_evaluation = Some((node, context_hash, data.clone()));
data
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::EditorTestUtils;
use glam::DVec2;
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
@@ -1,185 +0,0 @@
use super::{context_hash, evaluated_output};
use crate::messages::portfolio::document::data_panel::shareable_inspect_output;
use glam::DVec2;
use graph_craft::document::{NodeId, NodeNetwork};
use graphene_std::{Context, ContextFeatures, ContextOverrides, OwnedContextImpl};
use interpreted_executor::dynamic_executor::{BorrowTree, DynamicExecutor};
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
pub type ObservedValue = Arc<dyn std::any::Any + Send + Sync + 'static>;
/// A connector of a document node whose value the editor reads back after each evaluation.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Observation {
pub node_path: Vec<NodeId>,
pub connector: ObservedConnector,
/// Replaces parts of the context the value is evaluated with.
pub overrides: ContextOverrides,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum ObservedConnector {
Input(usize),
Output,
}
/// The value an observation read, with the context it was evaluated with.
#[derive(Clone, Debug, Default)]
pub struct InspectResult {
pub data: Option<ObservedValue>,
pub node_path: Vec<NodeId>,
pub context: InspectedContext,
}
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectedContext {
pub features: ContextOverrides,
pub positions: Vec<DVec2>,
pub variables: usize,
pub overrides: ContextOverrides,
pub dependencies: ContextFeatures,
}
// This is very ugly but is required to be inside a message
impl PartialEq for InspectResult {
fn eq(&self, other: &Self) -> bool {
self.node_path == other.node_path
}
}
/// Evaluates each observed connector again from the context its node was last evaluated with.
pub struct Observer<Key> {
observations: HashMap<Key, ObservationState>,
}
struct ObservationState {
observation: Observation,
last_evaluation: Option<Evaluation>,
}
struct Evaluation {
source: NodeId,
context_hash: u64,
value: Option<ObservedValue>,
}
impl<Key> Default for Observer<Key> {
fn default() -> Self {
Self { observations: HashMap::new() }
}
}
impl<Key: Clone + Eq + Hash> Observer<Key> {
/// Replaces every observation, keeping the last evaluation of those that stayed the same.
pub fn replace_all(&mut self, observations: HashMap<Key, Observation>) {
let mut previous = std::mem::take(&mut self.observations);
self.observations = observations
.into_iter()
.map(|(key, observation)| {
let state = ObservationState::new(observation, previous.remove(&key));
(key, state)
})
.collect();
}
/// Starts, changes, or with `None` stops the observation under this key.
pub fn set(&mut self, key: Key, observation: Option<Observation>) {
let previous = self.observations.remove(&key);
let Some(observation) = observation else { return };
self.observations.insert(key, ObservationState::new(observation, previous));
}
/// Evaluates the observations whose source or context changed, giving back the latest result of each.
pub fn evaluate(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> HashMap<Key, InspectResult> {
let tree = executor.tree();
self.observations.iter_mut().map(|(key, state)| (key.clone(), state.evaluate(tree, network))).collect()
}
}
impl ObservationState {
fn new(observation: Observation, previous: Option<ObservationState>) -> Self {
let last_evaluation = previous.filter(|previous| previous.observation == observation).and_then(|previous| previous.last_evaluation);
Self { observation, last_evaluation }
}
fn evaluate(&mut self, tree: &BorrowTree, network: Option<&NodeNetwork>) -> InspectResult {
let Observation { node_path, connector, overrides } = &self.observation;
let source = match connector {
ObservedConnector::Input(index) => tree.input_node(node_path, *index).ok(),
ObservedConnector::Output => network.and_then(|network| tree.output_node(network, node_path)),
};
let context = source.and_then(|source| tree.last_context(source).ok().flatten()).map(|context| with_overrides(context, overrides));
let introspected_data = source
.zip(context.clone())
.and_then(|(source, context)| evaluate_value(&mut self.last_evaluation, tree, source, context));
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
let context = InspectedContext {
overrides: overrides.clone(),
dependencies: source.map(|source| tree.context_features(source)).unwrap_or_default(),
..features
};
InspectResult {
data: introspected_data,
node_path: node_path.clone(),
context,
}
}
}
/// Evaluates the node with the context, reusing the last result if neither changed.
fn evaluate_value(last_evaluation: &mut Option<Evaluation>, tree: &BorrowTree, source: NodeId, context: Context<'static>) -> Option<ObservedValue> {
let context_hash = context_hash(&context);
if let Some(evaluation) = last_evaluation
&& (evaluation.source, evaluation.context_hash) == (source, context_hash)
{
return evaluation.value.clone();
}
let output = evaluated_output(tree.evaluate(source, &context).ok()?)?;
// Output that can't be shared is remembered too, so it isn't evaluated again for nothing
let value = shareable_inspect_output(output);
*last_evaluation = Some(Evaluation {
source,
context_hash,
value: value.clone(),
});
value
}
fn with_overrides(context: Context<'static>, overrides: &ContextOverrides) -> Context<'static> {
if overrides.is_empty() {
return context;
}
let context = context
.as_deref()
.map(|context| context.with_overrides(overrides))
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(overrides));
Some(Arc::new(context))
}
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
InspectedContext {
features: ContextOverrides {
footprint: context.try_footprint().copied(),
real_time: context.try_real_time(),
animation_time: context.try_animation_time(),
pointer_position: context.try_pointer_position(),
index: context.try_index().map(|index| index.collect()),
},
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
variables: context.varargs_len().unwrap_or_default(),
..Default::default()
}
}
@@ -21,36 +21,8 @@
$: nodeCategories = buildNodeCategories(searchTerm);
type TextSegment = {
text: string;
highlighted: boolean;
};
type NodeCatalogEntry = {
nodeType: FrontendNodeType;
matchedAliasSegments: TextSegment[] | undefined;
};
// Splits `text` into runs that are highlighted where one of the lowercase `terms` occurs
function highlightTerms(text: string, terms: string[]): TextSegment[] {
const lowercaseText = text.toLowerCase();
const highlighted = new Array<boolean>(text.length).fill(false);
terms.forEach((term) => {
const start = lowercaseText.indexOf(term);
if (term.length > 0 && start !== -1) highlighted.fill(true, start, start + term.length);
});
const segments: TextSegment[] = [];
highlighted.forEach((isHighlighted, index) => {
const last = segments.at(-1);
if (last?.highlighted === isHighlighted) last.text += text[index];
else segments.push({ text: text[index], highlighted: isHighlighted });
});
return segments;
}
type NodeCategoryDetails = {
nodes: NodeCatalogEntry[];
nodes: FrontendNodeType[];
open: boolean;
};
@@ -71,24 +43,23 @@
nodeTypes.forEach((node) => {
let matchesTypeSearch = true;
let matchesRemainingTerms = true;
if (isTypeSearch && typeSearchTerm) {
matchesTypeSearch = node.inputTypes?.some((constraint) => constraint === "All" || constraint.Limited.some((inputType) => inputType.toLowerCase().includes(typeSearchTerm))) || false;
}
const termsUnmatchedByName = remainingSearchTerms.filter((term) => {
const nameMatch = node.name.toLowerCase().includes(term);
const categoryMatch = node.category.toLowerCase().includes(term);
if (remainingSearchTerms.length > 0) {
matchesRemainingTerms = remainingSearchTerms.every((term) => {
const nameMatch = node.name.toLowerCase().includes(term);
const categoryMatch = node.category.toLowerCase().includes(term);
// Quick and dirty hack to alias "Layer" to "Merge" in the search
const layerAliasMatch = node.name === "Merge" && "layer".includes(term);
// Quick and dirty hack to alias "Layer" to "Merge" in the search
const layerAliasMatch = node.name === "Merge" && "layer".includes(term);
return !nameMatch && !categoryMatch && !layerAliasMatch;
});
const matchedAlias = termsUnmatchedByName.length > 0 ? node.searchAliases.find((alias) => termsUnmatchedByName.every((term) => alias.toLowerCase().includes(term))) : undefined;
const matchesRemainingTerms = termsUnmatchedByName.length === 0 || matchedAlias !== undefined;
const matchedAliasSegments = matchedAlias !== undefined ? highlightTerms(matchedAlias, termsUnmatchedByName) : undefined;
return nameMatch || categoryMatch || layerAliasMatch;
});
}
// Node matches if it passes both type search and remaining terms filters
const includesSearchTerm = matchesTypeSearch && matchesRemainingTerms;
@@ -105,11 +76,11 @@
if (category) {
category.open = category.open || open;
category.nodes.push({ nodeType: node, matchedAliasSegments });
category.nodes.push(node);
} else {
categories.set(node.category, {
open,
nodes: [{ nodeType: node, matchedAliasSegments }],
nodes: [node],
});
}
});
@@ -131,20 +102,14 @@
<summary>
<TextLabel>{nodeCategory[0]}</TextLabel>
</summary>
{#each nodeCategory[1].nodes as { nodeType, matchedAliasSegments }}
{#each nodeCategory[1].nodes as nodeType}
<TextButton
{disabled}
label={nodeType.name}
tooltipLabel={nodeType.name}
tooltipDescription={nodeType.identifier ? $nodeGraph.nodeDescriptions.get(nodeType.identifier) : undefined}
action={() => dispatch("selectNodeType", nodeType.identifier)}
>
{#if matchedAliasSegments}
<span class="matched-alias"
>{#each matchedAliasSegments as segment}<span class:highlighted={segment.highlighted}>{segment.text}</span>{/each}</span
>
{/if}
</TextButton>
/>
{/each}
</details>
{:else}
@@ -207,17 +172,6 @@
&:last-child .text-button {
margin-bottom: 0;
}
.matched-alias {
margin-left: 8px;
overflow: hidden;
text-overflow: ellipsis;
color: var(--color-8-uppergray);
.highlighted {
color: var(--button-text-color);
}
}
}
}
}
@@ -88,7 +88,6 @@
{#if label}
<TextLabel>{label}</TextLabel>
{/if}
<slot />
</button>
{#if menuListChildrenExists}
<MenuList
@@ -333,19 +333,10 @@ impl BorrowTree {
self.context_features.get(&id).copied().unwrap_or_default()
}
/// The node feeding an input of the proto node at this path, looking past the nodes wrapping it under the same path such as 'Memoize'.
pub fn input_node(&self, node_path: &[NodeId], input_index: usize) -> Result<NodeId, IntrospectError> {
let (mut id, _) = *self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
loop {
let (_, _, inputs) = self.nodes.get(&id).ok_or(IntrospectError::ProtoNodeNotFound(id))?;
let wrapped = inputs.first().filter(|first| self.nodes.get(first).is_some_and(|(_, path, _)| **path == *node_path));
match wrapped {
Some(&wrapped) => id = wrapped,
None => return inputs.get(input_index).copied().ok_or(IntrospectError::NoData),
}
}
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
let (_, _, inputs) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
inputs.get(input_index).copied().ok_or(IntrospectError::NoData)
}
/// The context this node was last evaluated with in the graph.
@@ -74,10 +74,13 @@ The function runs once per **anchor**: a node of the source declaration. The run
| `&mut Inputs` | the anchor's input slots | `set`, `insert`, `push`, `remove`, `truncate` |
| `&mut Upstream` | new and existing nodes upstream of the anchor | `add_node`, `add_node_keyed`, `remove_node` |
| `&mut Downstream` | the slots and exports reading the anchor's outputs, plus new downstream nodes | `consumers`, `add_node`, `add_node_keyed`, `connect` |
| `&mut Attributes` | attributes of the anchor and of the nodes the run adds | `set`, `remove` |
| `&mut Resources` | document resources | `add_embedded` |
`Inputs` operations apply in order to the target layout being built. `node.inputs()` is always the source layout. Reads through a mutable view (such as `Downstream::consumers`) also see the source state, so nodes added by the migration never appear among the anchor's consumers.
The runner places added nodes from the anchor's own position. Nodes leading up to the anchor's chain input form a row, or join the chain when the anchor is chained or a layer. Each other node sits below the first node reading it. A chained anchor has no coordinates of its own, so only its chain is placed. A migration overrides these positions, or clears a stored name that no longer fits the anchor, through `Attributes`.
A migration addresses declarations with `decl!`, values with a frozen mirror of the value variants it uses, and connections with plain connector types:
```rust
@@ -538,7 +541,7 @@ document/migrations/
- **Input attributes of inserted nodes.** `NewNode` takes bare `NodeInput`s, so inserted nodes start with empty per-input attributes. Taking `InputSlot`s would let a migration carry them over.
- **Removal safety.** `Upstream::remove_node` is only correct when nothing else reads the removed node, which the region system can't check.
- **`unrepresentable` in CI.** Whether reaching it in the commutation test fails CI outright.
- **Layout.** Whether migrations may write node positions and chain placement, or leave inserted nodes to a host-side layout pass.
- **Layout.** Migrations write positions of the nodes they add but can't move existing nodes, so an inserted node can overlap what sits upstream. Positions stored relative to each node's consumers would move the upstream without writing it.
- **Multiple pending migrations.** Whether consecutive pending node migrations run as separate rewrite passes or are fused into one replay.
- **Migrations reading a subgraph.** A migration that inspects an instance's inner nodes depends on their versions, which change independently of the definition's. The planned answer is a cascading bump: the API dump lists a definition's inner `identifier@version`s, so bumping an inner node also requires bumping every definition containing it, and pins order that node's migrations around the definition's. Nothing reads a subgraph yet, so neither a read view for it nor the cascading bump exists.
- **Detaching.** Whether a migration may clear an edited instance's reference, keeping it as a custom subgraph, instead of collapsing it.
@@ -88,6 +88,7 @@ You ask for what you need through the function's parameters, in any order. The f
| `&mut Upstream` | Nodes feeding the anchor | `add_node`, `add_node_keyed`, `remove_node` |
| `&mut Downstream` | Whatever reads the anchor's outputs | `consumers`, `add_node`, `add_node_keyed`, `connect` |
| `&mut Target` | Which declaration the anchor becomes, see [Choosing a target](#choosing-a-target) | `set` |
| `&mut Attributes` | Attributes of the anchor and of the nodes you add, see [Placing and naming nodes](#placing-and-naming-nodes) | `set`, `remove` |
Reads always see the old document. `node.inputs()` returns the old layout however many edits you've made, and nodes you add never show up in `consumers`. `Inputs` edits apply in order to the layout being built. After `inputs.insert(1, ...)`, later `Inputs` calls see the old slot 1 as slot 2. `node.inputs()[1]` is still the old slot 1.
@@ -202,6 +203,18 @@ pub fn vary_from_style(node: &Node, target: &mut Target) {
A wire written to a removed node brings that node back, so avoid switching a wire on and off depending on state. Keep the slot reading the same thing, and add nodes downstream of the anchor instead.
### Placing and naming nodes
Nodes you add are placed beside the anchor for you. Those leading up to the anchor's primary input form a row to its left, or join its layer's chain, and the others sit below the node they feed. Only the anchor's own position is used, so under a chained anchor the nodes off the chain aren't placed. `Attributes::set` writes an attribute of the anchor or of a node this run adds, named by the ID `add_node` returned, and `remove` deletes one. A display name stored as the old node's default would misname the new one, so clear it:
```rust
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Copy to Points") {
attributes.remove(node.id(), DISPLAY_NAME);
}
```
Writing to any other node fails, since another anchor's run may be editing it.
### Network definitions
Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix: