Compare commits

...
37 changed files with 1157 additions and 156 deletions

No files matched your search

+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());
}
}
+11
View File
@@ -7,6 +7,17 @@ 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`, `Chain`, or `Relative`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Position {
Absolute([i32; 2]),
Chain,
Stack(u32),
/// An offset from the top left corner of the bounding box of the positions of the nodes reading this one.
Relative([i32; 2]),
}
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,7 +183,9 @@ fn bias_keeping_average_scale(bias: f64) -> f64 {
mod tests {
use super::*;
use crate::CompilerHost;
use migration_core::Declaration;
use document_graph_storage::attr::node::ui::POSITION;
use document_graph_storage::{NodeId, Position, TimeStamp, Value, to_value};
use migration_core::{CHAIN_WIDTH, Declaration, FEEDER_ROW_HEIGHT};
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
@@ -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::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
#[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)]
+61 -1
View File
@@ -1,9 +1,14 @@
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode};
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp};
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);
@@ -16,6 +21,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)
@@ -225,6 +232,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 {
@@ -236,6 +245,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")]
+97 -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,94 @@ 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 relative to the nodes reading it,
/// below the first one of this run that does, or on the anchor when nothing reads it.
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 => {}
}
}
let readers: Vec<(NodeId, &[NodeInput])> = std::iter::once((anchor, anchor_inputs.as_slice()))
.chain(edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())))
.collect();
let mut feeders_below: HashMap<NodeId, i32> = HashMap::new();
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
let reader = readers.iter().find(|(_, inputs)| reads(inputs, added.id)).map(|(reader, _)| *reader);
let connected_downstream = edits.connections.iter().any(|(output, _)| output.node == added.id);
let position = match (reader, coordinates) {
(Some(reader), _) => {
let row = feeders_below.entry(reader).or_default();
*row += 1;
Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT * *row])
}
_ if connected_downstream => Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT]),
(None, Some(coordinates)) => Position::Absolute(coordinates),
(None, None) => continue,
};
positions.push((added.id, 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> {
+39 -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,38 @@ 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 coordinates = [self.random.below(20) as i32, self.random.below(20) as i32];
let position = match self.random.below(4) {
0 => Position::Chain,
1 => Position::Relative(coordinates),
_ => Position::Absolute(coordinates),
};
(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 +366,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::Relative([-CHAIN_WIDTH, 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, Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
}
#[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\
@@ -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;
@@ -2232,6 +2232,7 @@ impl DocumentMessageHandler {
self.network_interface.validate_input_metadata(node_id, node, &path);
self.network_interface.validate_output_names(node_id, node, &path);
}
self.network_interface.convert_positions_to_relative();
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
@@ -957,10 +957,10 @@ fn set_import_child_positions(
// Top of stack: set to `Absolute` position
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Absolute(child_pos), &[]);
} else {
// Below top: set `Stack` with `y_offset` based on previous sibling's subtree extent
// Below top: stack it `y_offset` below its previous sibling, based on that sibling's subtree extent
let prev_sibling_svg_index = n - i;
let y_offset = child_extents_svg_order[prev_sibling_svg_index] + STACK_VERTICAL_GAP as u32;
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Stack(y_offset), &[]);
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::stacked(y_offset), &[]);
}
// Recurse into group children to set their descendants' positions
@@ -1110,7 +1110,7 @@ pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, netw
if *was_chain {
network_interface.set_chain_position(&node_id, network_path);
} else if let Some(position) = position {
network_interface.set_absolute_position(&node_id, *position, network_path);
network_interface.place_at(&node_id, *position, network_path);
}
}
@@ -89,6 +89,8 @@ pub struct NodeGraphMessageHandler {
pub selection_before_pointer_down: Vec<NodeId>,
/// If the grip icon is held during a drag, then shift without pushing other nodes
shift_without_push: bool,
/// Whether dragging leaves the relative nodes upstream of the dragged ones where they are drawn.
keep_upstream_in_place: bool,
disconnecting: Option<InputConnector>,
initial_disconnecting: bool,
/// Node to select on pointer up if multiple nodes are selected and they were not dragged.
@@ -1437,6 +1439,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
self.keep_upstream_in_place = ipp.keyboard.get(Key::Control as usize);
let mut graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
let previous_round_x = drag_start.round_x;
let previous_round_y = drag_start.round_y;
@@ -1622,6 +1626,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// End of dragging a node
else if let Some((drag_start, _)) = &self.drag_start {
self.shift_without_push = false;
self.keep_upstream_in_place = false;
// Reset all offsets to end the rubber banding while dragging
network_interface.clear_drag_offsets(selection_network_path);
@@ -2165,7 +2170,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
// The shift can also push other nodes and the imports and exports, so everything it moves glides to where it lands
let positions_before = (glide && graph_view_overlay_open).then(|| Self::glide_positions(network_interface, selection_network_path));
network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path);
network_interface.shift_selected_nodes(direction, self.shift_without_push, self.keep_upstream_in_place, selection_network_path);
if !rubber_band {
network_interface.clear_drag_offsets(selection_network_path);
@@ -4076,6 +4081,7 @@ impl Default for NodeGraphMessageHandler {
double_click_used_by_press: false,
dot_drag_out: None,
shift_without_push: false,
keep_upstream_in_place: false,
box_selection_start: None,
drag_start_chain_nodes: Vec::new(),
wire_insertion_preview: None,
@@ -6,5 +6,6 @@
mod lifecycle_tests;
mod metadata_tests;
mod relative_positions_tests;
mod round_trip_tests;
pub(crate) mod test_support;
@@ -0,0 +1,87 @@
//! Opening a document converts its absolute and stacked positions to positions relative to the nodes reading them, without moving any node.
use super::test_support::{node_paths, open_demo};
use crate::messages::portfolio::document::utility_types::network_interface::{LayerPersistentMetadata, LayerPosition, NodeLocator, NodeNetworkInterface, NodeTypePersistentMetadata};
use glam::IVec2;
use graphene_std::uuid::NodeId;
const DEMOS: [&str; 8] = [
"changing-seasons.graphite",
"isometric-fountain.graphite",
"marbled-mandelbrot.graphite",
"painted-dreams.graphite",
"parametric-dunescape.graphite",
"procedural-string-lights.graphite",
"red-dress.graphite",
"valley-of-spires.graphite",
];
/// Each node in an editable network, by its network path and ID, with where it is drawn.
type DrawnPositions = Vec<((Vec<NodeId>, NodeId), Option<IVec2>)>;
fn editable_positions(interface: &NodeNetworkInterface) -> DrawnPositions {
node_paths(interface)
.into_iter()
.filter(|(network_path, _)| !interface.is_read_only(network_path))
.map(|(network_path, node_id)| {
let position = interface.position(&node_id, &network_path);
((network_path, node_id), position)
})
.collect()
}
/// Rewrites the converted positions the way older documents stored them, stacked layers as `Stack` and the rest as `Absolute`.
fn revert_to_stored_positions(interface: &mut NodeNetworkInterface, positions: &DrawnPositions) {
for ((network_path, node_id), position) in positions {
if !interface.is_relative(node_id, network_path) {
continue;
}
let stack_offset = interface.stack_offset(node_id, network_path);
let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) else { continue };
match (stack_offset, position) {
(Some(stack_offset), _) => {
node.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(stack_offset as u32),
}));
}
(None, Some(position)) => {
node.set_absolute_position(*position);
}
(None, None) => {}
}
interface.invalidate_position(node_id, network_path);
}
}
#[test]
fn opening_a_demo_makes_every_read_node_relative_where_it_was_drawn() {
for demo in DEMOS {
let mut document = open_demo(demo);
let interface = &mut document.network_interface;
let converted = editable_positions(interface);
assert!(converted.iter().all(|(_, position)| position.is_some()), "{demo}: every node should resolve a position");
for ((network_path, node_id), _) in &converted {
let read_by_a_node = interface
.with_outward_wires(network_path, |outward_wires| {
outward_wires
.iter()
.any(|(output, readers)| output.node_id() == Some(*node_id) && readers.iter().any(|reader| reader.node_id().is_some()))
})
.unwrap_or_default();
assert!(
!read_by_a_node || !interface.is_absolute(node_id, network_path),
"{demo}: node {node_id} is read by another node, so it should be relative"
);
}
revert_to_stored_positions(interface, &converted);
interface.convert_positions_to_relative();
let reconverted = editable_positions(interface);
let moved: Vec<_> = converted.iter().zip(&reconverted).filter(|(before, after)| before != after).collect();
assert!(moved.is_empty(), "{demo}: converting should leave every node where it was drawn, but moved {moved:?}");
}
}
@@ -141,7 +141,7 @@ impl NodeNetworkInterface {
for layer in &selected_layers {
let mut current_node = *layer;
loop {
if self.is_layer(&current_node, network_path) && self.is_absolute(&current_node, network_path) {
if self.is_layer(&current_node, network_path) && !self.is_stack(&current_node, network_path) {
stack_tops.insert(current_node);
break;
};
@@ -1,6 +1,6 @@
use super::{
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata,
OutputConnector, Previewing, RootNode, TransactionStatus,
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, NodeTemplate,
NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
};
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
@@ -278,7 +278,7 @@ async fn a_dot_on_a_stack_wire_leaves_the_layer_beneath_it_where_it_was() {
let network_interface = &editor.active_document().network_interface;
assert_eq!(feeding(&editor, upper), Some(OutputConnector::node(dot, 0)), "the dot should feed the upper layer");
assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(lower, 0)), "the lower layer should feed the dot");
assert!(network_interface.is_absolute(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
assert!(!network_interface.is_stack(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
assert_eq!(network_interface.position(&lower, &[]), lower_position, "the lower layer shouldn't move");
assert_invariants(&editor, "after putting a dot on a stack wire");
}
@@ -315,6 +315,163 @@ fn fill_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
}
#[tokio::test]
async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let lower_reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let upper_reader = editor.create_node_by_name_at(fill_definition(), 30, 4).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
for reader in [lower_reader, upper_reader] {
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
}
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.invalidate_position(&node, &[]);
// The offset applies to the top left corner of the box around both readers
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
network_interface.disconnect_input(&InputConnector::primary_input(upper_reader), &[]);
assert!(network_interface.is_relative(&node, &[]), "A node still read by another node should stay relative");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 13)));
network_interface.disconnect_input(&InputConnector::primary_input(lower_reader), &[]);
assert!(network_interface.is_absolute(&node, &[]), "A node losing its last reader should be pinned where it was drawn");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 13)));
assert_invariants(&editor, "after a relative node loses its readers");
}
#[tokio::test]
async fn a_connected_node_stays_where_it_is_drawn_and_follows_a_rewire() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let other_reader = editor.create_node_by_name_at(fill_definition(), 40, 30).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
assert!(network_interface.is_relative(&node, &[]), "A node gaining its first reader should become relative to it");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(0, 0)));
// Rewiring keeps the offset, so the node moves beside its new reader
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(other_reader), &[]);
network_interface.disconnect_input(&InputConnector::primary_input(reader), &[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(20, 20)));
assert_invariants(&editor, "after connecting and rewiring a relative node");
}
#[tokio::test]
async fn deleting_the_only_reader_of_a_relative_node_pins_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 10, 10).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
network_interface.delete_nodes(vec![reader], false, &[]);
assert!(network_interface.is_absolute(&node, &[]), "A node losing its last reader to a delete should be pinned");
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(10, 10)));
}
#[tokio::test]
async fn dragging_a_node_carries_its_upstream_unless_it_is_kept_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
let node = editor.create_node_by_name_at(fill_definition(), 10, 10).await;
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 10).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
network_interface.create_wire(&OutputConnector::primary_output(source), &InputConnector::primary_input(node), &[]);
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![reader]);
network_interface.shift_selected_nodes(Direction::Down, true, false, &[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(10, 11)), "The node read by the dragged one should follow it");
assert_eq!(network_interface.position(&source, &[]), Some(IVec2::new(0, 11)), "Everything upstream should follow too");
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
assert_eq!(network_interface.position(&reader, &[]), Some(IVec2::new(20, 12)));
assert_eq!(
network_interface.position(&node, &[]),
Some(IVec2::new(10, 11)),
"Keeping the upstream in place should leave the node where it was drawn"
);
assert_eq!(
network_interface.position(&source, &[]),
Some(IVec2::new(0, 11)),
"Keeping the upstream in place should leave its upstream too"
);
assert_invariants(&editor, "after dragging a node with and without its upstream");
}
#[tokio::test]
async fn moving_a_chain_node_out_of_its_chain_carries_its_upstream() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (_, near, far, source, outside) = layer_with_chain(&mut editor).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert!(network_interface.is_chain(&near, &[]) && network_interface.is_chain(&far, &[]), "fixture is wrong");
let [far_before, source_before, outside_before] = [far, source, outside].map(|node_id| network_interface.position(&node_id, &[]).expect("every node has a position"));
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![near]);
network_interface.shift_selected_nodes(Direction::Down, true, false, &[]);
assert!(!network_interface.is_chain(&far, &[]), "The chain upstream of a node moved out of it should leave the chain too");
for (node_id, before) in [(far, far_before), (source, source_before), (outside, outside_before)] {
assert_eq!(
network_interface.position(&node_id, &[]),
Some(before + IVec2::Y),
"Node {node_id} upstream of the moved node should follow it"
);
}
assert_invariants(&editor, "after moving a chain node out of its chain");
}
#[tokio::test]
async fn moving_a_chain_node_out_while_keeping_its_upstream_leaves_the_upstream_in_place() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (_, near, far, source, _) = layer_with_chain(&mut editor).await;
let network_interface = &mut editor.active_document_mut().network_interface;
let [far_before, source_before] = [far, source].map(|node_id| network_interface.position(&node_id, &[]).expect("every node has a position"));
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![near]);
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
assert_eq!(
network_interface.position(&far, &[]),
Some(far_before),
"The chain upstream of the moved node should stay where it was drawn"
);
assert_eq!(network_interface.position(&source, &[]), Some(source_before));
network_interface.shift_selected_nodes(Direction::Up, true, true, &[]);
network_interface.shift_selected_nodes(Direction::Up, true, true, &[]);
assert!(
network_interface.is_chain(&near, &[]) && network_interface.is_chain(&far, &[]),
"Moving the node back should restore the whole chain"
);
assert_invariants(&editor, "after moving a chain node out of its chain while keeping its upstream");
}
/// Builds a layer fed by the chain `near <- far <- source` (a generator fixed at the upstream end), with an outside node also wired into the near node's second input.
async fn layer_with_chain(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
let layer = editor.create_node_by_name_at(merge_definition(), 30, 10).await;
@@ -889,10 +889,12 @@ impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
LayerPosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
}),
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
NodePosition::Chain => Position::Chain,
NodePosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
}),
}
}
@@ -101,6 +101,12 @@ async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
// Already read by `a`, so `b` is relative and the wiring edit below doesn't also reposition it
editor
.active_document_mut()
.network_interface
.set_input(&InputConnector::node_at_index(a, 2), NodeInput::node(b, 0), &[]);
let working = convert(&editor);
let wire = NodeInput::node(b, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(a, 1), wire.clone(), &[]);
@@ -8,8 +8,8 @@ use graphene_std::{Color, Graphic};
impl NodeNetworkInterface {
/// The top left corner of a node in node graph grid coordinates.
///
/// Only absolute positions are stored. A stack layer sits below its downstream sibling and a chain node to the
/// left of the layer it feeds, so both are resolved by walking downstream to the first stored position.
/// A relative node sits at an offset from the nodes reading it and a chain node to the left of the layer it feeds,
/// so both are resolved by walking downstream to the first absolute position.
pub fn position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
self.position_from_downstream(node_id, network_path, &mut HashSet::new(), &mut HashMap::new())
}
@@ -42,7 +42,7 @@ impl NodeNetworkInterface {
}
/// Walks downstream to the first stored position, accumulating the relative offsets along the way. `visited`
/// stops the walk on a cyclic graph, which concurrent edits can produce, rather than recursing forever.
/// holds the nodes on the current walk, which stops it on a cyclic graph that concurrent edits can produce.
fn position_from_downstream(&self, node_id: &NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
if let Some(position) = resolved.get(node_id) {
return Some(*position);
@@ -53,6 +53,7 @@ impl NodeNetworkInterface {
}
let position = self.resolve_position(node_id, network_path, visited, resolved);
visited.remove(node_id);
if let Some(position) = position {
resolved.insert(*node_id, position);
}
@@ -69,6 +70,7 @@ impl NodeNetworkInterface {
match &node_metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => match layer_metadata.position {
LayerPosition::Absolute(position) => Some(position),
LayerPosition::Relative(offset) => self.relative_position(node_id, offset, network_path, visited, resolved),
LayerPosition::Stack(y_offset) => {
let downstream_node_id = self
.with_outward_wires(network_path, |outward_wires| {
@@ -91,10 +93,12 @@ impl NodeNetworkInterface {
},
NodeTypePersistentMetadata::Node(node_metadata) => match node_metadata.position {
NodePosition::Absolute(position) => Some(position),
NodePosition::Relative(offset) => self.relative_position(node_id, offset, network_path, visited, resolved),
NodePosition::Chain => {
// A chain node is placed by its distance from the layer it feeds, so walk downstream to that layer
let mut current_node_id = *node_id;
let mut node_distance_from_layer = 1;
let mut chain_visited = HashSet::new();
loop {
// TODO: Use root node to restore if previewing
let downstream_node_id = self
@@ -122,7 +126,7 @@ impl NodeNetworkInterface {
.map(|layer_position| layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
}
if !visited.insert(downstream_node_id) {
if !chain_visited.insert(downstream_node_id) {
log::error!("Cycle reached while resolving the chain position of node {node_id}");
return None;
}
@@ -134,6 +138,127 @@ impl NodeNetworkInterface {
}
}
fn relative_position(&self, node_id: &NodeId, offset: IVec2, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
let readers = self.reading_nodes(node_id, network_path);
let Some(top_left) = readers
.iter()
.filter_map(|reader| self.position_from_downstream(reader, network_path, visited, resolved))
.reduce(IVec2::min)
else {
log::error!("Could not get the position of any node reading relative node {node_id}");
return None;
};
Some(top_left + offset)
}
/// The top left corner of the bounding box of the positions of the nodes reading `node_id`.
fn readers_top_left(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
let readers = self.reading_nodes(node_id, network_path);
self.positions(readers, network_path).into_iter().map(|(_, position)| position).reduce(IVec2::min)
}
/// Stores `position` as an offset from the nodes reading the node, or as an absolute position if no node reads it.
pub(crate) fn place_at(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
match self.readers_top_left(node_id, network_path) {
Some(top_left) => self.set_relative_position(node_id, position - top_left, network_path),
None => self.set_absolute_position(node_id, position, network_path),
}
}
pub(crate) fn set_relative_position(&mut self, node_id: &NodeId, offset: IVec2, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node_metadata for node {node_id}");
return;
};
if !node.set_relative_position(offset) {
return;
}
self.transaction_modified();
self.invalidate_position(node_id, network_path);
}
/// Converts every absolute node that another node reads, and every stacked layer, in all networks to a position relative to its readers.
pub fn convert_positions_to_relative(&mut self) {
let mut network_paths = Vec::new();
self.for_each_network(&mut |network_path, _| network_paths.push(network_path.to_vec()));
network_paths.retain(|network_path| !self.is_read_only(network_path));
for network_path in network_paths {
let Some(network) = self.nested_network(&network_path) else { continue };
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
let positions: HashMap<NodeId, IVec2> = self.positions(node_ids.iter().copied(), &network_path).into_iter().collect();
let offsets: Vec<(NodeId, IVec2)> = node_ids
.iter()
.filter(|node_id| self.is_absolute(node_id, &network_path) || matches!(self.stored_layer_position(node_id, &network_path), Some(LayerPosition::Stack(_))))
.filter_map(|node_id| {
let top_left = self
.reading_nodes(node_id, &network_path)
.iter()
.filter_map(|reader| positions.get(reader).copied())
.reduce(IVec2::min)?;
Some((*node_id, positions.get(node_id)? - top_left))
})
.collect();
for (node_id, offset) in offsets {
self.set_relative_position(&node_id, offset, &network_path);
}
}
}
fn stored_layer_position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<LayerPosition> {
match &self.node_metadata(node_id, network_path)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => Some(layer_metadata.position.clone()),
NodeTypePersistentMetadata::Node(_) => None,
}
}
/// The nodes reading any output of `node_id`.
fn reading_nodes(&self, node_id: &NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
let output_count = self.number_of_outputs(node_id, network_path);
self.with_outward_wires(network_path, |outward_wires| {
(0..output_count)
.filter_map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)))
.flatten()
.filter_map(InputConnector::node_id)
.collect()
})
.unwrap_or_default()
}
/// Pins a relative node at its drawn position before `leaving_reader` stops reading it, if no other node reads it.
pub(crate) fn pin_relative_node_losing_its_readers(&mut self, node_id: &NodeId, leaving_reader: &InputConnector, network_path: &[NodeId]) {
if !self.is_relative(node_id, network_path) {
return;
}
let output_count = self.number_of_outputs(node_id, network_path);
let still_read = self.with_outward_wires(network_path, |outward_wires| {
(0..output_count)
.filter_map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)))
.flatten()
.any(|reader| reader != leaving_reader && reader.node_id().is_some())
});
if still_read != Some(false) {
return;
}
let Some(position) = self.position(node_id, network_path) else {
log::error!("Could not get the position of relative node {node_id} before it loses its readers");
return;
};
self.set_absolute_position(node_id, position, network_path);
}
/// Pins a relative node at `position`, where it was drawn, once no node reads it anymore.
pub(crate) fn pin_relative_node_without_readers(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
if self.is_relative(node_id, network_path) && self.reading_nodes(node_id, network_path).is_empty() {
self.set_absolute_position(node_id, position, network_path);
}
}
/// Sets the position of a node to an absolute position
pub(crate) fn set_absolute_position(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
@@ -307,19 +432,19 @@ impl NodeNetworkInterface {
}
}
/// node_id is the first chain node, not the layer
pub(crate) fn set_upstream_chain_to_absolute(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
/// Takes `node_id`, the first chain node rather than the layer, and the chain nodes upstream of it out of the chain where they are drawn.
pub(crate) fn unchain_upstream(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path) else {
log::error!("Could not get downstream layer in set_upstream_chain_to_absolute");
log::error!("Could not get downstream layer in unchain_upstream");
return;
};
for upstream_id in &self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).collect::<Vec<_>>() {
let Some(previous_position) = self.position(upstream_id, network_path) else {
log::error!("Could not get position in set_upstream_chain_to_absolute");
log::error!("Could not get position in unchain_upstream");
return;
};
if self.is_chain(upstream_id, network_path) {
self.set_absolute_position(upstream_id, previous_position, network_path);
self.place_at(upstream_id, previous_position, network_path);
// Reload click target of the layer which used to encapsulate the chain
self.unload_node_click_targets(&downstream_layer, network_path);
}
@@ -330,52 +455,44 @@ impl NodeNetworkInterface {
}
}
/// Places `upstream_node_id` for a connection just made to `input_connector`. Only layers move: one
/// that is the sole feed into the bottom of another layer stacks under it, and any other layer is
/// pinned where it already sits.
/// Places `upstream_node_id` for a connection just made to `input_connector`. A layer that is the sole
/// feed into the bottom of another layer stacks under it, a relative node keeps its offset from its
/// readers, and an absolute node becomes relative to them where it sits.
///
/// Returns whether the node could be placed, which is false only when it has no resolvable position.
pub(crate) fn reposition_connected_upstream(&mut self, upstream_node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
let Some(current_position) = self.position(upstream_node_id, network_path) else {
if self.position(upstream_node_id, network_path).is_none() {
log::error!("Could not get position of node {upstream_node_id} in reposition_connected_upstream");
return false;
};
if !self.is_layer(upstream_node_id, network_path) {
return true;
}
// Only the bottom input of a layer stacks what feeds it; everything else leaves the layer where it is
let InputConnector::Node {
node_id: downstream_node_id,
input_index,
} = input_connector
else {
self.set_absolute_position(upstream_node_id, current_position, network_path);
return true;
let feeds_bottom_of_layer = match input_connector {
InputConnector::Node { node_id, input_index: 0 } => self.is_layer(node_id, network_path),
_ => false,
};
if *input_index != 0 || !self.is_layer(downstream_node_id, network_path) {
self.set_absolute_position(upstream_node_id, current_position, network_path);
return true;
}
let multiple_outward_wires = self
let single_outward_wire = self
.outward_wires(network_path)
.and_then(|all_outward_wires| all_outward_wires.get(&OutputConnector::primary_output(*upstream_node_id)))
.is_some_and(|outward_wires| outward_wires.len() > 1);
.is_some_and(|outward_wires| outward_wires.len() == 1);
if multiple_outward_wires {
self.set_absolute_position(upstream_node_id, current_position, network_path);
} else {
if let InputConnector::Node { node_id: downstream_node_id, .. } = input_connector
&& feeds_bottom_of_layer
&& single_outward_wire
&& self.is_layer(upstream_node_id, network_path)
{
self.set_stack_position_calculated_offset(upstream_node_id, downstream_node_id, network_path);
} else if self.is_absolute(upstream_node_id, network_path)
&& let Some(position) = self.position(upstream_node_id, network_path)
{
self.place_at(upstream_node_id, position, network_path);
}
true
}
/// Places `node_id` after the connection feeding it was removed. A layer that still feeds the bottom
/// of a single layer stacks under it, a node joins a chain where it is eligible, and any other layer
/// is pinned at `previous_position`.
/// of a single layer stacks under it, a node joins a chain where it is eligible, and any other absolute
/// layer is placed at `previous_position`.
///
/// Returns whether the node could be placed, which is false only when its outward wires are missing.
pub(crate) fn reposition_disconnected_upstream(&mut self, node_id: &NodeId, previous_position: IVec2, network_path: &[NodeId]) -> bool {
@@ -398,8 +515,8 @@ impl NodeNetworkInterface {
}
} else if !is_layer {
self.try_set_node_to_chain(node_id, network_path);
} else {
self.set_absolute_position(node_id, previous_position, network_path);
} else if !self.is_relative(node_id, network_path) {
self.place_at(node_id, previous_position, network_path);
}
true
@@ -436,7 +553,8 @@ impl NodeNetworkInterface {
self.invalidate_position(layer, network_path);
}
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
/// Shifts the selected nodes one grid step. The relative nodes upstream of them follow, unless `keep_upstream` leaves them where they are drawn.
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, keep_upstream: bool, network_path: &[NodeId]) {
let Some(node_ids) = self
.selected_nodes_in_nested_network(network_path)
.map(|selected_nodes| selected_nodes.selected_nodes().copied().collect::<HashSet<_>>())
@@ -444,7 +562,90 @@ impl NodeNetworkInterface {
log::error!("Could not get selected nodes in shift_selected_nodes");
return;
};
self.shift_nodes(node_ids, direction, shift_without_push, network_path);
let placements_before = keep_upstream.then(|| self.placements(network_path));
self.shift_nodes(node_ids.clone(), direction, shift_without_push, network_path);
if let Some(placements_before) = placements_before {
self.restore_followers(&placements_before, &node_ids, network_path);
}
}
/// The stored position of each node in the network and where it is drawn.
fn placements(&self, network_path: &[NodeId]) -> HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)> {
let Some(network) = self.nested_network(network_path) else { return HashMap::new() };
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
self.positions(node_ids, network_path)
.into_iter()
.filter_map(|(node_id, position)| Some((node_id, (self.node_metadata(&node_id, network_path)?.persistent_metadata.node_type_metadata.clone(), position))))
.collect()
}
/// Moves each relative node that was only carried along by the nodes reading it back to where it was drawn, which keeps its upstream in place too.
/// A node the shift made relative, such as a chain leaving its layer, counts as carried along, while a relative node the shift pushed does not.
fn restore_followers(&mut self, placements_before: &HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)>, moved_nodes: &HashSet<NodeId>, network_path: &[NodeId]) {
let followers: HashSet<NodeId> = placements_before
.iter()
.filter(|(node_id, (stored_position, position))| {
let was_relative = matches!(
stored_position,
NodeTypePersistentMetadata::Node(NodePersistentMetadata { position: NodePosition::Relative(_) })
| NodeTypePersistentMetadata::Layer(LayerPersistentMetadata { position: LayerPosition::Relative(_) })
);
let stored_position_unchanged = self
.node_metadata(node_id, network_path)
.is_some_and(|metadata| metadata.persistent_metadata.node_type_metadata == *stored_position);
!moved_nodes.contains(node_id) && self.is_relative(node_id, network_path) && (stored_position_unchanged || !was_relative) && self.position(node_id, network_path) != Some(*position)
})
.map(|(node_id, _)| *node_id)
.collect();
let mut restored = HashSet::new();
for follower in &followers {
self.restore_follower(follower, &followers, placements_before, &mut restored, network_path);
}
// Joining a chain needs a node to line up with its reader, which a follower only does again once restored
for follower in &followers {
if !self.is_layer(follower, network_path) {
self.try_set_node_to_chain(follower, network_path);
}
}
}
/// Restores the followers reading `node_id` first, since each one moves everything it reads.
fn restore_follower(
&mut self,
node_id: &NodeId,
followers: &HashSet<NodeId>,
placements_before: &HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)>,
restored: &mut HashSet<NodeId>,
network_path: &[NodeId],
) {
if !restored.insert(*node_id) {
return;
}
for reader in self.reading_nodes(node_id, network_path) {
if followers.contains(&reader) {
self.restore_follower(&reader, followers, placements_before, restored, network_path);
}
}
if let Some((_, previous_position)) = placements_before.get(node_id) {
self.keep_drawn_at(node_id, *previous_position, network_path);
}
}
/// Moves an absolute or relative node back to `position` after an edit carried it away, along with everything relative to it.
pub(crate) fn keep_drawn_at(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
let Some(current_position) = self.position(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) {
self.transaction_modified();
self.invalidate_position(node_id, network_path);
}
}
pub(crate) fn shift_nodes(&mut self, node_ids: HashSet<NodeId>, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
@@ -510,6 +711,15 @@ impl NodeNetworkInterface {
}
}
// A relative node already follows its readers, so shifting it with all of them would move it twice
let shifting_nodes = node_ids.clone();
for selected_node in &shifting_nodes {
let readers = self.reading_nodes(selected_node, network_path);
if self.is_relative(selected_node, network_path) && !readers.is_empty() && readers.iter().all(|reader| shifting_nodes.contains(reader)) {
node_ids.remove(selected_node);
}
}
node_ids
}
@@ -518,14 +728,7 @@ impl NodeNetworkInterface {
/// A node that cannot be read blocks the shift rather than letting part of it through.
fn stack_shift_up_is_blocked(&mut self, node_ids: &HashSet<NodeId>, network_path: &[NodeId]) -> bool {
for node_id in node_ids {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get node metadata for node {node_id} in stack_shift_up_is_blocked");
return true;
};
let NodeTypePersistentMetadata::Layer(layer_metadata) = &node_metadata.persistent_metadata.node_type_metadata else {
continue;
};
let LayerPosition::Stack(offset) = layer_metadata.position else { continue };
let Some(offset) = self.stack_offset(node_id, network_path) else { continue };
let Some(outward_wires) = self.outward_wires(network_path).and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id))) else {
log::error!("Could not get outward wires in stack_shift_up_is_blocked");
@@ -537,7 +740,7 @@ impl NodeNetworkInterface {
continue;
}
if offset == 0 {
if offset <= 0 {
return true;
}
}
@@ -562,9 +765,9 @@ impl NodeNetworkInterface {
return;
}
// Walk down the stack to the layer holding an absolute position, which anchors the rest
// Walk down the stack to its top layer, which anchors the rest
let mut downstream_absolute_layer = *node_id;
while !self.is_absolute(&downstream_absolute_layer, network_path) {
while self.is_stack(&downstream_absolute_layer, network_path) {
let Some(downstream_node) = self
.outward_wires(network_path)
.and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(downstream_absolute_layer)))
@@ -602,8 +805,7 @@ impl NodeNetworkInterface {
}
}
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare
/// shift. A layer that moves drags its stacked sibling the other way, so the sibling stays put.
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare shift.
fn shift_vertically(&mut self, node_id: &NodeId, shift_sign: i32, shift_without_push: bool, shifted_nodes: &mut HashSet<NodeId>, network_path: &[NodeId]) {
if !shift_without_push && self.is_layer(node_id, network_path) {
self.shift_node_or_parent(node_id, shift_sign, shifted_nodes, network_path);
@@ -618,18 +820,6 @@ impl NodeNetworkInterface {
if self.with_stack_dependents_if_loaded(network_path, |stack_dependents| matches!(stack_dependents.get(node_id), Some(LayerOwner::None))) == Some(true) {
self.add_drag_offset(node_id, shift_sign, network_path);
}
if !self.is_layer(node_id, network_path) {
return;
}
let upstream_layer = self
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow)
.nth(1)
.filter(|upstream_node| self.is_stack(upstream_node, network_path));
if let Some(upstream_layer) = upstream_layer {
self.shift_node(&upstream_layer, IVec2::new(0, -shift_sign), network_path);
}
}
/// Moves every node the shift pushed out of place back to where it started, as far as nothing has since
@@ -712,18 +902,6 @@ impl NodeNetworkInterface {
None => log::error!("Stack dependents should be loaded in vertical_shift_with_push"),
}
// Shift the upstream layer so that it stays in the same place
if self.is_layer(node_id, network_path) {
let upstream_layer = {
self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow)
.nth(1)
.filter(|upstream_node| self.is_stack(upstream_node, network_path))
};
if let Some(upstream_layer) = upstream_layer {
self.shift_node(&upstream_layer, IVec2::new(0, -shift_sign), network_path);
}
}
if let Some(owned_nodes) = self.with_owned_nodes_if_loaded(node_id, network_path, |owned_nodes| owned_nodes.clone()) {
for owned_node in owned_nodes {
if self.is_absolute(&owned_node, network_path) {
@@ -845,7 +1023,7 @@ impl NodeNetworkInterface {
// A chain node has no position of its own to shift, so it leaves the chain first
NodeTypePersistentMetadata::Node(node_position) if matches!(node_position.position(), NodePosition::Chain) => {
self.set_upstream_chain_to_absolute(node_id, network_path);
self.unchain_upstream(node_id, network_path);
self.shift_node(node_id, shift, network_path);
}
@@ -1277,6 +1455,7 @@ impl NodeNetworkInterface {
/// upstream node's spot and that whole branch is shifted left (in absolute graph space) to make room.
pub fn insert_node_before_input(&mut self, node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) {
let feeder = self.upstream_output_connector(input_connector, network_path).and_then(|output| output.node_id());
let feeder_position = feeder.and_then(|feeder| self.position(&feeder, network_path));
let Some(current_input) = self.input_from_connector(input_connector, network_path).cloned() else {
log::error!("Could not get input in insert_node_before_input");
@@ -1291,20 +1470,26 @@ impl NodeNetworkInterface {
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do
if !self.is_absolute(node_id, network_path) {
if self.is_chain(node_id, network_path) {
return;
}
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room
let Some(feeder) = feeder else { return };
// Otherwise place the node where the displaced feeder was, then move the feeder's branch left to make room
let (Some(feeder), Some(feeder_position)) = (feeder, feeder_position) else { return };
let Some(node_position) = self.position(node_id, network_path) else { return };
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
self.shift_node(node_id, feeder_position - node_position, network_path);
// A chain feeder derives its position from its distance to the layer, which this insertion already grew,
// so shifting it would move it twice and cost it its place in the chain
if !self.is_absolute(&feeder, network_path) {
if self.is_chain(&feeder, network_path) {
return;
}
// A relative feeder carries its upstream along
if self.is_relative(&feeder, network_path) {
let Some(current_feeder_position) = self.position(&feeder, network_path) else { return };
self.shift_node(&feeder, feeder_position + IVec2::new(-NODE_CHAIN_WIDTH, 0) - current_feeder_position, network_path);
return;
}
@@ -437,7 +437,7 @@ impl NodeNetworkInterface {
let new_inputs = std::mem::take(&mut new_template.inputs);
let new_input_metadata = std::mem::take(&mut new_template.input_metadata);
// A chain whose link into this node is dropped loses the layer it's positioned against, so it becomes absolute while that layer is still reachable
// A chain whose link into this node is dropped loses the layer it's positioned against, so it leaves the chain while that layer is still reachable
let chain_input_index = if self.is_layer(node_id, network_path) { LAYER_SECONDARY_INPUT_INDEX } else { PRIMARY_INPUT_INDEX };
let disconnected_chain_node = self
.document_node(node_id, network_path)
@@ -453,9 +453,24 @@ impl NodeNetworkInterface {
})
.filter(|upstream_node_id| self.is_chain(upstream_node_id, network_path));
if let Some(upstream_node_id) = disconnected_chain_node {
self.set_upstream_chain_to_absolute(&upstream_node_id, network_path);
self.unchain_upstream(&upstream_node_id, network_path);
}
let disconnected_upstream_positions: Vec<(NodeId, IVec2)> = self
.document_node(node_id, network_path)
.map(|node| {
node.inputs
.iter()
.enumerate()
.filter(|(index, old_input)| new_inputs.get(*index) != Some(*old_input))
.filter_map(|(_, old_input)| old_input.as_node())
.collect::<Vec<_>>()
})
.unwrap_or_default()
.into_iter()
.filter_map(|upstream_node_id| Some((upstream_node_id, self.position(&upstream_node_id, network_path)?)))
.collect();
let Some(mut node) = self.node_interface_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in replace_inputs");
return None;
@@ -463,6 +478,10 @@ impl NodeNetworkInterface {
let old_inputs = node.replace_inputs(new_inputs.clone(), new_input_metadata);
self.update_outward_wires_for_inputs(network_path, node_id, &old_inputs, &new_inputs);
for (upstream_node_id, position) in disconnected_upstream_positions {
self.pin_relative_node_without_readers(&upstream_node_id, position, network_path);
}
Some(old_inputs)
}
@@ -600,13 +619,17 @@ impl NodeNetworkInterface {
return;
}
if let NodeInput::Node { node_id: upstream_node_id, .. } = &previous_input {
self.pin_relative_node_losing_its_readers(upstream_node_id, input_connector, network_path);
}
// A chain positions its nodes relative to the layer they feed, so either end of the rewire
// leaving that layer breaks the chain it belonged to
for chain_input in [&previous_input, &new_input] {
if let NodeInput::Node { node_id: chain_node_id, .. } = chain_input
&& self.is_chain(chain_node_id, network_path)
{
self.set_upstream_chain_to_absolute(chain_node_id, network_path);
self.unchain_upstream(chain_node_id, network_path);
}
}
@@ -775,7 +798,7 @@ impl NodeNetworkInterface {
{
// If the node upstream from the disconnected input is a chain, then break the chain by setting it to absolute positioning
if self.is_chain(upstream_node_id, network_path) {
self.set_upstream_chain_to_absolute(upstream_node_id, network_path);
self.unchain_upstream(upstream_node_id, network_path);
}
// If the node upstream from the disconnected input has an outward wire to the bottom of a layer, set it back to stack positioning
if self.is_layer(upstream_node_id, network_path) {
@@ -887,10 +910,17 @@ impl NodeNetworkInterface {
dot_template.node_type_metadata = NodeTypePersistentMetadata::node(center - IVec2::Y);
self.insert_node(dot, dot_template, network_path);
let upstream_node = output_connector.node_id();
let upstream_position = upstream_node.and_then(|upstream_node| self.position(&upstream_node, network_path));
self.create_wire(output_connector, &InputConnector::primary_input(dot), network_path);
for fed_input in fed_inputs {
self.create_wire(&OutputConnector::primary_output(dot), fed_input, network_path);
}
if let (Some(upstream_node), Some(upstream_position)) = (upstream_node, upstream_position) {
self.keep_drawn_at(&upstream_node, upstream_position, network_path);
}
}
/// Used to insert a group of nodes into the network
@@ -1321,20 +1351,20 @@ impl NodeNetworkInterface {
}
pub fn set_to_node_or_layer(&mut self, node_id: &NodeId, network_path: &[NodeId], is_layer: bool) {
// If a layer is set to a node, set upstream nodes to absolute position, and upstream siblings to absolute position
// If a layer is set to a node, take its chain out of the chain and its upstream sibling out of the stack where they are drawn
let child_id = { self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).nth(1) };
let upstream_sibling_id = { self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow).nth(1) };
match (self.is_layer(node_id, network_path), is_layer) {
(true, false) => {
if let Some(child_id) = child_id {
self.set_upstream_chain_to_absolute(&child_id, network_path);
self.unchain_upstream(&child_id, network_path);
}
if let Some(upstream_sibling_id) = upstream_sibling_id {
let Some(upstream_sibling_position) = self.position(&upstream_sibling_id, network_path) else {
log::error!("Could not get upstream sibling position in set_to_node_or_layer");
return;
};
self.set_absolute_position(&upstream_sibling_id, upstream_sibling_position, network_path);
self.place_at(&upstream_sibling_id, upstream_sibling_position, network_path);
}
}
(false, true) => {
@@ -1349,7 +1379,7 @@ impl NodeNetworkInterface {
{
self.set_stack_position_calculated_offset(&upstream_sibling_id, node_id, network_path);
} else {
self.set_upstream_chain_to_absolute(&upstream_sibling_id, network_path);
self.unchain_upstream(&upstream_sibling_id, network_path);
}
}
}
@@ -1372,7 +1402,7 @@ impl NodeNetworkInterface {
.filter(|downstream_node_id| self.is_layer(downstream_node_id, network_path))
.and_then(|downstream_layer| self.position(&downstream_layer, network_path));
// First set the position to absolute
// First switch between layer and node where it is drawn
let absolute = match is_layer {
true => NodeTypePersistentMetadata::layer(position),
false => NodeTypePersistentMetadata::node(position),
@@ -1382,6 +1412,7 @@ impl NodeNetworkInterface {
return;
};
node.set_node_type(absolute);
self.place_at(node_id, position, network_path);
// Try build the chain
if is_layer {
@@ -954,8 +954,27 @@ impl NodeNetworkInterface {
self.query(network_path, "is_chain", |view| view.is_chain(node_id)).unwrap_or_default()
}
pub fn is_relative(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "is_relative", |view| view.is_relative(node_id)).unwrap_or_default()
}
/// Whether the layer sits straight below the one layer reading it through its stack input.
pub fn is_stack(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
self.query(network_path, "is_stack", |view| view.is_stack(node_id)).unwrap_or_default()
self.stack_offset(node_id, network_path).is_some()
}
/// The rows a stacked layer sits below the gap under the layer reading it.
pub fn stack_offset(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<i32> {
let stack_offset = self.query(network_path, "stack_offset", |view| view.stack_offset(node_id)).flatten()?;
let read_by_one_stack_input = self
.with_outward_wires(network_path, |outward_wires| match outward_wires.get(&OutputConnector::primary_output(*node_id)).map(Vec::as_slice) {
Some([InputConnector::Node { node_id: reader, input_index: 0 }]) => self.is_layer(reader, network_path),
_ => false,
})
.unwrap_or_default();
read_by_one_stack_input.then_some(stack_offset)
}
/// Whether the node is an Artboard node by identity, regardless of whether it currently participates in the scene.
@@ -14,8 +14,8 @@ use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId,
use graphene_std::vector::style::RenderMode;
use super::{
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface,
NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
};
use crate::messages::portfolio::document::node_graph::document_node_definitions::network_definition_version;
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
@@ -180,10 +180,12 @@ pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
LayerPosition::Absolute(v) => Position::Absolute([v.x, v.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
LayerPosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
},
NodeTypePersistentMetadata::Node(node) => match *node.position() {
NodePosition::Absolute(v) => Position::Absolute([v.x, v.y]),
NodePosition::Chain => Position::Chain,
NodePosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
},
}
}
@@ -202,6 +204,10 @@ pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersis
metadata
}
(Position::Chain, _) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)),
(Position::Relative([x, y]), true) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(IVec2::new(x, y)),
}),
(Position::Relative([x, y]), false) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(x, y)))),
}
}
@@ -144,14 +144,31 @@ impl NodeMut<'_> {
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
/// Places the node at an offset from the top left corner of the bounding box of the nodes reading it.
pub(crate) fn set_relative_position(&mut self, offset: IVec2) -> bool {
let node_type = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(offset),
}),
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(offset))),
};
self.set_node_type(node_type)
}
/// Offsets a node that is absolutely or relatively positioned, leaving a stack or chain node where it is.
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
let shifted = match self.metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Absolute(position),
}) => NodeTypePersistentMetadata::layer(position + shift),
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(offset),
}) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Relative(offset + shift),
}),
NodeTypePersistentMetadata::Node(ref node) => match node.position {
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
NodePosition::Relative(offset) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(offset + shift))),
NodePosition::Chain => return false,
},
NodeTypePersistentMetadata::Layer(_) => return false,
@@ -165,7 +182,7 @@ impl NodeMut<'_> {
return false;
}
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
position: LayerPosition::Stack(y_offset),
position: LayerPosition::stacked(y_offset),
}))
}
@@ -1111,7 +1111,7 @@ impl NodeTypePersistentMetadata {
/// All fields in LayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LayerPersistentMetadata {
/// Stores the position of a layer node, which can either be Absolute or Stack
/// Stores the position of a layer node, which can be Absolute or Relative, or Stack in older documents
pub position: LayerPosition,
}
@@ -1123,7 +1123,7 @@ impl PartialEq for LayerPersistentMetadata {
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodePersistentMetadata {
/// Stores the position of a non layer node, which can either be Absolute or Chain
/// Stores the position of a non layer node, which can be Absolute, Chain, or Relative
pub(crate) position: NodePosition,
}
@@ -1136,22 +1136,33 @@ impl NodePersistentMetadata {
}
}
/// A layer can either be position as Absolute or in a Stack
/// A layer is positioned as Absolute or Relative to the nodes reading it. Stack is only read from older documents, which opening converts to Relative.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum LayerPosition {
// Position of the node in grid spaces
Absolute(IVec2),
// A layer is in a Stack when it feeds into the bottom input of a layer. The Y position stores the vertical distance between the layer and its upstream sibling/parent.
Stack(u32),
// Offset from the top left corner of the bounding box of the positions of the nodes reading this one
Relative(IVec2),
}
/// A node can either be position as Absolute or in a Chain
impl LayerPosition {
/// Stacked `y_offset` rows below the gap under the layer reading it.
pub fn stacked(y_offset: u32) -> Self {
Self::Relative(IVec2::new(0, STACK_VERTICAL_GAP + y_offset as i32))
}
}
/// A node can be positioned as Absolute, in a Chain, or Relative to the nodes reading it
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum NodePosition {
// Position of the node in grid spaces
Absolute(IVec2),
// In a chain the position is based on the number of nodes to the first layer node
Chain,
// Offset from the top left corner of the bounding box of the positions of the nodes reading this one
Relative(IVec2),
}
/// 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.
@@ -237,10 +237,22 @@ impl<'a, 'p> NetworkView<'a, 'p> {
})
}
pub fn is_stack(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
pub fn is_relative(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Stack(_)),
_ => false,
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Relative(_)),
NodeTypePersistentMetadata::Node(node_metadata) => matches!(node_metadata.position, NodePosition::Relative(_)),
})
}
/// The rows a layer sits below the gap under the node reading it, if its position places it straight below that node.
pub fn stack_offset(&self, node_id: &NodeId) -> Result<Option<i32>, NetworkError> {
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer_metadata) => match layer_metadata.position {
LayerPosition::Stack(y_offset) => Some(y_offset as i32),
LayerPosition::Relative(offset) if offset.x == 0 => Some(offset.y - STACK_VERTICAL_GAP),
_ => None,
},
NodeTypePersistentMetadata::Node(_) => None,
})
}
@@ -1910,6 +1910,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
migrate_copy_to_points_nodes(document);
// After the upgrades that add or rewire nodes, so the nodes they place are converted too
document.network_interface.convert_positions_to_relative();
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
@@ -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 gets a `Position::Relative` offset, which places it below and left of the nodes reading it wherever they are drawn, so it needs no coordinates of the anchor. 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. Storing every node's position relative to its consumers, as `Position::Relative` does for the nodes migrations add, 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.
@@ -204,6 +205,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 are stored relative to the node they feed, so they sit below it wherever it is drawn. `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: