mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb71fe436b |
No files matched your search
@@ -47,7 +47,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
||||
if let Err(e) = self.editor.poll_node_graph_evaluation(&mut responses)
|
||||
&& e != "No active document"
|
||||
{
|
||||
tracing::error!("Error polling node graph: {}", e);
|
||||
tracing::error!("Error poling node graph: {}", e);
|
||||
}
|
||||
while let Some(message) = responses.pop_front() {
|
||||
self.queue_editor_message(message);
|
||||
|
||||
@@ -150,7 +150,6 @@ impl<L: Layout> Gdd<L> {
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
next_hot_sequence: self.session.next_hot_sequence(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
|
||||
@@ -158,8 +158,6 @@ impl<L: Layout> Gdd<L> {
|
||||
if let Some(rev) = session_state.last_broadcast_rev {
|
||||
session.publish_up_to(rev);
|
||||
}
|
||||
// Every arm must continue this peer's authored-op count too.
|
||||
session.restore_hot_sequence(session_state.next_hot_sequence);
|
||||
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
|
||||
@@ -198,7 +198,6 @@ impl<L: Layout> Gdd<L> {
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
next_hot_sequence: self.session.next_hot_sequence(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use document_graph_storage::{HotSequence, NetworkId, PeerId, Rev};
|
||||
use document_graph_storage::{NetworkId, PeerId, Rev};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
@@ -39,9 +39,4 @@ pub struct SessionState {
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
|
||||
/// How many hot ops this peer has authored, feeding [`document_graph_storage::HotOp::sequence`]. A
|
||||
/// reopen continues the run instead of reusing a spent sequence. Appended last: a positional codec
|
||||
/// decodes these fields in declaration order.
|
||||
#[serde(default)]
|
||||
pub next_hot_sequence: HotSequence,
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use document_graph_storage::{HotOp, HotSequence, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
use document_graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
@@ -128,7 +128,6 @@ fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
@@ -155,7 +154,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
@@ -163,7 +161,6 @@ fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
sequence: HotSequence(2),
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
@@ -203,7 +200,6 @@ fn last_broadcast_rev_persists_across_reopen() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
@@ -659,7 +655,6 @@ fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
sequence: HotSequence(1),
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ pub mod node {
|
||||
|
||||
pub mod session {
|
||||
pub mod network {
|
||||
pub const PREVIEWING: &str = "ui::previewing";
|
||||
// TODO: Remove these graph ui nav-specific attributes
|
||||
pub const NAV_PTZ: &str = "ui::nav::ptz";
|
||||
pub const NAV_TRANSFORM: &str = "ui::nav::transform";
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
use crate::{
|
||||
Attributes, AttributesWrite, Implementation, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev,
|
||||
};
|
||||
use crate::{Attributes, AttributesWrite, InputSlot, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ResourceEntry, ResourceId, Rev, SourceKey, TimeStamp, UserId, Value, attr, compute_rev};
|
||||
use graphene_resource::ResourceHash;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -121,15 +119,6 @@ pub enum RegistryDelta {
|
||||
id: NodeId,
|
||||
inputs: Vec<InputSlot>,
|
||||
},
|
||||
/// A node's implementation, for swapping what it computes without rebuilding the node.
|
||||
///
|
||||
/// Removing and re-adding the node would express the same change, but would also clear every
|
||||
/// attribute it carries, so restating them would clobber whatever a concurrent peer wrote to the
|
||||
/// node's name, lock or pin.
|
||||
SetNodeImplementation {
|
||||
id: NodeId,
|
||||
implementation: Implementation,
|
||||
},
|
||||
ChangeNodeAttribute {
|
||||
id: NodeId,
|
||||
delta: AttributeDelta,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, HotOpId, HotSequence, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, RetiredHotOps,
|
||||
Rev, SourceValue, TimeStamp, apply_attribute_delta, reverse_attribute_delta,
|
||||
CrdtError, Delta, ExportSlot, History, HotOp, LamportClock, MAX_EXPORT_SLOTS, NetworkId, NodeId, NodeInput, PeerId, Registry, RegistryDelta, ResourceEntry, Rev, SourceValue, TimeStamp,
|
||||
apply_attribute_delta, reverse_attribute_delta,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -11,10 +11,6 @@ pub struct Document {
|
||||
/// Live broadcast stream, applied to the `working_registry` on receive, GC'd at retirement.
|
||||
/// Persisted for crash recovery so in-flight unretired work survives editor restarts.
|
||||
pub(crate) hot_log: Vec<HotOp>,
|
||||
/// Which hot ops history already covers, so one arriving after its own retirement is dropped instead
|
||||
/// of re-entering the log. Retirement discards the delta's link back to its hot op, leaving this the
|
||||
/// only record. See [`RetiredHotOps`].
|
||||
pub(crate) retired: RetiredHotOps,
|
||||
/// The registry as of the last retirement, with no un-retired hot ops applied. Retirement computes
|
||||
/// each delta's `reverse` against this (so LWW reverses capture the true pre-op value, not the
|
||||
/// hot-polluted working state) and advances it, stamping fields at the fresh `T_retire`. Kept equal
|
||||
@@ -40,11 +36,6 @@ pub struct Document {
|
||||
/// peer is calling; collision avoidance comes from hashing `(self.peer, counter)`, so two peers
|
||||
/// reading the same counter still produce distinct IDs.
|
||||
pub(crate) next_node_counter: u64,
|
||||
/// Counts this peer's own hot ops, so each carries its position in a gap-free run. See [`HotOp::sequence`].
|
||||
pub(crate) next_hot_sequence: HotSequence,
|
||||
/// Set while the registries are still folded from an older history. A failed refold is retried; the
|
||||
/// derived state does not stay behind the history it comes from.
|
||||
pub(crate) refold_owed: bool,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
@@ -75,12 +66,24 @@ impl Document {
|
||||
self.revert_delta(target, delta)
|
||||
}
|
||||
|
||||
/// The last match in canonical history order, over everything reachable from `head` or any tip. Not a
|
||||
/// walk from `head`: peers sit on different merge revs, and resurrection must pick the same delta.
|
||||
/// Search every delta reachable from `head` (following all parents, including a merge's
|
||||
/// `extra_parents`) for the first matching `predicate`, breadth-first. Resurrection needs full
|
||||
/// ancestry reachability, so a node added only on a merged-in branch is still found.
|
||||
fn find_in_ancestry(&self, predicate: impl Fn(&Delta) -> bool) -> Option<Delta> {
|
||||
let reachable = self.history.ancestors(self.head.into_iter().chain(self.history.tips()));
|
||||
|
||||
self.history.iter().filter(|delta| reachable.contains(&delta.id) && predicate(delta)).last().cloned()
|
||||
let mut queue: std::collections::VecDeque<Rev> = self.head.into_iter().collect();
|
||||
let mut seen: std::collections::HashSet<Rev> = self.head.into_iter().collect();
|
||||
while let Some(rev) = queue.pop_front() {
|
||||
let Some(delta) = self.history.get(rev) else { continue };
|
||||
if predicate(delta) {
|
||||
return Some(delta.clone());
|
||||
}
|
||||
for parent in delta.all_parents() {
|
||||
if seen.insert(parent) {
|
||||
queue.push_back(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Apply a delta's `reverse` as the new forward op (silent-zone undo). Force-applied: structural
|
||||
@@ -96,10 +99,9 @@ impl Document {
|
||||
self.apply_op_with(target, delta.kind, delta.timestamp, ApplyMode::Force)
|
||||
}
|
||||
|
||||
/// Apply a locally staged op: LWW into the registry, append to the hot log, leave history and `head`
|
||||
/// alone. Crate-private because it skips the retirement check an op off the wire needs; staging must
|
||||
/// not have a covered sequence silently drop local work. Outside callers use [`Session::apply_hot_op`].
|
||||
pub(crate) fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
/// Apply a live broadcast op. Updates the registry via LWW and appends to the hot log.
|
||||
/// Doesn't touch history or `head` — hot ops are transient.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.apply_op(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
@@ -109,55 +111,11 @@ impl Document {
|
||||
/// re-applying an op whose effect is already reflected in the registry is a no-op rather
|
||||
/// than an error.
|
||||
pub fn replay_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
// Already in retired history; re-adding it would leave an entry no retirement will ever name.
|
||||
if self.is_retired(hot_op.id()) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Identified by timestamp, so a re-announcement of one already held must not become a second copy.
|
||||
if self.hot_log.iter().any(|held| held.timestamp == hot_op.timestamp) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Replaying our own ops is what carries the sequence counter across a reload.
|
||||
if hot_op.timestamp.peer == self.peer {
|
||||
self.next_hot_sequence = self.next_hot_sequence.max(hot_op.sequence);
|
||||
}
|
||||
|
||||
self.apply_op_idempotent(hot_op.op.clone(), hot_op.timestamp)?;
|
||||
self.hot_log.push(hot_op);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether this hot op has already been promoted into history.
|
||||
pub(crate) fn is_retired(&self, id: HotOpId) -> bool {
|
||||
self.retired.covers(id)
|
||||
}
|
||||
|
||||
/// Record newly retired hot ops, dropping any the hot log still holds.
|
||||
pub(crate) fn mark_retired(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
self.retired.extend(retired);
|
||||
|
||||
self.drop_retired_hot_ops();
|
||||
}
|
||||
|
||||
/// Take on a peer's retirement marks as well as this peer's. Returns whether a hot op was dropped,
|
||||
/// which owes the caller a refold.
|
||||
pub(crate) fn absorb_retired(&mut self, remote: &RetiredHotOps) -> bool {
|
||||
self.retired.absorb(remote);
|
||||
|
||||
self.drop_retired_hot_ops()
|
||||
}
|
||||
|
||||
/// Drop hot ops the retired snapshot already accounts for. A mark alone will not do: it can arrive
|
||||
/// ahead of the delta carrying the op into history, stranding its effect in the working registry.
|
||||
fn drop_retired_hot_ops(&mut self) -> bool {
|
||||
let before = self.hot_log.len();
|
||||
self.hot_log.retain(|hot_op| !self.history.contains_timestamp(hot_op.timestamp));
|
||||
|
||||
before != self.hot_log.len()
|
||||
}
|
||||
|
||||
/// Apply a retired commit. Idempotent on structural ops (AddNode/AddNetwork on existing
|
||||
/// targets, Remove on missing ones) since hot ops already produced the structural state.
|
||||
/// The point is to bump field timestamps to T_retire via the LWW arms.
|
||||
@@ -238,15 +196,7 @@ impl Document {
|
||||
}
|
||||
RegistryDelta::SetNodeInputs { id, inputs } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
// The list is one value rather than independently mergeable slots, so the newest slot stands in
|
||||
// for a timestamp the list itself does not carry, and an older write is dropped whole.
|
||||
let newest = node.inputs.iter().map(|slot| slot.timestamp).max().unwrap_or(TimeStamp::ORIGIN);
|
||||
if force || timestamp > newest {
|
||||
// The slots arrive carrying the placeholder timestamp they were built with, so they take this
|
||||
// op's instead. Leaving the placeholder would reset every slot to the origin and make each
|
||||
// later per-slot gate vacuously true, letting a stale write win.
|
||||
node.inputs = inputs.into_iter().map(|slot| crate::InputSlot { timestamp, ..slot }).collect();
|
||||
}
|
||||
node.inputs = inputs;
|
||||
}
|
||||
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
@@ -256,13 +206,6 @@ impl Document {
|
||||
input.timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
if force || timestamp > node.implementation_timestamp {
|
||||
node.implementation = implementation;
|
||||
node.implementation_timestamp = timestamp;
|
||||
}
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, delta } => {
|
||||
let node = registry.node_instances.get_mut(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
apply_attribute_delta(delta, timestamp, force, &mut node.attributes);
|
||||
@@ -357,7 +300,7 @@ impl Document {
|
||||
/// Resurrect (from history) any nodes/networks an op references that were concurrently removed, so
|
||||
/// the op applies against a consistent registry. Cascading: a node's owning network is restored
|
||||
/// before the node. No-op for ops that reference nothing absent.
|
||||
pub(crate) fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||
fn ensure_referenced_exist(&mut self, target: RegistryTarget, op: &RegistryDelta) -> Result<(), CrdtError> {
|
||||
match op {
|
||||
RegistryDelta::AddNode { node, .. } => self.ensure_network_exists(target, node.network())?,
|
||||
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
|
||||
@@ -374,12 +317,6 @@ impl Document {
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::SetNodeImplementation { id, implementation } => {
|
||||
if let crate::Implementation::Network(network) = implementation {
|
||||
self.ensure_network_exists(target, *network)?;
|
||||
}
|
||||
self.ensure_node_exists(target, *id)?;
|
||||
}
|
||||
RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => self.ensure_node_exists(target, *id)?,
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: network, export: export_target, ..
|
||||
@@ -396,51 +333,17 @@ impl Document {
|
||||
}
|
||||
|
||||
fn ensure_node_exists(&mut self, target: RegistryTarget, node_id: NodeId) -> Result<(), CrdtError> {
|
||||
if self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
return Ok(());
|
||||
if !self.registry_ref(target).node_instances.contains_key(&node_id) {
|
||||
self.restore_node_from_history(target, node_id)?;
|
||||
}
|
||||
let removal = self.hot_log_node_removal(target, node_id);
|
||||
match removal {
|
||||
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
|
||||
None => self.restore_node_from_history(target, node_id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The most recent hot removal of a network, for reviving it in the working zone. `None` for the
|
||||
/// snapshot, which stays a function of history alone.
|
||||
fn hot_log_removal(&self, target: RegistryTarget, network_id: NetworkId) -> Option<(RegistryDelta, TimeStamp)> {
|
||||
if target != RegistryTarget::Working {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
|
||||
RegistryDelta::RemoveNetwork { id, snapshot } if *id == network_id => Some((RegistryDelta::AddNetwork { id: *id, network: snapshot.clone() }, hot_op.timestamp)),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The node equivalent of [`hot_log_removal`](Self::hot_log_removal).
|
||||
fn hot_log_node_removal(&self, target: RegistryTarget, node_id: NodeId) -> Option<(RegistryDelta, TimeStamp)> {
|
||||
if target != RegistryTarget::Working {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.hot_log.iter().rev().find_map(|hot_op| match &hot_op.op {
|
||||
RegistryDelta::RemoveNode { id, snapshot } if *id == node_id => Some((RegistryDelta::AddNode { id: *id, node: snapshot.clone() }, hot_op.timestamp)),
|
||||
_ => None,
|
||||
})
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ensure_network_exists(&mut self, target: RegistryTarget, network_id: NetworkId) -> Result<(), CrdtError> {
|
||||
if self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
return Ok(());
|
||||
}
|
||||
// The hot log is peer-local, so reviving retired state from it would make it peer-dependent.
|
||||
let removal = self.hot_log_removal(target, network_id);
|
||||
match removal {
|
||||
Some((revive, timestamp)) => self.apply_op_with(target, revive, timestamp, ApplyMode::Force),
|
||||
None => self.restore_network_from_history(target, network_id),
|
||||
if !self.registry_ref(target).networks.contains_key(&network_id) {
|
||||
self.restore_network_from_history(target, network_id)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compute the inverse of `delta` against the registry named by `target`. Retirement passes
|
||||
@@ -455,13 +358,6 @@ impl Document {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeInputs { id, inputs: node.inputs.clone() }
|
||||
}
|
||||
&RegistryDelta::SetNodeImplementation { id, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node.implementation.clone(),
|
||||
}
|
||||
}
|
||||
&RegistryDelta::ChangeNodeInput { id, index: input_idx, .. } => {
|
||||
let node = registry.node_instances.get(&id).ok_or(CrdtError::TargetNodeDoesNotExist(id))?;
|
||||
let slot = node.inputs().get(input_idx as usize).ok_or(CrdtError::InputIndexOutOfBounds(input_idx as usize))?;
|
||||
|
||||
@@ -333,7 +333,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
let mut attributes = crate::Attributes::new();
|
||||
write_ui_network_attributes(&mut attributes, node_network, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_ui_network_attributes(&mut attributes, ctx.metadata, metadata_path, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
write_scope_injections(&mut attributes, node_network, parent_path, network_id, ctx.ids(metadata_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
@@ -447,7 +447,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
|
||||
Ok(Node {
|
||||
implementation,
|
||||
implementation_timestamp: timestamp,
|
||||
inputs,
|
||||
attributes,
|
||||
network: network_id,
|
||||
@@ -543,25 +542,20 @@ fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
/// does it: a runtime ID is not stable across a round trip.
|
||||
fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
||||
attributes: &mut crate::Attributes,
|
||||
node_network: &NodeNetwork,
|
||||
metadata: &M,
|
||||
network_path: &[RuntimeNodeId],
|
||||
parent_path: Option<&NodePath>,
|
||||
network_id: NetworkId,
|
||||
ids: NodeIds<'_, M>,
|
||||
timestamp: TimeStamp,
|
||||
) -> Result<(), ConversionError> {
|
||||
// The same source the IDs resolve through, so a network's attributes and the nodes they name agree.
|
||||
let Some(metadata) = ids.metadata else { return Ok(()) };
|
||||
if let Some(reference) = metadata.reference(network_path) {
|
||||
attributes.set(node::ui::REFERENCE, serde_json::Value::String(reference.to_string()), timestamp);
|
||||
}
|
||||
|
||||
let to_storage_id = |runtime_id: RuntimeNodeId| ids.resolve(&child_path(parent_path, network_id, runtime_id), runtime_id);
|
||||
|
||||
// Only nodes the converted network still holds: the read side drops a stored ID it cannot find, so
|
||||
// persisting one for a node deleted or reparented elsewhere would leave stored state disagreeing with
|
||||
// what a peer converting the same input produces.
|
||||
let pinned_order: Vec<_> = metadata.pinned_order(network_path).into_iter().filter(|pinned| node_network.nodes.contains_key(pinned)).collect();
|
||||
let pinned_order = metadata.pinned_order(network_path);
|
||||
if !pinned_order.is_empty() {
|
||||
let stored: Vec<NodeId> = pinned_order.into_iter().map(to_storage_id).collect();
|
||||
attributes
|
||||
@@ -810,7 +804,15 @@ impl<'m> ScopedConversion<'m> {
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
let mut attributes = crate::Attributes::new();
|
||||
write_ui_network_attributes(&mut attributes, node_network, local_path, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
write_ui_network_attributes(
|
||||
&mut attributes,
|
||||
self.ctx.metadata,
|
||||
local_path,
|
||||
owner_path.as_ref(),
|
||||
network_id,
|
||||
self.ctx.ids(local_path),
|
||||
TimeStamp::ORIGIN,
|
||||
)?;
|
||||
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.ids(local_path), TimeStamp::ORIGIN)?;
|
||||
|
||||
registry.networks.insert(network_id, Network { exports, attributes });
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! construction. The only operation that introduces out-of-order deltas is [`merge`](History::merge),
|
||||
//! which re-sorts the combined set into the canonical order to restore the invariant.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{AttributesWrite, CrdtError, Delta, Rev, TimeStamp};
|
||||
|
||||
@@ -39,11 +39,6 @@ impl History {
|
||||
self.index.contains_key(&rev)
|
||||
}
|
||||
|
||||
/// Whether history holds a delta authored at `timestamp`.
|
||||
pub fn contains_timestamp(&self, timestamp: TimeStamp) -> bool {
|
||||
self.deltas.iter().any(|delta| delta.timestamp == timestamp)
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.deltas.len()
|
||||
}
|
||||
@@ -69,12 +64,22 @@ impl History {
|
||||
self.deltas.iter()
|
||||
}
|
||||
|
||||
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
|
||||
///
|
||||
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
|
||||
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
|
||||
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
|
||||
/// (LWW apply is commutative, so the registry converges regardless of order).
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
|
||||
for delta in incoming {
|
||||
self.push(delta);
|
||||
}
|
||||
self.canonical_sort();
|
||||
}
|
||||
|
||||
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
|
||||
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
|
||||
///
|
||||
/// Deterministic: two peers that absorb the same delta set end up with byte-identical history, not two
|
||||
/// different valid orderings. Arrival order is erased.
|
||||
pub fn canonical_sort(&mut self) {
|
||||
fn canonical_sort(&mut self) {
|
||||
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
|
||||
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
@@ -114,51 +119,6 @@ impl History {
|
||||
}
|
||||
}
|
||||
|
||||
/// `roots` and everything reachable from them through all parent links. Unknown roots are skipped.
|
||||
pub fn ancestors(&self, roots: impl IntoIterator<Item = Rev>) -> HashSet<Rev> {
|
||||
let mut seen = HashSet::new();
|
||||
let mut stack: Vec<Rev> = roots.into_iter().filter(|rev| self.contains(*rev)).collect();
|
||||
while let Some(rev) = stack.pop() {
|
||||
if !seen.insert(rev) {
|
||||
continue;
|
||||
}
|
||||
if let Some(delta) = self.get(rev) {
|
||||
stack.extend(delta.all_parents());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
pub fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
|
||||
self.ancestors([descendant]).contains(&ancestor)
|
||||
}
|
||||
|
||||
/// `tip` plus the revs at first-parent distance 1, 2, 4, 8, ... behind it. Sent to a remote peer
|
||||
/// so it can locate the divergence point within a factor of two of the true distance.
|
||||
pub fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
|
||||
let mut samples = vec![tip];
|
||||
let mut current = tip;
|
||||
let mut distance = 0;
|
||||
let mut next_sample_distance = 1;
|
||||
|
||||
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
|
||||
current = parent;
|
||||
distance += 1;
|
||||
if distance == next_sample_distance {
|
||||
samples.push(current);
|
||||
next_sample_distance *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
samples
|
||||
}
|
||||
|
||||
/// Every delta not reachable from the `known` revs the remote peer reported, in topological order.
|
||||
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
|
||||
let known = self.ancestors(known);
|
||||
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
|
||||
}
|
||||
|
||||
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
|
||||
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
|
||||
pub fn tips(&self) -> Vec<Rev> {
|
||||
|
||||
@@ -5,10 +5,6 @@ use std::borrow::Cow;
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Node {
|
||||
pub(crate) implementation: Implementation,
|
||||
/// When the implementation was last written, so a swap resolves by last-writer-wins rather than by
|
||||
/// the order ops happen to arrive in. Absent from documents written before swaps were expressible.
|
||||
#[serde(default)]
|
||||
pub(crate) implementation_timestamp: TimeStamp,
|
||||
pub(crate) inputs: Vec<InputSlot>,
|
||||
pub(crate) attributes: Attributes,
|
||||
pub(crate) network: NetworkId,
|
||||
@@ -47,35 +43,10 @@ impl Node {
|
||||
attributes_value_equal(&self.attributes, &other.attributes)
|
||||
}
|
||||
|
||||
/// A node in `network` whose `inputs` slots are unset, for a caller that fills them in with
|
||||
/// `ChangeNodeInput`. The slot count is fixed at creation, since changing an input addresses a
|
||||
/// slot by position.
|
||||
pub fn new(network: NetworkId, implementation: Implementation, inputs: usize) -> Self {
|
||||
// `to_runtime` reads this back as a `TaggedValue`, whose unit `None` variant encodes as this string.
|
||||
// Pinned by `unset_input_slot_deserializes_as_tagged_value_none`.
|
||||
let slot = InputSlot {
|
||||
input: NodeInput::Value {
|
||||
value: serde_json::Value::String("None".to_string()),
|
||||
exposed: false,
|
||||
},
|
||||
timestamp: TimeStamp::ORIGIN,
|
||||
attributes: Attributes::new(),
|
||||
};
|
||||
|
||||
Self {
|
||||
implementation,
|
||||
implementation_timestamp: TimeStamp::ORIGIN,
|
||||
inputs: vec![slot; inputs],
|
||||
attributes: Attributes::new(),
|
||||
network,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn dummy() -> Self {
|
||||
Self {
|
||||
implementation: Implementation::ProtoNode(ResourceId::new()),
|
||||
implementation_timestamp: TimeStamp::default(),
|
||||
inputs: vec![],
|
||||
attributes: Attributes::new(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
@@ -183,19 +154,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// `to_runtime` has to read back what `Node::new` writes into an unset slot, so its literal must stay
|
||||
/// in step with how `TaggedValue::None` serializes.
|
||||
#[test]
|
||||
fn unset_input_slot_deserializes_as_tagged_value_none() {
|
||||
let node = Node::new(crate::ROOT_NETWORK, Implementation::Network(crate::ROOT_NETWORK), 1);
|
||||
let NodeInput::Value { value, .. } = &node.inputs()[0].input else {
|
||||
panic!("a fresh slot holds a value input");
|
||||
};
|
||||
|
||||
let tagged: graph_craft::document::value::TaggedValue = serde_json::from_value(value.clone()).expect("the unset slot value must deserialize");
|
||||
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
|
||||
}
|
||||
|
||||
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
|
||||
/// the same network without that slot, so the soak oracle doesn't false-report drift.
|
||||
#[test]
|
||||
|
||||
@@ -16,9 +16,6 @@ pub struct Session {
|
||||
/// leader-eligibility computation (lowest PeerId among peers whose tip matches the session max).
|
||||
#[expect(dead_code, reason = "Populated once heartbeat/leader-election transport lands; held now so the field and constructors are in place.")]
|
||||
remote_tips: HashMap<PeerId, Rev>,
|
||||
/// The registry the runtime was last built from or staged to. Local diffs are taken against it,
|
||||
/// so edits peers applied to the working registry in the meantime are not diffed away.
|
||||
runtime_base: Option<Registry>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -39,18 +36,14 @@ impl Session {
|
||||
retired_snapshot: Registry::default(),
|
||||
history: History::new(),
|
||||
hot_log: Vec::new(),
|
||||
retired: RetiredHotOps::default(),
|
||||
head: None,
|
||||
redo_stack: Vec::new(),
|
||||
clock: LamportClock::new(peer),
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter: 0,
|
||||
next_hot_sequence: HotSequence::NONE,
|
||||
refold_owed: false,
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,21 +77,11 @@ impl Session {
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
) -> Result<(Vec<HotOp>, from_runtime::RuntimeConversion), CommitError> {
|
||||
let conversion = Registry::convert_from_runtime(network, metadata, resources, self.document.peer)?;
|
||||
let base = self.runtime_base.as_ref().unwrap_or(&self.document.working_registry);
|
||||
let ops = crate::delta::compute_deltas(base, &conversion.registry);
|
||||
|
||||
// The base moves only once the ops are staged, so a failure leaves the next diff covering them.
|
||||
let ops = crate::delta::compute_deltas(&self.document.working_registry, &conversion.registry);
|
||||
let hot_ops = self.stage_ops(ops)?;
|
||||
self.runtime_base = Some(conversion.registry.clone());
|
||||
|
||||
Ok((hot_ops, conversion))
|
||||
}
|
||||
|
||||
/// Record that the runtime now reflects the working registry, after the caller rebuilt it from there.
|
||||
pub fn mark_runtime_current(&mut self) {
|
||||
self.runtime_base = Some(self.document.working_registry.clone());
|
||||
}
|
||||
|
||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`] for this document's peer, so the
|
||||
/// caller can key per-network, per-peer view state (`session.json`) by a stable id. Derived from the
|
||||
/// network structure alone; resources/declarations are irrelevant to the ids.
|
||||
@@ -157,8 +140,8 @@ impl Session {
|
||||
///
|
||||
/// The peer's first contribution is preceded by a `RegisterPeer` op, so the device's
|
||||
/// `PeerId → UserId` mapping is established (and, under causal delivery, observed by other peers)
|
||||
/// before any of its edits. A no-op batch doesn't register, since registration rides a real edit.
|
||||
pub fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
/// before any of its edits. A no-op batch doesn't register — registration rides a real edit.
|
||||
fn stage_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
|
||||
let mut pending: Vec<RegistryDelta> = ops.into_iter().collect();
|
||||
if pending.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
@@ -171,16 +154,11 @@ impl Session {
|
||||
|
||||
let mut staged = Vec::with_capacity(pending.len());
|
||||
for op in pending {
|
||||
// The counter advances only once the op is in the log, so a failure leaves no gap in the run.
|
||||
let sequence = self.document.next_hot_sequence.next();
|
||||
let hot_op = HotOp {
|
||||
op,
|
||||
timestamp: self.document.clock.tick(),
|
||||
sequence,
|
||||
};
|
||||
self.document.apply_hot_op(hot_op.clone())?;
|
||||
|
||||
self.document.next_hot_sequence = sequence;
|
||||
staged.push(hot_op);
|
||||
}
|
||||
Ok(staged)
|
||||
@@ -196,18 +174,11 @@ impl Session {
|
||||
/// `idempotent`: pass `true` when the snapshot already reflects the op (retirement of an already-
|
||||
/// applied hot op) so duplicate structural inserts no-op rather than error.
|
||||
fn commit_ops(&mut self, ops: impl IntoIterator<Item = RegistryDelta>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
self.commit_ops_authored_at(ops.into_iter().map(|op| (op, None)), idempotent)
|
||||
}
|
||||
|
||||
/// [`commit_ops`](Self::commit_ops) for ops authored elsewhere, paired with the timestamp they were
|
||||
/// authored at (`None` to mint one). The delta's timestamp is what the registry resolves LWW on, so
|
||||
/// retirement passes the op's own; a coarsened delta passes the newest it fuses.
|
||||
fn commit_ops_authored_at(&mut self, ops: impl IntoIterator<Item = (RegistryDelta, Option<TimeStamp>)>, idempotent: bool) -> Result<Vec<Rev>, CrdtError> {
|
||||
let target = RegistryTarget::Snapshot;
|
||||
let ops = ops.into_iter();
|
||||
let mut produced = Vec::with_capacity(ops.size_hint().0);
|
||||
|
||||
for (op, authored_at) in ops {
|
||||
for op in ops {
|
||||
// A new edit abandons any undone-forward branch: those revs stay in the DAG but are no
|
||||
// longer reachable via redo. (Mirrors the legacy editor clearing its redo history on
|
||||
// commit.) Done on the first real op so a no-op commit doesn't silently disable redo.
|
||||
@@ -215,12 +186,10 @@ impl Session {
|
||||
self.document.redo_stack.clear();
|
||||
}
|
||||
|
||||
// The reverse must read the pre-op value of a target that may have been concurrently removed.
|
||||
self.document.ensure_referenced_exist(target, &op)?;
|
||||
let reverse = self.document.compute_reverse_delta(target, &op)?;
|
||||
let timestamp = authored_at.unwrap_or_else(|| self.document.clock.tick());
|
||||
let timestamp = self.document.clock.tick();
|
||||
let parent = self.document.head;
|
||||
let author = timestamp.peer;
|
||||
let author = self.document.peer;
|
||||
|
||||
let delta = Delta::new(parent, author, timestamp, op, reverse);
|
||||
let rev = delta.id;
|
||||
@@ -258,18 +227,14 @@ impl Session {
|
||||
working_registry: registry,
|
||||
history: History::from_ordered(history),
|
||||
hot_log: Vec::new(),
|
||||
retired: RetiredHotOps::default(),
|
||||
head,
|
||||
redo_stack,
|
||||
clock,
|
||||
peer,
|
||||
last_broadcast_rev: None,
|
||||
next_node_counter,
|
||||
next_hot_sequence: HotSequence::NONE,
|
||||
refold_owed: false,
|
||||
},
|
||||
remote_tips: HashMap::new(),
|
||||
runtime_base: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -291,46 +256,9 @@ impl Session {
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Apply a hot op from another peer. Idempotent, and a no-op for one history already covers: a late
|
||||
/// delivery must not put a retired op back in the hot log.
|
||||
/// Apply a hot op without going through the broadcast stream.
|
||||
pub fn apply_hot_op(&mut self, hot_op: HotOp) -> Result<(), CrdtError> {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// The hot ops a `retire(up_to)` call would drain. Sent with the deltas for peers to drop exactly
|
||||
/// these; the cutoff alone doesn't transfer, a lagging op can arrive below it afterwards.
|
||||
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
|
||||
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
|
||||
}
|
||||
|
||||
/// Drop hot ops another peer has retired without retiring them locally. Refolds like
|
||||
/// [`absorb_retired_marks`](Self::absorb_retired_marks).
|
||||
pub fn discard_hot_ops(&mut self, retired: &[HotOpId]) -> Result<(), CrdtError> {
|
||||
let before = self.document.hot_log.len();
|
||||
self.document.hot_log.retain(|hot_op| !retired.contains(&hot_op.id()));
|
||||
// How a peer that did not retire these learns they are in history now.
|
||||
self.document.mark_retired(retired.iter().copied());
|
||||
|
||||
if before != self.document.hot_log.len() {
|
||||
self.refold_registries()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Which hot ops history already covers, for a peer catching up. See [`RetiredHotOps`].
|
||||
pub fn retired_marks(&self) -> &RetiredHotOps {
|
||||
&self.document.retired
|
||||
}
|
||||
|
||||
/// See [`RetiredHotOps::absorb`]. A drop owes a refold, since the working registry holds the op's
|
||||
/// effect in hot-log order where the snapshot holds it in canonical order.
|
||||
pub fn absorb_retired_marks(&mut self, remote: &RetiredHotOps) -> Result<(), CrdtError> {
|
||||
if self.document.absorb_retired(remote) {
|
||||
self.refold_registries()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
self.document.apply_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
|
||||
@@ -339,150 +267,55 @@ impl Session {
|
||||
self.document.replay_hot_op(hot_op)
|
||||
}
|
||||
|
||||
/// The retired snapshot as canonical history alone produces it, independent of arrival order and the
|
||||
/// hot log. Folded on a clone, over `head`'s ancestry only: an undone delta stays in the DAG for redo
|
||||
/// to find, and folding all of history would restore work the user undid.
|
||||
///
|
||||
/// The clone's history grows with the replay, as it did when each delta first landed. Resurrection
|
||||
/// takes the last removal in canonical order, and with the whole history in view that can be one past
|
||||
/// the replay position, whose snapshot places the entity in a network the replay has not created yet.
|
||||
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
|
||||
let reachable = self.document.history.ancestors(self.document.head);
|
||||
|
||||
let mut folded = self.clone();
|
||||
folded.document.retired_snapshot = Registry::default();
|
||||
folded.document.history = History::new();
|
||||
|
||||
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
|
||||
folded.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
folded.document.history.push(delta.clone());
|
||||
}
|
||||
|
||||
Ok(folded.document.retired_snapshot)
|
||||
}
|
||||
|
||||
/// Rebuild both registries from canonical history, then re-layer the hot tail. A full replay; callers
|
||||
/// check it is needed first.
|
||||
fn refold_registries(&mut self) -> Result<(), CrdtError> {
|
||||
// Cleared only on the way out. The deltas are in history either way, and a failure here leaves the
|
||||
// registries derived from an older one until something retries.
|
||||
self.document.refold_owed = true;
|
||||
self.document.retired_snapshot = self.snapshot_from_history()?;
|
||||
|
||||
// One left unapplicable is kept, not dropped: a later delta or hot op can still supply its referent.
|
||||
self.document.working_registry = self.document.retired_snapshot.clone();
|
||||
let mut failure = None;
|
||||
for hot_op in std::mem::take(&mut self.document.hot_log) {
|
||||
if let Err(error) = self.document.replay_hot_op(hot_op.clone()) {
|
||||
self.document.hot_log.push(hot_op);
|
||||
failure = failure.or(Some(error));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(error) = failure {
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
self.document.refold_owed = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Integrate `incoming` retired deltas (in causal order) from another peer. Moves `head` forward
|
||||
/// without a new delta when the incoming history extends it, otherwise joins `head` and the
|
||||
/// incoming tips with a [`RegistryDelta::Merge`].
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
|
||||
let length_before = self.document.history.len();
|
||||
|
||||
// Each delta enters history before the next is applied, so a later delta in the batch that
|
||||
// targets something an earlier one removed can resurrect it.
|
||||
let mut absorbed_ids = HashSet::new();
|
||||
let mut arrival_order = Vec::new();
|
||||
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
|
||||
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
|
||||
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
|
||||
/// deltas must arrive in causal order.
|
||||
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
|
||||
let mut absorbed: Vec<Delta> = Vec::new();
|
||||
for delta in incoming {
|
||||
if self.document.history.contains(delta.id) {
|
||||
continue;
|
||||
}
|
||||
arrival_order.push(delta.id);
|
||||
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
|
||||
// Working is snapshot plus hot tail, so a delta lands on both; cloning would promote hot ops.
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
|
||||
absorbed_ids.insert(delta.id);
|
||||
self.document.history.push(delta);
|
||||
absorbed.push(delta);
|
||||
}
|
||||
if absorbed_ids.is_empty() {
|
||||
// Nothing new, but a refold left owed by an earlier failure is still the only way the registries
|
||||
// catch up with the history they are derived from.
|
||||
if self.document.refold_owed {
|
||||
self.refold_registries()?;
|
||||
}
|
||||
|
||||
return Ok(MergeOutcome::NoOp);
|
||||
}
|
||||
self.document.history.canonical_sort();
|
||||
|
||||
// The loop folds in arrival order, and concurrent ops do not all commute: a remove and a change to
|
||||
// the same target resolve by whichever lands second.
|
||||
let folded_in_canonical_order = self.document.history.iter().skip(length_before).map(|delta| delta.id).eq(arrival_order.iter().copied());
|
||||
|
||||
let history = &self.document.history;
|
||||
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
|
||||
candidates.extend(self.document.head);
|
||||
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
|
||||
let parents: Vec<Rev> = candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect();
|
||||
|
||||
let outcome = match parents.as_slice() {
|
||||
[tip] => MergeOutcome::FastForward(*tip),
|
||||
_ => {
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(parents, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
|
||||
self.document.history.push(merge);
|
||||
MergeOutcome::Merged(merge_rev)
|
||||
}
|
||||
};
|
||||
self.document.head = outcome.head();
|
||||
|
||||
// After `head`, since the fold is over its ancestry.
|
||||
if !folded_in_canonical_order || self.document.refold_owed {
|
||||
self.refold_registries()?;
|
||||
if absorbed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
Ok(outcome)
|
||||
self.document.history.merge(absorbed);
|
||||
let tips = self.document.history.tips();
|
||||
let timestamp = self.document.clock.tick();
|
||||
let merge = Delta::merge(tips, self.document.peer, timestamp);
|
||||
let merge_rev = merge.id;
|
||||
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
|
||||
// order without re-sorting the whole history.
|
||||
self.document.history.push(merge);
|
||||
self.document.head = Some(merge_rev);
|
||||
|
||||
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(Some(merge_rev))
|
||||
}
|
||||
|
||||
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, each keeping the timestamp it was
|
||||
/// authored at.
|
||||
/// Promote hot ops with timestamp `≤ up_to` into retired deltas, re-applied with fresh
|
||||
/// retirement timestamps so LWW arms bump field timestamps to `T_retire`.
|
||||
///
|
||||
/// Today: one retired delta per hot op. Coarsening is a future step.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, CrdtError> {
|
||||
// Hot-log order is causal, so the deltas commit in an order their references survive.
|
||||
let mut drained = Vec::new();
|
||||
let mut remaining = Vec::with_capacity(self.document.hot_log.len());
|
||||
|
||||
// Retiring by timestamp reorders against the hot-log order the working registry applied: past a
|
||||
// skipped op, everything drained was applied here before it.
|
||||
let mut skipped = false;
|
||||
let mut reordered = false;
|
||||
for hot_op in self.document.hot_log.drain(..) {
|
||||
if hot_op.timestamp <= up_to {
|
||||
reordered |= skipped;
|
||||
drained.push(hot_op);
|
||||
} else {
|
||||
skipped = true;
|
||||
remaining.push(hot_op);
|
||||
}
|
||||
}
|
||||
self.document.hot_log = remaining;
|
||||
self.document.mark_retired(drained.iter().map(HotOp::id));
|
||||
|
||||
let revs = self.commit_ops_authored_at(drained.into_iter().map(|hot_op| (hot_op.op, Some(hot_op.timestamp))), true)?;
|
||||
|
||||
// Structural ops have no timestamp to arbitrate, so the reorder changes the outcome.
|
||||
if reordered {
|
||||
self.refold_registries()?;
|
||||
}
|
||||
|
||||
Ok(revs)
|
||||
self.commit_ops(drained.into_iter().map(|hot_op| hot_op.op), true)
|
||||
}
|
||||
|
||||
/// Mark a retired delta as the end of a user interaction, so the undo cursor treats it as a checkpoint.
|
||||
@@ -536,16 +369,16 @@ impl Session {
|
||||
!self.document.redo_stack.is_empty()
|
||||
}
|
||||
|
||||
/// Silent-zone undo of one *interaction*: revert deltas back along first-parents until `head` reaches
|
||||
/// the previous `interaction_end` boundary or the root. An interaction is a whole `commit_from_runtime`
|
||||
/// batch, so the run reverts together. Its `head` rev goes on the redo stack; the DAG is not rewritten.
|
||||
/// Silent-zone undo of one *interaction*: revert deltas walking `head` back along first-parents until
|
||||
/// it reaches the previous interaction boundary (a delta marked `interaction_end`) or the empty root. One
|
||||
/// interaction spans several deltas (one `commit_from_runtime` batch), so undo reverts the whole run,
|
||||
/// not a single delta — matching the legacy per-interaction undo granularity. The undone interaction's
|
||||
/// `head` rev is pushed onto the redo stack. Reflog semantics: the DAG is never rewritten.
|
||||
pub fn undo(&mut self) -> Result<Rev, CrdtError> {
|
||||
if !self.can_undo() {
|
||||
return Err(CrdtError::NothingToUndo);
|
||||
}
|
||||
let checkpoint = self.document.head.ok_or(CrdtError::NothingToUndo)?;
|
||||
// The caller rebuilds the runtime from the rewound registry; until then diff against it directly.
|
||||
self.runtime_base = None;
|
||||
|
||||
// Revert this interaction's last delta, then keep going back until `head` rests on the previous
|
||||
// interaction's boundary (its `interaction_end` delta) or the root.
|
||||
@@ -554,10 +387,7 @@ impl Session {
|
||||
let delta = self.document.history.get(rev).ok_or(CrdtError::NotFoundInHistory(rev))?.clone();
|
||||
let parent = delta.parent;
|
||||
|
||||
self.document.revert_delta(RegistryTarget::Working, delta.clone())?;
|
||||
// Working is snapshot plus hot tail, so rewind both; copying would promote unretired hot ops.
|
||||
self.document.revert_delta(RegistryTarget::Snapshot, delta)?;
|
||||
|
||||
self.document.revert_delta(RegistryTarget::Working, delta)?;
|
||||
self.document.head = parent;
|
||||
|
||||
match parent {
|
||||
@@ -567,6 +397,9 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
// Undo runs with an empty hot log, so keep the retired snapshot in lockstep with the rewound
|
||||
// working registry (the next interaction's reverses are computed against it).
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
self.document.redo_stack.push(checkpoint);
|
||||
Ok(checkpoint)
|
||||
}
|
||||
@@ -576,7 +409,6 @@ impl Session {
|
||||
/// parents back from the checkpoint to `head` (the chain is linear in the silent solo zone).
|
||||
pub fn redo(&mut self) -> Result<Rev, CrdtError> {
|
||||
let checkpoint = self.document.redo_stack.pop().ok_or(CrdtError::NothingToRedo)?;
|
||||
self.runtime_base = None;
|
||||
|
||||
let mut forward = Vec::new();
|
||||
let mut cursor = Some(checkpoint);
|
||||
@@ -591,11 +423,11 @@ impl Session {
|
||||
// at the same timestamp. Symmetric with `revert_delta`.
|
||||
for delta in forward.into_iter().rev() {
|
||||
self.document.force_apply_op(delta.kind.clone(), delta.timestamp)?;
|
||||
// Both zones move together, for the same reason `undo` rewinds both.
|
||||
self.document.apply_op_with(RegistryTarget::Snapshot, delta.kind.clone(), delta.timestamp, ApplyMode::Force)?;
|
||||
}
|
||||
self.document.head = Some(checkpoint);
|
||||
|
||||
// Redo runs with an empty hot log; keep the retired snapshot in lockstep with the working registry.
|
||||
self.document.retired_snapshot = self.document.working_registry.clone();
|
||||
Ok(checkpoint)
|
||||
}
|
||||
|
||||
@@ -615,17 +447,6 @@ impl Session {
|
||||
self.document.history.iter()
|
||||
}
|
||||
|
||||
/// Revs sampled at exponentially growing distances behind `head`, for a remote peer to locate what
|
||||
/// this session is missing (see [`History::sample_chain`]).
|
||||
pub fn known_revs(&self) -> Vec<Rev> {
|
||||
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Retired deltas not reachable from `known`, in replay order.
|
||||
pub fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
|
||||
self.document.history.deltas_unknown_to(known)
|
||||
}
|
||||
|
||||
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
|
||||
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
|
||||
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
|
||||
@@ -732,17 +553,6 @@ impl Session {
|
||||
pub fn next_node_counter(&self) -> u64 {
|
||||
self.document.next_node_counter
|
||||
}
|
||||
|
||||
/// How many hot ops this peer has authored. Carried across a reload; no sequence is spent twice.
|
||||
pub fn next_hot_sequence(&self) -> HotSequence {
|
||||
self.document.next_hot_sequence
|
||||
}
|
||||
|
||||
/// Restore the authored-op count after a load, keeping a fresh op off a spent sequence. Raises only:
|
||||
/// replaying a persisted hot log afterwards cannot lower it.
|
||||
pub fn restore_hot_sequence(&mut self, sequence: HotSequence) {
|
||||
self.document.next_hot_sequence = self.document.next_hot_sequence.max(sequence);
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors from `Session::commit_from_runtime`.
|
||||
@@ -762,147 +572,12 @@ impl Default for Session {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MergeOutcome {
|
||||
NoOp,
|
||||
FastForward(Rev),
|
||||
Merged(Rev),
|
||||
}
|
||||
|
||||
impl MergeOutcome {
|
||||
/// The head after the merge, or `None` when nothing changed.
|
||||
pub fn head(self) -> Option<Rev> {
|
||||
match self {
|
||||
Self::NoOp => None,
|
||||
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One live op in the hot zone. Carries only enough to drive live LWW; no parents (transient),
|
||||
/// no Rev (not content-addressed in the durable DAG). GC'd at retirement.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct HotOp {
|
||||
pub op: RegistryDelta,
|
||||
pub timestamp: TimeStamp,
|
||||
/// Position in its author's run, from 1 with no gaps. A watermark over it therefore means a contiguous
|
||||
/// prefix; one over the Lamport counter cannot, since that skips on observing a higher remote stamp.
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
impl HotOp {
|
||||
/// Identifies the op for retirement, which tracks a contiguous prefix per author.
|
||||
pub fn id(&self) -> HotOpId {
|
||||
HotOpId {
|
||||
peer: self.timestamp.peer,
|
||||
sequence: self.sequence,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Position in one author's run of hot ops, counting from 1 with no gaps. Kept apart from the Lamport
|
||||
/// counter, which skips on observing a higher remote timestamp and so cannot bound a contiguous prefix.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct HotSequence(pub u64);
|
||||
|
||||
impl HotSequence {
|
||||
/// Before this author has written anything, covering no op.
|
||||
pub const NONE: Self = Self(0);
|
||||
|
||||
/// The next position in the run.
|
||||
pub fn next(self) -> Self {
|
||||
Self(self.0 + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// One hot op's author and position in its run. Retirement names promoted ops by these, which tells a
|
||||
/// receiver which prefix history covers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct HotOpId {
|
||||
pub peer: PeerId,
|
||||
pub sequence: HotSequence,
|
||||
}
|
||||
|
||||
/// Which hot ops history already covers: `retired_up_to` is each author's gap-free retired prefix, and
|
||||
/// `unretired` the retired ops past it. Replicated, letting a peer catching up separate an op already in
|
||||
/// history from one still owed to it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RetiredHotOps {
|
||||
pub retired_up_to: HashMap<PeerId, HotSequence>,
|
||||
/// Retired ops sitting past their author's prefix, as inclusive runs. A gap that never fills pins the
|
||||
/// prefix and everything later from that author lands here, so runs keep this proportional to the
|
||||
/// number of gaps instead of the number of ops.
|
||||
pub retired_beyond: HashMap<PeerId, Vec<(HotSequence, HotSequence)>>,
|
||||
}
|
||||
|
||||
/// Sort and coalesce runs, joining any that touch or abut.
|
||||
fn coalesce(runs: &mut Vec<(HotSequence, HotSequence)>) {
|
||||
runs.sort_unstable();
|
||||
|
||||
let mut merged: Vec<(HotSequence, HotSequence)> = Vec::with_capacity(runs.len());
|
||||
for &(start, end) in runs.iter() {
|
||||
match merged.last_mut() {
|
||||
Some((_, last_end)) if start <= last_end.next() => *last_end = (*last_end).max(end),
|
||||
_ => merged.push((start, end)),
|
||||
}
|
||||
}
|
||||
|
||||
*runs = merged;
|
||||
}
|
||||
|
||||
impl RetiredHotOps {
|
||||
/// Whether history already holds this hot op.
|
||||
pub fn covers(&self, id: HotOpId) -> bool {
|
||||
if self.retired_up_to.get(&id.peer).is_some_and(|&through| id.sequence <= through) {
|
||||
return true;
|
||||
}
|
||||
|
||||
self.retired_beyond
|
||||
.get(&id.peer)
|
||||
.is_some_and(|runs| runs.iter().any(|&(start, end)| id.sequence >= start && id.sequence <= end))
|
||||
}
|
||||
|
||||
/// Take on `remote`'s coverage as well as this one's.
|
||||
pub fn absorb(&mut self, remote: &Self) {
|
||||
for (&peer, &remote_through) in &remote.retired_up_to {
|
||||
let through = self.retired_up_to.entry(peer).or_default();
|
||||
*through = (*through).max(remote_through);
|
||||
}
|
||||
for (&peer, runs) in &remote.retired_beyond {
|
||||
self.retired_beyond.entry(peer).or_default().extend(runs.iter().copied());
|
||||
}
|
||||
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Record newly retired ops.
|
||||
pub fn extend(&mut self, retired: impl IntoIterator<Item = HotOpId>) {
|
||||
for id in retired {
|
||||
self.retired_beyond.entry(id.peer).or_default().push((id.sequence, id.sequence));
|
||||
}
|
||||
|
||||
self.compact();
|
||||
}
|
||||
|
||||
/// Fold runs that continue their author's prefix into `retired_up_to`, leaving only those past a gap.
|
||||
fn compact(&mut self) {
|
||||
for (&peer, runs) in &mut self.retired_beyond {
|
||||
coalesce(runs);
|
||||
|
||||
let mut through = self.retired_up_to.get(&peer).copied().unwrap_or(HotSequence::NONE);
|
||||
while runs.first().is_some_and(|&(start, _)| start <= through.next()) {
|
||||
let (_, end) = runs.remove(0);
|
||||
through = through.max(end);
|
||||
}
|
||||
|
||||
if through != HotSequence::NONE {
|
||||
self.retired_up_to.insert(peer, through);
|
||||
}
|
||||
}
|
||||
|
||||
self.retired_beyond.retain(|_, runs| !runs.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
|
||||
@@ -40,7 +40,6 @@ fn apply_hot_op_advances_clock_past_observed_timestamp() {
|
||||
let hot_op = HotOp {
|
||||
op: remove_node_op(NodeId(99)),
|
||||
timestamp: observed,
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
|
||||
document.apply_hot_op(hot_op).expect("RemoveNode on absent node is a no-op, not an error");
|
||||
@@ -183,10 +182,9 @@ fn merge_converges_to_identical_history() {
|
||||
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
|
||||
let deltas_a = session_a.cloned_deltas();
|
||||
let deltas_b = session_b.cloned_deltas();
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
|
||||
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
|
||||
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
|
||||
|
||||
assert!(matches!(merge_a, crate::MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
|
||||
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
|
||||
|
||||
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
|
||||
@@ -195,29 +193,6 @@ fn merge_converges_to_identical_history() {
|
||||
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
|
||||
}
|
||||
|
||||
/// A peer whose history is a prefix of the incoming one moves its head forward without minting a
|
||||
/// merge delta, and the negotiated transfer sends only the deltas past the sampled known revs.
|
||||
#[test]
|
||||
fn merge_fast_forwards_a_prefix_history() {
|
||||
let mut session_a = Session::with_peer(PeerId(1));
|
||||
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
|
||||
let mut session_b = session_a.clone();
|
||||
|
||||
for value in 1..=5 {
|
||||
session_b.commit_op_for_test(set_document_attribute("compute::b", value)).expect("B edit");
|
||||
}
|
||||
|
||||
let known = session_a.known_revs();
|
||||
let missing: Vec<_> = session_b.deltas_unknown_to(known).into_iter().cloned().collect();
|
||||
assert_eq!(missing.len(), 5, "only B's new commits are unknown to A");
|
||||
|
||||
let outcome = session_a.merge(missing).expect("merge failed");
|
||||
assert_eq!(outcome, crate::MergeOutcome::FastForward(session_b.head_rev().unwrap()));
|
||||
assert_eq!(session_a.history().count(), session_b.history().count(), "no merge delta was added");
|
||||
|
||||
assert_eq!(session_b.merge(session_a.cloned_deltas()).expect("merge failed"), crate::MergeOutcome::NoOp);
|
||||
}
|
||||
|
||||
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
|
||||
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
|
||||
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
|
||||
@@ -862,7 +837,6 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
|
||||
Node {
|
||||
implementation: implementation.clone(),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs,
|
||||
attributes,
|
||||
network: ROOT_NETWORK,
|
||||
@@ -905,417 +879,3 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
|
||||
|
||||
assert_eq!(delta_forward.id, delta_reversed.id, "Rev must not depend on attribute insertion order");
|
||||
}
|
||||
|
||||
/// Commit a retired delta and mirror it onto the working registry; `commit_op_for_test` alone only
|
||||
/// advances the snapshot zone.
|
||||
fn commit_retired(session: &mut Session, op: RegistryDelta) {
|
||||
let before = session.history().count();
|
||||
session.commit_op_for_test(op).expect("commit failed");
|
||||
|
||||
for delta in session.cloned_deltas().into_iter().skip(before) {
|
||||
session.document.apply_op_idempotent(delta.kind, delta.timestamp).expect("mirroring onto the working registry");
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge `deltas` into a copy of `base` in the given order, reporting node 7's surviving `tint`.
|
||||
fn merge_order_outcome(base: &Session, deltas: &[Delta], order: [usize; 2]) -> Option<(serde_json::Value, TimeStamp)> {
|
||||
let mut session = base.clone();
|
||||
let ordered: Vec<Delta> = order.iter().map(|&index| deltas[index].clone()).collect();
|
||||
session.merge(ordered).expect("merge failed");
|
||||
|
||||
session
|
||||
.retired_registry()
|
||||
.node_instances
|
||||
.get(&NodeId(7))
|
||||
.and_then(|node| node.attributes.get("tint"))
|
||||
.map(|value| (value.value.clone(), value.timestamp))
|
||||
}
|
||||
|
||||
/// The raw ops are arrival-order dependent: change-first leaves the node gone, remove-first resurrects
|
||||
/// it from the removal's snapshot. Merge has to fold both orders onto the same retired registry.
|
||||
#[test]
|
||||
fn a_concurrent_remove_and_attribute_change_commute() {
|
||||
let network_id = NetworkId(5);
|
||||
let node = Node::new(network_id, crate::Implementation::Network(network_id), 0);
|
||||
|
||||
// Shared base holding node 7, then the two peers diverge.
|
||||
let mut base = Session::with_peer(PeerId(1));
|
||||
commit_retired(
|
||||
&mut base,
|
||||
RegistryDelta::AddNetwork {
|
||||
id: network_id,
|
||||
network: Network::default(),
|
||||
},
|
||||
);
|
||||
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
|
||||
|
||||
let mut remover = base.clone();
|
||||
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
|
||||
|
||||
let mut changer = Session::with_peer(PeerId(2));
|
||||
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
|
||||
commit_retired(
|
||||
&mut changer,
|
||||
RegistryDelta::ChangeNodeAttribute {
|
||||
id: NodeId(7),
|
||||
delta: crate::AttributeDelta {
|
||||
key: "tint".to_string(),
|
||||
value: Some(serde_json::json!(75)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// One delta from each branch, neither an ancestor of the other.
|
||||
let removal = remover.cloned_deltas().into_iter().last().expect("removal delta");
|
||||
let change = changer.cloned_deltas().into_iter().last().expect("change delta");
|
||||
let deltas = [removal, change];
|
||||
|
||||
let removal_first = merge_order_outcome(&base, &deltas, [0, 1]);
|
||||
let change_first = merge_order_outcome(&base, &deltas, [1, 0]);
|
||||
|
||||
assert_eq!(removal_first, change_first, "the retired registry must not depend on delta arrival order");
|
||||
}
|
||||
|
||||
/// An op can retire before an earlier one from its author arrives, so the marks cover it out of order.
|
||||
/// The prefix absorbs it once the gap fills, which bounds the exception set.
|
||||
#[test]
|
||||
fn retired_marks_cover_a_gap_and_compact_once_it_fills() {
|
||||
let author = PeerId(1);
|
||||
let id = |sequence: u64| crate::HotOpId {
|
||||
peer: author,
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
|
||||
let mut marks = crate::RetiredHotOps::default();
|
||||
marks.extend([id(1), id(2)]);
|
||||
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)), "a contiguous run folds straight into the prefix");
|
||||
assert!(marks.retired_beyond.is_empty());
|
||||
|
||||
// Sequence 3 never arrived, so 4 retires above the prefix rather than extending it.
|
||||
marks.extend([id(4)]);
|
||||
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(2)));
|
||||
assert!(marks.covers(id(4)), "an op past the gap is still recognized as retired");
|
||||
assert!(!marks.covers(id(3)), "the missing op is not claimed");
|
||||
|
||||
// The gap fills, so the prefix swallows both it and the exception behind it.
|
||||
marks.extend([id(3)]);
|
||||
assert_eq!(marks.retired_up_to.get(&author), Some(&crate::HotSequence(4)));
|
||||
assert!(marks.retired_beyond.is_empty(), "the exception set empties once the prefix reaches it");
|
||||
}
|
||||
|
||||
/// Marks merge by union, so adopting a peer's wholesale must not lose local coverage.
|
||||
#[test]
|
||||
fn absorbing_marks_keeps_both_sides_coverage() {
|
||||
let author = PeerId(1);
|
||||
let id = |sequence: u64| crate::HotOpId {
|
||||
peer: author,
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
|
||||
let mut local = crate::RetiredHotOps::default();
|
||||
local.extend([id(1), id(4)]);
|
||||
|
||||
let mut remote = crate::RetiredHotOps::default();
|
||||
remote.extend([id(1), id(2), id(3), id(5)]);
|
||||
|
||||
local.absorb(&remote);
|
||||
|
||||
// The union is 1..=5 contiguous, so it all collapses into the prefix.
|
||||
assert_eq!(local.retired_up_to.get(&author), Some(&crate::HotSequence(5)));
|
||||
assert!(local.retired_beyond.is_empty());
|
||||
for sequence in 1..=5 {
|
||||
assert!(local.covers(id(sequence)), "sequence {sequence} must stay covered");
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo rewinds retired history and must leave the hot tail alone: copying the working registry onto
|
||||
/// the snapshot promotes unretired work. Hot ops exist between staging and retirement even solo.
|
||||
#[test]
|
||||
fn undo_does_not_promote_hot_ops_into_the_retired_snapshot() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
// Two retired interactions, so the second is undoable.
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
// Unretired live work sitting on top, on a key no retired delta touches.
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
assert!(session.registry().attributes.contains_key("hot"), "the hot op must be in the working registry");
|
||||
assert!(!session.retired_registry().attributes.contains_key("hot"), "and must not be in the snapshot");
|
||||
|
||||
session.undo().expect("undo");
|
||||
|
||||
assert!(!session.retired_registry().attributes.contains_key("second"), "undo must rewind the retired snapshot");
|
||||
assert!(
|
||||
!session.retired_registry().attributes.contains_key("hot"),
|
||||
"undo promoted an unretired hot op into the retired snapshot"
|
||||
);
|
||||
}
|
||||
|
||||
/// Redo puts the interaction back on both zones, so the pair does not drift the other way.
|
||||
#[test]
|
||||
fn redo_restores_the_retired_snapshot_without_the_hot_tail() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
session.stage_ops([set_document_attribute("hot", 3)]).expect("stage");
|
||||
session.undo().expect("undo");
|
||||
session.redo().expect("redo");
|
||||
|
||||
assert!(session.retired_registry().attributes.contains_key("second"), "redo must restore the retired delta");
|
||||
assert!(
|
||||
!session.retired_registry().attributes.contains_key("hot"),
|
||||
"redo promoted an unretired hot op into the retired snapshot"
|
||||
);
|
||||
assert!(session.registry().attributes.contains_key("hot"), "the hot op must survive an undo/redo round trip");
|
||||
}
|
||||
|
||||
/// Silent undo emits nothing, so it is only legal while a commit is unpublished. Once peers hold it, a
|
||||
/// rewind would diverge from them for good.
|
||||
#[test]
|
||||
fn publishing_a_commit_disables_silent_undo() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
let head = session.head_rev().expect("a head");
|
||||
assert!(session.can_undo(), "an unpublished interaction is undoable");
|
||||
|
||||
session.publish_up_to(head);
|
||||
|
||||
assert!(!session.can_undo(), "a published interaction must not be silently rewound");
|
||||
}
|
||||
|
||||
/// An undone delta stays in the DAG for redo, outside `head`'s ancestry. A fold that ignores that
|
||||
/// restores work the user undid.
|
||||
#[test]
|
||||
fn snapshot_from_history_ignores_undone_deltas() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
let boundary = session.history().last().expect("a committed delta").id;
|
||||
session.mark_interaction_end(boundary);
|
||||
commit_retired(&mut session, set_document_attribute("second", 2));
|
||||
|
||||
session.undo().expect("undo");
|
||||
assert!(!session.retired_registry().attributes.contains_key("second"), "undo rewound the snapshot");
|
||||
|
||||
let folded = session.snapshot_from_history().expect("fold");
|
||||
|
||||
assert!(folded.attributes.contains_key("first"), "history still holds the kept interaction");
|
||||
assert!(!folded.attributes.contains_key("second"), "a fold restored an undone delta");
|
||||
}
|
||||
|
||||
/// Resurrection takes the last removal of the entity in canonical order. When the deltas first landed
|
||||
/// that was the latest one so far, but a fold over finished history also sees the removals after the
|
||||
/// replay position, and one of those can carry the node in a network the replay has not created yet
|
||||
/// (simulation seed 3588534).
|
||||
#[test]
|
||||
fn snapshot_from_history_resurrects_from_the_replay_position() {
|
||||
let node_id = NodeId(3);
|
||||
let first_network = NetworkId(1);
|
||||
let later_network = NetworkId(3);
|
||||
let node_in = |network: NetworkId| Node { network, ..Node::dummy() };
|
||||
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
commit_retired(
|
||||
&mut session,
|
||||
RegistryDelta::AddNetwork {
|
||||
id: first_network,
|
||||
network: Network::default(),
|
||||
},
|
||||
);
|
||||
commit_retired(
|
||||
&mut session,
|
||||
RegistryDelta::AddNode {
|
||||
id: node_id,
|
||||
node: node_in(first_network),
|
||||
},
|
||||
);
|
||||
commit_retired(
|
||||
&mut session,
|
||||
RegistryDelta::RemoveNode {
|
||||
id: node_id,
|
||||
snapshot: node_in(first_network),
|
||||
},
|
||||
);
|
||||
// Resurrects the node from the removal above, the only one so far.
|
||||
commit_retired(
|
||||
&mut session,
|
||||
RegistryDelta::SetNetworkExport {
|
||||
id: first_network,
|
||||
index: 0,
|
||||
export: Some(crate::NodeInput::Node { id: node_id, index: 0 }),
|
||||
},
|
||||
);
|
||||
commit_retired(
|
||||
&mut session,
|
||||
RegistryDelta::AddNetwork {
|
||||
id: later_network,
|
||||
network: Network::default(),
|
||||
},
|
||||
);
|
||||
// A later removal whose snapshot places the node in the network created after the export.
|
||||
commit_retired(
|
||||
&mut session,
|
||||
RegistryDelta::RemoveNode {
|
||||
id: node_id,
|
||||
snapshot: node_in(later_network),
|
||||
},
|
||||
);
|
||||
|
||||
let folded = session.snapshot_from_history().expect("a fold must resurrect from what the replay has seen, not from a later removal");
|
||||
|
||||
assert_eq!(&folded, session.retired_registry(), "the fold must reproduce the snapshot the deltas built as they landed");
|
||||
}
|
||||
|
||||
/// A failed refold leaves the registries on an older history, and the deltas are already absorbed, so
|
||||
/// re-merging them is a no-op. Without a retry the registries never catch up.
|
||||
#[test]
|
||||
fn an_owed_refold_is_retried_by_a_merge_that_absorbs_nothing() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
commit_retired(&mut session, set_document_attribute("first", 1));
|
||||
|
||||
// Stand in for a refold that failed partway: history moved on, the snapshot did not.
|
||||
session.document.retired_snapshot = crate::Registry::default();
|
||||
session.document.refold_owed = true;
|
||||
|
||||
let outcome = session.merge(Vec::new()).expect("a merge absorbing nothing still settles the refold");
|
||||
|
||||
assert_eq!(outcome, crate::MergeOutcome::NoOp);
|
||||
assert!(!session.document.refold_owed, "the refold must not stay owed");
|
||||
assert!(
|
||||
session.retired_registry().attributes.contains_key("first"),
|
||||
"the retried refold must bring the snapshot back to its history"
|
||||
);
|
||||
}
|
||||
|
||||
/// The newtype is `#[serde(transparent)]`, so persisted state and the wire carry a bare number and the
|
||||
/// field's encoding is unchanged.
|
||||
#[test]
|
||||
fn hot_sequence_serializes_as_a_bare_number() {
|
||||
let encoded = serde_json::to_string(&crate::HotSequence(7)).expect("serialize");
|
||||
|
||||
assert_eq!(encoded, "7");
|
||||
assert_eq!(serde_json::from_str::<crate::HotSequence>("7").expect("deserialize"), crate::HotSequence(7));
|
||||
}
|
||||
|
||||
/// Retirement drains the hot log, so a retirer that never received an author's earlier op cannot
|
||||
/// retire it. The later op still retires, landing beyond the author's prefix instead of extending it.
|
||||
#[test]
|
||||
fn retiring_over_a_gap_lands_beyond_the_prefix() {
|
||||
let author = PeerId(2);
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
|
||||
// Only the author's second op reaches this peer; the first was lost with the link that carried it.
|
||||
let second = HotOp {
|
||||
op: set_document_attribute("late", 1),
|
||||
timestamp: TimeStamp { counter: 9, peer: author },
|
||||
sequence: crate::HotSequence(2),
|
||||
};
|
||||
host.apply_hot_op(second.clone()).expect("apply");
|
||||
|
||||
host.retire(second.timestamp).expect("retire");
|
||||
|
||||
let retired = host.retired_marks();
|
||||
let prefix = retired.retired_up_to.get(&author).copied().unwrap_or(crate::HotSequence::NONE);
|
||||
assert_eq!(prefix, crate::HotSequence::NONE, "sequence 1 never arrived, so the prefix cannot move");
|
||||
assert!(retired.retired_beyond.contains_key(&author), "the retired op has to be recorded past the gap");
|
||||
assert!(retired.covers(second.id()), "and still count as retired");
|
||||
}
|
||||
|
||||
/// A gap that never fills pins the prefix, so every later op from that author lands past it. Stored as
|
||||
/// runs, that stays one entry however many ops follow.
|
||||
#[test]
|
||||
fn a_permanent_gap_accumulates_every_later_op() {
|
||||
let author = PeerId(2);
|
||||
let id = |sequence: u64| crate::HotOpId {
|
||||
peer: author,
|
||||
sequence: crate::HotSequence(sequence),
|
||||
};
|
||||
|
||||
let mut marks = crate::RetiredHotOps::default();
|
||||
|
||||
// Sequence 1 is lost for good; everything this author writes afterwards still retires.
|
||||
for sequence in 2..=20 {
|
||||
marks.extend([id(sequence)]);
|
||||
}
|
||||
|
||||
let runs = marks.retired_beyond.get(&author).map(Vec::len).unwrap_or_default();
|
||||
assert_eq!(runs, 1, "the ops after the gap coalesce into a single run");
|
||||
for sequence in 2..=20 {
|
||||
assert!(marks.covers(id(sequence)), "sequence {sequence} must stay covered");
|
||||
}
|
||||
assert!(!marks.covers(id(1)), "the lost op is not claimed");
|
||||
}
|
||||
|
||||
/// A retired delta keeps its op's authoring timestamp, so the snapshot resolves LWW on the same stamps
|
||||
/// the live view did rather than on retirement order.
|
||||
#[test]
|
||||
fn retirement_preserves_the_live_lww_winner() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
|
||||
// Same key from two authors, the newer op arriving first, so LWW keeps it and discards the older.
|
||||
let newer = HotOp {
|
||||
op: set_document_attribute("k", 1),
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
let older = HotOp {
|
||||
op: set_document_attribute("k", 2),
|
||||
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
host.apply_hot_op(newer.clone()).expect("apply newer");
|
||||
host.apply_hot_op(older).expect("apply older");
|
||||
|
||||
let live = host.registry().attributes.get("k").cloned();
|
||||
host.retire(newer.timestamp).expect("retire");
|
||||
|
||||
assert_eq!(host.registry().attributes.get("k"), live.as_ref(), "retirement must not move the live value");
|
||||
assert_eq!(
|
||||
host.retired_registry().attributes.get("k").map(|attribute| &attribute.value),
|
||||
live.as_ref().map(|attribute| &attribute.value),
|
||||
"the snapshot has to record the value the live view settled on"
|
||||
);
|
||||
}
|
||||
|
||||
/// A straggler LWW discarded still retires, and must not return by doing so: stamped at retirement it
|
||||
/// would outrank the op that beat it, putting the discarded value into history itself.
|
||||
#[test]
|
||||
fn retiring_a_straggler_leaves_the_discarded_value_behind() {
|
||||
let mut host = Session::with_peer(PeerId(1));
|
||||
|
||||
let winner = HotOp {
|
||||
op: set_document_attribute("k", 1),
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(2) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
host.apply_hot_op(winner.clone()).expect("apply winner");
|
||||
host.retire(winner.timestamp).expect("retire winner");
|
||||
|
||||
// Arriving behind the winner, this op loses in the live view and its value is dropped.
|
||||
let straggler = HotOp {
|
||||
op: set_document_attribute("k", 2),
|
||||
timestamp: TimeStamp { counter: 5, peer: PeerId(3) },
|
||||
sequence: crate::HotSequence(1),
|
||||
};
|
||||
host.apply_hot_op(straggler.clone()).expect("apply straggler");
|
||||
host.retire(straggler.timestamp).expect("retire straggler");
|
||||
|
||||
let value = |registry: &crate::Registry| registry.attributes.get("k").map(|attribute| attribute.value.clone());
|
||||
assert_eq!(value(host.registry()), Some(serde_json::json!(1)), "the live view keeps the winner");
|
||||
assert_eq!(value(host.retired_registry()), Some(serde_json::json!(1)), "and retiring the straggler must not overwrite it");
|
||||
|
||||
let replayed = host.snapshot_from_history().expect("refold");
|
||||
assert_eq!(value(&replayed), Some(serde_json::json!(1)), "nor may history replay to the discarded value");
|
||||
}
|
||||
@@ -609,7 +609,7 @@ fn unreferenced_runtime_resource_is_not_snapshotted() {
|
||||
assert!(!registry.resources.contains_key(&orphan), "the unreferenced (orphan) resource must not be snapshotted");
|
||||
}
|
||||
|
||||
/// A node-input `TaggedValue::Number` must survive the storage round-trip bit-exact. Inputs are stored as a
|
||||
/// A node-input `TaggedValue::F64` must survive the storage round-trip bit-exact. Inputs are stored as a
|
||||
/// self-describing `serde_json::Value` (encoded with the registry's MessagePack codec), so this guards
|
||||
/// against any precision loss in the f64 -> serde_json::Number -> f64 path for a value with a full
|
||||
/// 17-significant-digit mantissa.
|
||||
@@ -623,7 +623,7 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
nodes: [(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(precise), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::F64(precise), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -640,8 +640,8 @@ fn node_input_f64_round_trips_bit_exact() {
|
||||
let NodeInput::Value { tagged_value, .. } = input else {
|
||||
panic!("expected a value input, got {input:?}")
|
||||
};
|
||||
let TaggedValue::Number(actual) = &**tagged_value else {
|
||||
panic!("expected Number, got {:?}", tagged_value)
|
||||
let TaggedValue::F64(actual) = &**tagged_value else {
|
||||
panic!("expected F64, got {:?}", tagged_value)
|
||||
};
|
||||
|
||||
assert_eq!(actual.to_bits(), precise.to_bits(), "f64 node input drifted: {actual} != {precise}");
|
||||
@@ -759,7 +759,6 @@ fn cyclic_network_reference_is_rejected() {
|
||||
crate::NodeId(0),
|
||||
Node {
|
||||
implementation: Implementation::Network(child_network_id),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
network: crate::ROOT_NETWORK,
|
||||
@@ -769,7 +768,6 @@ fn cyclic_network_reference_is_rejected() {
|
||||
crate::NodeId(1),
|
||||
Node {
|
||||
implementation: Implementation::Network(crate::ROOT_NETWORK),
|
||||
implementation_timestamp: Default::default(),
|
||||
inputs: Vec::new(),
|
||||
attributes: crate::Attributes::default(),
|
||||
network: child_network_id,
|
||||
|
||||
@@ -38,8 +38,7 @@ pub enum ConversionError {
|
||||
pub type Declarations = std::collections::HashMap<ResourceId, ProtoNode>;
|
||||
|
||||
impl Registry {
|
||||
/// Returns the network plus one metadata entry per node, since every node carries an identity to
|
||||
/// restore even when it has no `ui::*` attribute.
|
||||
/// Returns the network plus per-node metadata entries (one per node carrying any `ui::*` attribute).
|
||||
pub fn to_runtime_with_metadata(&self, declarations: &Declarations) -> Result<(NodeNetwork, Vec<NodeMetadataEntry>), ConversionError> {
|
||||
let (network, node_entries, _) = self.to_runtime_with_full_metadata(declarations)?;
|
||||
Ok((network, node_entries))
|
||||
|
||||
@@ -29,12 +29,6 @@ pub struct DocumentHistory {
|
||||
/// and extended on each staging, so a cursor rebuild never touches the byte store.
|
||||
#[derivative(Debug = "ignore")]
|
||||
declarations: Declarations,
|
||||
/// Whether the next commit must convert the whole document rather than stage what the store recorded.
|
||||
///
|
||||
/// True when the working copy holds no baseline for a batch to apply to, and whenever the runtime has
|
||||
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
|
||||
/// part of the distance between the two.
|
||||
needs_whole_document_stage: bool,
|
||||
}
|
||||
|
||||
/// Why [`DocumentHistory::move_cursor`] produced no interface.
|
||||
@@ -101,17 +95,10 @@ impl DocumentHistory {
|
||||
|
||||
/// Attach the `Gdd` working copy once the mount future resolves, with the declarations it references.
|
||||
pub fn set_storage(&mut self, storage: document_format::GddV1, declarations: Declarations) {
|
||||
self.needs_whole_document_stage |= storage.registry().node_instances.is_empty();
|
||||
self.storage = Some(storage);
|
||||
self.declarations = declarations;
|
||||
}
|
||||
|
||||
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
|
||||
/// runtime that went unrecorded and so cannot be described by the recorded batch.
|
||||
pub fn require_whole_document_stage(&mut self) {
|
||||
self.needs_whole_document_stage = true;
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops into durable Gdd history as one undo unit. Called at each undo-step
|
||||
/// boundary (a new `StartTransaction`) and before undo/redo, so the per-`CommitTransaction` staging
|
||||
/// coalesces into one interaction aligned with the legacy step. No-op while unmounted.
|
||||
@@ -135,10 +122,12 @@ impl DocumentHistory {
|
||||
legacy_document: &str,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) {
|
||||
let needs_whole_document_stage = self.needs_whole_document_stage;
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
|
||||
let staged = match needs_whole_document_stage {
|
||||
// A working copy that does not hold the document yet has no baseline for a batch of changes to apply
|
||||
// to. Reading that from the working copy rather than from the caller means a path that mounts storage
|
||||
// and then commits does not have to know which of the two cases it is in.
|
||||
let staged = match storage.registry().node_instances.is_empty() {
|
||||
true => Self::stage_whole_document(storage, interface, registry, byte_store),
|
||||
// An autosave with nothing edited since the last commit still persists the view state below.
|
||||
false if deltas.is_empty() => Ok(Declarations::new()),
|
||||
@@ -151,10 +140,7 @@ impl DocumentHistory {
|
||||
}),
|
||||
};
|
||||
match staged {
|
||||
Ok(declarations) => {
|
||||
self.declarations.extend(declarations);
|
||||
self.needs_whole_document_stage = false;
|
||||
}
|
||||
Ok(declarations) => self.declarations.extend(declarations),
|
||||
Err(error) => {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
|
||||
@@ -1834,12 +1834,6 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.validate_output_names(node_id, node, &path);
|
||||
}
|
||||
|
||||
// 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,
|
||||
// so the next commit converts the whole document rather than staging the batch that follows them.
|
||||
self.network_interface.discard_deltas();
|
||||
self.history.require_whole_document_stage();
|
||||
|
||||
self.network_interface.load_structure();
|
||||
}
|
||||
|
||||
@@ -2033,12 +2027,6 @@ impl DocumentMessageHandler {
|
||||
self.history.retire_storage_interaction();
|
||||
}
|
||||
|
||||
/// Marks the working copy as needing a whole-document stage on its next commit, for a change to the
|
||||
/// runtime that went unrecorded.
|
||||
pub(crate) fn require_whole_document_stage(&mut self) {
|
||||
self.history.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Stages what the store recorded since the last commit into the `Gdd` working copy.
|
||||
///
|
||||
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
|
||||
@@ -2818,7 +2806,7 @@ impl DocumentMessageHandler {
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_i64, 1_i64);
|
||||
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(existing_index), false))]);
|
||||
let existing_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::I64(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
@@ -2840,7 +2828,7 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Integer(new_index), false))]);
|
||||
let new_index_template = item_at_index_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::I64(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
|
||||
+3
-3
@@ -881,9 +881,9 @@ fn insert_brush_strokes_chain(network_interface: &mut NodeNetworkInterface, laye
|
||||
let strokes_node = strokes_node_type.node_template_input_override([
|
||||
Some(NodeInput::value(TaggedValue::Strokes(Vec::new()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Color(color), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(flow), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(diameter), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(hardness), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(flow), false)),
|
||||
]);
|
||||
network_interface.insert_node(strokes_node_id, strokes_node, &[]);
|
||||
network_interface.set_input(&InputConnector::node_at_index(layer.to_node(), 1), NodeInput::node(strokes_node_id, 0), &[]);
|
||||
|
||||
@@ -19,7 +19,7 @@ pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &
|
||||
);
|
||||
network_interface.set_input(
|
||||
&InputConnector::node(*node_id, graphene_std::transform_nodes::transform::RotationInput),
|
||||
NodeInput::value(TaggedValue::Number(rotation), false),
|
||||
NodeInput::value(TaggedValue::F64(rotation), false),
|
||||
&[],
|
||||
);
|
||||
network_interface.set_input(
|
||||
@@ -70,7 +70,7 @@ pub fn get_current_transform(inputs: &[NodeInput]) -> DAffine2 {
|
||||
} else {
|
||||
DVec2::ZERO
|
||||
};
|
||||
let rotation = if let Some(&TaggedValue::Number(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
||||
let rotation = if let Some(&TaggedValue::F64(rotation)) = inputs[2].as_value() { rotation } else { 0. };
|
||||
let scale = if let Some(&TaggedValue::DVec2(scale)) = inputs[3].as_value() { scale } else { DVec2::ONE };
|
||||
let skew = if let Some(&TaggedValue::DVec2(skew)) = inputs[4].as_value() { skew } else { DVec2::ZERO };
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_blend_data(&mut self, layer: LayerNodeIdentifier, count: i64) -> NodeId {
|
||||
let blend = resolve_network_node_type("Blend")
|
||||
.expect("Blend node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Integer(count), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::I64(count), false))]);
|
||||
|
||||
let blend_id = NodeId::new();
|
||||
self.network_interface.insert_node(blend_id, blend, &[]);
|
||||
@@ -109,7 +109,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
pub fn insert_morph_data(&mut self, layer: LayerNodeIdentifier) -> NodeId {
|
||||
let morph = resolve_proto_node_type(graphene_std::vector::morph::IDENTIFIER)
|
||||
.expect("Morph node does not exist")
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::Number(0.5), false))]);
|
||||
.node_template_input_override([Some(NodeInput::type_default(list!(Graphic), true)), Some(NodeInput::value(TaggedValue::F64(0.5), false))]);
|
||||
|
||||
let morph_id = NodeId::new();
|
||||
self.network_interface.insert_node(morph_id, morph, &[]);
|
||||
@@ -131,7 +131,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
// Add Auto-Tangents node (between Origins to Polyline and Path), with spread=1 and preserve_existing=false
|
||||
let auto_tangents = resolve_proto_node_type(graphene_std::vector::auto_tangents::IDENTIFIER)
|
||||
.expect("Auto-Tangents node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::Bool(false), false))]);
|
||||
let auto_tangents_id = NodeId::new();
|
||||
self.network_interface.insert_node(auto_tangents_id, auto_tangents, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&auto_tangents_id, layer, &[], self.import);
|
||||
@@ -193,14 +193,14 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::None, false)),
|
||||
Some(NodeInput::value(TaggedValue::String(text), false)),
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
@@ -526,7 +526,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::OpacityInput),
|
||||
NodeInput::value(TaggedValue::Number(opacity * 100.), false),
|
||||
NodeInput::value(TaggedValue::F64(opacity * 100.), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
@@ -555,7 +555,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(opacity_node_id, graphene_std::blending_nodes::opacity::FillInput),
|
||||
NodeInput::value(TaggedValue::Number(fill * 100.), false),
|
||||
NodeInput::value(TaggedValue::F64(fill * 100.), false),
|
||||
false,
|
||||
);
|
||||
}
|
||||
@@ -666,7 +666,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_positions::PositionsInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(positions), false), false);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(positions), false), false);
|
||||
}
|
||||
|
||||
/// The 'Gradient Midpoints' counterpart of [`Self::gradient_positions_set`], likewise update-only.
|
||||
@@ -690,7 +690,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_midpoints::MidpointsInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Numbers(midpoints), false), false);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64Array(midpoints), false), false);
|
||||
}
|
||||
|
||||
/// Update the transform to map the unit gradient ((0,0), (1, 0)) to the geometry's local space.
|
||||
@@ -865,7 +865,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::PaintInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(color.map_or_else(TaggedValue::no_paint, TaggedValue::Color), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::WeightInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.weight), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.weight), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::AlignInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeAlign(stroke.align), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::CapInput);
|
||||
@@ -873,11 +873,11 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::JoinInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::StrokeJoin(stroke.join), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::MiterLimitInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.join_miter_limit), false), false);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.join_miter_limit), false), false);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashPatternInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::DashPattern(stroke.dash_lengths), false), true);
|
||||
let input_connector = InputConnector::node(stroke_node_id, graphene_std::vector::stroke::DashOffsetInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::Number(stroke.dash_offset), false), true);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::F64(stroke.dash_offset), false), true);
|
||||
}
|
||||
|
||||
/// Update the transform value of the upstream Transform node based a change to its existing value and the given parent transform.
|
||||
|
||||
@@ -40,30 +40,17 @@ pub struct NodePropertiesContext<'a> {
|
||||
impl NodePropertiesContext<'_> {
|
||||
pub fn call_widget_override(&mut self, node_id: &NodeId, index: usize) -> Option<Vec<LayoutGroup>> {
|
||||
let input_properties_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
|
||||
// The stored override wins, falling back to the definition's own so documents saved before it gained one still
|
||||
// pick it up. Only `Custom` is recovered, since the other kinds also need input data stored at insertion time.
|
||||
let widget_override = input_properties_row.widget_override.clone().or_else(|| {
|
||||
let implementation = self.network_interface.implementation(node_id, self.selection_network_path)?;
|
||||
let DocumentNodeImplementation::ProtoNode(proto_node_identifier) = implementation else {
|
||||
if let Some(widget_override) = &input_properties_row.widget_override {
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
};
|
||||
|
||||
let metadata = registry::NODE_METADATA.lock().unwrap();
|
||||
let field = metadata.get(proto_node_identifier)?.fields.get(index)?;
|
||||
match field.widget_override {
|
||||
registry::RegistryWidgetOverride::Custom(name) => Some(name.to_string()),
|
||||
_ => None,
|
||||
}
|
||||
})?;
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
};
|
||||
widget_override_lambda(*node_id, index, self)
|
||||
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
|
||||
.ok()
|
||||
widget_override_lambda(*node_id, index, self)
|
||||
.map_err(|error| log::error!("Error in widget override lambda: {error}"))
|
||||
.ok()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,7 +348,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -382,14 +369,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::I64(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -438,7 +425,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::F64(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -472,14 +459,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::F64(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -492,7 +479,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::I64(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
@@ -824,14 +811,14 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::I64(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::I64(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
@@ -846,7 +833,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::I64(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
@@ -1110,11 +1097,6 @@ fn static_input_properties() -> InputProperties {
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// A type-witness input, whose stored value's type selects the node's row: the dropdown lists the types the rows accept there
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_properties::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1368,7 +1350,7 @@ fn static_input_properties() -> InputProperties {
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
return Err("Input not found in transform rotation input override".to_string());
|
||||
};
|
||||
if let Some(&TaggedValue::Number(val)) = input.as_non_exposed_value() {
|
||||
if let Some(&TaggedValue::F64(val)) = input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(val))
|
||||
@@ -1377,7 +1359,7 @@ fn static_input_properties() -> InputProperties {
|
||||
.range_min(Some(-180.))
|
||||
.range_max(Some(180.))
|
||||
.on_update(node_properties::update_value_at_index(
|
||||
|number_input: &NumberInput| TaggedValue::Number(number_input.value.unwrap()),
|
||||
|number_input: &NumberInput| TaggedValue::F64(number_input.value.unwrap()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
|
||||
@@ -60,7 +60,6 @@ pub enum NodeGraphMessage {
|
||||
DisconnectInput {
|
||||
input_connector: InputConnector,
|
||||
},
|
||||
DisconnectRootNode,
|
||||
EnterNestedNetwork,
|
||||
DuplicateSelectedNodes,
|
||||
ExposeInput {
|
||||
|
||||
@@ -406,9 +406,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::DisconnectInput { input_connector } => {
|
||||
network_interface.disconnect_input(&input_connector, selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::DisconnectRootNode => {
|
||||
network_interface.start_previewing_without_restore(selection_network_path);
|
||||
}
|
||||
NodeGraphMessage::DuplicateSelectedNodes => {
|
||||
let all_selected_nodes = network_interface.upstream_chain_nodes(selection_network_path);
|
||||
|
||||
@@ -1099,18 +1096,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.wire_in_progress_to_connector = Some(point);
|
||||
// Disconnect if the wire was previously connected to an input
|
||||
if let Some(disconnecting) = &self.disconnecting {
|
||||
let mut disconnect_root_node = false;
|
||||
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
|
||||
&& root_node_to_restore.is_some()
|
||||
&& *disconnecting == InputConnector::Export(0)
|
||||
{
|
||||
disconnect_root_node = true;
|
||||
}
|
||||
if disconnect_root_node {
|
||||
responses.add(NodeGraphMessage::DisconnectRootNode);
|
||||
} else {
|
||||
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
|
||||
}
|
||||
// Previewing leaves the export alone, so dragging its wire off is an ordinary disconnect
|
||||
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
|
||||
// Update the frontend that the node is disconnected
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
@@ -2691,8 +2678,8 @@ impl NodeGraphMessageHandler {
|
||||
wire_path_update: None,
|
||||
}));
|
||||
|
||||
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, breadcrumb_network_path) {
|
||||
added_wires.push(wire_to_root);
|
||||
if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, breadcrumb_network_path) {
|
||||
added_wires.push(wire_to_preview);
|
||||
} else {
|
||||
added_wires.push(WirePathUpdate {
|
||||
id: NodeId(u64::MAX),
|
||||
@@ -2743,11 +2730,8 @@ impl NodeGraphMessageHandler {
|
||||
log::error!("Could not get position for node: {node_id}");
|
||||
continue;
|
||||
};
|
||||
let is_export = network_interface
|
||||
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
|
||||
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
|
||||
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
|
||||
let previewed = is_export && !is_root_node;
|
||||
// Asked of the preview itself rather than inferred from the export, which previewing does not rewire
|
||||
let previewed = matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { previewed } if previewed.node_id == node_id);
|
||||
|
||||
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ use graphene_std::raster::{
|
||||
AdjustmentChannel, BlendMode, CellularDistanceFunction, CellularReturnType, Color, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha,
|
||||
RelativeAbsolute, SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::raster_types::Image;
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
@@ -38,7 +38,6 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -171,19 +170,14 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
widgets
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
/// The numeric bounds and widget mode of a number parameter, sourced from the node's field metadata.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub(crate) struct NumberOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
pub hard_min: Option<f64>,
|
||||
pub hard_max: Option<f64>,
|
||||
pub slider: bool,
|
||||
pub multiline: bool,
|
||||
pub progression: bool,
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
}
|
||||
|
||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||
@@ -212,25 +206,28 @@ fn definition_default_number(parameter_widgets_info: &ParameterWidgetsInfo) -> O
|
||||
let input = resolve_document_node_type(&identifier)?.node_template.inputs.get(parameter_widgets_info.index)?;
|
||||
|
||||
match input.as_value()? {
|
||||
TaggedValue::Number(value) => Some(*value),
|
||||
TaggedValue::F64(value) => Some(*value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, options: ParameterOptions, context: &mut NodePropertiesContext) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
|
||||
let ParameterOptions {
|
||||
pub(crate) fn property_from_type(
|
||||
node_id: NodeId,
|
||||
index: usize,
|
||||
ty: &Type,
|
||||
number_options: NumberOptions,
|
||||
unit: Option<&str>,
|
||||
display_decimal_places: Option<u32>,
|
||||
step: Option<f64>,
|
||||
context: &mut NodePropertiesContext,
|
||||
) -> Result<Vec<LayoutGroup>, Vec<LayoutGroup>> {
|
||||
let NumberOptions {
|
||||
soft_min,
|
||||
soft_max,
|
||||
hard_min,
|
||||
hard_max,
|
||||
slider,
|
||||
multiline,
|
||||
progression,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
} = options;
|
||||
|
||||
} = number_options;
|
||||
let mut number_input = NumberInput::default();
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
@@ -245,8 +242,10 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
|
||||
// The hard bound sets the typing clamp, and the soft bound (or the hard one) the slider extent, each falling
|
||||
// back to the passed-in default. A soft bound alone leaves that end unclamped, since soft is only a suggestion.
|
||||
// Applies the parameter's typing clamp and slider extent to the widget, given the type's own default bounds.
|
||||
// Per end: the clamp is the hard bound (or unbounded if only a soft bound is given, since soft is a suggested
|
||||
// extent rather than a limit), and the slider extent is the soft bound, each falling back to the hard bound
|
||||
// and then to the type default when unspecified. An end with any explicit bound ignores the type default.
|
||||
let bounded = |number_input: NumberInput, type_min: f64, type_max: f64| {
|
||||
let clamp_min = hard_min.unwrap_or(if soft_min.is_some() { f64::NEG_INFINITY } else { type_min });
|
||||
let clamp_max = hard_max.unwrap_or(if soft_max.is_some() { f64::INFINITY } else { type_max });
|
||||
@@ -260,11 +259,12 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
|
||||
.range_max(Some(extent_max).filter(|bound| bound.is_finite()))
|
||||
};
|
||||
|
||||
// A range-mode number hard-clamped at both ends becomes a range slider beside its number input, unless a soft bound lets typing pass it
|
||||
// A range-mode number clamped at both ends by its own hard bounds, or by a type whose extent is a true limit, becomes a range
|
||||
// slider beside its number input, unless a soft bound lets typing pass the slider. An Angle's type default is no such limit.
|
||||
let no_soft_bounds = soft_min.is_none() && soft_max.is_none();
|
||||
let hard_both_ends = hard_min.is_some() && hard_max.is_some();
|
||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput| -> LayoutGroup {
|
||||
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && hard_both_ends;
|
||||
let number_or_slider = |default_info: ParameterWidgetsInfo, number_input: NumberInput, type_limits: bool| -> LayoutGroup {
|
||||
let fixed_extent = number_input.mode == NumberInputMode::Range && no_soft_bounds && (hard_both_ends || type_limits);
|
||||
match (number_input.min, number_input.max) {
|
||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||
let default = definition_default_number(&default_info);
|
||||
@@ -297,98 +297,109 @@ pub(crate) fn property_from_type(node_id: NodeId, index: usize, ty: &Type, optio
|
||||
let mut extra_widgets = vec![];
|
||||
let widgets = match ty {
|
||||
Type::Concrete(concrete_type) => {
|
||||
use std::any::TypeId;
|
||||
match concrete_type.alias.as_ref().map(|x| x.as_ref()) {
|
||||
// Aliased types (ambiguous values)
|
||||
Some("Percentage") => number_or_slider(default_info, bounded(number_input.percentage(), 0., 100.), true),
|
||||
Some("SignedPercentage") => number_or_slider(default_info, bounded(number_input.percentage(), -100., 100.), true),
|
||||
Some("Angle") => number_or_slider(default_info, bounded(number_input.mode_range(), -180., 180.).unit(unit.unwrap_or("°")), false),
|
||||
Some("Multiplier") => number_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY).unit(unit.unwrap_or("x"))).into(),
|
||||
Some("PixelLength") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY).unit(unit.unwrap_or(" px"))).into(),
|
||||
Some("Length") => number_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
Some("Fraction") => number_or_slider(default_info, bounded(number_input.mode_range(), 0., 1.), true),
|
||||
Some("Progression") => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
Some("PixelSize") => vec2_widget(default_info, "X", "Y", unit.unwrap_or(" px"), None, false),
|
||||
Some("TextArea") => text_area_widget(default_info).into(),
|
||||
|
||||
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
|
||||
fn id_is<T: 'static>(id: TypeId) -> bool {
|
||||
id == TypeId::of::<T>()
|
||||
}
|
||||
// For all other types, use TypeId-based matching
|
||||
_ => {
|
||||
use std::any::TypeId;
|
||||
|
||||
match concrete_type.id {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if id_is::<f64>(x) => match progression {
|
||||
true => progression_widget(default_info, bounded(number_input, 0., f64::INFINITY)).into(),
|
||||
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||
},
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => match multiline {
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||
// ===============================
|
||||
// MANUALLY IMPLEMENTED ENUM TYPES
|
||||
// ===============================
|
||||
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
|
||||
// =========================
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
// =====
|
||||
// OTHER
|
||||
// =====
|
||||
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
|
||||
// The compiler peels a rank-0 `Item` cell to its element before this arm runs, so widgets dispatch on the bare element `T`
|
||||
fn id_is<T: 'static>(id: TypeId) -> bool {
|
||||
id == TypeId::of::<T>()
|
||||
}
|
||||
|
||||
match concrete_type.id {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
Some(x) if id_is::<f64>(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false),
|
||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||
Some(x) if id_is::<String>(x) => text_widget(default_info).into(),
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", "", None, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||
// ===============================
|
||||
// MANUALLY IMPLEMENTED ENUM TYPES
|
||||
// ===============================
|
||||
Some(x) if id_is::<ReferencePoint>(x) => reference_point_widget(default_info, false).into(),
|
||||
Some(x) if id_is::<BlendMode>(x) => blend_mode_widget(default_info),
|
||||
// =========================
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<GradientInterpolation>(x) => enum_choice::<GradientInterpolation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RealTimeMode>(x) => enum_choice::<RealTimeMode>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlue>(x) => enum_choice::<RedGreenBlue>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RedGreenBlueAlpha>(x) => enum_choice::<RedGreenBlueAlpha>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<XY>(x) => enum_choice::<XY>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StringCapitalization>(x) => enum_choice::<StringCapitalization>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextDenomination>(x) => enum_choice::<TextDenomination>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<NoiseType>(x) => enum_choice::<NoiseType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<FractalType>(x) => enum_choice::<FractalType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularDistanceFunction>(x) => enum_choice::<CellularDistanceFunction>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<CellularReturnType>(x) => enum_choice::<CellularReturnType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<DomainWarpType>(x) => enum_choice::<DomainWarpType>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<RelativeAbsolute>(x) => enum_choice::<RelativeAbsolute>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<TonalRange>(x) => enum_choice::<TonalRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<AdjustmentChannel>(x) => enum_choice::<AdjustmentChannel>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<HueSaturationRange>(x) => enum_choice::<HueSaturationRange>().for_socket(default_info).disabled(false).property_row(),
|
||||
Some(x) if id_is::<GridType>(x) => enum_choice::<GridType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeCap>(x) => enum_choice::<StrokeCap>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeJoin>(x) => enum_choice::<StrokeJoin>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<StrokeAlign>(x) => enum_choice::<StrokeAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ArcType>(x) => enum_choice::<ArcType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<RowsOrColumns>(x) => enum_choice::<RowsOrColumns>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<TextAlign>(x) => enum_choice::<TextAlign>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<MergeByDistanceAlgorithm>(x) => enum_choice::<MergeByDistanceAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ExtrudeJoiningAlgorithm>(x) => enum_choice::<ExtrudeJoiningAlgorithm>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<PointSpacingType>(x) => enum_choice::<PointSpacingType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).property_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).property_row(),
|
||||
// =====
|
||||
// OTHER
|
||||
// =====
|
||||
_ => return Err(unsupported_widgets(default_info, concrete_type.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Type::Item(element) => return property_from_type(node_id, index, element, options, context),
|
||||
Type::Item(element) => return property_from_type(node_id, index, element, number_options, unit, display_decimal_places, step, context),
|
||||
Type::List(element) => match element.as_ref() {
|
||||
Type::Concrete(element_type) if element_type.name == std::any::type_name::<f64>() => array_of_number_widget(default_info, TextInput::default()).into(),
|
||||
_ => return Err(unsupported_widgets(default_info, ty.to_string())),
|
||||
},
|
||||
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
|
||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, options, context),
|
||||
Type::Future(out) => return property_from_type(node_id, index, out, options, context),
|
||||
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
|
||||
};
|
||||
|
||||
extra_widgets.push(widgets);
|
||||
@@ -792,7 +803,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
Some(&TaggedValue::Number(value)) => {
|
||||
Some(&TaggedValue::F64(value)) => {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(value))
|
||||
@@ -831,14 +842,14 @@ pub fn array_of_number_widget(parameter_widgets_info: ParameterWidgetsInfo, text
|
||||
.filter(|x| !x.is_empty())
|
||||
.map(graphene_std::core_types::misc::parse_f64)
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.map(TaggedValue::Numbers)
|
||||
.map(TaggedValue::F64Array)
|
||||
};
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(TaggedValue::Numbers(values)) = &input.as_non_exposed_value() {
|
||||
if let Some(TaggedValue::F64Array(values)) = &input.as_non_exposed_value() {
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
text_input
|
||||
@@ -993,7 +1004,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return vec![];
|
||||
};
|
||||
if let Some(&TaggedValue::Number(x)) = input.as_non_exposed_value() {
|
||||
if let Some(&TaggedValue::F64(x)) = input.as_non_exposed_value() {
|
||||
let whole_part = x.trunc();
|
||||
let fractional_part = x.fract();
|
||||
|
||||
@@ -1006,7 +1017,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
.min(0.)
|
||||
.max(0.99999)
|
||||
.value(Some(fractional_part))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(whole_part + input.value.unwrap())))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(whole_part + input.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
@@ -1018,7 +1029,7 @@ pub fn progression_widget(parameter_widgets_info: ParameterWidgetsInfo, number_p
|
||||
.min(0.)
|
||||
.is_integer(true)
|
||||
.value(Some(whole_part))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::Number(input.value.unwrap() + fractional_part)))
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::F64(input.value.unwrap() + fractional_part)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
])
|
||||
@@ -1105,19 +1116,19 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
return vec![];
|
||||
};
|
||||
match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::Number(x)) => widgets.extend_from_slice(&[
|
||||
Some(&TaggedValue::F64(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Some(&TaggedValue::Integer(x)) => widgets.extend_from_slice(&[
|
||||
Some(&TaggedValue::I64(x)) => widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
number_props
|
||||
.value(Some(x as f64))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Integer(x.value.unwrap().round() as i64)))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::I64(x.value.unwrap().round() as i64)))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
@@ -1126,7 +1137,7 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
||||
number_props
|
||||
// We use an arbitrary `y` instead of an arbitrary `x` here because the "Grid" node's "Spacing" value's height should be used from rectangular mode when transferred to "Y Spacing" in isometric mode
|
||||
.value(Some(dvec2.y))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::Number(x.value.unwrap())))
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::F64(x.value.unwrap())))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]),
|
||||
@@ -1170,96 +1181,6 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||
}
|
||||
|
||||
/// A dropdown choosing among the types this input takes across the node's registered rows. The input is a type witness:
|
||||
/// its stored value's type, not the value itself, selects the row, which is how a node offers a choice of output type.
|
||||
pub fn type_choice_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(current) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
|
||||
return LayoutGroup::row(widgets);
|
||||
};
|
||||
|
||||
// Every element type the node's rows accept at this input
|
||||
let mut offered: Vec<Type> = Vec::new();
|
||||
let implementation = parameter_widgets_info
|
||||
.network_interface
|
||||
.implementation(¶meter_widgets_info.node_id, parameter_widgets_info.selection_network_path);
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(identifier)) = implementation
|
||||
&& let Some(rows) = interpreted_executor::node_registry::NODE_REGISTRY.get(identifier)
|
||||
{
|
||||
for row in rows.keys() {
|
||||
let Some(ty) = row.inputs.get(parameter_widgets_info.index) else { continue };
|
||||
let element = wire_element(ty);
|
||||
if !offered.contains(&element) {
|
||||
offered.push(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
let sections = type_choice_sections(&offered);
|
||||
|
||||
let entry_sections = sections
|
||||
.iter()
|
||||
.map(|section| {
|
||||
section
|
||||
.iter()
|
||||
.map(|ty| {
|
||||
let chosen = TaggedValue::from_type_or_none(ty);
|
||||
MenuListEntry::new(ty.to_string())
|
||||
.label(ty.to_string())
|
||||
.on_update(parameter_widgets_info.update_value(move |_| chosen.clone()))
|
||||
.on_commit(commit_value)
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
// The dropdown counts its selection across every section, since separators divide the entries without renumbering them
|
||||
let current_element = wire_element(¤t.ty());
|
||||
let selected = sections.iter().flatten().position(|ty| *ty == current_element).map(|position| position as u32);
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entry_sections).selected_index(selected).widget_instance(),
|
||||
]);
|
||||
LayoutGroup::row(widgets)
|
||||
}
|
||||
|
||||
/// The element a wire type carries, peeling the `Item` or `List` rank a registry row or stored value wraps it in.
|
||||
fn wire_element(ty: &Type) -> Type {
|
||||
match ty.nested_type() {
|
||||
Type::Item(element) | Type::List(element) => (**element).clone(),
|
||||
other => other.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The canonical order and grouping of the graph's types, which a type choice renders as dropdown sections divided by separators.
|
||||
/// Enums stay unlisted on purpose, joining any other unnamed type in a trailing alphabetical section.
|
||||
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
||||
let vocabulary = [
|
||||
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
|
||||
vec![concrete!(DVec2)],
|
||||
vec![concrete!(DAffine2)],
|
||||
vec![concrete!(Artboard)],
|
||||
vec![
|
||||
concrete!(Graphic),
|
||||
concrete!(Vector),
|
||||
concrete!(Raster<CPU>),
|
||||
concrete!(Raster<GPU>),
|
||||
concrete!(Color),
|
||||
concrete!(Gradient),
|
||||
concrete!(String),
|
||||
],
|
||||
];
|
||||
|
||||
let mut sections: Vec<Vec<Type>> = vocabulary.iter().map(|section| section.iter().filter(|ty| offered.contains(ty)).cloned().collect()).collect();
|
||||
|
||||
let mut unlisted: Vec<Type> = offered.iter().filter(|ty| !vocabulary.iter().any(|section| section.contains(ty))).cloned().collect();
|
||||
unlisted.sort_by_key(|ty| ty.to_string());
|
||||
sections.push(unlisted);
|
||||
|
||||
sections.retain(|section| !section.is_empty());
|
||||
sections
|
||||
}
|
||||
|
||||
pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button: ColorInput) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
@@ -1778,7 +1699,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
let exposed = input.is_some_and(|input| input.is_exposed());
|
||||
let value = input
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None })
|
||||
.and_then(|tagged| if let TaggedValue::F64(value) = tagged { Some(*value) } else { None })
|
||||
.unwrap_or(0.);
|
||||
(exposed, value)
|
||||
})
|
||||
@@ -1901,7 +1822,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index,
|
||||
value: TaggedValue::Number(scale.value(scale_position)).into(),
|
||||
value: TaggedValue::F64(scale.value(scale_position)).into(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
@@ -1937,7 +1858,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodePropertiesCont
|
||||
.value(Some(current))
|
||||
.min_width(60)
|
||||
.max_width(60)
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::F64(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
@@ -1962,7 +1883,7 @@ pub(crate) fn hue_saturation_properties(node_id: NodeId, context: &mut NodePrope
|
||||
_ => HueSaturationRange::Master,
|
||||
};
|
||||
let slider_value = |parameter: &ParameterRef| match document_node.inputs.get(parameter.input_index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::Number(value)) => *value as f32,
|
||||
Some(TaggedValue::F64(value)) => *value as f32,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
@@ -2176,7 +2097,7 @@ fn slider_row(
|
||||
};
|
||||
// An exposed input shows only its label and source
|
||||
let (current, tagged_value): (f64, fn(f64) -> TaggedValue) = match input.as_non_exposed_value() {
|
||||
Some(&TaggedValue::Number(value)) => (value, TaggedValue::Number),
|
||||
Some(&TaggedValue::F64(value)) => (value, TaggedValue::F64),
|
||||
_ => return widgets,
|
||||
};
|
||||
let ParameterWidgetsInfo { node_id, index, .. } = parameter_widgets_info;
|
||||
@@ -2238,7 +2159,7 @@ fn gradient_slider_row(
|
||||
.ok()
|
||||
.and_then(|document_node| document_node.inputs.get(input_index))
|
||||
.and_then(|input| input.as_non_exposed_value())
|
||||
.and_then(|tagged| if let TaggedValue::Number(value) = tagged { Some(*value) } else { None });
|
||||
.and_then(|tagged| if let TaggedValue::F64(value) = tagged { Some(*value) } else { None });
|
||||
|
||||
// Only add the slider and number widgets when the input is not exposed
|
||||
if let Some(current) = current {
|
||||
@@ -2247,7 +2168,7 @@ fn gradient_slider_row(
|
||||
max: value_max,
|
||||
default: Some(default_value),
|
||||
};
|
||||
let value_at = move |position| TaggedValue::Number(slider.value(position));
|
||||
let value_at = move |position| TaggedValue::F64(slider.value(position));
|
||||
|
||||
row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
row.push(
|
||||
@@ -2270,7 +2191,7 @@ fn gradient_slider_row(
|
||||
.min_width(60)
|
||||
.max_width(60)
|
||||
.display_decimal_places(0)
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::Number(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_update(update_value_at_index(move |widget: &NumberInput| TaggedValue::F64(widget.value.unwrap_or(0.)), node_id, input_index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
@@ -2692,7 +2613,7 @@ pub(crate) fn format_number_properties(node_id: NodeId, context: &mut NodeProper
|
||||
let (no_decimals, decimal_sep_value, use_thousands, thousands_sep_value) = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let decimal_places = match document_node.input(DecimalPlacesInput).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Integer(x)) => x,
|
||||
Some(&TaggedValue::I64(x)) => x,
|
||||
_ => 2,
|
||||
};
|
||||
let decimal_sep = match document_node.input(DecimalSeparatorInput).and_then(|input| input.as_non_exposed_value()) {
|
||||
@@ -3016,7 +2937,10 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let mut number_options = NumberOptions::default();
|
||||
let mut display_decimal_places = None;
|
||||
let mut step = None;
|
||||
let mut unit_suffix = None;
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
@@ -3029,18 +2953,16 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions {
|
||||
number_options = NumberOptions {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
hard_min: field.number_hard_min,
|
||||
hard_max: field.number_hard_max,
|
||||
slider: field.number_mode_range,
|
||||
multiline: field.multiline,
|
||||
progression: field.progression,
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
};
|
||||
display_decimal_places = field.number_display_decimal_places;
|
||||
unit_suffix = field.unit;
|
||||
step = field.number_step;
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
@@ -3068,7 +2990,7 @@ pub(crate) fn generate_node_properties(node_id: NodeId, context: &mut NodeProper
|
||||
.unwrap_or(concrete!(())),
|
||||
};
|
||||
|
||||
property_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
property_from_type(node_id, input_index, &input_type, number_options, unit_suffix, display_decimal_places, step, context).unwrap_or_else(|value| value)
|
||||
});
|
||||
|
||||
layout.extend(row);
|
||||
@@ -3691,23 +3613,3 @@ pub mod choice {
|
||||
|
||||
pub struct ForValue<W>(PhantomData<W>);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::{item, list};
|
||||
|
||||
#[test]
|
||||
fn wire_element_reads_every_spelling_down_to_the_element() {
|
||||
// A stored value's ranked type, a registry row's fn type, and a mapped row's list all carry the same element
|
||||
let row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(item!(f64)))));
|
||||
let mapped_row = Type::Fn(Box::new(concrete!(())), Box::new(Type::Future(Box::new(list!(f64)))));
|
||||
for ty in [TaggedValue::Number(0.).ty(), item!(f64), list!(f64), row, mapped_row] {
|
||||
assert_eq!(wire_element(&ty), concrete!(f64), "{ty:?} should read down to its element");
|
||||
}
|
||||
|
||||
// The element of a stored value and of the row that accepts it agree, which is what selects the dropdown entry
|
||||
assert_eq!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(i64)));
|
||||
assert_ne!(wire_element(&TaggedValue::Integer(0).ty()), wire_element(&item!(f64)));
|
||||
}
|
||||
}
|
||||
@@ -680,26 +680,24 @@ impl NodeNetworkInterface {
|
||||
network_metadata.transient_metadata.wires.borrow_mut().remove(input);
|
||||
}
|
||||
|
||||
/// When previewing, there may be a second path to the root node.
|
||||
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
/// The dashed wire from the previewed node to the export, drawn alongside the solid wire the export
|
||||
/// is really connected to.
|
||||
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, network_path: &[NodeId]) -> Option<WirePathUpdate> {
|
||||
let input = InputConnector::Export(0);
|
||||
let current_export = self.upstream_output_connector(&input, network_path)?;
|
||||
|
||||
let root_node = match self.previewing(network_path) {
|
||||
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
|
||||
Previewing::No => None,
|
||||
}?;
|
||||
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
|
||||
|
||||
if Some(root_node.node_id) == current_export.node_id() {
|
||||
// The export already reaches it, so a second wire would land on top of the solid one
|
||||
if self.upstream_output_connector(&input, network_path).and_then(|export| export.node_id()) == Some(previewed.node_id) {
|
||||
return None;
|
||||
}
|
||||
let Some(input_position) = self.get_input_center(&input, network_path) else {
|
||||
log::error!("Could not get input position for wire end in root node: {input:?}");
|
||||
log::error!("Could not get input position for wire end in preview: {input:?}");
|
||||
return None;
|
||||
};
|
||||
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
|
||||
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
|
||||
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
|
||||
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
|
||||
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
|
||||
return None;
|
||||
};
|
||||
let vertical_end = input.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path) && input.input_index() == 0);
|
||||
|
||||
+108
-39
@@ -172,31 +172,6 @@ async fn connecting_an_export_is_never_cyclic() {
|
||||
assert_invariants(&editor, "after connecting the export");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn toggling_preview_on_a_disconnected_export() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let node = editor.create_node_by_name(rectangle_definition()).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
|
||||
|
||||
// Previewing a node while the export is disconnected is a preview with nothing to restore
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
|
||||
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
|
||||
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
|
||||
|
||||
// Ending the preview restores the disconnected export
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
|
||||
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
|
||||
|
||||
assert_invariants(&editor, "after toggling preview twice");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn artboard_identity_is_independent_of_scene_connectivity() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -406,8 +381,10 @@ async fn signature_edits_keep_parallel_metadata_in_sync() {
|
||||
assert_invariants(&editor, "after removing the added export");
|
||||
}
|
||||
|
||||
/// Previewing renders a different node without rewiring anything: the export keeps whatever it is
|
||||
/// connected to, so ending a preview has nothing to restore and cannot disconnect anything.
|
||||
#[tokio::test]
|
||||
async fn toggle_preview_transitions_with_a_connected_export() {
|
||||
async fn previewing_leaves_the_export_alone() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
@@ -419,31 +396,123 @@ async fn toggle_preview_transitions_with_a_connected_export() {
|
||||
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
|
||||
assert_eq!(export_node(network_interface), Some(artboard));
|
||||
|
||||
// Previewing a node remembers the artboard as the connection to restore
|
||||
// Previewing a node names it without touching the export
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
assert_eq!(export_node(network_interface), Some(node));
|
||||
assert_eq!(
|
||||
network_interface.previewing(&[]),
|
||||
Previewing::Yes {
|
||||
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
|
||||
previewed: RootNode { node_id: node, output_index: 0 }
|
||||
}
|
||||
);
|
||||
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
|
||||
|
||||
// Toggling the previewed node again restores the artboard connection
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
assert_eq!(export_node(network_interface), Some(artboard));
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
|
||||
// Toggling the restore node while previewing promotes it to the export with nothing left to restore
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
// Previewing a different node moves the preview, still without touching the export
|
||||
network_interface.toggle_preview(artboard, &[]);
|
||||
assert_eq!(
|
||||
network_interface.previewing(&[]),
|
||||
Previewing::Yes {
|
||||
previewed: RootNode { node_id: artboard, output_index: 0 }
|
||||
}
|
||||
);
|
||||
assert_eq!(export_node(network_interface), Some(artboard));
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
|
||||
|
||||
// Toggling it once more ends the preview by disconnecting the export entirely
|
||||
// Toggling the previewed node again ends the preview, leaving the export as it always was
|
||||
network_interface.toggle_preview(artboard, &[]);
|
||||
assert_eq!(export_node(network_interface), None);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
assert_eq!(export_node(network_interface), Some(artboard));
|
||||
|
||||
assert_invariants(&editor, "after cycling through the preview states");
|
||||
}
|
||||
|
||||
/// The graph handed to the compiler renders the previewed node, which is the whole point of a preview
|
||||
/// that does not rewire the document.
|
||||
#[tokio::test]
|
||||
async fn the_evaluated_network_renders_the_previewed_node() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let artboard = NodeId::new();
|
||||
editor.handle_message(new_artboard_message(artboard)).await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
|
||||
let evaluated = network_interface.network_to_evaluate();
|
||||
assert_eq!(
|
||||
evaluated.exports.first().and_then(|export| export.as_node()),
|
||||
Some(node),
|
||||
"The network being evaluated should export the previewed node"
|
||||
);
|
||||
assert_eq!(
|
||||
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
|
||||
Some(artboard),
|
||||
"The document itself should be unchanged"
|
||||
);
|
||||
}
|
||||
|
||||
/// The previewed node is marked for the frontend so it can be highlighted. The mark comes from the
|
||||
/// preview state itself, not from the export.
|
||||
#[tokio::test]
|
||||
async fn the_previewed_node_is_flagged_for_the_frontend() {
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageHandler;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let artboard = NodeId::new();
|
||||
editor.handle_message(new_artboard_message(artboard)).await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
|
||||
|
||||
let handler = NodeGraphMessageHandler::default();
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
let flagged = |handler: &NodeGraphMessageHandler, network_interface: &mut super::NodeNetworkInterface| {
|
||||
handler
|
||||
.collect_nodes(network_interface, &[])
|
||||
.into_iter()
|
||||
.filter(|node| node.previewed)
|
||||
.map(|node| node.id)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
assert!(flagged(&handler, network_interface).is_empty(), "Nothing is previewed to begin with");
|
||||
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
assert_eq!(flagged(&handler, network_interface), vec![node], "The previewed node should be the one flagged");
|
||||
|
||||
network_interface.toggle_preview(node, &[]);
|
||||
assert!(flagged(&handler, network_interface).is_empty(), "Ending the preview should unflag it");
|
||||
}
|
||||
|
||||
/// Resolving a batch of positions shares one downstream walk, so it has to agree with resolving each
|
||||
/// node on its own, with a stack as the case that matters.
|
||||
#[tokio::test]
|
||||
async fn batched_positions_agree_with_resolving_each_node() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
|
||||
for offset in 0..4 {
|
||||
editor.draw_rect(0., offset as f64 * 20., 100., offset as f64 * 20. + 10.).await;
|
||||
}
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let node_ids = network_interface.document_network().nodes.keys().copied().collect::<Vec<_>>();
|
||||
assert!(node_ids.len() > 4, "the fixture should build a stack, found {} nodes", node_ids.len());
|
||||
|
||||
let batched = network_interface.positions(node_ids.iter().copied(), &[]);
|
||||
let individually = node_ids
|
||||
.iter()
|
||||
.filter_map(|node_id| network_interface.position(node_id, &[]).map(|position| (*node_id, position)))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(batched.len(), individually.len(), "The batch should resolve exactly the nodes that resolve on their own");
|
||||
for (node_id, position) in individually {
|
||||
assert_eq!(
|
||||
batched.iter().find(|(batched_id, _)| *batched_id == node_id).map(|(_, position)| *position),
|
||||
Some(position),
|
||||
"Batched position disagrees for node {node_id}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+24
-163
@@ -124,8 +124,8 @@ pub fn construct_batch(
|
||||
delta.construct(&context, &mut batch, &mut batch_removed_nodes, &mut ops, &mut declarations)?;
|
||||
}
|
||||
|
||||
batch_removed_nodes.sort_by_key(|(id, _)| *id);
|
||||
batch_removed_nodes.dedup_by_key(|(id, _)| *id);
|
||||
batch_removed_nodes.sort();
|
||||
batch_removed_nodes.dedup();
|
||||
construct_resource_removals(&batch_removed_nodes, &batch, &mut ops);
|
||||
Ok(ConstructedOps { ops, declarations })
|
||||
}
|
||||
@@ -143,7 +143,7 @@ impl EditorDelta {
|
||||
&self,
|
||||
context: &ConversionContext,
|
||||
batch: &mut BatchRegistry,
|
||||
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
|
||||
batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
declarations: &mut BatchDeclarations,
|
||||
) -> Result<(), ConversionError> {
|
||||
@@ -153,9 +153,7 @@ impl EditorDelta {
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
|
||||
// Only what the previous implementation owned goes; the node stays so the addition below
|
||||
// updates it in place and its `ui::*` attributes survive the swap.
|
||||
construct_removals_below(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
construct_removals(context.resolver.node_id(network_path, *node_id), batch, batch_removed_nodes, ops);
|
||||
construct_structural_additions(network_path, *node_id, node, batch, context, ops, declarations)?;
|
||||
}
|
||||
|
||||
@@ -179,26 +177,18 @@ impl EditorDelta {
|
||||
input_index,
|
||||
input,
|
||||
}) => {
|
||||
let new_input = context.resolver.convert_input_at(input, network_path)?;
|
||||
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &new_input, context, batch, ops)?;
|
||||
|
||||
ops.push(RegistryDelta::ChangeNodeInput {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
|
||||
new_input,
|
||||
new_input: context.resolver.convert_input_at(input, network_path)?,
|
||||
});
|
||||
}
|
||||
|
||||
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
|
||||
let export = input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?;
|
||||
if let Some(export) = export.as_ref() {
|
||||
construct_referenced_resource(None, export, context, batch, ops)?;
|
||||
}
|
||||
|
||||
ops.push(RegistryDelta::SetNetworkExport {
|
||||
id: context.resolver.network_id(network_path),
|
||||
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
|
||||
export,
|
||||
export: input.as_ref().map(|input| context.resolver.convert_input_at(input, network_path)).transpose()?,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -237,10 +227,6 @@ impl EditorDelta {
|
||||
})
|
||||
.collect::<Result<Vec<_>, ConversionError>>()?;
|
||||
|
||||
for slot in &inputs {
|
||||
construct_referenced_resource(Some(context.resolver.node_id(network_path, *node_id)), &slot.input, context, batch, ops)?;
|
||||
}
|
||||
|
||||
ops.push(RegistryDelta::SetNodeInputs {
|
||||
id: context.resolver.node_id(network_path, *node_id),
|
||||
inputs,
|
||||
@@ -378,19 +364,7 @@ fn construct_structural_additions(
|
||||
nodes.sort_by_key(|(id, _)| **id);
|
||||
let added: Vec<_> = nodes.into_iter().map(|(id, node)| (*id, node.clone())).collect();
|
||||
for (id, node) in added {
|
||||
// A node the registry already holds is updated rather than rebuilt: rebuilding would clear the
|
||||
// `ui::*` attributes it carries, and restating those would clobber whatever a concurrent peer
|
||||
// wrote to its name, lock or pin.
|
||||
match batch.node(id).is_some() {
|
||||
true => {
|
||||
ops.push(RegistryDelta::SetNodeImplementation {
|
||||
id,
|
||||
implementation: node.implementation().clone(),
|
||||
});
|
||||
ops.push(RegistryDelta::SetNodeInputs { id, inputs: node.inputs().to_vec() });
|
||||
}
|
||||
false => ops.push(RegistryDelta::AddNode { id, node: node.clone() }),
|
||||
}
|
||||
ops.push(RegistryDelta::AddNode { id, node: node.clone() });
|
||||
batch.record_addition(id, node);
|
||||
}
|
||||
|
||||
@@ -422,31 +396,6 @@ fn construct_structural_additions(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stages the resource a value input references, so setting an input to an asset persists the entry
|
||||
/// alongside the reference rather than leaving the registry pointing at something it does not hold.
|
||||
fn construct_referenced_resource(
|
||||
owner: Option<document_graph_storage::NodeId>,
|
||||
input: &document_graph_storage::NodeInput,
|
||||
context: &ConversionContext,
|
||||
batch: &mut BatchRegistry,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
) -> Result<(), ConversionError> {
|
||||
let Some(id) = value_resource_ref(input) else { return Ok(()) };
|
||||
if let Some(owner) = owner {
|
||||
batch.record_input_resource(owner, id);
|
||||
}
|
||||
if batch.resource(id).is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(entry) = convert_resource_entry(context.resources, id, context.peer)? else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
batch.record_resource(id, entry.clone());
|
||||
ops.push(RegistryDelta::AddResource { id, entry });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn construct_metadata_snapshot(
|
||||
network_path: &[NodeId],
|
||||
node_id: NodeId,
|
||||
@@ -491,11 +440,10 @@ fn construct_metadata_snapshot(
|
||||
let network_id = resolver.network_id(&nested_path);
|
||||
|
||||
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
|
||||
// Read through the batch rather than the pre-batch registry: a `ReplaceNode` earlier in this
|
||||
// batch rebuilds the network without a reference, so comparing against the old state would
|
||||
// suppress the write and leave the rebuilt network missing it.
|
||||
let current = batch
|
||||
.network(network_id)
|
||||
.working
|
||||
.networks
|
||||
.get(&network_id)
|
||||
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
|
||||
.map(|value| value.value.clone());
|
||||
if current != target {
|
||||
@@ -508,22 +456,6 @@ fn construct_metadata_snapshot(
|
||||
});
|
||||
}
|
||||
|
||||
// Restated alongside the reference, since a rebuild clears the network's attributes and the
|
||||
// order would otherwise be lost for every nested network the snapshot covers.
|
||||
let pinned_order: Vec<_> = network_metadata
|
||||
.persistent_metadata
|
||||
.pinned_node_order
|
||||
.iter()
|
||||
.map(|pinned| resolver.node_id(&nested_path, *pinned))
|
||||
.collect();
|
||||
ops.push(RegistryDelta::ChangeNetworkAttribute {
|
||||
id: network_id,
|
||||
delta: AttributeDelta {
|
||||
key: network_attr::PINNED_ORDER.to_string(),
|
||||
value: (!pinned_order.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &pinned_order)).transpose()?,
|
||||
},
|
||||
});
|
||||
|
||||
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
|
||||
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
|
||||
}
|
||||
@@ -564,69 +496,37 @@ fn ui_attribute_writes(current: Option<&Attributes>, encoded: &Attributes) -> Ve
|
||||
|
||||
/// Emits the removal of a node and everything nested under it, recording what was removed so the
|
||||
/// batch's resource liveness accounts for all of it at the end.
|
||||
fn construct_removals(
|
||||
node_id: document_graph_storage::NodeId,
|
||||
batch: &mut BatchRegistry,
|
||||
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
) {
|
||||
construct_removals_with(node_id, true, batch, batch_removed_nodes, ops)
|
||||
}
|
||||
|
||||
/// Removes everything the node's implementation owns while leaving the node itself, for a swap that
|
||||
/// keeps the node in place.
|
||||
fn construct_removals_below(
|
||||
node_id: document_graph_storage::NodeId,
|
||||
batch: &mut BatchRegistry,
|
||||
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
) {
|
||||
construct_removals_with(node_id, false, batch, batch_removed_nodes, ops)
|
||||
}
|
||||
|
||||
fn construct_removals_with(
|
||||
node_id: document_graph_storage::NodeId,
|
||||
include_node: bool,
|
||||
batch: &mut BatchRegistry,
|
||||
batch_removed_nodes: &mut Vec<(document_graph_storage::NodeId, document_graph_storage::Node)>,
|
||||
ops: &mut Vec<RegistryDelta>,
|
||||
) {
|
||||
fn construct_removals(node_id: document_graph_storage::NodeId, batch: &BatchRegistry, batch_removed_nodes: &mut Vec<document_graph_storage::NodeId>, ops: &mut Vec<RegistryDelta>) {
|
||||
let (mut removed_nodes, mut removed_networks) = removal_closure(node_id, batch);
|
||||
|
||||
removed_nodes.sort();
|
||||
removed_networks.sort();
|
||||
for id in &removed_nodes {
|
||||
if !include_node && *id == node_id {
|
||||
continue;
|
||||
}
|
||||
let Some(snapshot) = batch.node(*id).cloned() else { continue };
|
||||
let Some(snapshot) = batch.node(*id) else { continue };
|
||||
ops.push(RegistryDelta::RemoveNode { id: *id, snapshot: snapshot.clone() });
|
||||
// Kept by value: a replacement later in this batch re-adds the same ID with different content, so
|
||||
// looking the node up again at the end would read what replaced it rather than what was removed.
|
||||
batch_removed_nodes.push((*id, snapshot));
|
||||
batch.record_removal(*id);
|
||||
}
|
||||
for id in &removed_networks {
|
||||
let Some(snapshot) = batch.network(*id) else { continue };
|
||||
ops.push(RegistryDelta::RemoveNetwork { id: *id, snapshot: snapshot.clone() });
|
||||
}
|
||||
|
||||
batch_removed_nodes.extend(removed_nodes);
|
||||
}
|
||||
|
||||
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
|
||||
/// removal is known.
|
||||
fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::NodeId, document_graph_storage::Node)], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
|
||||
// A node this batch wrote an input on and then removed orphans whatever that write referenced, which
|
||||
// the stored node does not mention.
|
||||
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], batch: &BatchRegistry, ops: &mut Vec<RegistryDelta>) {
|
||||
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
|
||||
let mut candidates: Vec<ResourceId> = batch_removed_nodes
|
||||
.iter()
|
||||
.flat_map(|(id, _)| batch.input_resources.get(id).into_iter().flatten().copied())
|
||||
.chain(batch_removed_nodes.iter().map(|(_, node)| node).flat_map(|node| {
|
||||
.filter_map(|id| batch.node(*id))
|
||||
.flat_map(|node| {
|
||||
let declaration = match node.implementation() {
|
||||
Implementation::ProtoNode(declaration) => Some(*declaration),
|
||||
Implementation::Network(_) => None,
|
||||
};
|
||||
declaration.into_iter().chain(node_value_resource_refs(node))
|
||||
}))
|
||||
})
|
||||
.collect();
|
||||
candidates.sort();
|
||||
candidates.dedup();
|
||||
@@ -636,18 +536,16 @@ fn construct_resource_removals(batch_removed_nodes: &[(document_graph_storage::N
|
||||
|
||||
// Gathered in one pass so each candidate is a lookup rather than another scan of the whole registry
|
||||
let mut still_referenced: HashSet<ResourceId> = HashSet::new();
|
||||
for (id, node) in batch.live_nodes() {
|
||||
for (id, node) in batch.working.node_instances.iter().chain(&batch.added) {
|
||||
if removed_node_set.contains(id) {
|
||||
continue;
|
||||
}
|
||||
if let Implementation::ProtoNode(declaration) = node.implementation() {
|
||||
still_referenced.insert(*declaration);
|
||||
}
|
||||
still_referenced.extend(node_value_resource_refs(node));
|
||||
// What this batch wrote onto a node that survives it is a live reference, even though the stored
|
||||
// node still carries the input it had before.
|
||||
still_referenced.extend(batch.input_resources.get(&id).into_iter().flatten().copied());
|
||||
}
|
||||
// The batch's own networks count too: one added earlier in it can export a resource the removal would
|
||||
// otherwise see as orphaned.
|
||||
for network in batch.working.networks.values().chain(batch.added_networks.values()) {
|
||||
for network in batch.working.networks.values() {
|
||||
still_referenced.extend(network.exports.iter().filter_map(|slot| slot.target.as_ref().and_then(value_resource_ref)));
|
||||
}
|
||||
|
||||
@@ -675,13 +573,6 @@ struct BatchRegistry<'a> {
|
||||
added_networks: HashMap<document_graph_storage::NetworkId, document_graph_storage::Network>,
|
||||
added_resources: HashMap<ResourceId, document_graph_storage::ResourceEntry>,
|
||||
by_network: HashMap<document_graph_storage::NetworkId, Vec<document_graph_storage::NodeId>>,
|
||||
/// Nodes the batch has removed and not since re-added, so a lookup answers with the state the ops so
|
||||
/// far have produced rather than the state the batch started from.
|
||||
removed: HashSet<document_graph_storage::NodeId>,
|
||||
/// Resources the batch's own input writes reference, keyed by the node written to. The stored node
|
||||
/// still holds its pre-batch inputs, so liveness would otherwise miss both the reference these writes
|
||||
/// create and the orphan they leave when that node is later removed.
|
||||
input_resources: HashMap<document_graph_storage::NodeId, HashSet<ResourceId>>,
|
||||
}
|
||||
|
||||
impl<'a> BatchRegistry<'a> {
|
||||
@@ -696,29 +587,15 @@ impl<'a> BatchRegistry<'a> {
|
||||
added_networks: HashMap::new(),
|
||||
added_resources: HashMap::new(),
|
||||
by_network,
|
||||
removed: HashSet::new(),
|
||||
input_resources: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records that an input write on `owner` references `resource`.
|
||||
fn record_input_resource(&mut self, owner: document_graph_storage::NodeId, resource: ResourceId) {
|
||||
self.input_resources.entry(owner).or_default().insert(resource);
|
||||
}
|
||||
|
||||
/// Records a node an earlier delta in this batch added, so a later one can read it back.
|
||||
fn record_addition(&mut self, id: document_graph_storage::NodeId, node: document_graph_storage::Node) {
|
||||
self.by_network.entry(node.network()).or_default().push(id);
|
||||
self.removed.remove(&id);
|
||||
self.added.insert(id, node);
|
||||
}
|
||||
|
||||
/// Records a node this batch removed, so a later delta reading it back finds it gone.
|
||||
fn record_removal(&mut self, id: document_graph_storage::NodeId) {
|
||||
self.added.remove(&id);
|
||||
self.removed.insert(id);
|
||||
}
|
||||
|
||||
/// Records a network an earlier delta in this batch added, so removing the node that owns it finds
|
||||
/// the network to remove alongside it.
|
||||
fn record_network(&mut self, id: document_graph_storage::NetworkId, network: document_graph_storage::Network) {
|
||||
@@ -732,25 +609,9 @@ impl<'a> BatchRegistry<'a> {
|
||||
}
|
||||
|
||||
fn node(&self, id: document_graph_storage::NodeId) -> Option<&document_graph_storage::Node> {
|
||||
if self.removed.contains(&id) {
|
||||
return None;
|
||||
}
|
||||
self.added.get(&id).or_else(|| self.working.node_instances.get(&id))
|
||||
}
|
||||
|
||||
/// Every node the batch leaves in place, which is what the working registry held plus what the batch
|
||||
/// added, less what it removed.
|
||||
fn live_nodes(&self) -> impl Iterator<Item = (document_graph_storage::NodeId, &document_graph_storage::Node)> {
|
||||
self.working
|
||||
.node_instances
|
||||
.keys()
|
||||
.chain(self.added.keys())
|
||||
.copied()
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.filter_map(|id| Some((id, self.node(id)?)))
|
||||
}
|
||||
|
||||
fn network(&self, id: document_graph_storage::NetworkId) -> Option<&document_graph_storage::Network> {
|
||||
self.added_networks.get(&id).or_else(|| self.working.networks.get(&id))
|
||||
}
|
||||
|
||||
+4
-40
@@ -78,7 +78,7 @@ async fn set_input_value_constructs_the_exact_diff_op() {
|
||||
let node = editor.create_node_by_name(rectangle_definition()).await;
|
||||
|
||||
let working = convert(&editor);
|
||||
let input = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
let input = NodeInput::value(TaggedValue::F64(42.), false);
|
||||
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(node, 1), input.clone(), &[]);
|
||||
|
||||
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
|
||||
@@ -337,7 +337,7 @@ async fn emitted_deltas_reproduce_the_diff_for_an_arity_change() {
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
|
||||
|
||||
let emitted = editor.active_document_mut().network_interface.take_deltas();
|
||||
assert!(!emitted.is_empty(), "adding an import should have emitted deltas");
|
||||
@@ -378,7 +378,7 @@ async fn an_arity_change_keeps_an_earlier_edit_to_the_same_node() {
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
|
||||
|
||||
let emitted = editor.active_document_mut().network_interface.take_deltas();
|
||||
let constructed = construct(&editor, &emitted, &working);
|
||||
@@ -452,7 +452,7 @@ async fn replaying_an_arity_change_reproduces_the_interface() {
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.add_import(TaggedValue::Number(7.), true, -1, "Added", "An added import", &[group]);
|
||||
.add_import(TaggedValue::F64(7.), true, -1, "Added", "An added import", &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -576,39 +576,3 @@ async fn a_group_added_and_removed_in_one_batch_leaves_nothing_behind() {
|
||||
let diffed = compute_deltas(&working, &convert(&editor));
|
||||
assert_same_stored_effect(&working, constructed, diffed, "group added then removed in one batch");
|
||||
}
|
||||
|
||||
/// Swapping a node's implementation must not restate the node's own metadata: the swap did not write it,
|
||||
/// and asserting it would overwrite whatever a concurrent peer set for the node's name, lock or pin.
|
||||
#[tokio::test]
|
||||
async fn swapping_an_implementation_leaves_the_node_in_place() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
|
||||
let working = convert(&editor);
|
||||
|
||||
let deltas = {
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.discard_deltas();
|
||||
let Some(mut cursor) = interface.node_mut(super::NodeLocator::new(node, &[])) else {
|
||||
panic!("the node should resolve")
|
||||
};
|
||||
cursor.replace_implementation(graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), None);
|
||||
interface.take_deltas()
|
||||
};
|
||||
|
||||
let ops = construct(&editor, &deltas, &working);
|
||||
|
||||
assert!(
|
||||
ops.iter().any(|op| matches!(op, RegistryDelta::SetNodeImplementation { .. })),
|
||||
"the swap should update the implementation in place"
|
||||
);
|
||||
assert!(
|
||||
!ops.iter().any(|op| matches!(op, RegistryDelta::RemoveNode { .. })),
|
||||
"the node itself should not be rebuilt, since that would clear the attributes it carries"
|
||||
);
|
||||
assert!(
|
||||
!deltas.iter().any(|delta| matches!(delta, EditorDelta::NodeMetadataSnapshot { node_id, .. } if *node_id == node)),
|
||||
"the node's own metadata should not be restated by a swap that did not write it"
|
||||
);
|
||||
}
|
||||
+22
-115
@@ -19,12 +19,11 @@ impl NodeNetworkInterface {
|
||||
let other_persistent = &other_network_metadata.persistent_metadata;
|
||||
*view.navigation = other_persistent.navigation_metadata.clone();
|
||||
|
||||
// The live preview root may name a node that the rebuilt-from-storage network no longer contains
|
||||
// (e.g. after a storage undo), so only carry it over when the root still exists; otherwise drop it.
|
||||
// The preview is this peer's and survives a rebuild, unless it names a node the rebuilt
|
||||
// network no longer contains (e.g. after a storage undo), in which case there is nothing
|
||||
// left to look at.
|
||||
*view.previewing = match other_persistent.previewing {
|
||||
Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node),
|
||||
} if !view.nodes.contains_key(&root_node.node_id) => Previewing::No,
|
||||
Previewing::Yes { previewed } if !view.nodes.contains_key(&previewed.node_id) => Previewing::No,
|
||||
previewing => previewing,
|
||||
};
|
||||
|
||||
@@ -62,11 +61,10 @@ impl NodeNetworkInterface {
|
||||
self.edit_input_value(&InputConnector::node_at_index(*node_id, 1), &[], |value| {
|
||||
let TaggedValue::VectorModification(modification) = value else {
|
||||
log::error!("Path node {node_id} does not have a modification input");
|
||||
return false;
|
||||
return;
|
||||
};
|
||||
modification.modify(&modification_type);
|
||||
modified = true;
|
||||
true
|
||||
});
|
||||
|
||||
if modified {
|
||||
@@ -849,8 +847,13 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Removes all references to the node with the given id from the network, and reconnects the input to the node below.
|
||||
pub fn remove_references_from_network(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
// TODO: Add more logic to support retaining preview when removing references. Since there are so many edge cases/possible crashes, for now the preview is ended.
|
||||
self.stop_previewing(network_path);
|
||||
// A preview of the node being removed cannot outlive it. A preview of any other node is untouched:
|
||||
// previewing does not rewire anything, so the reconnection below cannot invalidate it.
|
||||
if matches!(self.previewing(network_path), Previewing::Yes { previewed } if previewed.node_id == *node_id)
|
||||
&& let Some(mut network) = self.network_mut(network_path)
|
||||
{
|
||||
network.set_previewing(Previewing::No);
|
||||
}
|
||||
|
||||
// The wire the downstream inputs reconnect to, which is the first exposed input of the node being removed
|
||||
let reconnect_to_input = self.document_node(node_id, network_path).and_then(|node| {
|
||||
@@ -917,34 +920,6 @@ impl NodeNetworkInterface {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn start_previewing_without_restore(&mut self, network_path: &[NodeId]) {
|
||||
// Some logic will have to be performed to prevent the graph positions from being completely changed when the export changes to some previewed node
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in start_previewing_without_restore");
|
||||
return;
|
||||
};
|
||||
network.set_previewing(Previewing::Yes { root_node_to_restore: None });
|
||||
}
|
||||
|
||||
fn stop_previewing(&mut self, network_path: &[NodeId]) {
|
||||
if let Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node_to_restore),
|
||||
} = self.previewing(network_path)
|
||||
{
|
||||
self.set_input(
|
||||
&InputConnector::Export(0),
|
||||
NodeInput::node(root_node_to_restore.node_id, root_node_to_restore.output_index),
|
||||
network_path,
|
||||
);
|
||||
}
|
||||
|
||||
let Some(mut network) = self.network_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in stop_previewing");
|
||||
return;
|
||||
};
|
||||
network.set_previewing(Previewing::No);
|
||||
}
|
||||
|
||||
pub fn set_display_name(&mut self, node_id: &NodeId, display_name: String, network_path: &[NodeId]) {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node {node_id} in set_display_name");
|
||||
@@ -1138,87 +1113,19 @@ impl NodeNetworkInterface {
|
||||
self.load_structure();
|
||||
}
|
||||
|
||||
/// Renders `toggle_id` instead of the network's export, or stops doing so if it already is.
|
||||
///
|
||||
/// Per-peer and not a change to the document: the export keeps whatever it is wired to, and the
|
||||
/// compile path substitutes the previewed node into the graph it evaluates, so no other peer sees it.
|
||||
pub fn toggle_preview(&mut self, toggle_id: NodeId, network_path: &[NodeId]) {
|
||||
let Some(network) = self.nested_network(network_path) else {
|
||||
return;
|
||||
let previewing = match self.previewing(network_path) {
|
||||
Previewing::Yes { previewed } if previewed.node_id == toggle_id => Previewing::No,
|
||||
_ => Previewing::Yes {
|
||||
previewed: RootNode { node_id: toggle_id, output_index: 0 },
|
||||
},
|
||||
};
|
||||
// If new_export is None then disconnect
|
||||
let mut new_export = None;
|
||||
let mut new_previewing_state = Previewing::No;
|
||||
if let Some(export) = network.exports.first() {
|
||||
// If there currently an export
|
||||
if let NodeInput::Node { node_id, output_index, .. } = export {
|
||||
let previous_export_id = *node_id;
|
||||
let previous_output_index = *output_index;
|
||||
|
||||
// The export is clicked
|
||||
if *node_id == toggle_id {
|
||||
// If the current export is clicked and is being previewed end the preview and set either export back to root node or disconnect
|
||||
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
|
||||
new_export = root_node_to_restore.map(|root_node| root_node.to_connector());
|
||||
new_previewing_state = Previewing::No;
|
||||
}
|
||||
// The export is clicked and there is no preview
|
||||
else {
|
||||
new_previewing_state = Previewing::Yes {
|
||||
root_node_to_restore: Some(RootNode {
|
||||
node_id: previous_export_id,
|
||||
output_index: previous_output_index,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
// The export is not clicked
|
||||
else {
|
||||
new_export = Some(OutputConnector::primary_output(toggle_id));
|
||||
|
||||
// There is currently a dashed line being drawn
|
||||
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
|
||||
// There is also a solid line being drawn
|
||||
if let Some(root_node_to_restore) = root_node_to_restore {
|
||||
// If the node with the solid line is clicked, then start previewing that node without restore
|
||||
if root_node_to_restore.node_id == toggle_id {
|
||||
new_export = Some(OutputConnector::primary_output(toggle_id));
|
||||
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
|
||||
} else {
|
||||
// Root node to restore does not change
|
||||
new_previewing_state = Previewing::Yes {
|
||||
root_node_to_restore: Some(root_node_to_restore),
|
||||
};
|
||||
}
|
||||
}
|
||||
// There is a dashed line without a solid line.
|
||||
else {
|
||||
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
|
||||
}
|
||||
}
|
||||
// Not previewing, there is no dashed line being drawn
|
||||
else {
|
||||
new_export = Some(OutputConnector::primary_output(toggle_id));
|
||||
new_previewing_state = Previewing::Yes {
|
||||
root_node_to_restore: Some(RootNode {
|
||||
node_id: previous_export_id,
|
||||
output_index: previous_output_index,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
// The primary export is disconnected, so preview the node with nothing to restore, which disconnects the export again when the preview ends
|
||||
else {
|
||||
new_export = Some(OutputConnector::primary_output(toggle_id));
|
||||
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
|
||||
}
|
||||
}
|
||||
match new_export {
|
||||
Some(new_export) => {
|
||||
self.create_wire(&new_export, &InputConnector::Export(0), network_path);
|
||||
}
|
||||
None => {
|
||||
self.disconnect_input(&InputConnector::Export(0), network_path);
|
||||
}
|
||||
}
|
||||
let Some(mut network) = self.network_mut(network_path) else { return };
|
||||
network.set_previewing(new_previewing_state);
|
||||
network.set_previewing(previewing);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,20 @@ impl NodeNetworkInterface {
|
||||
pub fn document_network(&self) -> &NodeNetwork {
|
||||
self.network.network()
|
||||
}
|
||||
|
||||
/// The document network as it should be evaluated, which is the document itself with the previewed
|
||||
/// node substituted for the export.
|
||||
pub fn network_to_evaluate(&self) -> NodeNetwork {
|
||||
let mut network = self.document_network().clone();
|
||||
|
||||
if let Previewing::Yes { previewed } = self.previewing(&[])
|
||||
&& let Some(export) = network.exports.first_mut()
|
||||
{
|
||||
*export = NodeInput::node(previewed.node_id, previewed.output_index);
|
||||
}
|
||||
|
||||
network
|
||||
}
|
||||
/// Gets the nested network based on network_path
|
||||
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
|
||||
let Some(network) = self.document_network().nested_network(network_path) else {
|
||||
|
||||
+1
-15
@@ -15,7 +15,7 @@ use graphene_std::vector::style::RenderMode;
|
||||
|
||||
use super::{
|
||||
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
|
||||
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
|
||||
NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ,
|
||||
};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
|
||||
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
|
||||
@@ -230,13 +230,6 @@ pub fn collect_network_view_settings(
|
||||
settings.insert(session::network::NAV_WIDTH.to_string(), value);
|
||||
}
|
||||
|
||||
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
|
||||
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
|
||||
&& let Ok(value) = serde_json::to_value(network_metadata.persistent_metadata.previewing)
|
||||
{
|
||||
settings.insert(session::network::PREVIEWING.to_string(), value);
|
||||
}
|
||||
|
||||
if !settings.is_empty() {
|
||||
out.insert(network_id, settings);
|
||||
}
|
||||
@@ -275,13 +268,6 @@ pub fn apply_network_view_settings(
|
||||
{
|
||||
navigation.node_graph_width = width;
|
||||
}
|
||||
|
||||
if let Some(value) = settings.get(session::network::PREVIEWING)
|
||||
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
|
||||
&& let Some(mut network) = interface.network_mut(network_path)
|
||||
{
|
||||
network.set_previewing(previewing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-23
@@ -96,16 +96,6 @@ impl NodeDeltas<'_> {
|
||||
});
|
||||
}
|
||||
|
||||
/// Records a snapshot for a node inside the network this one owns, for metadata that arrived with a
|
||||
/// new nested network rather than describing this node.
|
||||
fn snapshot_owned(&mut self, node_id: NodeId, metadata: Box<DocumentNodePersistentMetadata>) {
|
||||
self.deltas.push(EditorDelta::NodeMetadataSnapshot {
|
||||
network_path: self.locator.owned_network_path(),
|
||||
node_id,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
|
||||
fn network_path(&self) -> Vec<NodeId> {
|
||||
self.locator.network_path.to_vec()
|
||||
}
|
||||
@@ -357,19 +347,8 @@ impl NodeMut<'_> {
|
||||
node: Box::new(self.node.clone()),
|
||||
};
|
||||
self.deltas.graph(delta);
|
||||
|
||||
// Only what the new implementation brought with it. A swap leaves the node's own metadata alone,
|
||||
// and restating it would assert values this peer did not write, clobbering a concurrent rename.
|
||||
let owned: Vec<_> = self
|
||||
.metadata
|
||||
.network_metadata
|
||||
.iter()
|
||||
.flat_map(|network_metadata| &network_metadata.persistent_metadata.node_metadata)
|
||||
.map(|(child_id, child)| (*child_id, Box::new(child.persistent_metadata.clone())))
|
||||
.collect();
|
||||
for (child_id, metadata) in owned {
|
||||
self.deltas.snapshot_owned(child_id, metadata);
|
||||
}
|
||||
let metadata = Box::new(self.metadata.clone());
|
||||
self.deltas.snapshot(metadata);
|
||||
}
|
||||
|
||||
/// Replaces the node's whole persistent metadata, including that of everything nested under it,
|
||||
|
||||
+2
-11
@@ -206,7 +206,7 @@ impl NodeNetworkInterface {
|
||||
/// For a change expressed as an operation on the existing value rather than as a replacement of it,
|
||||
/// which avoids copying the value out and back. The recorded delta still carries the whole result,
|
||||
/// since the storage op is a whole-value write.
|
||||
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue) -> bool) -> bool {
|
||||
pub(crate) fn edit_input_value(&mut self, connector: &InputConnector, network_path: &[NodeId], edit: impl FnOnce(&mut TaggedValue)) -> bool {
|
||||
let Some(network) = self.network_graph_mut(network_path) else {
|
||||
log::error!("Could not get nested network in edit_input_value");
|
||||
return false;
|
||||
@@ -221,18 +221,9 @@ impl NodeNetworkInterface {
|
||||
return false;
|
||||
};
|
||||
|
||||
// The edit reports whether it changed anything, rather than this comparing before and after.
|
||||
// Comparing the values would mean copying one out, which is the copy this method exists to avoid,
|
||||
// and comparing their memoized hashes would let a collision silently drop a real edit.
|
||||
let changed = edit(&mut value);
|
||||
edit(&mut value);
|
||||
drop(value);
|
||||
|
||||
// An edit that changes nothing still carries a timestamp, which would let it supersede a concurrent
|
||||
// peer's real edit to the same input.
|
||||
if !changed {
|
||||
return true;
|
||||
}
|
||||
|
||||
let input = slot.clone();
|
||||
self.deltas.push(input_write_delta(connector, network_path, input));
|
||||
true
|
||||
|
||||
@@ -338,11 +338,16 @@ impl RootNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Which node the node graph renders instead of the network's export.
|
||||
///
|
||||
/// Per-peer view state, not part of the document: the export keeps whatever it is wired to, and the
|
||||
/// compile path substitutes the previewed node into the graph it evaluates. So previewing a node
|
||||
/// changes nothing another peer would see.
|
||||
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Previewing {
|
||||
/// If there is a node to restore the connection to the export for, then it is stored in the option.
|
||||
/// Otherwise, nothing gets restored and the primary export is disconnected.
|
||||
Yes { root_node_to_restore: Option<RootNode> },
|
||||
Yes {
|
||||
previewed: RootNode,
|
||||
},
|
||||
#[default]
|
||||
No,
|
||||
}
|
||||
|
||||
@@ -282,19 +282,15 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
}
|
||||
|
||||
/// The root node (the node that the solid line is connected to), or None if no nodes are connected to the output.
|
||||
///
|
||||
/// Simply what the export is wired to: previewing renders a different node but does not rewire it.
|
||||
pub fn root_node(&self) -> Option<RootNode> {
|
||||
match &self.metadata.persistent_metadata.previewing {
|
||||
Previewing::Yes { root_node_to_restore } => *root_node_to_restore,
|
||||
Previewing::No => self.network.exports.first().and_then(|export| {
|
||||
if let NodeInput::Node { node_id, output_index, .. } = export {
|
||||
Some(RootNode {
|
||||
node_id: *node_id,
|
||||
output_index: *output_index,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
match self.network.exports.first() {
|
||||
Some(NodeInput::Node { node_id, output_index, .. }) => Some(RootNode {
|
||||
node_id: *node_id,
|
||||
output_index: *output_index,
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ const TEXT_REPLACEMENTS: &[(&str, &str)] = &[
|
||||
"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>",
|
||||
),
|
||||
("graphene_core::transform::Footprint", "graphene_core::transform::Footprint"),
|
||||
("\"OptionalF64\":", "\"Number\":"),
|
||||
("\"OptionalF64\":", "\"F64\":"),
|
||||
("\"path_bool_nodes::BooleanOperation\"", "\"vector_types::vector::misc::BooleanOperation\""),
|
||||
("\"core_types::table::Table<", "\"core_types::list::List<"),
|
||||
// The `GradientStops` type was renamed to `Gradient`; stale stored output names are cleared so the display falls back to the live type name
|
||||
@@ -1205,8 +1205,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *old_inputs_count == 6 {
|
||||
match old_inputs.get(2) {
|
||||
Some(NodeInput::Value { tagged_value, exposed }) => {
|
||||
if let TaggedValue::Number(radians) = *tagged_value.clone().into_inner() {
|
||||
let degrees = NodeInput::value(TaggedValue::Number(radians.to_degrees()), *exposed);
|
||||
if let TaggedValue::F64(radians) = *tagged_value.clone().into_inner() {
|
||||
let degrees = NodeInput::value(TaggedValue::F64(radians.to_degrees()), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), degrees, network_path);
|
||||
}
|
||||
}
|
||||
@@ -1215,7 +1215,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
// (which represented radians in the legacy format) reaches the now-degrees Rotation input correctly.
|
||||
if let Some(multiply_node) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::multiply::IDENTIFIER)) {
|
||||
let mut multiply_template = multiply_node.default_node_template();
|
||||
multiply_template.inputs[1] = NodeInput::value(TaggedValue::Number(180. / PI), false);
|
||||
multiply_template.inputs[1] = NodeInput::value(TaggedValue::F64(180. / PI), false);
|
||||
let multiply_node_id = NodeId::new();
|
||||
if let Some(transform_position) = document.network_interface.position(node_id, network_path) {
|
||||
let multiply_position = transform_position + IVec2::new(-7, 1);
|
||||
@@ -1301,7 +1301,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
|
||||
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
|
||||
let inline_b_constant = match operand_b.as_value() {
|
||||
Some(TaggedValue::Number(constant)) => Some(*constant),
|
||||
Some(TaggedValue::F64(constant)) => Some(*constant),
|
||||
_ => None,
|
||||
};
|
||||
let fx_expression = match &static_expression {
|
||||
@@ -1336,7 +1336,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
} else {
|
||||
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
|
||||
let as_list_input = |input: &NodeInput| match input.as_value() {
|
||||
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
|
||||
Some(TaggedValue::F64(value)) => NodeInput::value(TaggedValue::F64Array(vec![*value]), input.is_exposed()),
|
||||
_ => input.clone(),
|
||||
};
|
||||
let Some(extend_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::graphic::extend::IDENTIFIER)) else {
|
||||
@@ -1532,7 +1532,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
.iter()
|
||||
.filter_map(|&index| {
|
||||
let NodeInput::Value { tagged_value, exposed } = node.inputs.get(index)? else { return None };
|
||||
let TaggedValue::Number(value) = &**tagged_value else { return None };
|
||||
let TaggedValue::F64(value) = &**tagged_value else { return None };
|
||||
Some((*node_id, path.clone(), index, *value as i64, *exposed))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
@@ -1541,22 +1541,21 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
for (node_id, network_path, index, integer, exposed) in fractional_value_inputs {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::I64(integer), exposed), &network_path);
|
||||
}
|
||||
|
||||
// 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.
|
||||
document.network_interface.discard_deltas();
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let lengths = match &*tagged_value.clone().into_inner() {
|
||||
TaggedValue::Numbers(lengths) => lengths.clone(),
|
||||
TaggedValue::Number(length) => vec![*length],
|
||||
TaggedValue::F64Array(lengths) => lengths.clone(),
|
||||
TaggedValue::F64(length) => vec![*length],
|
||||
TaggedValue::String(text) => graphene_std::core_types::misc::parse_f64_list(text),
|
||||
_ => return None,
|
||||
};
|
||||
@@ -1567,8 +1566,8 @@ fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
fn migrate_corner_radius_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
let values = match &*tagged_value.clone().into_inner() {
|
||||
TaggedValue::Numbers(values) => values.clone(),
|
||||
TaggedValue::Number(value) => vec![*value],
|
||||
TaggedValue::F64Array(values) => values.clone(),
|
||||
TaggedValue::F64(value) => vec![*value],
|
||||
_ => return None,
|
||||
};
|
||||
Some(NodeInput::value(TaggedValue::BoxCorners(values), *exposed))
|
||||
@@ -1637,20 +1636,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
let mut inputs_count = node.inputs.len();
|
||||
|
||||
// The expression nodes gained an output-type input, a type witness the Properties panel edits. A node from before it
|
||||
// takes the definition's default choice, Number, which is the output type every such node had.
|
||||
let expression_node_identifiers = [graphene_std::math_nodes::math_fx::IDENTIFIER, graphene_std::math_nodes::math_f::IDENTIFIER];
|
||||
if expression_node_identifiers.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && inputs_count == 2 {
|
||||
let definition = resolve_document_node_type(&reference)?;
|
||||
let mut template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
for (index, input) in old_inputs.into_iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
inputs_count = 3;
|
||||
}
|
||||
|
||||
// Split the legacy combined "Blending" node into a chain of separate Blend Mode, Opacity (now also covers fill), and Clip nodes.
|
||||
// `NODE_REPLACEMENTS` rewrites the old `Blending` proto identifier (and its older aliases) to `blend_mode::IDENTIFIER`, so a leftover
|
||||
// 5-input shape on a Blend Mode node identifies an old Blending node that still needs structural splitting. Sub-nodes whose values
|
||||
@@ -1670,8 +1655,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// A sub-node is kept if its input is exposed/wired (so the user can drive it from the graph) OR if its value differs from the default
|
||||
let keep_blend_mode = blend_mode_input.is_exposed() || !matches!(blend_mode_input.as_value(), Some(TaggedValue::BlendMode(BlendMode::Normal)));
|
||||
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::Number(v)) if (*v - 100.).abs() < f64::EPSILON);
|
||||
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::Number(v)) if (*v - 100.).abs() < f64::EPSILON);
|
||||
let keep_opacity = opacity_input.is_exposed() || !matches!(opacity_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
|
||||
let keep_fill = fill_input.is_exposed() || !matches!(fill_input.as_value(), Some(TaggedValue::F64(v)) if (*v - 100.).abs() < f64::EPSILON);
|
||||
let keep_clip = clip_input.is_exposed() || !matches!(clip_input.as_value(), Some(TaggedValue::Bool(false)));
|
||||
|
||||
// Find the downstream connection so we can chain new nodes between this node and downstream
|
||||
@@ -1817,7 +1802,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 3), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::Number(100.), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 4), NodeInput::value(TaggedValue::F64(100.), false), network_path);
|
||||
|
||||
inputs_count = 5;
|
||||
}
|
||||
@@ -2163,9 +2148,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
|
||||
// Line height and character spacing were hardcoded to 1 in the era before they became inputs
|
||||
let hardcoded_to_one = || NodeInput::value(TaggedValue::Number(1.), false);
|
||||
let hardcoded_to_one = || NodeInput::value(TaggedValue::F64(1.), false);
|
||||
// Zero is how an absent `Option<f64>` maximum reads to the split below
|
||||
let unset_maximum = || NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let unset_maximum = || NodeInput::value(TaggedValue::F64(0.), false);
|
||||
|
||||
let upgraded_inputs = [
|
||||
old_inputs[0].clone(),
|
||||
@@ -2179,7 +2164,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
old_inputs
|
||||
.get(8)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| NodeInput::value(TaggedValue::Number(TypesettingConfig::default().letter_tilt), false)),
|
||||
.unwrap_or_else(|| NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)),
|
||||
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false),
|
||||
old_inputs.get(9).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(false), false)),
|
||||
];
|
||||
@@ -2206,7 +2191,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
// The old `Option<f64>` maximum becomes a bool plus a value, with zero standing in for the absent option.
|
||||
// A wired maximum has no value to read, so it keeps its connection and counts as present.
|
||||
let split_maximum = |input: &NodeInput| match input.as_value() {
|
||||
Some(&TaggedValue::Number(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::Number(if maximum == 0. { 100. } else { maximum }), false)),
|
||||
Some(&TaggedValue::F64(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::F64(if maximum == 0. { 100. } else { maximum }), false)),
|
||||
_ => (true, input.clone()),
|
||||
};
|
||||
|
||||
@@ -2329,7 +2314,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(old_offset), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::F64(old_offset), false), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[2].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 4), old_inputs[3].clone(), network_path);
|
||||
}
|
||||
@@ -2463,17 +2448,17 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
let output_level = |index: usize, default: f64| match old_inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::Number(percent)) => percent / 100.,
|
||||
Some(TaggedValue::F64(percent)) => percent / 100.,
|
||||
_ => default,
|
||||
};
|
||||
let (output_minimums, output_maximums) = (output_level(4, 0.), output_level(5, 1.));
|
||||
for (index, input) in old_inputs.iter().take(6).enumerate() {
|
||||
let input = match (index, input.as_value()) {
|
||||
(2, Some(TaggedValue::Number(percent))) => {
|
||||
(2, Some(TaggedValue::F64(percent))) => {
|
||||
// The old node's midtones-to-gamma mapping, from https://stackoverflow.com/questions/39510072/algorithm-for-adjustment-of-image-levels
|
||||
let midtones = output_minimums + (output_maximums - output_minimums) * percent / 100.;
|
||||
let gamma = if midtones < 0.5 { 1. + 9. * (1. - midtones * 2.) } else { ((1. - midtones) * 2.).max(0.01) };
|
||||
NodeInput::value(TaggedValue::Number(gamma.clamp(0.01, 9.99)), input.is_exposed())
|
||||
NodeInput::value(TaggedValue::F64(gamma.clamp(0.01, 9.99)), input.is_exposed())
|
||||
}
|
||||
_ => input.clone(),
|
||||
};
|
||||
@@ -2528,7 +2513,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(0.), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::F64(0.), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
|
||||
@@ -2583,7 +2568,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
let new_spacing_value = NodeInput::value(TaggedValue::PointSpacingType(graphene_std::vector::misc::PointSpacingType::Separation), false);
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::Integer(100), false);
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::I64(100), false);
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), new_spacing_value, network_path);
|
||||
@@ -2602,9 +2587,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.input_from_connector(&InputConnector::Node { node_id: *node_id, input_index: 3 }, network_path)?;
|
||||
|
||||
if let NodeInput::Value { tagged_value, exposed } = quantity_value
|
||||
&& let TaggedValue::Number(value) = **tagged_value
|
||||
&& let TaggedValue::F64(value) = **tagged_value
|
||||
{
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::Integer(value as i64), *exposed);
|
||||
let new_quantity_value = NodeInput::value(TaggedValue::I64(value as i64), *exposed);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), new_quantity_value, network_path);
|
||||
}
|
||||
}
|
||||
@@ -2652,7 +2637,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
node_path.push(*node_id);
|
||||
|
||||
document.network_interface.add_import(TaggedValue::None, false, 0, "Primary", "", &node_path);
|
||||
document.network_interface.add_import(TaggedValue::Integer(0), false, 1, "Loop Level", "TODO", &node_path);
|
||||
document.network_interface.add_import(TaggedValue::I64(0), false, 1, "Loop Level", "TODO", &node_path);
|
||||
}
|
||||
|
||||
// Drop the placeholder primary input the "Read Vector" node used to carry, since it reads its value from the context
|
||||
@@ -2699,7 +2684,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(1.), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::F64(1.), false), network_path);
|
||||
}
|
||||
|
||||
// Upgrade the "Read Position" node to add the "Loop Level" input
|
||||
@@ -2713,7 +2698,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Integer(0), false), network_path);
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::I64(0), false), network_path);
|
||||
}
|
||||
|
||||
// Migrate from the old source/target v1 "Morph" node to the new `List<Vector>`-based v2 "Morph" node.
|
||||
@@ -2806,7 +2791,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
return None;
|
||||
};
|
||||
let mut subtract_template = subtract_def.default_node_template();
|
||||
subtract_template.inputs[1] = NodeInput::value(TaggedValue::Number(1.), false);
|
||||
subtract_template.inputs[1] = NodeInput::value(TaggedValue::F64(1.), false);
|
||||
let subtract_id = NodeId::new();
|
||||
|
||||
// Create Divide node: old_progression / (N-1) → new progression
|
||||
@@ -3282,12 +3267,12 @@ mod tests {
|
||||
NodeInput::scope("editor-api"),
|
||||
NodeInput::value(TaggedValue::String("Lorem".into()), false),
|
||||
NodeInput::value(TaggedValue::Font(Font::new("Lato".to_string(), "Regular (400)".to_string())), false),
|
||||
NodeInput::value(TaggedValue::Number(48.), false),
|
||||
NodeInput::value(TaggedValue::Number(1.5), false),
|
||||
NodeInput::value(TaggedValue::Number(2.), false),
|
||||
NodeInput::value(TaggedValue::Number(0.), false),
|
||||
NodeInput::value(TaggedValue::Number(0.), false),
|
||||
NodeInput::value(TaggedValue::Number(10.), false),
|
||||
NodeInput::value(TaggedValue::F64(48.), false),
|
||||
NodeInput::value(TaggedValue::F64(1.5), false),
|
||||
NodeInput::value(TaggedValue::F64(2.), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
NodeInput::value(TaggedValue::F64(10.), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
];
|
||||
|
||||
@@ -3333,56 +3318,29 @@ mod tests {
|
||||
);
|
||||
|
||||
let input_value = |index: usize| text_node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::Number(48.)), "shape {shape} lost its size");
|
||||
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::F64(48.)), "shape {shape} lost its size");
|
||||
if shape >= 6 {
|
||||
assert_eq!(
|
||||
input_value(graphene_std::text::text::LineHeightInput::INDEX),
|
||||
Some(TaggedValue::Number(1.5)),
|
||||
Some(TaggedValue::F64(1.5)),
|
||||
"shape {shape} lost its line height"
|
||||
);
|
||||
assert_eq!(
|
||||
input_value(graphene_std::text::text::LetterSpacingInput::INDEX),
|
||||
Some(TaggedValue::Number(2.)),
|
||||
Some(TaggedValue::F64(2.)),
|
||||
"shape {shape} lost its letter spacing"
|
||||
);
|
||||
}
|
||||
if shape >= 9 {
|
||||
assert_eq!(
|
||||
input_value(graphene_std::text::text::LetterTiltInput::INDEX),
|
||||
Some(TaggedValue::Number(10.)),
|
||||
Some(TaggedValue::F64(10.)),
|
||||
"shape {shape} lost its letter tilt"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An expression node saved before the output-type witness input had only its value and expression inputs
|
||||
#[test]
|
||||
fn expression_nodes_gain_the_output_type_witness() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
// The old inputs stay in place and the witness defaults to Number, the output type every such node had
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(node.inputs.len(), 3);
|
||||
assert_eq!(value_at(0), Some(TaggedValue::Number(4.)));
|
||||
assert_eq!(value_at(1), Some(TaggedValue::String("x^2".into())));
|
||||
assert_eq!(value_at(2), Some(TaggedValue::Number(0.)));
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
|
||||
#[test]
|
||||
@@ -3440,21 +3398,16 @@ mod tests {
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
NodeInput::value(TaggedValue::String("2 - 0.2A".into()), false),
|
||||
NodeInput::value(TaggedValue::Number(0.), false),
|
||||
NodeInput::value(TaggedValue::F64(0.), false),
|
||||
];
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.len(),
|
||||
3,
|
||||
"the old `B` input should be dropped, leaving the value, the expression, and the output-type witness"
|
||||
);
|
||||
assert_eq!(node.inputs.len(), 2, "the old `B` input should be dropped");
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_a_id, 0)));
|
||||
assert_eq!(node.inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::String("2 - 0.2x".into())));
|
||||
assert_eq!(node.inputs.get(2).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(0.)));
|
||||
}
|
||||
|
||||
// A constant `B` inlines into the rewritten string as a parenthesized literal; an alias spelling of the old identifier also matches
|
||||
@@ -3462,7 +3415,7 @@ mod tests {
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
NodeInput::value(TaggedValue::String("sqrt(A + B) - B^2".into()), false),
|
||||
NodeInput::value(TaggedValue::Number(3.), false),
|
||||
NodeInput::value(TaggedValue::F64(3.), false),
|
||||
];
|
||||
let mut document = build_document("graphene_core::ops::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
@@ -3501,9 +3454,9 @@ mod tests {
|
||||
// A wired expression cannot be inspected, so it splices too, wrapping unwired constant operands as one-item list values
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::value(TaggedValue::Number(2.), true),
|
||||
NodeInput::value(TaggedValue::F64(2.), true),
|
||||
NodeInput::node(source_expression_id, 0),
|
||||
NodeInput::value(TaggedValue::Number(5.), false),
|
||||
NodeInput::value(TaggedValue::F64(5.), false),
|
||||
];
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
document_migration_upgrades(&mut document, false);
|
||||
@@ -3512,8 +3465,8 @@ mod tests {
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::value(TaggedValue::Numbers(vec![2.]), true)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::value(TaggedValue::Numbers(vec![5.]), false)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.first(), Some(&NodeInput::value(TaggedValue::F64Array(vec![2.]), true)));
|
||||
assert_eq!(network.nodes[&extend_id].inputs.get(1), Some(&NodeInput::value(TaggedValue::F64Array(vec![5.]), false)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3526,7 +3479,7 @@ mod tests {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut node_template = resolve_network_node_type("Blend").expect("Blend should exist").default_node_template();
|
||||
node_template.inputs[1] = NodeInput::value(TaggedValue::Number(6.9), false);
|
||||
node_template.inputs[1] = NodeInput::value(TaggedValue::F64(6.9), false);
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
@@ -3540,7 +3493,7 @@ mod tests {
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(6)),
|
||||
Some(TaggedValue::I64(6)),
|
||||
"the count truncates as the retired Floor did, so the document keeps drawing six"
|
||||
);
|
||||
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
|
||||
@@ -3565,7 +3518,7 @@ mod tests {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::F64(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
@@ -3573,7 +3526,7 @@ mod tests {
|
||||
let DocumentNodeImplementation::Network(inner) = &document.network_interface.document_network().nodes[&node_id].implementation else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::F64(42.)));
|
||||
}
|
||||
|
||||
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
|
||||
@@ -3585,12 +3538,12 @@ mod tests {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let mut node_template = resolve_network_node_type("Regex Find").expect("Regex Find should exist").default_node_template();
|
||||
node_template.inputs[2] = NodeInput::value(TaggedValue::Number(1.6), false);
|
||||
node_template.inputs[2] = NodeInput::value(TaggedValue::F64(1.6), false);
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::F64(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
document_migration_upgrades(&mut document, false);
|
||||
@@ -3598,14 +3551,14 @@ mod tests {
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(2).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(1)),
|
||||
Some(TaggedValue::I64(1)),
|
||||
"the match index truncates as the retired cast did"
|
||||
);
|
||||
let DocumentNodeImplementation::Network(inner) = &node.implementation else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&NodeId(0)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&NodeId(1)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Integer(0)));
|
||||
assert_eq!(inner.nodes[&NodeId(1)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::I64(0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -642,6 +642,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document.network_interface.validate_input_metadata(node_id, node, &path);
|
||||
document.network_interface.validate_output_names(node_id, node, &path);
|
||||
}
|
||||
|
||||
// Ensure layers are positioned as stacks if they are upstream siblings of another layer
|
||||
document.network_interface.load_structure();
|
||||
let all_layers = LayerNodeIdentifier::ROOT_PARENT.descendants(document.network_interface.document_metadata()).collect::<Vec<_>>();
|
||||
@@ -672,12 +673,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
}
|
||||
}
|
||||
|
||||
// Everything above is how the document arrives rather than an edit to it, so what those fix-ups
|
||||
// recorded must not ride along in the first real commit. They still have to reach storage, so
|
||||
// the next commit converts the whole document instead of staging the batch that follows them.
|
||||
document.network_interface.discard_deltas();
|
||||
document.require_whole_document_stage();
|
||||
|
||||
// Set the save state of the document based on what's given to us by the caller to this message
|
||||
document.set_auto_save_state(document_is_auto_saved);
|
||||
document.set_save_state(document_is_saved);
|
||||
|
||||
+1
-1
@@ -173,7 +173,7 @@ impl RadiusHandle {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, radius_parameter),
|
||||
input: NodeInput::value(TaggedValue::Number(current_radius + net_delta), false),
|
||||
input: NodeInput::value(TaggedValue::F64(current_radius + net_delta), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@ impl RowColumnGizmo {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, self.gizmo_type.parameter()),
|
||||
input: NodeInput::value(TaggedValue::Integer((self.initial_dimension() as i32 + dimensions_to_add).max(1) as i64), false),
|
||||
input: NodeInput::value(TaggedValue::I64((self.initial_dimension() as i32 + dimensions_to_add).max(1) as i64), false),
|
||||
});
|
||||
|
||||
responses.add(GraphOperationMessage::TransformChange {
|
||||
|
||||
+1
-1
@@ -209,7 +209,7 @@ impl NumberOfPointsDial {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, sides_parameter),
|
||||
input: NodeInput::value(TaggedValue::Integer(new_point_count as i64), false),
|
||||
input: NodeInput::value(TaggedValue::I64(new_point_count as i64), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
+4
-4
@@ -343,13 +343,13 @@ impl PointRadiusHandle {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
let (Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
|
||||
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
let other_radius = if *radius_parameter == ParameterRef::from(star::Radius2Input) { radius_1 } else { radius_2 };
|
||||
|
||||
let Some(&TaggedValue::Integer(sides)) = parameters.value(star::SidesInput) else {
|
||||
let Some(&TaggedValue::I64(sides)) = parameters.value(star::SidesInput) else {
|
||||
return snap_radii;
|
||||
};
|
||||
|
||||
@@ -452,7 +452,7 @@ impl PointRadiusHandle {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, radius_parameter),
|
||||
input: NodeInput::value(TaggedValue::Number(original_radius + net_delta), false),
|
||||
input: NodeInput::value(TaggedValue::F64(original_radius + net_delta), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
@@ -462,7 +462,7 @@ impl PointRadiusHandle {
|
||||
return;
|
||||
};
|
||||
|
||||
let (Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
|
||||
let (Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) = (parameters.value(star::Radius1Input), parameters.value(star::Radius2Input)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
|
||||
+5
-5
@@ -191,15 +191,15 @@ impl SpiralTurns {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, StartAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(self.initial_start_angle + total_delta), false),
|
||||
input: NodeInput::value(TaggedValue::F64(self.initial_start_angle + total_delta), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, TurnsInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_turns), false),
|
||||
input: NodeInput::value(TaggedValue::F64(new_turns), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_outer_radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(new_outer_radius), false),
|
||||
});
|
||||
}
|
||||
GizmoType::End => {
|
||||
@@ -208,11 +208,11 @@ impl SpiralTurns {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, TurnsInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_turns), false),
|
||||
input: NodeInput::value(TaggedValue::F64(new_turns), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_outer_radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(new_outer_radius), false),
|
||||
});
|
||||
}
|
||||
GizmoType::None => {
|
||||
|
||||
+2
-2
@@ -333,11 +333,11 @@ impl SweepAngleGizmo {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::StartAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(start_angle), false),
|
||||
input: NodeInput::value(TaggedValue::F64(start_angle), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::SweepAngleInput),
|
||||
input: NodeInput::value(TaggedValue::Number(sweep_angle), false),
|
||||
input: NodeInput::value(TaggedValue::F64(sweep_angle), false),
|
||||
});
|
||||
|
||||
self.previous_mouse_position = input.mouse.position;
|
||||
|
||||
@@ -428,7 +428,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
|
||||
if positions_pending && reference == positions_reference {
|
||||
positions_pending = false;
|
||||
if let Some(TaggedValue::Numbers(positions)) = node
|
||||
if let Some(TaggedValue::F64Array(positions)) = node
|
||||
.and_then(|node| node.input(graphene_std::math_nodes::gradient_positions::PositionsInput))
|
||||
.and_then(|input| input.as_value())
|
||||
{
|
||||
@@ -436,7 +436,7 @@ pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
}
|
||||
} else if midpoints_pending && reference == midpoints_reference {
|
||||
midpoints_pending = false;
|
||||
if let Some(TaggedValue::Numbers(midpoints)) = node
|
||||
if let Some(TaggedValue::F64Array(midpoints)) = node
|
||||
.and_then(|node| node.input(graphene_std::math_nodes::gradient_midpoints::MidpointsInput))
|
||||
.and_then(|input| input.as_value())
|
||||
{
|
||||
@@ -517,7 +517,7 @@ pub fn get_opacity(layer: LayerNodeIdentifier, network_interface: &NodeNetworkIn
|
||||
let TaggedValue::Bool(true) = inputs.get(1)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
let TaggedValue::Number(opacity) = inputs.get(2)?.as_value()? else {
|
||||
let TaggedValue::F64(opacity) = inputs.get(2)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*opacity)
|
||||
@@ -537,7 +537,7 @@ pub fn get_fill(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInter
|
||||
let TaggedValue::Bool(true) = inputs.get(3)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
let TaggedValue::Number(fill) = inputs.get(4)?.as_value()? else {
|
||||
let TaggedValue::F64(fill) = inputs.get(4)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(*fill)
|
||||
@@ -606,26 +606,24 @@ pub fn get_text<'a>(
|
||||
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
|
||||
_ => Font::default(),
|
||||
};
|
||||
let Some(&TaggedValue::Number(font_size)) = parameters.value(text::SizeInput) else { return None };
|
||||
let Some(&TaggedValue::Number(line_height_ratio)) = parameters.value(text::LineHeightInput) else {
|
||||
let Some(&TaggedValue::F64(font_size)) = parameters.value(text::SizeInput) else { return None };
|
||||
let Some(&TaggedValue::F64(line_height_ratio)) = parameters.value(text::LineHeightInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(letter_spacing)) = parameters.value(text::LetterSpacingInput) else {
|
||||
let Some(&TaggedValue::F64(letter_spacing)) = parameters.value(text::LetterSpacingInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Bool(has_max_width)) = parameters.value(text::HasMaxWidthInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(max_width)) = parameters.value(text::MaxWidthInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(max_width)) = parameters.value(text::MaxWidthInput) else { return None };
|
||||
let Some(&TaggedValue::Bool(has_max_height)) = parameters.value(text::HasMaxHeightInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(max_height)) = parameters.value(text::MaxHeightInput) else {
|
||||
let Some(&TaggedValue::F64(max_height)) = parameters.value(text::MaxHeightInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Number(letter_tilt)) = parameters.value(text::LetterTiltInput) else {
|
||||
let Some(&TaggedValue::F64(letter_tilt)) = parameters.value(text::LetterTiltInput) else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::TextAlign(align)) = parameters.value(text::AlignInput) else { return None };
|
||||
@@ -643,7 +641,7 @@ pub fn get_text<'a>(
|
||||
}
|
||||
|
||||
pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
if let TaggedValue::Number(width) = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::WeightInput)? {
|
||||
if let TaggedValue::F64(width) = NodeGraphLayer::new(layer, network_interface).parameter_value(graphene_std::vector::stroke::WeightInput)? {
|
||||
Some(*width)
|
||||
} else {
|
||||
None
|
||||
@@ -681,7 +679,7 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
_ => StrokeJoin::default(),
|
||||
};
|
||||
let miter_limit = match parameters.value(stroke::MiterLimitInput) {
|
||||
Some(TaggedValue::Number(value)) => *value,
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 4.,
|
||||
};
|
||||
let paint_order = get_stroke_paint_order(layer, network_interface);
|
||||
@@ -690,7 +688,7 @@ pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNe
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match parameters.value(stroke::DashOffsetInput) {
|
||||
Some(TaggedValue::Number(value)) => *value,
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
@@ -780,7 +778,7 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::vector::stroke::WeightInput::INDEX,
|
||||
value: TaggedValue::Number(weight).into(),
|
||||
value: TaggedValue::F64(weight).into(),
|
||||
});
|
||||
} else if weight > 0. {
|
||||
let color = Some(Color::BLACK);
|
||||
|
||||
@@ -134,9 +134,9 @@ impl Arc {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::arc::IDENTIFIER).expect("Ellipse node does not exist");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::Number(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(270.), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(270.), false)),
|
||||
Some(NodeInput::value(TaggedValue::ArcType(arc_type), false)),
|
||||
])
|
||||
}
|
||||
@@ -173,7 +173,7 @@ impl Arc {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::arc::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
|
||||
|
||||
@@ -25,10 +25,10 @@ impl Arrow {
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Arrow node can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false)), // arrow_to
|
||||
Some(NodeInput::value(TaggedValue::Number(shaft_width), false)), // shaft_width
|
||||
Some(NodeInput::value(TaggedValue::Number(head_width), false)), // head_width
|
||||
Some(NodeInput::value(TaggedValue::Number(head_length), false)), // head_length
|
||||
Some(NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false)), // arrow_to
|
||||
Some(NodeInput::value(TaggedValue::F64(shaft_width), false)), // shaft_width
|
||||
Some(NodeInput::value(TaggedValue::F64(head_width), false)), // head_width
|
||||
Some(NodeInput::value(TaggedValue::F64(head_length), false)), // head_length
|
||||
])
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,7 @@ pub struct Circle;
|
||||
impl Circle {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::circle::IDENTIFIER).expect("Circle can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(0.), false))])
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(0.), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -107,7 +107,7 @@ impl Circle {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::circle::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
|
||||
|
||||
@@ -15,7 +15,7 @@ pub struct Ellipse;
|
||||
impl Ellipse {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::ellipse::IDENTIFIER).expect("Ellipse node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(0.5), false)), Some(NodeInput::value(TaggedValue::Number(0.5), false))])
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(0.5), false)), Some(NodeInput::value(TaggedValue::F64(0.5), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -38,11 +38,11 @@ impl Ellipse {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::ellipse::RadiusXInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius.x), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius.x), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::ellipse::RadiusYInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius.y), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius.y), false),
|
||||
});
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
|
||||
}
|
||||
|
||||
@@ -111,8 +111,8 @@ impl Polygon {
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Regular Polygon can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::Integer(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::I64(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -152,7 +152,7 @@ impl Polygon {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
|
||||
@@ -173,7 +173,7 @@ impl Polygon {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(&TaggedValue::Integer(n)) = node_inputs.get(1).unwrap().as_value() else {
|
||||
let Some(&TaggedValue::I64(n)) = node_inputs.get(1).unwrap().as_value() else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -185,7 +185,7 @@ impl Polygon {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::regular_polygon::SidesInput),
|
||||
input: NodeInput::value(TaggedValue::Integer(new_dimension), false),
|
||||
input: NodeInput::value(TaggedValue::I64(new_dimension), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ pub struct Rectangle;
|
||||
impl Rectangle {
|
||||
pub fn create_node() -> NodeTemplate {
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER).expect("Rectangle node can't be found");
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::Number(1.), false)), Some(NodeInput::value(TaggedValue::Number(1.), false))])
|
||||
node_type.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(1.), false)), Some(NodeInput::value(TaggedValue::F64(1.), false))])
|
||||
}
|
||||
|
||||
pub fn update_shape(
|
||||
@@ -38,11 +38,11 @@ impl Rectangle {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::rectangle::WidthInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size.x), false),
|
||||
input: NodeInput::value(TaggedValue::F64(size.x), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::rectangle::HeightInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size.y), false),
|
||||
input: NodeInput::value(TaggedValue::F64(size.y), false),
|
||||
});
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), DVec2::ONE));
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
|
||||
let sign_num = if end[1] > start[1] { 1. } else { -1. };
|
||||
let new_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
|
||||
if let Some(&TaggedValue::Integer(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput)
|
||||
if let Some(&TaggedValue::I64(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::regular_polygon::SidesInput)
|
||||
&& sides % 2 != 0
|
||||
{
|
||||
let Some(polygon_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::regular_polygon::IDENTIFIER)) else {
|
||||
@@ -220,12 +220,12 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(polygon_node_id, graphene_std::vector::generator_nodes::regular_polygon::RadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(sign_num * 0.5), false),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(&TaggedValue::Integer(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput)
|
||||
if let Some(&TaggedValue::I64(sides)) = new_layer.parameter_value(graphene_std::vector::generator_nodes::star::SidesInput)
|
||||
&& sides % 2 != 0
|
||||
{
|
||||
let Some(star_node_id) = new_layer.upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::star::IDENTIFIER)) else {
|
||||
@@ -234,11 +234,11 @@ pub fn update_radius_sign(end: DVec2, start: DVec2, layer: LayerNodeIdentifier,
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius1Input),
|
||||
input: NodeInput::value(TaggedValue::Number(sign_num * 0.5), false),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.5), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(star_node_id, graphene_std::vector::generator_nodes::star::Radius2Input),
|
||||
input: NodeInput::value(TaggedValue::Number(sign_num * 0.25), false),
|
||||
input: NodeInput::value(TaggedValue::F64(sign_num * 0.25), false),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -301,7 +301,7 @@ pub fn anchor_overlays(document: &DocumentMessageHandler, overlay_context: &mut
|
||||
pub fn extract_star_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(u32, f64, f64)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::star::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::Integer(sides)), Some(&TaggedValue::Number(radius_1)), Some(&TaggedValue::Number(radius_2))) =
|
||||
let (Some(&TaggedValue::I64(sides)), Some(&TaggedValue::F64(radius_1)), Some(&TaggedValue::F64(radius_2))) =
|
||||
(node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value(), node_inputs.get(3)?.as_value())
|
||||
else {
|
||||
return None;
|
||||
@@ -316,7 +316,7 @@ pub fn extract_polygon_parameters(layer: Option<LayerNodeIdentifier>, document:
|
||||
let node_inputs =
|
||||
NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::Integer(n)), Some(&TaggedValue::Number(radius))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value()) else {
|
||||
let (Some(&TaggedValue::I64(n)), Some(&TaggedValue::F64(radius))) = (node_inputs.get(1)?.as_value(), node_inputs.get(2)?.as_value()) else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -328,7 +328,7 @@ pub fn extract_polygon_parameters(layer: Option<LayerNodeIdentifier>, document:
|
||||
pub fn extract_arc_parameters(layer: Option<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> Option<(f64, f64, f64, ArcType)> {
|
||||
let node_inputs = NodeGraphLayer::new(layer?, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::arc::IDENTIFIER))?;
|
||||
|
||||
let (Some(&TaggedValue::Number(radius)), Some(&TaggedValue::Number(start_angle)), Some(&TaggedValue::Number(sweep_angle)), Some(&TaggedValue::ArcType(arc_type))) = (
|
||||
let (Some(&TaggedValue::F64(radius)), Some(&TaggedValue::F64(start_angle)), Some(&TaggedValue::F64(sweep_angle)), Some(&TaggedValue::ArcType(arc_type))) = (
|
||||
node_inputs.get(1)?.as_value(),
|
||||
node_inputs.get(2)?.as_value(),
|
||||
node_inputs.get(3)?.as_value(),
|
||||
@@ -349,11 +349,11 @@ pub fn extract_spiral_parameters(layer: LayerNodeIdentifier, document: &Document
|
||||
|
||||
let (
|
||||
Some(&TaggedValue::SpiralType(spiral_type)),
|
||||
Some(&TaggedValue::Number(start_angle)),
|
||||
Some(&TaggedValue::Number(inner_radius)),
|
||||
Some(&TaggedValue::Number(outer_radius)),
|
||||
Some(&TaggedValue::Number(turns)),
|
||||
Some(&TaggedValue::Number(angle_resolution)),
|
||||
Some(&TaggedValue::F64(start_angle)),
|
||||
Some(&TaggedValue::F64(inner_radius)),
|
||||
Some(&TaggedValue::F64(outer_radius)),
|
||||
Some(&TaggedValue::F64(turns)),
|
||||
Some(&TaggedValue::F64(angle_resolution)),
|
||||
) = (
|
||||
parameters.value(SpiralTypeInput),
|
||||
parameters.value(StartAngleInput),
|
||||
@@ -397,7 +397,7 @@ pub fn arc_end_points_ignore_layer(radius: f64, start_angle: f64, sweep_angle: f
|
||||
pub fn extract_circle_radius(layer: LayerNodeIdentifier, document: &DocumentMessageHandler) -> Option<f64> {
|
||||
let node_inputs = NodeGraphLayer::new(layer, &document.network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::circle::IDENTIFIER))?;
|
||||
|
||||
let Some(&TaggedValue::Number(radius)) = node_inputs.get(1)?.as_value() else {
|
||||
let Some(&TaggedValue::F64(radius)) = node_inputs.get(1)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -594,7 +594,7 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
|
||||
let parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(IDENTIFIER)?;
|
||||
|
||||
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::DVec2(spacing)), Some(&TaggedValue::Integer(columns)), Some(&TaggedValue::Integer(rows)), Some(&TaggedValue::DVec2(angles))) = (
|
||||
let (Some(&TaggedValue::GridType(grid_type)), Some(&TaggedValue::DVec2(spacing)), Some(&TaggedValue::I64(columns)), Some(&TaggedValue::I64(rows)), Some(&TaggedValue::DVec2(angles))) = (
|
||||
parameters.value(GridTypeInput),
|
||||
parameters.value(SpacingInput),
|
||||
parameters.value(ColumnsInput),
|
||||
|
||||
@@ -105,11 +105,11 @@ impl Spiral {
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::SpiralType(spiral_type), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(turns), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(inner_radius), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.1), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(90.), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(turns), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(inner_radius), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.1), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(90.), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ impl Spiral {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, OuterRadiusInput),
|
||||
input: NodeInput::value(TaggedValue::Number(new_radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(new_radius), false),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ impl Spiral {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(&TaggedValue::Number(mut turns)) = parameters.value(TurnsInput) else {
|
||||
let Some(&TaggedValue::F64(mut turns)) = parameters.value(TurnsInput) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -189,7 +189,7 @@ impl Spiral {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, TurnsInput),
|
||||
input: NodeInput::value(TaggedValue::Number(turns), false),
|
||||
input: NodeInput::value(TaggedValue::F64(turns), false),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -111,9 +111,9 @@ impl Star {
|
||||
let node_type = resolve_document_node_type(&identifier).expect("Star node can't be found");
|
||||
node_type.node_template_input_override([
|
||||
None,
|
||||
Some(NodeInput::value(TaggedValue::Integer(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::Number(0.25), false)),
|
||||
Some(NodeInput::value(TaggedValue::I64(vertices as i64), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.5), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(0.25), false)),
|
||||
])
|
||||
}
|
||||
|
||||
@@ -153,12 +153,12 @@ impl Star {
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::star::Radius1Input),
|
||||
input: NodeInput::value(TaggedValue::Number(radius), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius), false),
|
||||
});
|
||||
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::vector::generator_nodes::star::Radius2Input),
|
||||
input: NodeInput::value(TaggedValue::Number(radius / 2.), false),
|
||||
input: NodeInput::value(TaggedValue::F64(radius / 2.), false),
|
||||
});
|
||||
|
||||
responses.add(window_aligned_transform_set(document, layer, start.midpoint(end), aspect));
|
||||
|
||||
@@ -196,7 +196,7 @@ pub fn apply_stroke_join(drawing: &mut DrawingToolState, join: StrokeJoin, docum
|
||||
|
||||
pub fn apply_miter_limit(drawing: &mut DrawingToolState, limit: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.miter_limit = Some(limit);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::MiterLimitInput, TaggedValue::Number(limit), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::MiterLimitInput, TaggedValue::F64(limit), responses);
|
||||
}
|
||||
|
||||
pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
@@ -216,5 +216,5 @@ pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, doc
|
||||
|
||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_offset = Some(offset);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::DashOffsetInput, TaggedValue::Number(offset), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(document, graphene_std::vector::stroke::DashOffsetInput, TaggedValue::F64(offset), responses);
|
||||
}
|
||||
@@ -269,13 +269,13 @@ impl BrushTool {
|
||||
return;
|
||||
};
|
||||
let value = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||
if let Some(TaggedValue::Number(diameter)) = value(brush_strokes::DiameterInput::INDEX) {
|
||||
if let Some(TaggedValue::F64(diameter)) = value(brush_strokes::DiameterInput::INDEX) {
|
||||
self.options.diameter = if self.options.scale_with_viewport { *diameter * viewport_zoom(document) } else { *diameter };
|
||||
}
|
||||
if let Some(TaggedValue::Number(hardness)) = value(brush_strokes::HardnessInput::INDEX) {
|
||||
if let Some(TaggedValue::F64(hardness)) = value(brush_strokes::HardnessInput::INDEX) {
|
||||
self.options.hardness = *hardness;
|
||||
}
|
||||
if let Some(TaggedValue::Number(flow)) = value(brush_strokes::FlowInput::INDEX) {
|
||||
if let Some(TaggedValue::F64(flow)) = value(brush_strokes::FlowInput::INDEX) {
|
||||
self.options.flow = *flow;
|
||||
}
|
||||
if let Some(TaggedValue::Color(color)) = value(brush_strokes::ColorInput::INDEX)
|
||||
@@ -387,11 +387,11 @@ impl BrushToolData {
|
||||
};
|
||||
let value = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||
matches!(value(brush_strokes::ColorInput::INDEX), Some(TaggedValue::Color(color)) if *color == options.active_color())
|
||||
&& matches!(value(brush_strokes::DiameterInput::INDEX), Some(TaggedValue::Number(diameter)) if {
|
||||
&& matches!(value(brush_strokes::DiameterInput::INDEX), Some(TaggedValue::F64(diameter)) if {
|
||||
let target = options.stroke_diameter(document);
|
||||
(*diameter - target).abs() <= diameter.abs().max(target.abs()) * (f64::EPSILON * 8.)
|
||||
}) && matches!(value(brush_strokes::HardnessInput::INDEX), Some(TaggedValue::Number(hardness)) if *hardness == options.hardness)
|
||||
&& matches!(value(brush_strokes::FlowInput::INDEX), Some(TaggedValue::Number(flow)) if *flow == options.flow)
|
||||
}) && matches!(value(brush_strokes::HardnessInput::INDEX), Some(TaggedValue::F64(hardness)) if *hardness == options.hardness)
|
||||
&& matches!(value(brush_strokes::FlowInput::INDEX), Some(TaggedValue::F64(flow)) if *flow == options.flow)
|
||||
}
|
||||
|
||||
fn push_sample(&mut self, position: DVec2, pressure: Option<f64>, elapsed_milliseconds: f64) {
|
||||
|
||||
@@ -431,7 +431,7 @@ fn read_transform_node_value(inputs: &[graph_craft::document::NodeInput]) -> DAf
|
||||
let rotation_degrees = inputs
|
||||
.get(2)
|
||||
.and_then(|input| input.as_value())
|
||||
.and_then(|value| if let TaggedValue::Number(v) = value { Some(*v) } else { None })
|
||||
.and_then(|value| if let TaggedValue::F64(v) = value { Some(*v) } else { None })
|
||||
.unwrap_or(0.);
|
||||
let scale = inputs
|
||||
.get(3)
|
||||
|
||||
@@ -349,7 +349,7 @@ fn sync_shape_options_from_selection(options: &mut ShapeToolOptions, tool_data:
|
||||
} else {
|
||||
ParameterRef::from(star::SidesInput)
|
||||
};
|
||||
if let Some(&TaggedValue::Integer(sides)) = layer_view.parameter_value(sides_parameter)
|
||||
if let Some(&TaggedValue::I64(sides)) = layer_view.parameter_value(sides_parameter)
|
||||
&& options.vertices != sides.max(0) as u32
|
||||
{
|
||||
options.vertices = sides.max(0) as u32;
|
||||
@@ -371,7 +371,7 @@ fn sync_shape_options_from_selection(options: &mut ShapeToolOptions, tool_data:
|
||||
options.spiral_type = spiral_type;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(&TaggedValue::Number(turns)) = layer_view.parameter_value(spiral::TurnsInput)
|
||||
if let Some(&TaggedValue::F64(turns)) = layer_view.parameter_value(spiral::TurnsInput)
|
||||
&& options.turns != turns
|
||||
{
|
||||
options.turns = turns;
|
||||
@@ -387,19 +387,19 @@ fn sync_shape_options_from_selection(options: &mut ShapeToolOptions, tool_data:
|
||||
}
|
||||
}
|
||||
ShapeType::Arrow => {
|
||||
if let Some(&TaggedValue::Number(shaft)) = layer_view.parameter_value(arrow::ShaftWidthInput)
|
||||
if let Some(&TaggedValue::F64(shaft)) = layer_view.parameter_value(arrow::ShaftWidthInput)
|
||||
&& options.arrow_shaft_width != shaft
|
||||
{
|
||||
options.arrow_shaft_width = shaft;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(&TaggedValue::Number(head_w)) = layer_view.parameter_value(arrow::HeadWidthInput)
|
||||
if let Some(&TaggedValue::F64(head_w)) = layer_view.parameter_value(arrow::HeadWidthInput)
|
||||
&& options.arrow_head_width != head_w
|
||||
{
|
||||
options.arrow_head_width = head_w;
|
||||
changed = true;
|
||||
}
|
||||
if let Some(&TaggedValue::Number(head_l)) = layer_view.parameter_value(arrow::HeadLengthInput)
|
||||
if let Some(&TaggedValue::F64(head_l)) = layer_view.parameter_value(arrow::HeadLengthInput)
|
||||
&& options.arrow_head_length != head_l
|
||||
{
|
||||
options.arrow_head_length = head_l;
|
||||
@@ -622,7 +622,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
ShapeType::Star => ParameterRef::from(star::SidesInput),
|
||||
_ => return,
|
||||
};
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, sides_parameter, TaggedValue::Integer(vertices as i64), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, sides_parameter, TaggedValue::I64(vertices as i64), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::ArcType(arc_type) => {
|
||||
self.options.arc_type = arc_type;
|
||||
@@ -634,7 +634,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
}
|
||||
ShapeOptionsUpdate::Turns(turns) => {
|
||||
self.options.turns = turns;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, spiral::TurnsInput, TaggedValue::Number(turns), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, spiral::TurnsInput, TaggedValue::F64(turns), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::GridType(grid_type) => {
|
||||
self.options.grid_type = grid_type;
|
||||
@@ -642,15 +642,15 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
}
|
||||
ShapeOptionsUpdate::ArrowShaftWidth(shaft_width) => {
|
||||
self.options.arrow_shaft_width = shaft_width;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::ShaftWidthInput, TaggedValue::Number(shaft_width), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::ShaftWidthInput, TaggedValue::F64(shaft_width), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::ArrowHeadWidth(head_width) => {
|
||||
self.options.arrow_head_width = head_width;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadWidthInput, TaggedValue::Number(head_width), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadWidthInput, TaggedValue::F64(head_width), responses);
|
||||
}
|
||||
ShapeOptionsUpdate::ArrowHeadLength(head_length) => {
|
||||
self.options.arrow_head_length = head_length;
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadLengthInput, TaggedValue::Number(head_length), responses);
|
||||
graph_modification_utils::set_parameter_for_selected_layers(context.document, arrow::HeadLengthInput, TaggedValue::F64(head_length), responses);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -337,7 +337,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
responses.add(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: graphene_std::text::text::SizeInput::INDEX,
|
||||
value: TaggedValue::Number(font_size).into(),
|
||||
value: TaggedValue::F64(font_size).into(),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -880,7 +880,7 @@ impl Fsm for TextToolFsmState {
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::MaxWidthInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size_layer.x), false),
|
||||
input: NodeInput::value(TaggedValue::F64(size_layer.x), false),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::HasMaxHeightInput),
|
||||
@@ -888,7 +888,7 @@ impl Fsm for TextToolFsmState {
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetInput {
|
||||
input_connector: InputConnector::node(node_id, graphene_std::text::text::MaxHeightInput),
|
||||
input: NodeInput::value(TaggedValue::Number(size_layer.y), false),
|
||||
input: NodeInput::value(TaggedValue::F64(size_layer.y), false),
|
||||
});
|
||||
responses.add(GraphOperationMessage::TransformSet {
|
||||
layer: dragging_layer.id,
|
||||
|
||||
@@ -138,7 +138,7 @@ impl NodeGraphExecutor {
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
// We should always invalidate the cache.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
let mut network = document.network_interface.network_to_evaluate();
|
||||
let instrumented = Instrumented::new(&mut network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
@@ -158,7 +158,7 @@ impl NodeGraphExecutor {
|
||||
let network_hash = document.network_interface.network_hash();
|
||||
// Refresh the graph when it changes or the inspect node changes
|
||||
if network_hash != self.node_graph_hash || self.previous_node_to_inspect != node_to_inspect || ignore_hash {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let network = document.network_interface.network_to_evaluate();
|
||||
self.previous_node_to_inspect.clone_from(&node_to_inspect);
|
||||
self.node_graph_hash = network_hash;
|
||||
|
||||
@@ -286,7 +286,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
/// Evaluates a node graph for export
|
||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, mut export_config: ExportConfig) -> Result<(), String> {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let network = document.network_interface.network_to_evaluate();
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
let export_format = if export_config.file_type == FileType::Svg {
|
||||
@@ -522,7 +522,7 @@ impl NodeGraphExecutor {
|
||||
scale: f64,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
let mut network = document.network_interface.network_to_evaluate();
|
||||
|
||||
// On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough.
|
||||
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
|
||||
|
||||
+4
-10
@@ -39,7 +39,7 @@ Only the definitions of nodes built from a nested network, such as the empty "Cu
|
||||
|
||||
Each input of a node is a `NodeInput`: either a wire from another node or a constant `TaggedValue` (a dynamically typed value that serializes with serde) paired with an exposed flag, which is whether the input is shown as a connector in the node graph by default. Both come from the function signature. A parameter's type picks the `TaggedValue` variant, `#[default(...)]` sets the value a new node starts with and the value an input falls back to when its wire is disconnected, and `#[expose]` shows a secondary input's connector, while the primary input always has one. In the Opacity node, `content` is the primary input while `opacity` and `fill` appear only in the Properties panel by default, keeping the graph uncluttered.
|
||||
|
||||
The Properties panel is generated from the same signature, which can be seen by selecting the Opacity node in the graph. A number parameter becomes a number input whose bounds and slider come from `#[soft]`, `#[hard]`, and `#[range]` (see [Additional Macro Options](#additional-macro-options)), and `#[unit(...)]` sets the `%` suffix here. A `bool` becomes a checkbox and a `ChoiceType` enum becomes a dropdown. When the generated widget isn't right, `#[widget(ParsedWidgetOverride::Hidden)]` hides it and `#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]` names a hand-written widget function in `node_properties.rs`, which is how the Opacity node pairs each percentage with the checkbox that enables it.
|
||||
The Properties panel is generated from the same signature, which can be seen by selecting the Opacity node in the graph. A number parameter becomes a number input whose bounds and slider come from `#[soft]`, `#[hard]`, and `#[range]` (see [Additional Macro Options](#additional-macro-options)), or from a typedef such as `Percentage`, which stands for a 0 to 100 `%` slider. A `bool` becomes a checkbox and a `ChoiceType` enum becomes a dropdown. When the generated widget isn't right, `#[widget(ParsedWidgetOverride::Hidden)]` hides it and `#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]` names a hand-written widget function in `node_properties.rs`, which is how the Opacity node pairs each percentage with the checkbox that enables it.
|
||||
|
||||
## Graphene (proto node executor)
|
||||
|
||||
@@ -95,19 +95,13 @@ fn opacity<T>(
|
||||
#[default(true)]
|
||||
has_opacity: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
opacity: Item<Percentage>,
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_fill: Item<bool>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
fill: Item<f64>,
|
||||
fill: Item<Percentage>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
let (has_opacity, opacity, has_fill, fill) = (*has_opacity.element(), *opacity.element(), *has_fill.element(), *fill.element());
|
||||
@@ -128,7 +122,7 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the properties are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, and `range` attributes to influence how the properties are generated. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -1400,7 +1400,7 @@ mod test {
|
||||
nodes: [(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::value(TaggedValue::I64(2), false)],
|
||||
implementation: DocumentNodeImplementation::Network(add_network()),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1479,7 +1479,7 @@ mod test {
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
|
||||
call_argument: concrete!(core_types::Context),
|
||||
construction_args: ConstructionArgs::Value(TaggedValue::Integer(2).into()),
|
||||
construction_args: ConstructionArgs::Value(TaggedValue::I64(2).into()),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(1), NodeId(4)]),
|
||||
inputs_source: HashMap::new(),
|
||||
@@ -1522,7 +1522,7 @@ mod test {
|
||||
(
|
||||
NodeId(14),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::I64(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(4)]),
|
||||
@@ -1573,7 +1573,7 @@ mod test {
|
||||
(
|
||||
NodeId(14),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::I64(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(1), NodeId(4)]),
|
||||
@@ -1639,7 +1639,7 @@ mod test {
|
||||
(
|
||||
NodeId(1),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(1.), false), NodeInput::value(TaggedValue::Number(2.), false)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::F64(1.), false), NodeInput::value(TaggedValue::F64(2.), false)],
|
||||
implementation: DocumentNodeImplementation::Network(two_node_passthrough()),
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -47,7 +47,7 @@ macro_rules! for_each_item_type_default {
|
||||
}
|
||||
|
||||
/// List element types routed through [`TaggedValue::TypeDefault`], stored as the structural [`Type::List`] form.
|
||||
/// `List<f64>` is absent because it stores as `TaggedValue::Numbers`.
|
||||
/// `List<f64>` is absent because it stores as `TaggedValue::F64Array`.
|
||||
macro_rules! for_each_list_type_default {
|
||||
($action:ident) => {
|
||||
$action!(Graphic);
|
||||
@@ -83,9 +83,9 @@ macro_rules! tagged_value {
|
||||
/// (Old documents stored a bare `TypeDescriptor` payload, routed to this shape by `deserialize_tagged_value_with_legacy_migration`.)
|
||||
TypeDefault(Type),
|
||||
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
|
||||
Numbers(Vec<f64>),
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_f64_array")] // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
|
||||
F64Array(Vec<f64>),
|
||||
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
|
||||
DashPattern(Vec<f64>),
|
||||
/// Stored compactly as a `Vec<f64>` of corner values, materializes as an `Item<BoxCorners>` at runtime via `to_dynany`/`to_any`.
|
||||
@@ -136,7 +136,7 @@ macro_rules! tagged_value {
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => { x.cache_hash(state) }),*
|
||||
Self::Numbers(values) => values.cache_hash(state),
|
||||
Self::F64Array(values) => values.cache_hash(state),
|
||||
Self::DashPattern(lengths) => lengths.cache_hash(state),
|
||||
Self::BoxCorners(values) => values.cache_hash(state),
|
||||
Self::TransferCurve(points) => points.cache_hash(state),
|
||||
@@ -198,7 +198,7 @@ macro_rules! tagged_value {
|
||||
}
|
||||
Self::from_type_or_none(&td).to_dynany()
|
||||
}
|
||||
Self::Numbers(values) => {
|
||||
Self::F64Array(values) => {
|
||||
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Box::new(list)
|
||||
}
|
||||
@@ -266,7 +266,7 @@ macro_rules! tagged_value {
|
||||
}
|
||||
Self::from_type_or_none(&td).to_any()
|
||||
}
|
||||
Self::Numbers(values) => {
|
||||
Self::F64Array(values) => {
|
||||
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
|
||||
Arc::new(list)
|
||||
}
|
||||
@@ -303,7 +303,7 @@ macro_rules! tagged_value {
|
||||
// ===============
|
||||
Self::None => concrete!(()),
|
||||
Self::TypeDefault(td) => td.clone(),
|
||||
Self::Numbers(_) => list!(f64),
|
||||
Self::F64Array(_) => list!(f64),
|
||||
Self::DashPattern(_) => item!(DashPattern),
|
||||
Self::BoxCorners(_) => item!(BoxCorners),
|
||||
Self::TransferCurve(_) => item!(TransferCurve),
|
||||
@@ -340,8 +340,8 @@ macro_rules! tagged_value {
|
||||
// ===============
|
||||
// The manual variants convert from both their payload and wire forms, with the newtypes flattening to their stored `Vec<f64>` form
|
||||
x if x == TypeId::of::<()>() => Ok(TaggedValue::None),
|
||||
x if x == TypeId::of::<Vec<f64>>() => Ok(TaggedValue::Numbers(*downcast(input).unwrap())),
|
||||
x if x == TypeId::of::<List<f64>>() => Ok(TaggedValue::Numbers(downcast::<List<f64>>(input).unwrap().iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<Vec<f64>>() => Ok(TaggedValue::F64Array(*downcast(input).unwrap())),
|
||||
x if x == TypeId::of::<List<f64>>() => Ok(TaggedValue::F64Array(downcast::<List<f64>>(input).unwrap().iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<DashPattern>() => Ok(TaggedValue::DashPattern(downcast::<DashPattern>(input).unwrap().0.iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<Item<DashPattern>>() => Ok(TaggedValue::DashPattern(downcast::<Item<DashPattern>>(input).unwrap().into_element().0.iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<BoxCorners>() => Ok(TaggedValue::BoxCorners(downcast::<BoxCorners>(input).unwrap().0.iter_element_values().copied().collect())),
|
||||
@@ -376,8 +376,8 @@ macro_rules! tagged_value {
|
||||
// ===============
|
||||
// The manual variants convert from both their payload and wire forms, with the newtypes flattening to their stored `Vec<f64>` form
|
||||
x if x == TypeId::of::<()>() => Ok(TaggedValue::None),
|
||||
x if x == TypeId::of::<Vec<f64>>() => Ok(TaggedValue::Numbers(input.downcast_ref::<Vec<f64>>().unwrap().clone())),
|
||||
x if x == TypeId::of::<List<f64>>() => Ok(TaggedValue::Numbers(input.downcast_ref::<List<f64>>().unwrap().iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<Vec<f64>>() => Ok(TaggedValue::F64Array(input.downcast_ref::<Vec<f64>>().unwrap().clone())),
|
||||
x if x == TypeId::of::<List<f64>>() => Ok(TaggedValue::F64Array(input.downcast_ref::<List<f64>>().unwrap().iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<DashPattern>() => Ok(TaggedValue::DashPattern(input.downcast_ref::<DashPattern>().unwrap().0.iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<Item<DashPattern>>() => Ok(TaggedValue::DashPattern(input.downcast_ref::<Item<DashPattern>>().unwrap().element().0.iter_element_values().copied().collect())),
|
||||
x if x == TypeId::of::<BoxCorners>() => Ok(TaggedValue::BoxCorners(input.downcast_ref::<BoxCorners>().unwrap().0.iter_element_values().copied().collect())),
|
||||
@@ -439,10 +439,10 @@ macro_rules! tagged_value {
|
||||
for_each_item_type_default!(check);
|
||||
None
|
||||
}),
|
||||
// Structural lists match by element; `List<f64>` stays the dedicated `Numbers` variant
|
||||
// Structural lists match by element; `List<f64>` stays the dedicated `F64Array` variant
|
||||
Type::List(element) => {
|
||||
if **element == concrete!(f64) {
|
||||
return Some(TaggedValue::Numbers(Vec::new()));
|
||||
return Some(TaggedValue::F64Array(Vec::new()));
|
||||
}
|
||||
if **element == concrete!(Stroke) {
|
||||
return Some(TaggedValue::Strokes(Vec::new()));
|
||||
@@ -469,7 +469,7 @@ macro_rules! tagged_value {
|
||||
// ===============
|
||||
Self::None => "()".to_string(),
|
||||
Self::TypeDefault(td) => format!("TypeDefault({td})"),
|
||||
Self::Numbers(values) => format!("Numbers({values:?})"),
|
||||
Self::F64Array(values) => format!("F64Array({values:?})"),
|
||||
Self::DashPattern(lengths) => format!("DashPattern({lengths:?})"),
|
||||
Self::BoxCorners(values) => format!("BoxCorners({values:?})"),
|
||||
Self::TransferCurve(points) => format!("TransferCurve({points:?})"),
|
||||
@@ -519,11 +519,11 @@ tagged_value! {
|
||||
// ===============
|
||||
// PRIMITIVE TYPES
|
||||
// ===============
|
||||
#[serde(alias = "F64", alias = "F32")] // TODO: Eventually remove this document upgrade code
|
||||
Number(f64),
|
||||
#[serde(alias = "F32")] // TODO: Eventually remove this document upgrade code
|
||||
F64(f64),
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_i64")] // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "I64", alias = "U32", alias = "U64")]
|
||||
Integer(i64),
|
||||
#[serde(alias = "U32", alias = "U64")]
|
||||
I64(i64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
#[serde(alias = "IVec2", alias = "UVec2", alias = "Vec2")]
|
||||
@@ -604,8 +604,8 @@ impl TaggedValue {
|
||||
match self {
|
||||
TaggedValue::None => "()".to_string(),
|
||||
TaggedValue::String(x) => format!("\"{x}\""),
|
||||
TaggedValue::Integer(x) => x.to_string() + "_i64",
|
||||
TaggedValue::Number(x) => x.to_string() + "_f64",
|
||||
TaggedValue::I64(x) => x.to_string() + "_i64",
|
||||
TaggedValue::F64(x) => x.to_string() + "_f64",
|
||||
TaggedValue::Bool(x) => x.to_string(),
|
||||
TaggedValue::BlendMode(x) => "BlendMode::".to_string() + &x.to_string(),
|
||||
_ => panic!("Cannot convert to primitive string"),
|
||||
@@ -700,8 +700,8 @@ impl TaggedValue {
|
||||
let ty = match () {
|
||||
() if ty == TypeId::of::<()>() => TaggedValue::None,
|
||||
() if ty == TypeId::of::<String>() => TaggedValue::String(string.into()),
|
||||
() if ty == TypeId::of::<f64>() => FromStr::from_str(string).map(TaggedValue::Number).ok()?,
|
||||
() if ty == TypeId::of::<i64>() => FromStr::from_str(string).map(TaggedValue::Integer).ok()?,
|
||||
() if ty == TypeId::of::<f64>() => FromStr::from_str(string).map(TaggedValue::F64).ok()?,
|
||||
() if ty == TypeId::of::<i64>() => FromStr::from_str(string).map(TaggedValue::I64).ok()?,
|
||||
() if ty == TypeId::of::<DVec2>() => to_dvec2(string).map(TaggedValue::DVec2)?,
|
||||
() if ty == TypeId::of::<bool>() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?,
|
||||
() if ty == TypeId::of::<Color>() => to_color(string).map(TaggedValue::Color)?,
|
||||
@@ -854,8 +854,8 @@ impl Display for TaggedValue {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
TaggedValue::String(x) => f.write_str(x),
|
||||
TaggedValue::Integer(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::Number(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::I64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::F64(x) => f.write_fmt(format_args!("{x}")),
|
||||
TaggedValue::Bool(x) => f.write_fmt(format_args!("{x}")),
|
||||
_ => panic!("Cannot convert to string"),
|
||||
}
|
||||
@@ -1169,19 +1169,19 @@ mod retired_numeric_variants {
|
||||
|
||||
#[test]
|
||||
fn unsigned_tags_read_as_integers() {
|
||||
assert_eq!(load(serde_json::json!({ "U32": 7 })), TaggedValue::Integer(7));
|
||||
assert_eq!(load(serde_json::json!({ "U64": 9 })), TaggedValue::Integer(9));
|
||||
assert_eq!(load(serde_json::json!({ "U32": 7 })), TaggedValue::I64(7));
|
||||
assert_eq!(load(serde_json::json!({ "U64": 9 })), TaggedValue::I64(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsigned_value_past_the_signed_range_saturates() {
|
||||
assert_eq!(load(serde_json::json!({ "U64": u64::MAX })), TaggedValue::Integer(i64::MAX));
|
||||
assert_eq!(load(serde_json::json!({ "U64": u64::MAX })), TaggedValue::I64(i64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_32_bit_float_tag_reads_the_digits_it_stored() {
|
||||
// The stored text is what the author chose, so reading it as f64 beats widening the 32-bit value it parsed into
|
||||
assert_eq!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2));
|
||||
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64));
|
||||
assert_eq!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::F64(2.2));
|
||||
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::F64(2.2_f32 as f64));
|
||||
}
|
||||
}
|
||||
@@ -140,7 +140,7 @@ impl Default for ProtoNode {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
identifier: graphene_core::ops::passthrough::IDENTIFIER,
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::Integer(0).into()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::I64(0).into()),
|
||||
call_argument: concrete!(()),
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
@@ -1109,7 +1109,7 @@ mod test {
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::new("value"),
|
||||
call_argument: concrete!(()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::Integer(2).into()),
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::I64(2).into()),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
|
||||
@@ -9,12 +9,11 @@ use core_types::{ContextDependencies, Type};
|
||||
/// states: a delta derived by comparison would assert values nobody wrote, and its timestamp would
|
||||
/// win against a concurrent peer that did write them.
|
||||
///
|
||||
/// A node's inputs are addressed by index, which is stable only while its arity is. Changing arity is
|
||||
/// therefore a [`SetInputs`](Self::SetInputs), which restates the whole list, rather than a
|
||||
/// [`SetInput`](Self::SetInput) naming one index.
|
||||
/// A node's inputs are addressed by index, which is stable only while its arity is. Changing arity
|
||||
/// is therefore a `ReplaceNode`, not an edit to the input list.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum RuntimeDelta {
|
||||
/// The node's nested network, if it implements one, rides inside the [`DocumentNode`].
|
||||
/// The node's nested network, if it implements one, rides inside the `DocumentNode`.
|
||||
AddNode {
|
||||
network_path: Vec<NodeId>,
|
||||
node_id: NodeId,
|
||||
@@ -37,7 +36,7 @@ pub enum RuntimeDelta {
|
||||
input: NodeInput,
|
||||
},
|
||||
/// A node's whole input list, which is how a change to the number or order of its slots is
|
||||
/// expressed, since [`SetInput`](Self::SetInput) addresses one index and cannot move the others.
|
||||
/// expressed, since `SetInput` addresses one index and cannot move the others.
|
||||
SetInputs {
|
||||
network_path: Vec<NodeId>,
|
||||
node_id: NodeId,
|
||||
@@ -54,13 +53,13 @@ pub enum RuntimeDelta {
|
||||
node_id: NodeId,
|
||||
visible: bool,
|
||||
},
|
||||
/// The [`Type`] of argument the node can be evaluated with.
|
||||
/// The type of argument the node can be evaluated with.
|
||||
SetCallArgument {
|
||||
network_path: Vec<NodeId>,
|
||||
node_id: NodeId,
|
||||
call_argument: Type,
|
||||
},
|
||||
/// The Extract and Inject annotations the node declares for the Context, as [`ContextDependencies`].
|
||||
/// The Extract and Inject annotations the node declares for the Context.
|
||||
SetContextFeatures {
|
||||
network_path: Vec<NodeId>,
|
||||
node_id: NodeId,
|
||||
|
||||
@@ -9,7 +9,7 @@ use graphene_std::vector::Vector;
|
||||
#[test]
|
||||
fn push_node_sync() {
|
||||
let mut tree = BorrowTree::default();
|
||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
|
||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::I64(2_i64).into()), vec![]);
|
||||
let context = TypingContext::default();
|
||||
let future = tree.push_node(NodeId(0), val_1_protonode, &context);
|
||||
futures::executor::block_on(future).unwrap();
|
||||
@@ -108,7 +108,7 @@ fn rank_0_content_promotes_through_the_layer_coercion_path() {
|
||||
/// Builds a network feeding the given content plus an f64 distance value into Offset Points, whose distance input is ranked `Item<f64>`.
|
||||
fn offset_points_network(content: TaggedValue) -> ProtoNetwork {
|
||||
let content_node = ProtoNode::value(ConstructionArgs::Value(content.into()), vec![NodeId(0)]);
|
||||
let distance_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(10.).into()), vec![NodeId(1)]);
|
||||
let distance_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(10.).into()), vec![NodeId(1)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
@@ -187,7 +187,7 @@ fn transform_network(content: TaggedValue, rotation: TaggedValue) -> ProtoNetwor
|
||||
fn transform_composes_onto_item_wire() {
|
||||
use glam::{DAffine2, DVec2};
|
||||
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::Number(0.));
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64(0.));
|
||||
let output = network.output;
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&network).expect("Transform should resolve its rank-0 variant");
|
||||
@@ -205,7 +205,7 @@ fn transform_composes_onto_item_wire() {
|
||||
fn transform_broadcasts_item_content_across_a_framed_parameter() {
|
||||
use glam::DAffine2;
|
||||
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::Numbers(vec![0., 90.]));
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64Array(vec![0., 90.]));
|
||||
let output = network.output;
|
||||
let mut typing_context = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
|
||||
typing_context
|
||||
@@ -230,7 +230,7 @@ fn generator_frames_over_a_list_parameter() {
|
||||
// A `()` generator (Circle) fed a `List<f64>` radius should frame into one circle per slot
|
||||
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
|
||||
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20., 30.]).into()), vec![NodeId(1)]);
|
||||
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
|
||||
@@ -294,7 +294,7 @@ fn value_wires_materialize_as_items_at_resolution() {
|
||||
let values = [
|
||||
TaggedValue::DAffine2(DAffine2::IDENTITY),
|
||||
TaggedValue::DVec2(DVec2::new(7., 0.)),
|
||||
TaggedValue::Number(0.),
|
||||
TaggedValue::F64(0.),
|
||||
TaggedValue::DVec2(DVec2::ONE),
|
||||
TaggedValue::DVec2(DVec2::ZERO),
|
||||
];
|
||||
@@ -413,7 +413,7 @@ fn as_graphic_converts_a_vector_list_element_wise() {
|
||||
|
||||
// Two radii frame the Circle generator into a two-element `List<Vector>`, the wire As Graphic then converts
|
||||
let primary = ProtoNode::value(ConstructionArgs::Value(TaggedValue::None.into()), vec![NodeId(0)]);
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![10., 20.]).into()), vec![NodeId(1)]);
|
||||
let radii = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![10., 20.]).into()), vec![NodeId(1)]);
|
||||
|
||||
let mut radius_adapter = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(1)]), vec![NodeId(2)]);
|
||||
radius_adapter.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
@@ -497,7 +497,7 @@ fn gradient_value_embeds_through_the_graphic_input_adapter() {
|
||||
// A scalar wire feeding a `DVec2` connector splats into both axes through the input adapter's `Convert` row
|
||||
#[test]
|
||||
fn number_value_splats_through_the_vec2_input_adapter() {
|
||||
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(-60.).into()), vec![NodeId(0)]);
|
||||
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(-60.).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<DVec2>");
|
||||
@@ -519,7 +519,7 @@ fn number_value_splats_through_the_vec2_input_adapter() {
|
||||
// A scalar wire feeding a `String` connector formats as text through the input adapter's `Convert` row
|
||||
#[test]
|
||||
fn number_value_formats_through_the_string_input_adapter() {
|
||||
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(42.).into()), vec![NodeId(0)]);
|
||||
let number_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(42.).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<String>");
|
||||
@@ -591,7 +591,7 @@ fn bool_value_formats_through_the_string_input_adapter() {
|
||||
fn list_wire_erases_through_the_list_dyn_input_adapter() {
|
||||
use core_types::list::ListDyn;
|
||||
|
||||
let list_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![1., 2., 3.]).into()), vec![NodeId(0)]);
|
||||
let list_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<ListDyn>");
|
||||
@@ -613,7 +613,7 @@ fn list_wire_erases_through_the_list_dyn_input_adapter() {
|
||||
|
||||
#[test]
|
||||
fn value_wire_passes_through_the_input_adapter_as_item() {
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(3.).into()), vec![NodeId(0)]);
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
|
||||
|
||||
let mut input_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
input_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<f64>");
|
||||
@@ -663,7 +663,7 @@ fn modification_value_rides_the_item_wire_through_its_input_adapter() {
|
||||
fn item_wire_boxes_into_the_attribute_value_connector() {
|
||||
use graphene_std::list::AttributeValueDyn;
|
||||
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Number(3.).into()), vec![NodeId(0)]);
|
||||
let value_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(3.).into()), vec![NodeId(0)]);
|
||||
let mut attribute_adapter_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0)]), vec![NodeId(1)]);
|
||||
attribute_adapter_node.identifier = ProtoNodeIdentifier::new("input_adapter<AttributeValueDyn>");
|
||||
|
||||
@@ -747,8 +747,8 @@ fn expander_flattens_under_the_frame() {
|
||||
fn whole_list_switches_as_one_bundle() {
|
||||
// One bool selecting between two whole `List<f64>` stacks: each branch bundles into a rank-0 cell, and the result unbundles back to the flat stack
|
||||
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
|
||||
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![1., 2., 3.]).into()), vec![NodeId(1)]);
|
||||
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![4., 5.]).into()), vec![NodeId(2)]);
|
||||
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2., 3.]).into()), vec![NodeId(1)]);
|
||||
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![4., 5.]).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
|
||||
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
|
||||
@@ -824,8 +824,8 @@ fn a_bundle_unbundles_into_a_list_connector() {
|
||||
fn a_whole_list_of_scalars_switches_as_one_bundle() {
|
||||
// A single bool selecting between two whole `List<f64>` values, covering a primitive element type and confirming the selected list survives intact
|
||||
let condition_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Bool(true).into()), vec![NodeId(0)]);
|
||||
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![1., 2.]).into()), vec![NodeId(1)]);
|
||||
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Numbers(vec![3., 4., 5.]).into()), vec![NodeId(2)]);
|
||||
let if_true_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![1., 2.]).into()), vec![NodeId(1)]);
|
||||
let if_false_node = ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64Array(vec![3., 4., 5.]).into()), vec![NodeId(2)]);
|
||||
|
||||
let mut switch_node = ProtoNode::value(ConstructionArgs::Nodes(vec![NodeId(0), NodeId(1), NodeId(2)]), vec![NodeId(3)]);
|
||||
switch_node.identifier = ProtoNodeIdentifier::new("math_nodes::SwitchNode");
|
||||
|
||||
@@ -108,19 +108,19 @@ pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Re
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
pub fn migrate_to_numbers<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f64>, D::Error> {
|
||||
pub fn migrate_to_f64_array<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<f64>, D::Error> {
|
||||
use serde::Deserialize;
|
||||
|
||||
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
|
||||
#[cfg_attr(feature = "serde", serde(untagged))]
|
||||
enum NumbersFormat {
|
||||
enum F64ArrayFormat {
|
||||
Array(Vec<f64>),
|
||||
List(LegacyTable<f64>),
|
||||
}
|
||||
|
||||
Ok(match NumbersFormat::deserialize(deserializer)? {
|
||||
NumbersFormat::Array(values) => values,
|
||||
NumbersFormat::List(list) => list.element,
|
||||
Ok(match F64ArrayFormat::deserialize(deserializer)? {
|
||||
F64ArrayFormat::Array(values) => values,
|
||||
F64ArrayFormat::List(list) => list.element,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::{Color, ContextFeature, Node, NodeIO, NodeIOTypes, ProtoNodeIdentifier, Type, WasmNotSend};
|
||||
use dyn_any::{DynAny, StaticType};
|
||||
pub use no_std_types::registry::types;
|
||||
use std::collections::HashMap;
|
||||
use std::marker::PhantomData;
|
||||
use std::ops::Deref;
|
||||
@@ -41,10 +42,6 @@ pub struct FieldMetadata {
|
||||
pub number_display_decimal_places: Option<u32>,
|
||||
pub number_step: Option<f64>,
|
||||
pub unit: Option<&'static str>,
|
||||
/// Whether a `String` parameter uses the multi-line text area widget instead of the single-line field, from `#[multiline]`.
|
||||
pub multiline: bool,
|
||||
/// Whether a number parameter uses the progression widget, which splits the value into fractional-progress and whole-element-number fields, from `#[progression]`.
|
||||
pub progression: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
||||
@@ -7,6 +7,9 @@ macro_rules! concrete {
|
||||
($type:ty) => {
|
||||
$crate::Type::Concrete($crate::descriptor!($type))
|
||||
};
|
||||
($type:ty, $name:ty) => {
|
||||
$crate::Type::Concrete($crate::descriptor!($type, $name))
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
@@ -15,6 +18,16 @@ macro_rules! descriptor {
|
||||
$crate::TypeDescriptor {
|
||||
id: Some(std::any::TypeId::of::<$type>()),
|
||||
name: $crate::Cow::Borrowed(std::any::type_name::<$type>()),
|
||||
alias: None,
|
||||
size: std::mem::size_of::<$type>(),
|
||||
align: std::mem::align_of::<$type>(),
|
||||
}
|
||||
};
|
||||
($type:ty, $name:ty) => {
|
||||
$crate::TypeDescriptor {
|
||||
id: Some(std::any::TypeId::of::<$type>()),
|
||||
name: $crate::Cow::Borrowed(std::any::type_name::<$type>()),
|
||||
alias: Some($crate::Cow::Borrowed(stringify!($name))),
|
||||
size: std::mem::size_of::<$type>(),
|
||||
align: std::mem::align_of::<$type>(),
|
||||
}
|
||||
@@ -27,6 +40,7 @@ macro_rules! concrete_with_name {
|
||||
$crate::Type::Concrete($crate::TypeDescriptor {
|
||||
id: Some(std::any::TypeId::of::<$type>()),
|
||||
name: $crate::Cow::Borrowed($name),
|
||||
alias: None,
|
||||
size: std::mem::size_of::<$type>(),
|
||||
align: std::mem::align_of::<$type>(),
|
||||
})
|
||||
@@ -39,6 +53,7 @@ macro_rules! generic {
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of an `Item` holding the given element type, e.g. `item!(f64)` is the type of an `Item<f64>`.
|
||||
/// The two-argument form tags the element descriptor with an alias, preserving the source spelling for widget dispatch.
|
||||
#[macro_export]
|
||||
macro_rules! item {
|
||||
(Item<$inner:ty>) => {
|
||||
@@ -47,6 +62,9 @@ macro_rules! item {
|
||||
($element:ty) => {
|
||||
$crate::Type::Item(Box::new($crate::concrete!($element)))
|
||||
};
|
||||
($element:ty, $alias:ty) => {
|
||||
$crate::Type::Item(Box::new($crate::concrete!($element, $alias)))
|
||||
};
|
||||
}
|
||||
|
||||
/// Constructs the [`Type`] of a `List` holding the given element type, e.g. `list!(f64)` is the type of a `List<f64>`.
|
||||
@@ -67,10 +85,19 @@ macro_rules! future {
|
||||
(List<$inner:ty>) => {
|
||||
$crate::Type::Future(Box::new($crate::list!($inner)))
|
||||
};
|
||||
(List<$inner:ty>, $name:ty) => {
|
||||
$crate::Type::Future(Box::new($crate::list!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>) => {
|
||||
$crate::Type::Future(Box::new($crate::item!($inner)))
|
||||
};
|
||||
(Item<$inner:ty>, $name:ty) => {
|
||||
$crate::Type::Future(Box::new($crate::item!($inner, $name)))
|
||||
};
|
||||
($type:ty) => {{ $crate::Type::Future(Box::new(concrete!($type))) }};
|
||||
($type:ty, $name:ty) => {
|
||||
$crate::Type::Future(Box::new(concrete!($type, $name)))
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
@@ -84,12 +111,21 @@ macro_rules! fn_type {
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(concrete!($type)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::list!($inner)))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner, $inner)))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::item!($inner)))
|
||||
};
|
||||
($in_type:ty, $type:ty, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type, $outname)))
|
||||
};
|
||||
($in_type:ty, $type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(concrete!($type)))
|
||||
};
|
||||
@@ -105,12 +141,21 @@ macro_rules! fn_type_fut {
|
||||
($type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!(())), Box::new(future!($type)))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
($in_type:ty, List<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::list!($inner)))))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner, $inner)))))
|
||||
};
|
||||
($in_type:ty, Item<$inner:ty>) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new($crate::Type::Future(Box::new($crate::item!($inner)))))
|
||||
};
|
||||
($in_type:ty, $type:ty, alias: $outname:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type, $outname)))
|
||||
};
|
||||
($in_type:ty, $type:ty) => {
|
||||
$crate::Type::Fn(Box::new(concrete!($in_type)), Box::new(future!($type)))
|
||||
};
|
||||
@@ -143,12 +188,14 @@ impl NodeIOTypes {
|
||||
let tds1 = TypeDescriptor {
|
||||
id: None,
|
||||
name: Cow::Borrowed("()"),
|
||||
alias: None,
|
||||
size: 0,
|
||||
align: 0,
|
||||
};
|
||||
let tds2 = TypeDescriptor {
|
||||
id: None,
|
||||
name: Cow::Borrowed("()"),
|
||||
alias: None,
|
||||
size: 0,
|
||||
align: 0,
|
||||
};
|
||||
@@ -220,6 +267,8 @@ pub struct TypeDescriptor {
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub id: Option<TypeId>,
|
||||
pub name: Cow<'static, str>,
|
||||
#[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
|
||||
pub alias: Option<Cow<'static, str>>,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub size: usize,
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
@@ -336,6 +385,7 @@ impl Type {
|
||||
Self::Concrete(TypeDescriptor {
|
||||
id: Some(TypeId::of::<T::Static>()),
|
||||
name: Cow::Borrowed(std::any::type_name::<T::Static>()),
|
||||
alias: None,
|
||||
size: size_of::<T>(),
|
||||
align: align_of::<T>(),
|
||||
})
|
||||
@@ -428,6 +478,7 @@ impl Type {
|
||||
let element = Type::Concrete(TypeDescriptor {
|
||||
id: None,
|
||||
name: Cow::Owned(element_name.to_string()),
|
||||
alias: None,
|
||||
size: 0,
|
||||
align: 0,
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod choice_type;
|
||||
pub mod color;
|
||||
pub mod context;
|
||||
pub mod list;
|
||||
pub mod registry;
|
||||
pub mod shaders;
|
||||
|
||||
pub use context::Ctx;
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
pub mod types {
|
||||
/// 0% - 100%
|
||||
pub type Percentage = f64;
|
||||
/// -100% - 100%
|
||||
pub type SignedPercentage = f64;
|
||||
/// -180° - 180°
|
||||
pub type Angle = f64;
|
||||
/// Ends in the unit of x
|
||||
pub type Multiplier = f64;
|
||||
/// Non-negative integer with px unit
|
||||
pub type PixelLength = f64;
|
||||
/// Non-negative
|
||||
pub type Length = f64;
|
||||
/// 0 to 1
|
||||
pub type Fraction = f64;
|
||||
/// Non-negative number broken into whole and fractional parts
|
||||
pub type Progression = f64;
|
||||
/// DVec2 with px unit
|
||||
pub type PixelSize = glam::DVec2;
|
||||
/// String with one or more than one line
|
||||
#[cfg(feature = "std")]
|
||||
pub type TextArea = String;
|
||||
}
|
||||
@@ -233,13 +233,14 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
if let Some(element) = peel_list(implementation_ty) {
|
||||
quote!(Some(#core_types::list!(#element)))
|
||||
} else if let Some(element) = peel_item(implementation_ty) {
|
||||
quote!(Some(#core_types::item!(#element)))
|
||||
quote!(Some(#core_types::item!(#element, #element)))
|
||||
} else {
|
||||
quote!(Some(concrete!(#implementation_ty)))
|
||||
}
|
||||
}
|
||||
// A concrete ranked `Item<T>` param's scalar `#[default]` parses as a bare `T` literal (unranked, promoted at resolution);
|
||||
// without one it keeps the structural `Type::Item` wire type, and `node_inputs` peels to `T` if no `Item` type default exists
|
||||
// A concrete ranked `Item<T>` param's scalar `#[default]` parses as a bare `T` literal (unranked, promoted at resolution); without one it keeps
|
||||
// the structural `Type::Item` wire type, and `node_inputs` peels to `T` if no `Item` type default exists. Either way the element's alias stays
|
||||
// on its descriptor so the rank-0 Properties widget still dispatches, e.g. `Progression`.
|
||||
None => match &field.ty {
|
||||
ParsedFieldType::Item {
|
||||
field: RegularParsedField { value_source, .. },
|
||||
@@ -251,8 +252,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
// The fn's lifetimes are elided since the metadata registration fn declares none of them
|
||||
let element = substitute_lifetimes(element.clone(), "_");
|
||||
match value_source {
|
||||
ParsedValueSource::Default(_) => quote!(Some(concrete!(#element))),
|
||||
_ => quote!(Some(#core_types::item!(#element))),
|
||||
ParsedValueSource::Default(_) => quote!(Some(concrete!(#element, #element))),
|
||||
_ => quote!(Some(#core_types::item!(#element, #element))),
|
||||
}
|
||||
}
|
||||
_ => quote!(None),
|
||||
@@ -288,20 +289,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let number_step: Vec<_> = regular_fields.iter().map(|field| field.number_step.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
|
||||
|
||||
let unit_suffix: Vec<_> = regular_fields.iter().map(|field| field.unit.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
|
||||
let multiline: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let multiline = field.multiline;
|
||||
quote!(#multiline)
|
||||
})
|
||||
.collect();
|
||||
let progression: Vec<_> = regular_fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let progression = field.progression;
|
||||
quote!(#progression)
|
||||
})
|
||||
.collect();
|
||||
|
||||
let exposed: Vec<_> = regular_fields
|
||||
.iter()
|
||||
@@ -927,8 +914,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
number_display_decimal_places: #number_display_decimal_places,
|
||||
number_step: #number_step,
|
||||
unit: #unit_suffix,
|
||||
multiline: #multiline,
|
||||
progression: #progression,
|
||||
},
|
||||
)*
|
||||
],
|
||||
@@ -1199,9 +1184,7 @@ fn generate_register_node_impl(
|
||||
(WireWrapper::List.apply(&gcore, &element_ty), Some(quote!(List<#element_ty>)))
|
||||
} else {
|
||||
match (field_is_ranked, variant.param_wrap()) {
|
||||
// A ranked field's bare rows take the variant's wire shape, or the field's own `Item` shape in a variant without one
|
||||
(true, wrap) => {
|
||||
let wrap = wrap.unwrap_or(WireWrapper::Item);
|
||||
(true, Some(wrap)) => {
|
||||
let element_ty = peel_item(output_type).unwrap_or_else(|| output_type.clone());
|
||||
let signature = match wrap {
|
||||
WireWrapper::List => quote!(List<#element_ty>),
|
||||
@@ -1223,7 +1206,7 @@ fn generate_register_node_impl(
|
||||
return Err(Error::new_spanned(&parsed.fn_name, "Node needs to be async if you want to use lambda parameters"));
|
||||
}
|
||||
temp_constructors.push(downcast_node);
|
||||
temp_node_io.push(quote!(fn_type_fut!(#input_type, #signature_type)));
|
||||
temp_node_io.push(quote!(fn_type_fut!(#input_type, #signature_type, alias: #signature_type)));
|
||||
panic_node_types.push(quote!(#input_type, DynFuture<'static, #output_type>));
|
||||
}
|
||||
let input_type = match parsed.input.implementations.is_empty() {
|
||||
|
||||
@@ -119,8 +119,6 @@ pub struct ParsedField {
|
||||
pub number_display_decimal_places: Option<LitInt>,
|
||||
pub number_step: Option<LitFloat>,
|
||||
pub unit: Option<LitStr>,
|
||||
pub multiline: bool,
|
||||
pub progression: bool,
|
||||
pub is_data_field: bool,
|
||||
}
|
||||
|
||||
@@ -860,17 +858,12 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
.map(|attr| attr.parse_args::<LitStr>().map_err(|_e| Error::new_spanned(attr, "Expected a unit type as string".to_string())))
|
||||
.transpose()?;
|
||||
|
||||
// Widget-selection markers: `#[multiline]` gives a `String` parameter the multi-line text area widget, and `#[progression]`
|
||||
// splits a number into fractional-progress and whole-element-number fields
|
||||
let multiline = extract_attribute(attrs, "multiline").is_some();
|
||||
let progression = extract_attribute(attrs, "progression").is_some();
|
||||
|
||||
let number_display_decimal_places = extract_attribute(attrs, "display_decimal_places")
|
||||
.map(|attr| {
|
||||
attr.parse_args::<LitInt>().map_err(|e| {
|
||||
Error::new_spanned(
|
||||
attr,
|
||||
format!("Invalid whole number of decimal places for argument '{ident}': {e}\nUSAGE EXAMPLE: #[display_decimal_places(2)]"),
|
||||
format!("Invalid `integer` for number of decimals for argument '{ident}': {e}\nUSAGE EXAMPLE: #[display_decimal_places(2)]"),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -944,8 +937,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_display_decimal_places,
|
||||
number_step,
|
||||
unit,
|
||||
multiline,
|
||||
progression,
|
||||
is_data_field,
|
||||
})
|
||||
} else {
|
||||
@@ -997,8 +988,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_display_decimal_places,
|
||||
number_step,
|
||||
unit,
|
||||
multiline,
|
||||
progression,
|
||||
is_data_field,
|
||||
})
|
||||
}
|
||||
@@ -1043,14 +1032,16 @@ fn narrow_shader_fields(fields: &mut [ParsedField]) -> syn::Result<()> {
|
||||
}
|
||||
|
||||
let element = peel_item(&declared).unwrap_or_else(|| declared.clone());
|
||||
if is_primitive_type(&element, "f32") || is_primitive_type(&element, "i32") {
|
||||
if ["f32", "i32", "PercentageF32", "SignedPercentageF32", "AngleF32"].iter().any(|name| is_primitive_type(&element, name)) {
|
||||
return Err(Error::new_spanned(
|
||||
&declared,
|
||||
"A shader node's parameters are declared as `f64` or `i64`, the graph's Number and Integer types; the macro narrows them to the `f32` or `i32` the shader computes with",
|
||||
));
|
||||
}
|
||||
|
||||
let counterpart: Type = if is_primitive_type(&element, "f64") {
|
||||
// The registry's f64 typedefs, like `Percentage` and `Angle`, spell the graph's Number by its widget meaning and narrow the same way
|
||||
let spells_f64 = ["f64", "Percentage", "SignedPercentage", "Angle", "Multiplier", "PixelLength", "Length", "Fraction", "Progression"];
|
||||
let counterpart: Type = if spells_f64.iter().any(|name| is_primitive_type(&element, name)) {
|
||||
parse_quote!(f32)
|
||||
} else if is_primitive_type(&element, "i64") {
|
||||
parse_quote!(i32)
|
||||
@@ -1307,8 +1298,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1375,8 +1364,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
},
|
||||
ParsedField {
|
||||
@@ -1400,8 +1387,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
},
|
||||
],
|
||||
@@ -1472,8 +1457,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1547,8 +1530,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1624,8 +1605,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
@@ -1709,8 +1688,6 @@ mod tests {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
}],
|
||||
body: TokenStream2::new(),
|
||||
|
||||
@@ -270,8 +270,6 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
is_data_field: false,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core_types::list::Item;
|
||||
use core_types::registry::types::Percentage;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
@@ -38,22 +39,16 @@ fn opacity<T>(
|
||||
/// How visible the content should be, including any content clipped to it.
|
||||
/// Ranges from the default of 100% (fully opaque) to 0% (fully transparent).
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
opacity: Item<Percentage>,
|
||||
/// Whether the *Fill* property is enabled, multiplying the existing fill by the chosen percentage.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_fill: Item<bool>,
|
||||
/// How visible the content should be, independent of any content clipped to it.
|
||||
/// Ranges from 0% (fully transparent) to the default of 100% (fully opaque).
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_percentage")]
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
fill: Item<f64>,
|
||||
fill: Item<Percentage>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
let (has_opacity, opacity, has_fill, fill) = (*has_opacity.element(), *opacity.element(), *has_fill.element(), *fill.element());
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core_types::list::{ATTR_COLOR, ATTR_DIAMETER, ATTR_FLOW, ATTR_HARDNESS, Item, List};
|
||||
use core_types::registry::types::Percentage;
|
||||
use core_types::{Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
|
||||
@@ -17,27 +18,16 @@ fn brush_strokes(
|
||||
_: impl Ctx,
|
||||
strokes: List<Stroke>,
|
||||
color: List<Color>,
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(40.)]
|
||||
diameter: Item<f64>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(0.)]
|
||||
hardness: Item<f64>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
flow: Item<f64>,
|
||||
#[default(40.)] diameter: Item<f64>,
|
||||
#[default(0.)] hardness: Item<Percentage>,
|
||||
#[default(100.)] flow: Item<Percentage>,
|
||||
) -> List<Graphic> {
|
||||
let (diameter, hardness, flow) = (diameter.into_element(), hardness.into_element(), flow.into_element());
|
||||
List::new_from_item(
|
||||
Item::new_from_element(Graphic::from(strokes))
|
||||
.with_attribute(ATTR_COLOR, color.element(0).copied().unwrap_or_default())
|
||||
.with_attribute(ATTR_DIAMETER, diameter)
|
||||
.with_attribute(ATTR_HARDNESS, hardness / 100.)
|
||||
.with_attribute(ATTR_FLOW, flow / 100.),
|
||||
.with_attribute(ATTR_DIAMETER, diameter.max(0.))
|
||||
.with_attribute(ATTR_HARDNESS, (hardness / 100.).clamp(0., 1.))
|
||||
.with_attribute(ATTR_FLOW, (flow / 100.).clamp(0., 1.)),
|
||||
)
|
||||
}
|
||||
@@ -94,7 +94,7 @@ async fn quantize_real_time<T>(
|
||||
)]
|
||||
value: impl Node<'n, Context<'static>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit(" sec")]
|
||||
#[unit("sec")]
|
||||
quantum: Item<f64>,
|
||||
) -> T {
|
||||
let time = ctx.try_real_time().unwrap_or_default();
|
||||
@@ -140,7 +140,7 @@ async fn quantize_animation_time<T>(
|
||||
)]
|
||||
value: impl Node<'n, Context<'static>, Output = T>,
|
||||
#[default(1)]
|
||||
#[unit(" sec")]
|
||||
#[unit("sec")]
|
||||
quantum: Item<f64>,
|
||||
) -> T {
|
||||
let time = ctx.try_animation_time().unwrap_or_default();
|
||||
|
||||
@@ -24,10 +24,8 @@ pub async fn create_artboard<T: IntoGraphicList>(
|
||||
)]
|
||||
content: impl Node<Context<'static>, Output = T>,
|
||||
/// Coordinate of the top-left corner of the artboard within the document.
|
||||
#[unit(" px")]
|
||||
location: Item<DVec2>,
|
||||
/// Width and height of the artboard within the document.
|
||||
#[unit(" px")]
|
||||
dimensions: Item<DVec2>,
|
||||
/// Color of the artboard background.
|
||||
background: Item<Color>,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
||||
use core_types::registry::types::Angle;
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
|
||||
@@ -446,10 +447,9 @@ async fn mirror<T: BoundingBox + 'n + Send + Clone>(
|
||||
content: Item<T>,
|
||||
#[default(ReferencePoint::Center)] relative_to_bounds: Item<ReferencePoint>,
|
||||
#[unit(" px")] offset: Item<f64>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-90..90)]
|
||||
angle: Item<f64>,
|
||||
angle: Item<Angle>,
|
||||
#[default(true)] keep_original: Item<bool>,
|
||||
) -> List<T> {
|
||||
let (relative_to_bounds, offset, angle, keep_original) = (relative_to_bounds.into_element(), offset.into_element(), angle.into_element(), keep_original.into_element());
|
||||
|
||||
@@ -29,7 +29,6 @@ fn text(
|
||||
/// 0 means all lines overlap. 1 means all lines are spaced by just the font size. 1.2 is a common default for readable text. 2 means double-spaced text.
|
||||
#[unit("x")]
|
||||
#[hard(0..)]
|
||||
#[soft(..2)]
|
||||
#[step(0.1)]
|
||||
#[default(1.2)]
|
||||
line_height: Item<f64>,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use core_types::Context;
|
||||
use core_types::context::{CloneVarArgs, ExtractAll};
|
||||
use core_types::list::{Bundle, Item, List};
|
||||
use core_types::registry::types::{Fraction, Percentage, PixelSize};
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{Color, Ctx, OwnedContextImpl, num_traits};
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -88,17 +89,6 @@ fn output<T: ExpressionValue>(result: Option<Value>) -> T {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
impl ExpressionValue for i64 {
|
||||
fn into_f64(self) -> f64 {
|
||||
self as f64
|
||||
}
|
||||
|
||||
// Evaluation happens in real numbers, so the result snaps to the nearest whole number (the graph's one Number to Integer rule)
|
||||
fn from_value(value: &Value) -> Option<Self> {
|
||||
value.as_i64()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExpressionValue for bool {
|
||||
fn into_f64(self) -> f64 {
|
||||
self as u8 as f64
|
||||
@@ -124,27 +114,19 @@ impl ValueProvider for SingleVariableMathContext {
|
||||
|
||||
/// Evaluates a math expression written in terms of the single variable `x`, which carries the input value.
|
||||
///
|
||||
/// The result is read as the chosen output type: an Integer rounds a fractional result to the nearest whole number, and a Bool requires the expression to produce exactly 0 or 1, since any other number is not a truth value. A boolean input reads as 0 or 1.
|
||||
/// A boolean input reads as 0 or 1, and a boolean output requires the expression to produce exactly 0 or 1, since any other number is not a truth value.
|
||||
#[node_macro::node(name("Math f(x)"), category("Math: Arithmetic"))]
|
||||
fn math_fx<T: ExpressionValue, U: ExpressionValue>(
|
||||
fn math_fx<T: ExpressionValue>(
|
||||
_: impl Ctx,
|
||||
/// The value passed into the expression as `x`.
|
||||
#[implementations(f64, f64, f64, i64, i64, i64, bool, bool, bool)]
|
||||
#[implementations(f64, bool)]
|
||||
value: Item<T>,
|
||||
/// The expression evaluated for the input value, in terms of `x`, such as `4sin(x/2)`.
|
||||
#[name("f(x) =")]
|
||||
#[default("x")]
|
||||
fx: Item<String>,
|
||||
/// The type the result is read as.
|
||||
#[implementations(f64, i64, bool, f64, i64, bool, f64, i64, bool)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "type_choice")]
|
||||
#[name("Output Type")]
|
||||
output_type: Item<U>,
|
||||
#[data] parsed: ParseCache,
|
||||
) -> Item<U> {
|
||||
// The output type input is a type witness: its type selects the implementation, and its value is never read
|
||||
let _ = output_type;
|
||||
|
||||
) -> Item<T> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let x = value.into_f64();
|
||||
@@ -179,26 +161,18 @@ impl ValueProvider for PositionalMathContext {
|
||||
|
||||
/// Evaluates a math expression across all of the input items at once. A full expression reads the items as `a`, `b`, `c`, …, while a math operator or N-argument function name (like `*` or `min`) applies across every item.
|
||||
///
|
||||
/// The result is read as the chosen output type: an Integer rounds a fractional result to the nearest whole number, and a Bool requires the expression to produce exactly 0 or 1, since any other number is not a truth value. Boolean items read as 0 or 1.
|
||||
/// Boolean items read as 0 or 1, and a boolean output requires the expression to produce exactly 0 or 1, since any other number is not a truth value.
|
||||
#[node_macro::node(name("Math f(…)"), category("Math: Arithmetic"))]
|
||||
fn math_f<T: ExpressionValue, U: ExpressionValue>(
|
||||
fn math_f<T: ExpressionValue>(
|
||||
_: impl Ctx,
|
||||
/// The items the expression reads.
|
||||
#[implementations(List<f64>, List<f64>, List<f64>, List<i64>, List<i64>, List<i64>, List<bool>, List<bool>, List<bool>)]
|
||||
#[implementations(List<f64>, List<bool>)]
|
||||
values: List<T>,
|
||||
/// The expression evaluated over the items, such as `a * b + c`, or a lone operator or function applied across all of them.
|
||||
#[name("f(…) =")]
|
||||
f: Item<String>,
|
||||
/// The type the result is read as.
|
||||
#[implementations(f64, i64, bool, f64, i64, bool, f64, i64, bool)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "type_choice")]
|
||||
#[name("Output Type")]
|
||||
output_type: Item<U>,
|
||||
#[data] parsed: ParseCache,
|
||||
) -> Item<U> {
|
||||
// The output type input is a type witness: its type selects the implementation, and its value is never read
|
||||
let _ = output_type;
|
||||
|
||||
) -> Item<T> {
|
||||
let expression = f.element();
|
||||
let items: Vec<f64> = values.iter_element_values().map(|&value| value.into_f64()).collect();
|
||||
let bindings = PositionalMathContext { items };
|
||||
@@ -207,7 +181,7 @@ fn math_f<T: ExpressionValue, U: ExpressionValue>(
|
||||
if let Some(reducer) = classify_reducer(expression, &bindings) {
|
||||
let Some(result) = reducer.evaluate(&bindings.items) else {
|
||||
warn!("The `{expression}` reducer cannot be applied to {} items", bindings.items.len());
|
||||
return Item::new_from_element(U::default());
|
||||
return Item::new_from_element(T::default());
|
||||
};
|
||||
return Item::new_from_element(output(Some(Value::from_f64(result))));
|
||||
}
|
||||
@@ -620,15 +594,13 @@ fn tangent<T: Componentwise>(
|
||||
fn sine_inverse(
|
||||
_: impl Ctx,
|
||||
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
|
||||
#[range]
|
||||
#[hard(-1..1)]
|
||||
value: Item<f64>,
|
||||
/// Whether the resulting angle should be given in as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let angle = value.asin();
|
||||
let angle = value.clamp(-1., 1.).asin();
|
||||
let result = if *radians.element() { angle } else { angle.to_degrees() };
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
@@ -638,15 +610,13 @@ fn sine_inverse(
|
||||
fn cosine_inverse(
|
||||
_: impl Ctx,
|
||||
/// The given value for which the angle is calculated. Must be in the domain `[-1, 1]` (it will be clamped to -1 or 1 otherwise).
|
||||
#[range]
|
||||
#[hard(-1..1)]
|
||||
value: Item<f64>,
|
||||
/// Whether the resulting angle should be given in as radians instead of degrees.
|
||||
radians: Item<bool>,
|
||||
) -> Item<f64> {
|
||||
let (value, attributes) = value.into_parts();
|
||||
|
||||
let angle = value.acos();
|
||||
let angle = value.clamp(-1., 1.).acos();
|
||||
let result = if *radians.element() { angle } else { angle.to_degrees() };
|
||||
Item::from_parts(result, attributes)
|
||||
}
|
||||
@@ -1341,14 +1311,7 @@ fn number_value(_: impl Ctx, _primary: (), number: Item<f64>) -> Item<f64> {
|
||||
|
||||
/// Constructs a number value which may be set to any value from 0% to 100% by dragging the slider.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn percentage_value(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
percentage: Item<f64>,
|
||||
) -> Item<f64> {
|
||||
fn percentage_value(_: impl Ctx, _primary: (), percentage: Item<Percentage>) -> Item<f64> {
|
||||
percentage
|
||||
}
|
||||
|
||||
@@ -1366,27 +1329,11 @@ fn color_value(_: impl Ctx, _primary: (), #[default(Color::BLACK)] color: Item<C
|
||||
|
||||
/// Constructs a color value from red, green, blue, and alpha components given as numbers from 0 to 1.
|
||||
#[node_macro::node(category("Color"), name("RGBA to Color"))]
|
||||
fn rgba_to_color(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
red: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
green: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
blue: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(1.)]
|
||||
alpha: Item<f64>,
|
||||
) -> Item<Color> {
|
||||
let red = *red.element() as f32;
|
||||
let green = *green.element() as f32;
|
||||
let blue = *blue.element() as f32;
|
||||
let alpha = *alpha.element() as f32;
|
||||
fn rgba_to_color(_: impl Ctx, _primary: (), red: Item<Fraction>, green: Item<Fraction>, blue: Item<Fraction>, #[default(1.)] alpha: Item<Fraction>) -> Item<Color> {
|
||||
let red = (*red.element() as f32).clamp(0., 1.);
|
||||
let green = (*green.element() as f32).clamp(0., 1.);
|
||||
let blue = (*blue.element() as f32).clamp(0., 1.);
|
||||
let alpha = (*alpha.element() as f32).clamp(0., 1.);
|
||||
|
||||
// RGB user inputs are interpreted as sRGB display values; lift to linear-light for the internal `Color`
|
||||
Item::new_from_element(Color::from_gamma_srgb_channels(red, green, blue, alpha))
|
||||
@@ -1394,30 +1341,11 @@ fn rgba_to_color(
|
||||
|
||||
/// Constructs a color value from hue, saturation, value, and alpha components given as numbers from 0 to 1.
|
||||
#[node_macro::node(category("Color"), name("HSVA to Color"))]
|
||||
fn hsva_to_color(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
// Hue is periodic, so a value past either end wraps around instead of clamping
|
||||
#[range]
|
||||
#[soft(0..1)]
|
||||
hue: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(1.)]
|
||||
saturation: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(1.)]
|
||||
value: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(1.)]
|
||||
alpha: Item<f64>,
|
||||
) -> Item<Color> {
|
||||
fn hsva_to_color(_: impl Ctx, _primary: (), hue: Item<Fraction>, #[default(1.)] saturation: Item<Fraction>, #[default(1.)] value: Item<Fraction>, #[default(1.)] alpha: Item<Fraction>) -> Item<Color> {
|
||||
let hue = (*hue.element() as f32) - (*hue.element() as f32).floor();
|
||||
let saturation = *saturation.element() as f32;
|
||||
let value = *value.element() as f32;
|
||||
let alpha = *alpha.element() as f32;
|
||||
let saturation = (*saturation.element() as f32).clamp(0., 1.);
|
||||
let value = (*value.element() as f32).clamp(0., 1.);
|
||||
let alpha = (*alpha.element() as f32).clamp(0., 1.);
|
||||
|
||||
Item::new_from_element(Color::from_hsva(hue, saturation, value, alpha))
|
||||
}
|
||||
@@ -1427,26 +1355,15 @@ fn hsva_to_color(
|
||||
fn hsla_to_color(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[range]
|
||||
#[soft(0..1)]
|
||||
hue: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(1.)]
|
||||
saturation: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(0.5)]
|
||||
lightness: Item<f64>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(1.)]
|
||||
alpha: Item<f64>,
|
||||
hue: Item<Fraction>,
|
||||
#[default(1.)] saturation: Item<Fraction>,
|
||||
#[default(0.5)] lightness: Item<Fraction>,
|
||||
#[default(1.)] alpha: Item<Fraction>,
|
||||
) -> Item<Color> {
|
||||
let hue = (*hue.element() as f32) - (*hue.element() as f32).floor();
|
||||
let saturation = *saturation.element() as f32;
|
||||
let lightness = *lightness.element() as f32;
|
||||
let alpha = *alpha.element() as f32;
|
||||
let saturation = (*saturation.element() as f32).clamp(0., 1.);
|
||||
let lightness = (*lightness.element() as f32).clamp(0., 1.);
|
||||
let alpha = (*alpha.element() as f32).clamp(0., 1.);
|
||||
|
||||
Item::new_from_element(Color::from_hsla(hue, saturation, lightness, alpha))
|
||||
}
|
||||
@@ -1603,18 +1520,10 @@ fn evaluate_gradient(
|
||||
|
||||
/// Constructs a footprint value which may be set to any transformation of a unit square describing a render area, and a render resolution at least 1x1 integer pixels.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn footprint_value(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
transform: Item<DAffine2>,
|
||||
#[unit(" px")]
|
||||
#[hard(1..)]
|
||||
#[default(100., 100.)]
|
||||
resolution: Item<DVec2>,
|
||||
) -> Item<Footprint> {
|
||||
fn footprint_value(_: impl Ctx, _primary: (), transform: Item<DAffine2>, #[default(100., 100.)] resolution: Item<PixelSize>) -> Item<Footprint> {
|
||||
Item::new_from_element(Footprint {
|
||||
transform: *transform.element(),
|
||||
resolution: resolution.element().as_uvec2(),
|
||||
resolution: resolution.element().max(DVec2::ONE).as_uvec2(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
@@ -1920,75 +1829,6 @@ mod test {
|
||||
assert_eq!(logarithm((), vec2(8., 100.), vec2(2., 10.)).into_element(), DVec2::new(3., 2.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_lane_keeps_integers_and_rounds_fractions() {
|
||||
let integer = |value: i64, expression: &str| {
|
||||
math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(value),
|
||||
Item::new_from_element(expression.to_string()),
|
||||
Item::new_from_element(0_i64),
|
||||
)
|
||||
.into_element()
|
||||
};
|
||||
assert_eq!(integer(3, "x * 2"), 6);
|
||||
assert_eq!(integer(3, "x / 2"), 2, "1.5 rounds away from zero");
|
||||
assert_eq!(integer(-3, "x / 2"), -2, "-1.5 rounds away from zero");
|
||||
assert_eq!(integer(3, "x * 1.1 / 1.1"), 3, "float noise snaps back to the whole number");
|
||||
|
||||
let items: List<i64> = [1_i64, 2, 4].into_iter().map(Item::new_from_element).collect();
|
||||
assert_eq!(
|
||||
math_f((), &ParseCache::default(), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64)).into_element(),
|
||||
2,
|
||||
"7/3 rounds to 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_type_witness_picks_the_output_rung() {
|
||||
// The witness input's type, not the input value's, decides how the result is read
|
||||
assert_eq!(
|
||||
math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(2.5),
|
||||
Item::new_from_element("x * 2".to_string()),
|
||||
Item::new_from_element(0_i64)
|
||||
)
|
||||
.into_element(),
|
||||
5
|
||||
);
|
||||
assert!(
|
||||
math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(3_i64),
|
||||
Item::new_from_element("x > 2".to_string()),
|
||||
Item::new_from_element(false)
|
||||
)
|
||||
.into_element()
|
||||
);
|
||||
assert_eq!(
|
||||
math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(true),
|
||||
Item::new_from_element("x / 2".to_string()),
|
||||
Item::new_from_element(0.)
|
||||
)
|
||||
.into_element(),
|
||||
0.5
|
||||
);
|
||||
|
||||
let items: List<f64> = [1., 2.].into_iter().map(Item::new_from_element).collect();
|
||||
assert_eq!(
|
||||
math_f((), &ParseCache::default(), items, Item::new_from_element("mean".to_string()), Item::new_from_element(0_i64)).into_element(),
|
||||
2,
|
||||
"1.5 rounds to 2"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
pub fn round_floor_ceiling_vec2() {
|
||||
let vec2 = |x, y| Item::new_from_element(DVec2::new(x, y));
|
||||
@@ -1999,49 +1839,25 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn test_basic_expression() {
|
||||
let result = math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element("2 + 2".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
);
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(0.), Item::new_from_element("2 + 2".to_string()));
|
||||
assert_eq!(result.into_element(), 4.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_complex_expression() {
|
||||
let result = math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element("(5 * 3) + (10 / 2)".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
);
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(0.), Item::new_from_element("(5 * 3) + (10 / 2)".to_string()));
|
||||
assert_eq!(result.into_element(), 20.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_variable_binding() {
|
||||
let result = math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(7.),
|
||||
Item::new_from_element("x * 2".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
);
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(7.), Item::new_from_element("x * 2".to_string()));
|
||||
assert_eq!(result.into_element(), 14.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_expression() {
|
||||
let result = math_fx(
|
||||
(),
|
||||
&ParseCache::default(),
|
||||
Item::new_from_element(0.),
|
||||
Item::new_from_element("invalid".to_string()),
|
||||
Item::new_from_element(0.),
|
||||
);
|
||||
let result = math_fx((), &ParseCache::default(), Item::new_from_element(0.), Item::new_from_element("invalid".to_string()));
|
||||
assert_eq!(result.into_element(), 0.);
|
||||
}
|
||||
|
||||
@@ -2057,17 +1873,16 @@ mod test {
|
||||
#[test]
|
||||
fn test_boolean_items() {
|
||||
// Booleans read as exactly 0 and 1, and logical results convert back
|
||||
let as_bool = Item::new_from_element(false);
|
||||
assert!(!math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("!x".to_string()), as_bool.clone()).into_element());
|
||||
assert!(math_fx((), &ParseCache::default(), Item::new_from_element(false), Item::new_from_element("x == 0".to_string()), as_bool.clone()).into_element());
|
||||
assert!(!math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("!x".to_string())).into_element());
|
||||
assert!(math_fx((), &ParseCache::default(), Item::new_from_element(false), Item::new_from_element("x == 0".to_string())).into_element());
|
||||
|
||||
// A result that is not exactly 0 or 1 cannot be a truth value, so it reads as false
|
||||
assert!(!math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("x + 1".to_string()), as_bool.clone()).into_element());
|
||||
assert!(!math_fx((), &ParseCache::default(), Item::new_from_element(true), Item::new_from_element("x + 1".to_string())).into_element());
|
||||
|
||||
let bools = || [true, true, false].into_iter().map(Item::new_from_element).collect::<List<bool>>();
|
||||
assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("&&".to_string()), as_bool.clone()).into_element());
|
||||
assert!(math_f((), &ParseCache::default(), bools(), Item::new_from_element("||".to_string()), as_bool.clone()).into_element());
|
||||
assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("xor".to_string()), as_bool).into_element());
|
||||
assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("&&".to_string())).into_element());
|
||||
assert!(math_f((), &ParseCache::default(), bools(), Item::new_from_element("||".to_string())).into_element());
|
||||
assert!(!math_f((), &ParseCache::default(), bools(), Item::new_from_element("xor".to_string())).into_element());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2088,16 +1903,9 @@ mod test {
|
||||
let values = || [4., 1., 7.].into_iter().map(Item::new_from_element).collect::<List<f64>>();
|
||||
|
||||
// A full expression reads the items positionally as `a`, `b`, `c`, while a lone token applies across all of them
|
||||
let as_number = Item::new_from_element(0.);
|
||||
assert_eq!(
|
||||
math_f((), &ParseCache::default(), values(), Item::new_from_element("a - b + c".to_string()), as_number.clone()).into_element(),
|
||||
10.
|
||||
);
|
||||
assert_eq!(
|
||||
math_f((), &ParseCache::default(), values(), Item::new_from_element("min".to_string()), as_number.clone()).into_element(),
|
||||
1.
|
||||
);
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("+".to_string()), as_number).into_element(), 12.);
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("a - b + c".to_string())).into_element(), 10.);
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("min".to_string())).into_element(), 1.);
|
||||
assert_eq!(math_f((), &ParseCache::default(), values(), Item::new_from_element("+".to_string())).into_element(), 12.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -6,6 +6,7 @@ use no_std_types::blending::BlendMode;
|
||||
use no_std_types::color::{Color, Pixel};
|
||||
#[cfg(not(feature = "std"))]
|
||||
use no_std_types::list::ShaderItem as Item;
|
||||
use no_std_types::registry::types::Percentage;
|
||||
#[cfg(feature = "std")]
|
||||
use raster_types::{CPU, Raster};
|
||||
#[cfg(feature = "std")]
|
||||
@@ -81,11 +82,7 @@ fn mix<T: Blend<Color> + Send>(
|
||||
#[gpu_image]
|
||||
under: Item<T>,
|
||||
blend_mode: Item<BlendMode>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
#[default(100.)] opacity: Item<Percentage>,
|
||||
) -> Item<T> {
|
||||
let mut over = over;
|
||||
let blend_mode = blend_mode.into_element();
|
||||
@@ -109,20 +106,18 @@ fn color_overlay<T: Adjust<Color>>(
|
||||
image: Item<T>,
|
||||
#[default(Color::BLACK)] color: Item<Color>,
|
||||
blend_mode: Item<BlendMode>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
opacity: Item<f64>,
|
||||
#[default(100.)] opacity: Item<Percentage>,
|
||||
) -> Item<T> {
|
||||
let mut image = image;
|
||||
let color = color.into_element();
|
||||
let blend_mode = blend_mode.into_element();
|
||||
let opacity = (opacity.into_element() / 100.) as f32;
|
||||
let opacity = opacity.into_element();
|
||||
|
||||
let opacity = (opacity / 100.).clamp(0., 1.);
|
||||
|
||||
image.element_mut().adjust(|pixel| {
|
||||
let overlay = apply_blend_mode(color, *pixel, blend_mode);
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity;
|
||||
let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity as f32;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a())
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::registry::types::Percentage;
|
||||
use image::{DynamicImage, GenericImage, GenericImageView, GrayImage, ImageBuffer, Luma, Rgba, RgbaImage};
|
||||
use ndarray::{Array2, ArrayBase, Dim, OwnedRepr};
|
||||
use raster_types::Image;
|
||||
@@ -7,14 +8,7 @@ use raster_types::{CPU, Raster};
|
||||
use std::cmp::{max, min};
|
||||
|
||||
#[node_macro::node(category("Raster: Filter"))]
|
||||
async fn dehaze(
|
||||
_: impl Ctx,
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
strength: Item<f64>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
async fn dehaze(_: impl Ctx, image_frame: Item<Raster<CPU>>, strength: Item<Percentage>) -> Item<Raster<CPU>> {
|
||||
let strength = *strength.element();
|
||||
|
||||
let (image, attributes) = image_frame.into_parts();
|
||||
|
||||
@@ -2,6 +2,7 @@ use bytemuck::{Pod, Zeroable};
|
||||
use core_types::color::{Alpha, Color, Pixel, RGB};
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::Item;
|
||||
use core_types::registry::types::PixelLength;
|
||||
use raster_types::Image;
|
||||
use raster_types::{Bitmap, BitmapMut};
|
||||
use raster_types::{CPU, Raster};
|
||||
@@ -91,11 +92,10 @@ async fn blur(
|
||||
/// The image to be blurred.
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
/// The radius of the blur kernel.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..100)]
|
||||
radius: Item<f64>,
|
||||
radius: Item<PixelLength>,
|
||||
/// Use a lower-quality box kernel instead of a circular Gaussian kernel. This is faster but produces boxy artifacts.
|
||||
box_blur: Item<bool>,
|
||||
/// Opt to incorrectly apply the filter with color calculations in gamma space for compatibility with the results from other software.
|
||||
@@ -126,11 +126,10 @@ async fn median_filter(
|
||||
/// The image to be filtered.
|
||||
image_frame: Item<Raster<CPU>>,
|
||||
/// The radius of the filter kernel. Larger values remove more noise but may blur fine details.
|
||||
#[unit(" px")]
|
||||
#[range]
|
||||
#[hard(0..)]
|
||||
#[soft(..50)]
|
||||
radius: Item<f64>,
|
||||
radius: Item<PixelLength>,
|
||||
) -> Item<Raster<CPU>> {
|
||||
let radius = *radius.element();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::gcore::Context;
|
||||
use core::f64::consts::TAU;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::{Angle, PixelSize};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
@@ -71,14 +72,10 @@ pub async fn repeat_array<T: Send + Clone + 'static>(
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
#[unit(" px")]
|
||||
#[default(100., 100.)]
|
||||
// TODO: When using a custom Properties panel layout in document_node_definitions.rs and this default is set, the widget weirdly doesn't show up in the Properties panel. Investigation is needed.
|
||||
direction: Item<DVec2>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-360..360)]
|
||||
angle: Item<f64>,
|
||||
direction: Item<PixelSize>,
|
||||
angle: Item<Angle>,
|
||||
#[default(5)]
|
||||
#[hard(1..)]
|
||||
count: Item<i64>,
|
||||
@@ -132,10 +129,7 @@ async fn repeat_radial<T: Send + Clone + 'static>(
|
||||
Context -> List<Artboard>,
|
||||
)]
|
||||
content: impl Node<'n, Context<'static>, Output = List<T>>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-180..180)]
|
||||
start_angle: Item<f64>,
|
||||
start_angle: Item<Angle>,
|
||||
#[unit(" px")]
|
||||
#[default(5)]
|
||||
radius: Item<f64>,
|
||||
|
||||
@@ -11,6 +11,7 @@ use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::float_noise::round_away_float_noise;
|
||||
use core_types::misc::{format_f64, parse_f64};
|
||||
use core_types::registry::types::TextArea;
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -186,7 +187,7 @@ pub enum StringCapitalization {
|
||||
|
||||
/// Constructs a string value which may be set to any plain text.
|
||||
#[node_macro::node(category("Value"))]
|
||||
fn string_value(_: impl Ctx, _primary: (), #[multiline] string: Item<String>) -> Item<String> {
|
||||
fn string_value(_: impl Ctx, _primary: (), string: Item<TextArea>) -> Item<String> {
|
||||
string
|
||||
}
|
||||
|
||||
@@ -263,7 +264,7 @@ fn as_string(_: impl Ctx, value: Item<String>) -> Item<String> {
|
||||
|
||||
/// Joins two strings together.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: Item<String>, #[multiline] second: Item<String>) -> Item<String> {
|
||||
fn string_concatenate(_: impl Ctx, #[implementations(String)] first: Item<String>, second: Item<TextArea>) -> Item<String> {
|
||||
let mut first = first;
|
||||
first.element_mut().push_str(second.element());
|
||||
first
|
||||
@@ -271,7 +272,7 @@ fn string_concatenate(_: impl Ctx, #[implementations(String)] first: Item<String
|
||||
|
||||
/// Replaces all occurrences of "From" with "To" in the input string.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn string_replace(_: impl Ctx, string: Item<String>, #[multiline] from: Item<String>, #[multiline] to: Item<String>) -> Item<String> {
|
||||
fn string_replace(_: impl Ctx, string: Item<String>, from: Item<TextArea>, to: Item<TextArea>) -> Item<String> {
|
||||
let mut string = string;
|
||||
let result = string.element().replace(from.element().as_str(), to.element());
|
||||
|
||||
|
||||
@@ -29,10 +29,7 @@ async fn transform<T: 'n + Send + 'static>(
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_scale")]
|
||||
#[default(1., 1.)]
|
||||
scale: Item<DVec2>,
|
||||
// TODO: Replace this pair of shear angles with a single `f64` skew angle
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_skew")]
|
||||
#[hard(-89.9..89.9)]
|
||||
skew: Item<DVec2>,
|
||||
#[widget(ParsedWidgetOverride::Custom = "transform_skew")] skew: Item<DVec2>,
|
||||
) -> Item<T> {
|
||||
let (translation, rotation, scale, skew) = (*translation.element(), *rotation.element(), *scale.element(), *skew.element());
|
||||
|
||||
@@ -64,7 +61,7 @@ async fn transform_list<T: 'n + Send + 'static>(
|
||||
translation: Item<DVec2>,
|
||||
rotation: Item<f64>,
|
||||
scale: Item<DVec2>,
|
||||
#[hard(-89.9..89.9)] skew: Item<DVec2>,
|
||||
skew: Item<DVec2>,
|
||||
) -> List<T> {
|
||||
let (translation, rotation, scale, skew) = (*translation.element(), *rotation.element(), *scale.element(), *skew.element());
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::{Angle, PixelLength, PixelSize};
|
||||
use core_types::{CacheHash, Ctx};
|
||||
use dyn_any::DynAny;
|
||||
use glam::DVec2;
|
||||
@@ -31,15 +32,11 @@ fn arc(
|
||||
#[unit(" px")]
|
||||
#[default(50.)]
|
||||
radius: Item<f64>,
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(-180..180)]
|
||||
start_angle: Item<f64>,
|
||||
#[unit("°")]
|
||||
start_angle: Item<Angle>,
|
||||
#[default(270.)]
|
||||
#[range]
|
||||
#[soft(0..360)]
|
||||
sweep_angle: Item<f64>,
|
||||
sweep_angle: Item<Angle>,
|
||||
arc_type: Item<ArcType>,
|
||||
) -> Item<Vector> {
|
||||
let (radius, start_angle, sweep_angle, arc_type) = (*radius.element(), *start_angle.element(), *sweep_angle.element(), arc_type.into_element());
|
||||
@@ -58,18 +55,10 @@ fn spiral(
|
||||
_primary: (),
|
||||
spiral_type: Item<SpiralType>,
|
||||
#[default(5.)] turns: Item<f64>,
|
||||
#[unit("°")]
|
||||
#[default(0.)]
|
||||
start_angle: Item<f64>,
|
||||
#[unit(" px")]
|
||||
#[default(0.)]
|
||||
inner_radius: Item<f64>,
|
||||
#[unit(" px")]
|
||||
#[default(25)]
|
||||
outer_radius: Item<f64>,
|
||||
#[unit("°")]
|
||||
#[default(90.)]
|
||||
angular_resolution: Item<f64>,
|
||||
#[default(0.)] start_angle: Item<f64>,
|
||||
#[default(0.)] inner_radius: Item<f64>,
|
||||
#[default(25)] outer_radius: Item<f64>,
|
||||
#[default(90.)] angular_resolution: Item<f64>,
|
||||
) -> Item<Vector> {
|
||||
let (turns, start_angle, inner_radius, outer_radius, angular_resolution) = (
|
||||
*turns.element(),
|
||||
@@ -278,34 +267,17 @@ fn qr_code(
|
||||
fn arrow(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit(" px")]
|
||||
#[default(100., 0.)]
|
||||
arrow_to: Item<DVec2>,
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(10)]
|
||||
shaft_width: Item<f64>,
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(30)]
|
||||
head_width: Item<f64>,
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(20)]
|
||||
head_length: Item<f64>,
|
||||
#[default(100., 0.)] arrow_to: Item<PixelSize>,
|
||||
#[default(10)] shaft_width: Item<PixelLength>,
|
||||
#[default(30)] head_width: Item<PixelLength>,
|
||||
#[default(20)] head_length: Item<PixelLength>,
|
||||
) -> Item<Vector> {
|
||||
let (arrow_to, shaft_width, head_width, head_length) = (*arrow_to.element(), *shaft_width.element(), *head_width.element(), *head_length.element());
|
||||
Item::new_from_element(Vector::from_bezpath(shapes::arrow_bezpath(DVec2::ZERO, arrow_to, shaft_width, head_width, head_length)))
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Shape"))]
|
||||
fn line(
|
||||
_: impl Ctx,
|
||||
_primary: (),
|
||||
#[unit(" px")]
|
||||
#[default(100., 100.)]
|
||||
line_to: Item<DVec2>,
|
||||
) -> Item<Vector> {
|
||||
fn line(_: impl Ctx, _primary: (), #[default(100., 100.)] line_to: Item<PixelSize>) -> Item<Vector> {
|
||||
Item::new_from_element(Vector::from_bezpath(shapes::line_bezpath(DVec2::ZERO, *line_to.element())))
|
||||
}
|
||||
|
||||
@@ -340,13 +312,11 @@ fn grid<T: GridSpacing>(
|
||||
#[default(10)]
|
||||
#[hard(0..)]
|
||||
rows: Item<i64>,
|
||||
#[unit("°")]
|
||||
#[default(30., 30.)]
|
||||
angles: Item<DVec2>,
|
||||
#[default(30., 30.)] angles: Item<DVec2>,
|
||||
#[default(true)] connect_cells: Item<bool>,
|
||||
) -> Item<Vector> {
|
||||
let (grid_type, columns, rows, angles, connect_cells) = (grid_type.into_element(), *columns.element(), *rows.element(), *angles.element(), *connect_cells.element());
|
||||
let (columns, rows) = (columns as u32, rows as u32);
|
||||
let (columns, rows) = (columns.max(0) as u32, rows.max(0) as u32);
|
||||
|
||||
let (x_spacing, y_spacing) = spacing.element().as_dvec2().into();
|
||||
let (angle_a, angle_b) = angles.into();
|
||||
|
||||
@@ -4,6 +4,7 @@ use core::hash::{Hash, Hasher};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{ATTR_APPEARANCE, Item, ItemAttributeValues, List, ListDyn, NodeIdPath};
|
||||
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{
|
||||
@@ -403,7 +404,6 @@ async fn stroke<V>(
|
||||
paint: Item<Graphic>,
|
||||
/// The stroke thickness.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(2.)]
|
||||
weight: Item<f64>,
|
||||
/// The alignment of stroke to the path's centerline or (for closed shapes) the inside or outside of the shape.
|
||||
@@ -413,7 +413,6 @@ async fn stroke<V>(
|
||||
/// The curvature of the bent stroke at sharp corners.
|
||||
join: Item<StrokeJoin>,
|
||||
/// The threshold for when a miter-joined stroke is converted to a bevel-joined stroke when a sharp angle becomes pointier than this ratio.
|
||||
#[hard(0..)]
|
||||
#[default(4.)]
|
||||
miter_limit: Item<f64>,
|
||||
/// The stroke dash pattern. Each length forms a distance in a pattern where the first length is a dash, the second is a gap, and so on. If the list is an odd length, the pattern repeats with solid-gap roles reversed.
|
||||
@@ -484,13 +483,13 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
#[range]
|
||||
#[soft(0..2)]
|
||||
#[unit("x")]
|
||||
random_scale_min: Item<f64>,
|
||||
random_scale_min: Item<Multiplier>,
|
||||
/// Maximum range of randomized sizes given to each placed copy.
|
||||
#[default(1)]
|
||||
#[range]
|
||||
#[soft(0..2)]
|
||||
#[unit("x")]
|
||||
random_scale_max: Item<f64>,
|
||||
random_scale_max: Item<Multiplier>,
|
||||
/// Bias for the probability distribution of randomized sizes (0 is uniform, negatives favor more of small sizes, positives favor more of large sizes).
|
||||
#[range]
|
||||
#[soft(-50..50)]
|
||||
@@ -499,10 +498,9 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
#[hard(0..)]
|
||||
random_scale_seed: Item<i64>,
|
||||
/// Range of randomized angles given to each placed copy, in degrees ranging from furthest clockwise to counterclockwise.
|
||||
#[unit("°")]
|
||||
#[range]
|
||||
#[soft(0..360)]
|
||||
random_rotation: Item<f64>,
|
||||
random_rotation: Item<Angle>,
|
||||
/// Seed to determine unique variations on all the randomized copy angles.
|
||||
#[hard(0..)]
|
||||
random_rotation_seed: Item<i64>,
|
||||
@@ -565,24 +563,18 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
async fn round_corners<V: MapVectorItems + 'n + Send>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Graphic, Vector)] source: Item<V>,
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(10.)]
|
||||
radius: Item<f64>,
|
||||
radius: Item<PixelLength>,
|
||||
#[range]
|
||||
#[hard(0..1)]
|
||||
#[default(0.5)]
|
||||
roundness: Item<f64>,
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
#[default(100.)]
|
||||
edge_length_limit: Item<f64>,
|
||||
#[unit("°")]
|
||||
#[default(100.)] edge_length_limit: Item<Percentage>,
|
||||
#[range]
|
||||
#[hard(0..180)]
|
||||
#[default(5.)]
|
||||
min_angle_threshold: Item<f64>,
|
||||
min_angle_threshold: Item<Angle>,
|
||||
) -> Item<V> {
|
||||
V::map_vector_items(source, |source| {
|
||||
let (radius, roundness, edge_length_limit, min_angle_threshold) = (*radius.element(), *roundness.element(), *edge_length_limit.element(), *min_angle_threshold.element());
|
||||
@@ -678,10 +670,9 @@ async fn round_corners<V: MapVectorItems + 'n + Send>(
|
||||
fn merge_by_distance<V: MapVectorItems + Send + Sync + 'static>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Graphic, Vector)] content: Item<V>,
|
||||
#[unit(" px")]
|
||||
#[default(0.1)]
|
||||
#[hard(0.0001..)]
|
||||
distance: Item<f64>,
|
||||
distance: Item<PixelLength>,
|
||||
algorithm: Item<MergeByDistanceAlgorithm>,
|
||||
) -> Item<V> {
|
||||
let (distance, algorithm) = (*distance.element(), *algorithm.element());
|
||||
@@ -1500,9 +1491,7 @@ async fn offset_path<V: MapVectorItems + 'n + Send>(
|
||||
#[implementations(Graphic, Vector)] content: Item<V>,
|
||||
distance: Item<f64>,
|
||||
join: Item<StrokeJoin>,
|
||||
#[hard(0..)]
|
||||
#[default(4.)]
|
||||
miter_limit: Item<f64>,
|
||||
#[default(4.)] miter_limit: Item<f64>,
|
||||
) -> Item<V> {
|
||||
V::map_vector_items(content, |content| {
|
||||
let mut content = content;
|
||||
@@ -1900,10 +1889,9 @@ async fn simplify<V: MapVectorItems + 'n + Send>(
|
||||
#[implementations(Graphic, Vector)]
|
||||
content: Item<V>,
|
||||
/// The maximum distance the simplified path may deviate from the original.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(5.)]
|
||||
tolerance: Item<f64>,
|
||||
#[unit(" px")]
|
||||
tolerance: Item<Length>,
|
||||
) -> Item<V> {
|
||||
let tolerance = *tolerance.element();
|
||||
|
||||
@@ -1942,10 +1930,9 @@ async fn decimate<V: MapVectorItems + 'n + Send>(
|
||||
#[implementations(Graphic, Vector)]
|
||||
content: Item<V>,
|
||||
/// The maximum distance a point can deviate from the simplified path before it is kept.
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(5.)]
|
||||
tolerance: Item<f64>,
|
||||
#[unit(" px")]
|
||||
tolerance: Item<Length>,
|
||||
) -> Item<V> {
|
||||
V::map_vector_items(content, |content| {
|
||||
let mut content = content;
|
||||
@@ -2069,8 +2056,7 @@ async fn cut_path<V: MapVectorItems + 'n + Send>(
|
||||
#[implementations(Graphic, Vector)]
|
||||
content: Item<V>,
|
||||
/// The factor from the start to the end of the path, 0–1 for one subpath, 1–2 for a second subpath, and so on.
|
||||
#[progression]
|
||||
progression: Item<f64>,
|
||||
progression: Item<Progression>,
|
||||
/// Swap the direction of the path.
|
||||
reverse: Item<bool>,
|
||||
/// Traverse the path using each segment's Bézier curve parameterization instead of the Euclidean distance. Faster to compute but doesn't respect actual distances.
|
||||
@@ -2181,8 +2167,7 @@ async fn position_on_path(
|
||||
/// The path to traverse.
|
||||
content: Item<Vector>,
|
||||
/// The factor from the start to the end of the path, 0–1 for one subpath, 1–2 for a second subpath, and so on.
|
||||
#[progression]
|
||||
progression: Item<f64>,
|
||||
progression: Item<Progression>,
|
||||
/// Swap the direction of the path.
|
||||
reverse: Item<bool>,
|
||||
/// Traverse the path using each segment's Bézier curve parameterization instead of the Euclidean distance. Faster to compute but doesn't respect actual distances.
|
||||
@@ -2219,8 +2204,7 @@ async fn tangent_on_path(
|
||||
/// The path to traverse.
|
||||
content: Item<Vector>,
|
||||
/// The factor from the start to the end of the path, 0–1 for one subpath, 1–2 for a second subpath, and so on.
|
||||
#[progression]
|
||||
progression: Item<f64>,
|
||||
progression: Item<Progression>,
|
||||
/// Swap the direction of the path.
|
||||
reverse: Item<bool>,
|
||||
/// Traverse the path using each segment's Bézier curve parameterization instead of the Euclidean distance. Faster to compute but doesn't respect actual distances.
|
||||
@@ -2408,8 +2392,8 @@ async fn jitter_points<V: MapVectorItems + 'n + Send>(
|
||||
#[implementations(Graphic, Vector)]
|
||||
content: Item<V>,
|
||||
/// The maximum extent of the random distance each point can be offset.
|
||||
#[unit(" px")]
|
||||
#[default(5.)]
|
||||
#[unit(" px")]
|
||||
max_distance: Item<f64>,
|
||||
/// Seed used to determine unique variations on all randomized offsets.
|
||||
#[hard(0..)]
|
||||
@@ -2505,8 +2489,7 @@ async fn morph(
|
||||
/// The vector objects to interpolate between. Mixed graphic content is deeply flattened to keep only vector elements.
|
||||
content: List<Graphic>,
|
||||
/// The fractional part `[0, 1)` traverses the morph uniformly along the path. If the control path has multiple subpaths, each added integer selects the next subpath.
|
||||
#[progression]
|
||||
progression: Item<f64>,
|
||||
progression: Item<Progression>,
|
||||
/// Swap the direction of the progression between objects or along the control path.
|
||||
reverse: Item<bool>,
|
||||
/// The parameter of change that influences the interpolation speed between each object. Equal slices in this parameter correspond to the rate of progression through the morph. This must be set to a parameter that changes.
|
||||
@@ -3441,14 +3424,7 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
fn bevel<V: MapVectorItems + Send + Sync + 'static>(
|
||||
_: impl Ctx,
|
||||
#[implementations(Graphic, Vector)] source: Item<V>,
|
||||
#[unit(" px")]
|
||||
#[hard(0..)]
|
||||
#[default(10.)]
|
||||
distance: Item<f64>,
|
||||
) -> Item<V> {
|
||||
fn bevel<V: MapVectorItems + Send + Sync + 'static>(_: impl Ctx, #[implementations(Graphic, Vector)] source: Item<V>, #[default(10.)] distance: Item<Length>) -> Item<V> {
|
||||
V::map_vector_items(source, |source| {
|
||||
let distance = *distance.element();
|
||||
|
||||
@@ -3766,9 +3742,7 @@ mod test {
|
||||
// Relaxation preserves the point count but repositions the interior anchors within the hull.
|
||||
assert_eq!(vector.point_domain.ids().len(), points.len());
|
||||
assert_ne!(vector.point_domain.positions(), &points[..]);
|
||||
// The convex-hull corners are pinned. Asserted on the count first, since zipping a short result
|
||||
// would skip the checks rather than fail them.
|
||||
assert!(vector.point_domain.positions().len() >= 4, "the relaxed hull should still have its four corners");
|
||||
// The convex-hull corners are pinned.
|
||||
for (corner, (&position, &point)) in vector.point_domain.positions().iter().zip(&points).take(4).enumerate() {
|
||||
assert_eq!(position, point, "hull corner {corner} should be pinned");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
# Runtime deltas: design context and follow-up plan
|
||||
|
||||
Working notes for the in-vivo runtime delta effort on this branch, recording what exists, the
|
||||
motivation behind each decision, and the context needed to complete the remaining phases. The
|
||||
decisions here were settled in design discussion between Keavon and TrueDoctor during July 2026.
|
||||
|
||||
## What exists on this branch
|
||||
|
||||
- `graph_craft::runtime_delta::RuntimeDelta`: the structural delta enum. Payload-carrying,
|
||||
constructed at mutation time, plain runtime types, no serialization. Variants: `AddNode`,
|
||||
`ReplaceNode` (carrying `Box<DocumentNode>`), `RemoveNode` (address-only), `SetInput`,
|
||||
`SetExport`, `SetVisibility`.
|
||||
- `editor::...::network_interface::editor_delta`: the editor-side wrapper `EditorDelta
|
||||
{ Graph(RuntimeDelta), NodeMetadata { .. } }` and `construct_batch`, which turns one gesture's
|
||||
deltas into storage `RegistryDelta` ops.
|
||||
- Parity tests (`editor_delta_tests`) proving the constructed ops equal the ops a whole-document
|
||||
diff would stage: exactly (op-for-op) for slot, export, visibility, and metadata changes;
|
||||
by stored-state equivalence for structural add/remove batches.
|
||||
- Substrate reused from the earlier marker-based experiment: `ScopedConversion` (per-entity
|
||||
conversion through the canonical `from_runtime` encoders), `PathResolver` (path-hash ID
|
||||
derivation without conversion), `Session::stage_computed_ops`, `GddV1::stage_runtime_deltas`.
|
||||
|
||||
Not yet wired: mutation sites do not emit deltas, staging does not consume them, and the compiler
|
||||
still receives whole-network clones.
|
||||
|
||||
## Decisions and their motivations
|
||||
|
||||
**In-vivo payload deltas, not dirty-set markers.** An earlier experiment (branches
|
||||
`runtime-deltas-1-record` / `runtime-deltas-3-flip`, kept for reference) recorded scope markers and
|
||||
re-derived deltas at staging by scoped reconversion. Rejected because the perf case did not hold
|
||||
holistically: the editor stages after every mutation for the compiler anyway, so the data is in
|
||||
hand at mutation time regardless, and payload capture costs nothing extra. Payloads also make the
|
||||
delta a bidirectional currency (storage, compiler, and later undo/collab all speak it), which
|
||||
markers structurally cannot.
|
||||
|
||||
**Graph-craft structural enum plus an editor wrapper.** The compiler must consume deltas without
|
||||
editor dependencies, and a separate compiler-only delta type (a third set) was explicitly ruled
|
||||
out. `SetInput`/`SetExport` are separate variants so the editor's `InputConnector` type does not
|
||||
leak into graph-craft.
|
||||
|
||||
**Wholesale metadata copies, diffed by storage.** Rather than per-field metadata variants, one
|
||||
`NodeMetadata` delta carries a copy of the node's persistent metadata (cheap to clone). Storage
|
||||
diffs it against the working registry so minimal attribute ops fall out; the compiler throws it
|
||||
away. This also absorbs ambiguity: the delta does not need to know which fields changed.
|
||||
|
||||
**`SetVisibility` is structural.** `visible` is a `DocumentNode` field the compiler consumes for
|
||||
rendering. The rare other scalar setters (`call_argument`, `context_features`) go through
|
||||
`ReplaceNode` instead of dedicated variants.
|
||||
|
||||
**Batch-scoped construction.** Removal closures and resource liveness are properties of the whole
|
||||
gesture, not one delta: deleting a group with children removes several nodes whose shared
|
||||
declaration only becomes unreferenced once all of them are gone. `construct_batch` is therefore
|
||||
the construction unit, matching how mutations emit (compound operations produce several deltas)
|
||||
and how staging consumes.
|
||||
|
||||
**Arc-backed input values (agreed, not yet implemented).** `NodeInput::Value`'s `TaggedValue`
|
||||
storage should become `Arc`-backed (inside the existing `MemoHash`), mutating via `Arc::make_mut`.
|
||||
Delta capture, compiler updates, and undo snapshots then share by pointer bump instead of cloning;
|
||||
copy-on-write fires only when an old version is genuinely still held, which is exactly when a copy
|
||||
is semantically required. This is a prerequisite for cheap drag/paint deltas and should land in
|
||||
graph-craft before the mutation sites are wired.
|
||||
|
||||
**Accumulation and desync carry over from the earlier design.** A pending buffer on the interface
|
||||
accumulates delta batches with same-target coalescing (a drag keeps first-to-last one `SetInput`).
|
||||
Anything that cannot itemize its changes (document open, snapshot install, raw network access,
|
||||
storage mount) desyncs the buffer, forcing one whole-document diff before delta staging resumes.
|
||||
The `verify_journal_projection` soak pattern from the earlier branches (constructed ops compared
|
||||
against the whole-document diff on every staging under the `validate_storage_round_trip`
|
||||
preference) is the validation harness to reuse; it caught real bugs twice there.
|
||||
|
||||
## Remaining phases to land forward deltas
|
||||
|
||||
1. Arc-backed values in graph-craft.
|
||||
2. The pending buffer on `NodeNetworkInterface` (accumulation, coalescing, desync states).
|
||||
3. Site wiring: roughly thirty mutation sites emit their delta batches, capturing state after
|
||||
mutating. The site catalog from the earlier experiment maps every `transaction_modified` call
|
||||
site to what it touches. **Open fork, see "Emission" below; do not start without a decision.**
|
||||
4. Staging: `construct_batch` into `Session::stage_computed_ops` via `GddV1::stage_runtime_deltas`,
|
||||
with the whole-document diff as the desync fallback and the parity soak in validate mode.
|
||||
5. Compiler consumption: replace the per-update whole-network clone in `GraphUpdate` with the
|
||||
`RuntimeDelta` stream reconciling a mirror on the runtime thread, using apply-reported change
|
||||
as the invalidation signal.
|
||||
|
||||
### Emission: the open fork on phase 3
|
||||
|
||||
Mutators do not yield deltas today; the delta is recovered by diffing the whole registry at commit
|
||||
time (`Session::stage_from_runtime`). Three shapes, none chosen:
|
||||
|
||||
- **(a) Emit at the `store.rs` primitives.** Every write already funnels through them, so emission
|
||||
cannot be forgotten. But they are finer-grained than `RuntimeDelta` (`insert_input_slot`, not
|
||||
`SetInput`), so peers would receive a different, lower-level language than `EditorDelta` defines.
|
||||
- **(b) Emit at the mutator level.** Matches `RuntimeDelta` granularity exactly, but must be
|
||||
hand-added to roughly forty public mutators and can silently be forgotten in a new one.
|
||||
- **(c) Keep diffing, but scope the diff to the batch's touched set** rather than the whole
|
||||
document. Reuses `compute_deltas`, cannot drift, and `verify_round_trip` already proves the diff
|
||||
faithful. Cost: no semantic delta, a move stays a remove-plus-add. Fine for peers, since
|
||||
`RegistryDelta` is the wire format anyway; not what incremental compilation wants.
|
||||
|
||||
Rough read at the time of writing: (c) if peer sync is the driver, (b) if incremental compilation
|
||||
is. (a) is the only structurally un-forgettable one but changes what a delta means.
|
||||
|
||||
Sequencing once that is decided: the **batch boundary** comes first (a scope a run of writes
|
||||
happens inside, collecting emitted deltas and the dirty set, flushed once at the end), because both
|
||||
emission and the deferred invalidation flush need it. Decide explicit `finish()` versus `Drop`;
|
||||
`Drop` cannot report failure and interacts awkwardly with `transaction_modified`. Then `apply` as
|
||||
mechanism only, which is the smaller half because `store.rs` is already total and already the
|
||||
single writer. Gate for `apply`: `validate_invariants()` empty afterwards, and applying a
|
||||
mutation's own delta to a clone of the interface reproduces that interface.
|
||||
|
||||
## Interface restructure state (branch `runtime-deltas-2`, 2026-09-22)
|
||||
|
||||
The restructure that prepares `NodeNetworkInterface` for the above. Twenty-two commits, rebased
|
||||
onto `origin/master` at `d7ae6029e0`, nothing pushed.
|
||||
|
||||
### Module shape
|
||||
|
||||
`editor/src/messages/portfolio/document/utility_types/network_interface/`
|
||||
|
||||
| file | role | lines, start to now |
|
||||
|---|---|---|
|
||||
| `store.rs` | the only writer of both parallel trees | new, 428 |
|
||||
| `mutations.rs` | policy: validation, layout decisions | 1629 to 1271 |
|
||||
| `layout.rs` | positioning policy | 1295 |
|
||||
| `caches.rs` | transient cache slots | 1258 to 876 |
|
||||
| `queries.rs` | reads | 1229 to 966 |
|
||||
| `geometry.rs` | click targets, ports, widths | new, 352 |
|
||||
| `frontend.rs` | frontend projections | new, 181 |
|
||||
| `invalidation.rs` | named invalidation rules | new, 40 |
|
||||
|
||||
`network: MemoNetwork` and `network_metadata: NodeNetworkMetadata` are parallel trees keyed by the
|
||||
same `NodeId`s. `store.rs` is their single writer, so every write keeps them in step by
|
||||
construction; `validate_invariants` (test-only, `validation.rs`) checks it.
|
||||
|
||||
The resolved cursors `NodeMut` / `NetworkMut` hold disjoint field borrows and therefore cannot call
|
||||
back into the interface. That is deliberate: it forces what a write invalidates to be *declared* by
|
||||
the caller rather than performed inside the write.
|
||||
|
||||
### Identity
|
||||
|
||||
Storage `NodeId` resolution goes through exactly one place, `NodeIds::resolve` in
|
||||
`document/graph-storage/src/from_runtime.rs`: it prefers the identity the metadata source holds and
|
||||
falls back to `blake3(peer, NodePath)`, a hash of the node's location. Every naming site routes
|
||||
through it, including the node's own registry key, input references, scope injections,
|
||||
`PathResolver` and `ScopedConversion`.
|
||||
|
||||
`NodeMetadataEntry` carries `storage_id` and is emitted for every node (`is_empty()` is gone).
|
||||
`build_interface_from_storage` pins it onto `DocumentNodePersistentMetadata::storage_id`, so a
|
||||
document that round-trips through storage keeps its identities.
|
||||
`rebuilt_interface_keeps_storage_identities` (in `storage_tests/metadata_tests.rs`) asserts a
|
||||
re-conversion under a *different peer* reproduces the same ids.
|
||||
|
||||
**Minting is deliberately not done** (Dennis chose this on 2026-09-22), because:
|
||||
|
||||
- `NodeTemplate` drops `storage_id` in both `from_parts` and `into_parts`, so a remove/insert
|
||||
template round trip loses the pin. Making the template carry it collides with its other role as
|
||||
the clipboard and definition type.
|
||||
- Grouping, ungrouping and paste all go through `copy_nodes`, which assigns *new runtime* `NodeId`s
|
||||
to everything, so a node entering a group is already a new node at the runtime level.
|
||||
- Nothing else in a session changes a node's location while keeping its runtime id, so a mint is
|
||||
currently unobservable.
|
||||
|
||||
Agreed sequencing: make grouping preserve runtime ids **first**, then mint. The north star stays
|
||||
"the gdd native path is minting, the hash is only polyfill".
|
||||
|
||||
### Open items
|
||||
|
||||
1. **Deferred dirty-set flush** (step 4 tail). Blocked on the batch boundary above; do not invent
|
||||
one just to have somewhere to flush into.
|
||||
2. **Deleting the `queries.rs` wrappers** (step 5). Standing objection: roughly forty one-line
|
||||
delegations against migrating hundreds of call sites. Not done; reopen only if Dennis disagrees.
|
||||
3. **Move the module up beside `node_graph/`** (step 6). Pure file shuffle, do it whenever.
|
||||
4. **Grouping preserving runtime ids**, the prerequisite for minting.
|
||||
|
||||
### Complexity
|
||||
|
||||
Fixed: `collect_removal_closure` was O(nested networks x all nodes), rescanning `node_instances`
|
||||
per network; it now uses a `NodesByNetwork` index built once. `construct_resource_removals` was
|
||||
O(candidates x (nodes + exports)); it now builds a `still_referenced` set in one pass. Dead
|
||||
plumbing removed along the way (`batch_removed_networks` was computed and never read; `construct`
|
||||
took `batch_removed_nodes` only to discard it).
|
||||
|
||||
Still open, design-level rather than local bugs:
|
||||
|
||||
- **`position()` is not memoized.** Each call walks downstream to the first stored absolute
|
||||
position, so computing positions for many nodes is O(n x depth). A document that is one tall
|
||||
stack makes `nodes_sorted_top_to_bottom`, and therefore every `shift_nodes`, quadratic. Fixing it
|
||||
means caching resolved positions against an invalidation epoch.
|
||||
- **`settle_drag_offsets` and `push_stack_down_to_fit` move one grid row per iteration**, calling
|
||||
`check_collision_with_stack_dependents` / `vertical_shift_with_push` each time, so cost scales
|
||||
with the distance moved times a stack walk rather than with node count. Inherent to the
|
||||
incremental-push model.
|
||||
|
||||
### Latent bugs found and left alone
|
||||
|
||||
- `reposition_disconnected_upstream` (`layout.rs`): the nested `if` is load-bearing. A layer left
|
||||
feeding the bottom of a *non-layer* currently does nothing, neither stacks nor goes absolute.
|
||||
Flattening it changes behaviour, so it was moved verbatim. Looks like a bug, not a deliberate
|
||||
case.
|
||||
- `add_export` reaches into `encapsulating_network_metadata_mut(..).transient_metadata` directly to
|
||||
unload two caches, bypassing `invalidation.rs`. It cannot simply call
|
||||
`unload_all_nodes_bounding_box`, which *also* invalidates import/export ports, so substituting
|
||||
would add an invalidation. Needs a decision.
|
||||
- `add_export` / `add_import` invalidate almost exactly what `finish_signature_edit` does, but in a
|
||||
different order, with different `load_structure` gates, and `add_export` must handle the root
|
||||
network. Merging them would be behaviour-changing, not a refactor.
|
||||
- The dead `lowest_upstream_node_height` loop removed from `move_layer_to_stack` had a `log::error!`
|
||||
plus `return` that aborted the whole move as a side effect of computing a value nobody read.
|
||||
Removing it narrows that abort; reinstate as an explicit check if it turns out to matter.
|
||||
|
||||
### Gates
|
||||
|
||||
- `cargo check -p graphite-editor --all-targets`
|
||||
- `cargo clippy --workspace --all-targets`, must be **zero** warnings; pre-existing ones were fixed
|
||||
too, on Dennis's instruction.
|
||||
- `cargo fmt --all` after every change.
|
||||
- `cargo test -p graphite-editor` (225 pass, 1 ignored);
|
||||
`cargo test -p document-graph-storage` (57); `-p document-format -p document-container` (48).
|
||||
- Wasm gate, needed only when touching `document-container`, `document-format`, `graph-storage` or
|
||||
the editor `future` module: `nix develop --command cargo run build web debug`, about two minutes.
|
||||
`wasm-pack` is not on the bare PATH; the flake provides it.
|
||||
|
||||
The sharp round-trip gate for identity work is `recommit_after_open_is_stable` in
|
||||
`storage_tests/round_trip_tests.rs`, plus `verify_round_trip` in `document_history.rs`, which
|
||||
panics under `#[cfg(test)]` on registry value drift after commit.
|
||||
|
||||
### Method note
|
||||
|
||||
Extracting named pieces from this code costs roughly as many lines as it saves once signatures, doc
|
||||
comments and the `-> bool` plumbing that preserves abort-on-error behaviour are counted. Across
|
||||
three refactors the net was about -38, +5 and +35 lines. Promise readability, not line reduction. A
|
||||
pedantic clippy sweep on the editor is not worth running: roughly five hundred warnings
|
||||
workspace-wide, dominated by house-style choices (`&NodeId` parameters, `use super::*`). Take idiom
|
||||
fixes only in code you are already touching.
|
||||
|
||||
## Follow-up PR: storage-driven undo (decided: debug-compare rollout)
|
||||
|
||||
Direction: undo/redo stop installing interface snapshots and instead replay deltas returned by the
|
||||
storage layer, whose retirement machinery already precomputes every delta's reverse and applies it
|
||||
to the working registry on cursor moves.
|
||||
|
||||
Shape agreed in discussion:
|
||||
|
||||
1. `Session::undo`/`redo` return the `RegistryDelta` ops they applied (today they are applied and
|
||||
discarded).
|
||||
2. A backward projection turns those ops into `EditorDelta`s: slot and export ops via single-input
|
||||
`to_runtime`; `AddNode`/`AddNetwork` ops materialize nodes from the op payloads (reverses carry
|
||||
full snapshots, so nothing is missing); attribute ops collapse into one `NodeMetadata` delta
|
||||
per touched node, read from the post-move registry through the existing `to_runtime` metadata
|
||||
path; global-to-local IDs resolve via the stashed `original_node_id` attributes.
|
||||
3. `NodeNetworkInterface::apply_deltas(&[EditorDelta])` maps each variant onto existing mutation
|
||||
primitives plus a shared cache-invalidation epilogue. Applying must not re-record into the
|
||||
pending buffer (the ops are already history), so apply runs with recording suppressed; that
|
||||
suppression flag is the one new piece of interface state.
|
||||
|
||||
Rollout decision: **debug-compare**. Legacy snapshot undo remains authoritative while the
|
||||
storage-driven path runs in parallel, applying to the same interface state and comparing against
|
||||
the snapshot result; divergence logs in release and panics in tests, mirroring the existing
|
||||
round-trip soak conventions. Snapshots are deleted only once the compare has been quiet across the
|
||||
test suite and real use.
|
||||
|
||||
Known open points for that PR:
|
||||
|
||||
- Compare granularity: full interface equality per undo step is the strongest check and is likely
|
||||
affordable at undo frequency; decide whether metadata-only divergence should fail equally hard.
|
||||
- Selection and view state are not in the registry, so storage-driven undo must leave them to the
|
||||
existing selection-history machinery rather than expecting them back from deltas.
|
||||
- The same backward projection and apply pair is the future collab receive path; keep signatures
|
||||
free of undo-specific assumptions.
|
||||
Reference in new issue
Block a user