Compare commits

...
Author SHA1 Message Date
Dennis Kobert e9e0477de3 Add a history graph overlay that draws every step and branch over the viewport as a tree 2026-11-07 19:46:38 +00:00
Dennis Kobert ad11756f4e Render History panel captures as rasters like layer thumbnails, with a close-up of what the step changed tinted by whether it was added, removed or changed 2026-11-07 19:46:31 +00:00
Dennis Kobert 789e9c90bf Capture an empty document as a blank History panel thumbnail rather than none 2026-11-07 19:46:31 +00:00
Dennis Kobert d51de170a7 Capture each History panel step as soon as no tool is mid-gesture, keyed by its newest change so a capture taken while hot stays with the step once it enters history 2026-11-07 19:46:31 +00:00
Dennis Kobert 994f18fb0d Ask for a History panel capture again when a newer graph replaced its request, handle captures after a failed run and keep at most 300 per open document 2026-11-07 19:46:30 +00:00
Dennis Kobert 2ff42eef90 Show each History panel step as the document looked once it was done, outlining what it added, removed and changed 2026-11-07 19:46:30 +00:00
Dennis Kobert af0e8614ac Repair the graph when a step is brought back or removed onto a line that changed since, and simulate every history operation to check it stays whole and converged 2026-11-07 19:46:16 +00:00
Dennis Kobert 0ef97e9dcc Name the History panel steps that add an image or SVG, cut nodes or paste layers 2026-11-07 13:41:25 +00:00
Dennis Kobert bffd30eca2 Name the History panel step a deletion makes and lead fallback names with the nodes a step adds or removes 2026-11-07 11:31:45 +00:00
Dennis Kobert 6d26c35b52 Mark the pending History panel step as now while alone and refresh the panel when a step is named 2026-11-07 10:23:12 +00:00
Dennis Kobert 763ad33587 Show History panel steps before they enter history while alone, take a retracted step's name back with it and name renamed nodes as nodes 2026-11-07 09:30:43 +00:00
Dennis Kobert 985a4f4a36 Name History panel steps by their tool action, by the nodes and inputs they change, and without the bookkeeping that comes along 2026-11-06 23:49:59 +00:00
Dennis Kobert 09175112aa Keep the History panel's rows on one rail, show the expand arrow only for steps of several changes and leave out collaboration details while nobody else is connected 2026-11-06 23:33:49 +00:00
36 changed files with 3051 additions and 203 deletions

No files matched your search

+5
View File
@@ -400,6 +400,11 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Names this peer's open interaction. Closing it takes the name along.
pub fn name_interaction(&mut self, action: &str) {
self.session.name_interaction(action);
}
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
let Some(retraction) = self.session.retract_interaction()? else {
@@ -74,4 +74,6 @@ pub mod delta {
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. Also set on
/// the last hot op of an interaction.
pub const INTERACTION_END: &str = "interaction_end";
/// What the user did in an interaction, such as a tool action. Set on the last hot op and the last delta.
pub const ACTION: &str = "action";
}
+8
View File
@@ -55,6 +55,14 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// What the user did in the interaction this delta ends, if it was named.
pub fn action(&self) -> Option<&str> {
match &self.attributes.get(attr::delta::ACTION)?.value {
Value::Str(action) => Some(action),
_ => None,
}
}
/// Take over `original`'s annotations and retirement time, for a delta that replaces it in rewritten history.
pub fn carry_annotations(&mut self, original: &Delta) {
self.attributes = original.attributes.clone();
+2
View File
@@ -10,6 +10,7 @@ pub mod ids;
pub mod model;
mod prior;
pub mod registry;
mod repair;
pub mod resources;
mod schema;
pub mod session;
@@ -49,6 +50,7 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
mod tests {
mod bookkeeping;
mod crdt;
mod history_simulation;
mod projection;
mod round_trip;
mod sessions;
+273
View File
@@ -0,0 +1,273 @@
//! Repairs the graph after steps are replayed onto a line that changed since they were made, as bringing a step back
//! or removing one does. Replayed writes keep their stamps, so a slot written since keeps the newer value, which can
//! leave an input naming a removed node, two nodes on one, or a node nothing reaches any more.
//!
//! Nodes connected through their primary inputs form chains, like a stack of layers or a node feeding the next. Each
//! chain hangs off a head slot: an export, or an input past the primary one. The repair rebuilds every chain from the
//! order the line had before the replay and the order the replayed step left it in when it was made, so the step's
//! own changes land on the chains as they are now.
use crate::{NetworkId, NodeId, NodeInput, Registry, RegistryDelta};
use std::collections::{BTreeSet, HashMap, HashSet};
/// Each node's network and newest primary input anywhere in history, for nodes this line no longer or never had.
pub(crate) type KnownInputs = HashMap<NodeId, (NetworkId, NodeInput)>;
/// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Slot {
Input(NodeId, u32),
Export(NetworkId, u32),
}
/// A chain's nodes from its head down, and what the last one rests on.
struct Chain {
head: Slot,
nodes: Vec<NodeId>,
bottom: Option<NodeInput>,
}
/// The ops that repair `registry`, which is `before` with `replayed` folded in. `intended` is the document as the
/// replayed step left it when it was made, and `gone` the nodes it must not have, as those the step deleted.
/// - A node in `gone`, or in neither `before` nor `intended`, is removed. A newer write to a node revives it over an
/// older removal, as one made on the line since does over a deletion brought back.
/// - Every chain keeps the nodes it had before, in their order, except those the replayed step moved, which take
/// their place from `intended`, after the node they followed there. A node the step added lands the same way.
/// - A node on no chain any more, which was on one, goes back where it was.
/// - An input naming a removed node takes that node's primary input instead, as deleting a node reconnects what it
/// sat between. A node this line never had counts as removed, with the primary input `known` gives it.
pub(crate) fn repair_ops(before: &Registry, registry: &Registry, intended: &Registry, replayed: &[RegistryDelta], gone: &HashSet<NodeId>, known: &KnownInputs) -> Vec<RegistryDelta> {
let mut registry = registry.clone();
let mut ops = Vec::new();
let mut unwanted: Vec<NodeId> = registry
.node_instances
.keys()
.filter(|id| gone.contains(id) || (!before.node_instances.contains_key(id) && !intended.node_instances.contains_key(id)))
.copied()
.collect();
unwanted.sort();
for id in unwanted {
if let Some(snapshot) = registry.node_instances.remove(&id) {
ops.push(RegistryDelta::RemoveNode { id, snapshot });
}
}
let live = |id: &NodeId| registry.node_instances.contains_key(id);
let placed_by_step: HashSet<NodeId> = replayed.iter().flat_map(placed_nodes).filter(live).collect();
let heads: BTreeSet<Slot> = [before, &registry, intended].into_iter().flat_map(head_slots).filter(|&slot| owner_is_live(&registry, slot)).collect();
let was_in = |registry: &Registry| -> HashMap<NodeId, Slot> { heads.iter().flat_map(|&head| chain(registry, head).nodes.into_iter().map(move |id| (id, head))).collect() };
let (was_before, was_intended) = (was_in(before), was_in(intended));
// Where each node goes: where the step put it if it placed it, else where it was
let home = |id: &NodeId| match placed_by_step.contains(id) {
true => was_intended.get(id).or(was_before.get(id)),
false => was_before.get(id).or(was_intended.get(id)),
};
let mut chains = Vec::new();
let mut taken = HashSet::new();
for &head in &heads {
let owner = match head {
Slot::Input(owner, _) => Some(owner),
Slot::Export(..) => None,
};
let fits = |id: &NodeId| live(id) && Some(*id) != owner && home(id) == Some(&head);
let earlier = chain(before, head);
let wanted = chain(intended, head);
// A node the step placed counts as moved when it sits on the other side of a node both orders have
let common: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| live(id) && wanted.nodes.contains(id)).collect();
let rank = |order: &[NodeId], id: &NodeId| order.iter().position(|node| node == id);
let moved = |id: &NodeId| {
placed_by_step.contains(id)
&& common.contains(id)
&& common
.iter()
.any(|other| other != id && (rank(&earlier.nodes, id) < rank(&earlier.nodes, other)) != (rank(&wanted.nodes, id) < rank(&wanted.nodes, other)))
};
let mut nodes: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| fits(id) && !moved(id)).collect();
for (position, id) in wanted.nodes.iter().enumerate() {
if nodes.contains(id) || !fits(id) {
continue;
}
let after = wanted.nodes[..position].iter().rev().find_map(|above| nodes.iter().position(|node| node == above));
nodes.insert(after.map_or(0, |index| index + 1), *id);
}
// What the chain rests on, as long as nothing else sits on it
let bottom = [earlier.bottom, wanted.bottom].into_iter().flatten().find(|bottom| match bottom {
NodeInput::Node { id, .. } => live(id) && home(id).is_none(),
_ => true,
});
taken.extend(nodes.iter().copied());
chains.push(Chain { head, nodes, bottom });
}
for chain in &chains {
let mut slot = chain.head;
for &id in &chain.nodes {
set(&mut registry, &mut ops, slot, Some(on(id)));
slot = Slot::Input(id, 0);
}
if let Some(bottom) = &chain.bottom {
set(&mut registry, &mut ops, slot, Some(bottom.clone()));
} else if let Some(NodeInput::Node { id, .. }) = slot_value(&registry, slot)
&& (taken.contains(&id) || !registry.node_instances.contains_key(&id))
{
// Resting on a node another chain holds, or one gone, it rests on nothing instead
let cleared = match slot {
Slot::Export(..) => None,
Slot::Input(..) => reconnect(&registry, id, slot_network(&registry, slot), known).filter(|input| !matches!(input, NodeInput::Node { .. })),
};
if cleared.is_some() || matches!(slot, Slot::Export(..)) {
set(&mut registry, &mut ops, slot, cleared);
}
}
}
// Inputs off every chain still naming a removed node
for (slot, named) in slots(&registry) {
if registry.node_instances.contains_key(&named) {
continue;
}
let reconnected = reconnect(&registry, named, slot_network(&registry, slot), known).or_else(|| slot_value(before, slot).filter(|earlier| !names_missing(&registry, earlier)));
if reconnected.is_some() || matches!(slot, Slot::Export(..)) {
set(&mut registry, &mut ops, slot, reconnected);
}
}
ops
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
fn names_missing(registry: &Registry, input: &NodeInput) -> bool {
matches!(input, NodeInput::Node { id, .. } if !registry.node_instances.contains_key(id))
}
/// The nodes a write places in a slot, or adds.
fn placed_nodes(op: &RegistryDelta) -> Vec<NodeId> {
match op {
RegistryDelta::AddNode { id, .. } => vec![*id],
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let placed = match new_input {
NodeInput::Node { id: placed, .. } => Some(*placed),
_ => None,
};
(*index == 0).then_some(*id).into_iter().chain(placed).collect()
}
RegistryDelta::SetNetworkExport {
export: Some(NodeInput::Node { id, .. }),
..
} => vec![*id],
_ => Vec::new(),
}
}
/// Every slot naming a node, in a fixed order.
fn slots(registry: &Registry) -> Vec<(Slot, NodeId)> {
let mut slots = Vec::new();
for (&id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = slot.input {
slots.push((Slot::Input(id, index as u32), named));
}
}
}
for (&id, network) in &registry.networks {
for (index, slot) in network.exports.iter().enumerate() {
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
slots.push((Slot::Export(id, index as u32), named));
}
}
}
slots.sort();
slots
}
/// The slots heading a chain: exports and inputs past the primary one, naming a node.
fn head_slots(registry: &Registry) -> impl Iterator<Item = Slot> + '_ {
slots(registry).into_iter().map(|(slot, _)| slot).filter(|slot| !matches!(slot, Slot::Input(_, 0)))
}
fn owner_is_live(registry: &Registry, slot: Slot) -> bool {
match slot {
Slot::Input(id, _) => registry.node_instances.contains_key(&id),
Slot::Export(id, _) => registry.networks.contains_key(&id),
}
}
/// The chain hanging off `head` in `registry`.
fn chain(registry: &Registry, head: Slot) -> Chain {
let mut nodes = Vec::new();
let mut below = slot_value(registry, head);
while let Some(NodeInput::Node { id, .. }) = below {
if nodes.contains(&id) || !registry.node_instances.contains_key(&id) {
return Chain { head, nodes, bottom: None };
}
nodes.push(id);
below = slot_value(registry, Slot::Input(id, 0));
}
Chain { head, nodes, bottom: below }
}
fn slot_network(registry: &Registry, slot: Slot) -> Option<NetworkId> {
match slot {
Slot::Input(id, _) => registry.node_instances.get(&id).map(|node| node.network),
Slot::Export(id, _) => Some(id),
}
}
fn slot_value(registry: &Registry, slot: Slot) -> Option<NodeInput> {
match slot {
Slot::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
Slot::Export(id, index) => registry.networks.get(&id)?.exports.get(index as usize)?.target.clone(),
}
}
/// What a removed node's primary input led to, through removed nodes, staying in `network`. None when the chain ends
/// at a node never seen or in another network.
fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, known: &KnownInputs) -> Option<NodeInput> {
let mut visited = HashSet::new();
let mut current = removed;
loop {
if !visited.insert(current) {
return None;
}
let (in_network, input) = match registry.removed_nodes.get(&current) {
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
None => known.get(&current).cloned()?,
};
if Some(in_network) != network {
return None;
}
match input {
NodeInput::Node { id, .. } if !registry.node_instances.contains_key(&id) => current = id,
NodeInput::Node { id, .. } if Some(registry.node_instances[&id].network) != network => return None,
input => return Some(input),
}
}
}
/// Records the op setting `slot` to `input`, None clearing an export, and applies it to the scratch `registry`. Writes
/// nothing when the slot holds it already.
fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input: Option<NodeInput>) {
if slot_value(registry, slot) == input {
return;
}
match slot {
Slot::Input(id, index) => {
let Some(input) = input else { return };
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
slot.input = input.clone();
}
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
}
Slot::Export(id, index) => {
if let Some(slot) = registry.networks.get_mut(&id).and_then(|network| network.exports.get_mut(index as usize)) {
slot.target = input.clone();
}
ops.push(RegistryDelta::SetNetworkExport { id, index, export: input });
}
}
}
+149 -11
View File
@@ -24,6 +24,8 @@ pub struct Session {
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
/// hold the only copy, so they stay garbage collection roots for the life of the session.
taken_back_resources: HashSet<ResourceHash>,
/// What this peer's open interaction is doing, for its closing marker to carry.
action: Option<String>,
}
impl Session {
@@ -47,6 +49,7 @@ impl Session {
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
action: None,
}
}
@@ -336,6 +339,7 @@ impl Session {
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
action: None,
}
}
@@ -386,6 +390,10 @@ impl Session {
return Ok(None);
}
self.runtime_base = None;
// The name belongs to the open interaction being taken back
if closed_before == own.len() {
self.action = None;
}
let (touched, taken) = self.document.retract_hot_ops(&ids);
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
@@ -430,23 +438,70 @@ impl Session {
}
let position = newest_first.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
// Minted on a scratch fold first, so a failing copy changes nothing.
// Minted on a scratch fold first, so a failing copy changes nothing. Each copied interaction ends with the
// repairs it needs on the changed line.
let mut scratch = self.fold_scratch_at(Some(base))?;
let mut copies = Vec::with_capacity(position);
// Per copy, the delta it carries attributes from, and the repair now closing that delta's interaction
let mut sources: Vec<(Option<&Delta>, Option<Rev>)> = Vec::with_capacity(position);
let mut parent = Some(base);
let mut replayed = Vec::new();
let mut before = scratch.working_registry.clone();
let known = self.known_inputs();
// What the removed step added must not come back through a later step writing to it
let gone: HashSet<NodeId> = newest_first[position..]
.iter()
.filter_map(|delta| match &delta.kind {
RegistryDelta::AddNode { id, .. } => Some(*id),
_ => None,
})
.collect();
for original in newest_first[..position].iter().rev() {
let reverse = crate::prior::capture(&scratch.working_registry, &original.kind);
scratch.apply_op_with(RegistryTarget::Working, original.kind.clone(), original.timestamp, ApplyMode::Idempotent)?;
let copy = Delta::new(parent, original.timestamp.peer, original.timestamp, original.kind.clone(), reverse);
parent = Some(copy.id);
copies.push(copy);
sources.push((Some(original), None));
replayed.push(original.kind.clone());
if !original.is_interaction_end() {
continue;
}
let closing_index = sources.len() - 1;
for op in crate::repair::repair_ops(
&before,
&scratch.working_registry,
&self.fold_scratch_at(Some(original.id))?.working_registry,
&std::mem::take(&mut replayed),
&gone,
&known,
) {
let reverse = crate::prior::capture(&scratch.working_registry, &op);
let timestamp = self.document.clock.tick();
scratch.apply_op_with(RegistryTarget::Working, op.clone(), timestamp, ApplyMode::Strict)?;
let repair = Delta::new(parent, original.author, timestamp, op, reverse);
parent = Some(repair.id);
sources[closing_index].1 = Some(repair.id);
copies.push(repair);
sources.push((None, None));
}
before = scratch.working_registry.clone();
}
let mut touched = Touched::default();
newest_first[position..].iter().for_each(|delta| touched.record(&delta.kind));
for (original, copy) in newest_first[..position].iter().rev().zip(&mut copies) {
for (copy, _) in copies.iter().zip(&sources).filter(|(_, (original, _))| original.is_none()) {
touched.record(&copy.kind);
}
for copy in &copies {
self.document.history.push(copy.clone());
self.carry_attributes(original, copy.id);
}
for (&(original, closing), copy) in sources.iter().zip(&copies) {
if let Some(original) = original {
self.carry_attributes_closing(original, copy.id, closing);
}
}
for copy in &mut copies {
if let Some(carried) = self.document.history.get(copy.id) {
*copy = carried.clone();
}
@@ -559,7 +614,8 @@ impl Session {
}
/// Mint a dropped interaction's deltas again on top of the line as one interaction. They keep their
/// original stamps, so a field someone wrote since keeps the newer value. Returns the new revs.
/// original stamps, so a field someone wrote since keeps the newer value, and the graph is repaired where that
/// left it broken (see [`repair_ops`](crate::repair::repair_ops)). Returns the new revs.
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?;
let mut originals = Vec::new();
@@ -571,10 +627,32 @@ impl Session {
originals.push(delta);
}
originals.reverse();
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
let before = self.document.retired_snapshot.clone();
let mut revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
let replayed: Vec<RegistryDelta> = originals.iter().map(|delta| delta.kind.clone()).collect();
let deleted: HashSet<NodeId> = replayed
.iter()
.filter_map(|op| match op {
RegistryDelta::RemoveNode { id, .. } => Some(*id),
_ => None,
})
.collect();
let repairs = crate::repair::repair_ops(
&before,
&self.document.retired_snapshot,
&self.fold_scratch_at(Some(dropped))?.working_registry,
&replayed,
&deleted,
&self.known_inputs(),
);
let author = originals.last().map_or(self.document.peer, |delta| delta.author);
let repaired = self.commit_repairs(repairs, author)?;
let closing = repaired.last().copied();
for (original, &rev) in originals.iter().zip(&revs) {
self.carry_attributes(original, rev);
let closes = original.id == dropped;
self.carry_attributes_closing(original, rev, closing.filter(|_| closes));
}
revs.extend(repaired);
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
}
@@ -630,6 +708,7 @@ impl Session {
/// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a
/// re-registration possibly before the marker; empty when nothing is open.
pub fn end_interaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
let action = self.action.take();
let peer = self.document.peer;
let open = self
.document
@@ -643,9 +722,22 @@ impl Session {
}
let mut closing = Attributes::new();
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
if let Some(action) = action {
closing.set(crate::attr::delta::ACTION, Value::Str(action), TimeStamp::ORIGIN);
}
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
}
/// Names this peer's open interaction, replacing an earlier name. Closing it takes the name along.
pub fn name_interaction(&mut self, action: &str) {
self.action = Some(action.to_string());
}
/// The name this peer's open interaction will close with.
pub fn pending_action(&self) -> Option<&str> {
self.action.as_deref()
}
/// Every author's closed interactions in the hot log, the earliest closed first.
pub fn closed_interactions(&self) -> Vec<ClosedInteraction> {
let mut by_author: HashMap<PeerId, Vec<&HotOp>> = HashMap::new();
@@ -842,9 +934,14 @@ impl Session {
/// Retire one closed interaction, coarsened, marking its last delta as the interaction's end. Every op is retired,
/// the ones coarsening drops included. Returns the new revs.
pub fn retire_interaction(&mut self, interaction: &ClosedInteraction) -> Result<Vec<Rev>, CrdtError> {
let marker = interaction.ops.last().and_then(|&id| self.document.hot_log.iter().find(|hot_op| hot_op.id() == id));
let action = marker.and_then(|hot_op| hot_op.attributes.get(crate::attr::delta::ACTION)).cloned();
let revs = self.retire_hot_ops_with(&interaction.ops, true)?;
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
if let Some(action) = action {
self.document.history.annotate(last, crate::attr::delta::ACTION, action.value, action.timestamp);
}
}
Ok(revs)
}
@@ -895,16 +992,57 @@ impl Session {
}
}
/// Give a minted copy the attributes and retirement time of the delta it stands for.
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
if let Some(wall_ms) = original.retired_at() {
self.document.history.set_retired_at(copy, wall_ms);
/// Give a minted copy the attributes and retirement time of the delta it stands for, with what closes the interaction moved to `closing` when repairs minted after the copy now end it.
fn carry_attributes_closing(&mut self, original: &Delta, copy: Rev, closing: Option<Rev>) {
use crate::attr::delta::{ACTION, INTERACTION_END};
for rev in std::iter::once(copy).chain(closing) {
if let Some(wall_ms) = original.retired_at() {
self.document.history.set_retired_at(rev, wall_ms);
}
}
for (key, value) in original.attributes.live() {
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp);
let moved = closing.filter(|_| key == INTERACTION_END || key == ACTION);
self.document.history.annotate(moved.unwrap_or(copy), key, value.value.clone(), value.timestamp);
}
}
/// Each node's network and newest primary input anywhere in history, branches included.
fn known_inputs(&self) -> crate::repair::KnownInputs {
let mut networks: HashMap<NodeId, NetworkId> = HashMap::new();
let mut inputs: HashMap<NodeId, (TimeStamp, crate::NodeInput)> = HashMap::new();
for delta in self.document.history.iter() {
let (id, input) = match &delta.kind {
RegistryDelta::AddNode { id, node } | RegistryDelta::RemoveNode { id, snapshot: node } => {
networks.insert(*id, node.network);
(*id, node.inputs.first().map(|slot| slot.input.clone()))
}
RegistryDelta::ChangeNodeInput { id, index: 0, new_input } => (*id, Some(new_input.clone())),
RegistryDelta::SetNodeInputs { id, inputs } => (*id, inputs.first().map(|slot| slot.input.clone())),
_ => continue,
};
let Some(input) = input else { continue };
if inputs.get(&id).is_none_or(|(newest, _)| *newest < delta.timestamp) {
inputs.insert(id, (delta.timestamp, input));
}
}
inputs.into_iter().filter_map(|(id, (_, input))| Some((id, (*networks.get(&id)?, input)))).collect()
}
/// Commit repair ops on top of the line, authored by whoever made the interaction they finish.
fn commit_repairs(&mut self, ops: Vec<RegistryDelta>, author: PeerId) -> Result<Vec<Rev>, CrdtError> {
let mut revs = Vec::with_capacity(ops.len());
for op in ops {
let reverse = crate::prior::capture(&self.document.retired_snapshot, &op);
let delta = Delta::new(self.document.head, author, self.document.clock.tick(), op, reverse);
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Strict)?;
self.document.head = Some(delta.id);
revs.push(delta.id);
self.document.history.push(delta);
}
Ok(revs)
}
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
@@ -597,3 +597,37 @@ fn undo_takes_back_the_interaction_before_one_already_taken_back() {
twice.retract_interaction().unwrap().expect("a is hot and now the latest");
assert!(twice.hot_log().is_empty());
}
#[test]
fn an_interaction_keeps_its_name_into_history() {
let mut session = Session::with_peer(PeerId(1));
session.name_interaction("Stale");
session.end_interaction().unwrap();
session.stage_ops([set_attribute("a", 1)]).unwrap();
session.name_interaction("Move");
session.end_interaction().unwrap();
session.stage_ops([set_attribute("b", 1)]).unwrap();
session.end_interaction().unwrap();
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).unwrap();
}
let actions: Vec<Option<&str>> = session.history().filter(|delta| delta.is_interaction_end()).map(|delta| delta.action()).collect();
assert_eq!(actions, [Some("Move"), None], "a name set while nothing was open is dropped at the next close");
}
#[test]
fn a_taken_back_interaction_takes_its_name_along() {
let mut session = Session::with_peer(PeerId(1));
session.stage_ops([set_attribute("a", 1)]).unwrap();
session.name_interaction("Move");
session.retract_interaction().unwrap().expect("a is open and hot");
session.stage_ops([set_attribute("b", 1)]).unwrap();
session.end_interaction().unwrap();
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).unwrap();
}
let actions: Vec<Option<&str>> = session.history().filter(|delta| delta.is_interaction_end()).map(|delta| delta.action()).collect();
assert_eq!(actions, [None]);
}
@@ -0,0 +1,427 @@
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
//! head moves must hold the same document.
//!
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use std::collections::HashSet;
/// What every layer's implementation names, so nodes need no proto-node declarations.
const LEAF: NetworkId = NetworkId(1);
/// A small xorshift generator, so a seed fixes the run.
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// The layers from the top of the stack down, following each layer's first input.
fn stack(registry: &Registry) -> Vec<NodeId> {
let mut layers = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
break;
}
layers.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
layers
}
/// What feeds into `layer` from below.
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
registry.node_instances[&layer].inputs[0].input.clone()
}
/// Points what sits directly above `layer`, a layer or the export, at `input`.
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
let layers = stack(registry);
match layers.iter().position(|&id| id == layer) {
Some(0) | None => RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(input),
},
Some(position) => RegistryDelta::ChangeNodeInput {
id: layers[position - 1],
index: 0,
new_input: input,
},
}
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let mut ops = vec![
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
];
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
ops
}
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
}
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = std::collections::HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The layers live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
let layers = stack(registry);
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
fn assert_consistent(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let networks = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
},
];
host.stage_ops(networks).expect("stage the networks");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
}
8 => {
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
continue;
};
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
}
9 => {
let steps = line_steps(&host);
// The first step adds the networks, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A layer the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A layer the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
}
#[test]
fn history_operations_keep_the_stack_whole_and_peers_converged() {
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
for seed in 0..seeds {
simulate(seed, steps, &mut Vec::new());
}
}
/// A seed fixes the run, so one that fails can be replayed.
#[test]
fn a_seed_fixes_the_history_run() {
let stacks = |seed| stack(simulate(seed, 60, &mut Vec::new()).retired_registry());
for seed in 0..5 {
assert_eq!(stacks(seed), stacks(seed), "seed {seed}");
}
}
#[test]
#[ignore]
fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
let mut log = Vec::new();
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let host = simulate(seed, steps, &mut log);
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
}
@@ -8,6 +8,7 @@ use crate::messages::portfolio::document::utility_types::network_interface;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::utility_functions::name_layer_action;
use crate::messages::tool::utility_types::ToolType;
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
@@ -166,6 +167,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
return;
}
responses.add(DocumentMessage::AddTransaction);
let nodes = deleted_with_children.len() + chain_nodes.len();
responses.add(match (layers.len() == nodes, nodes) {
(true, _) => name_layer_action("Cut", nodes),
(false, 1) => DocumentMessage::NameInteraction { action: "Cut a node".into() },
(false, count) => DocumentMessage::NameInteraction { action: format!("Cut {count} nodes") },
});
if !deleted_with_children.is_empty() {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: deleted_with_children,
@@ -377,6 +384,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut added_nodes = false;
let pasted = entries.len();
for entry in entries.into_iter().rev() {
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let Some(&root_id) = new_ids.get(&NodeId(0)) else {
@@ -388,6 +396,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
if !added_nodes {
responses.add(DocumentMessage::DeselectAllLayers);
responses.add(DocumentMessage::AddTransaction);
responses.add(name_layer_action("Pasted", pasted));
added_nodes = true;
}
@@ -199,6 +199,24 @@ pub enum FrontendMessage {
UpdateHistoryPanel {
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
},
UpdateHistoryGraph {
graph: crate::messages::portfolio::history::utility_types::HistoryGraphState,
},
UpdateHistoryGraphOverlay {
open: bool,
},
/// A History panel step's captured image as an SVG, sent when the GPU is unavailable, which the panel shows wherever a row names `id`.
UpdateHistoryThumbnail {
id: String,
svg: String,
},
/// A History panel step's captured image as straight RGBA pixels.
UpdateHistoryThumbnailPixels {
id: String,
width: u32,
height: u32,
pixels: serde_bytes::ByteBuf,
},
UpdateNodeGraphCursors {
cursors: Vec<FrontendRemoteCursor>,
},
@@ -345,6 +345,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
//
// DocumentMessage
entry!(DoubleTap(Space); action_dispatch=DocumentMessage::GraphViewOverlayToggle),
entry!(KeyDown(KeyH); modifiers=[Alt], action_dispatch=HistoryMessage::GraphOverlayToggle),
entry!(KeyDownNoRepeat(Escape); action_dispatch=DocumentMessage::Escape),
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
entry!(KeyDown(Backspace); action_dispatch=DocumentMessage::DeleteSelectedLayers),
@@ -131,6 +131,10 @@ pub enum DocumentMessage {
PasteNodes {
nodes: Vec<(NodeId, NodeTemplate)>,
},
/// Names the open interaction for the History panel, such as after the transaction a tool starts.
NameInteraction {
action: String,
},
MoveSelectedLayersToGroup {
parent: LayerNodeIdentifier,
},
@@ -477,6 +477,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::ChangeHistoryLine { rev, change } => {
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), preferences.validate_storage_round_trip, responses)
}
DocumentMessage::NameInteraction { action } => {
if let Some(storage) = self.history.storage_mut() {
storage.name_interaction(&action);
}
}
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -1044,6 +1049,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Added an image".into() });
let layer = graph_modification_utils::new_image_layer(data, layer_node_id, layer_parent, responses);
@@ -1105,6 +1111,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Added an SVG".into() });
let layer = graph_modification_utils::new_svg_layer(svg, transform, !place_at_origin, layer_node_id, layer_parent, responses);
@@ -2436,6 +2443,10 @@ impl DocumentMessageHandler {
self.history.storage()
}
pub fn declarations(&self) -> &document_graph_storage::Declarations {
self.history.declarations()
}
/// Mutable access to the `Gdd` working copy.
pub fn storage_mut(&mut self) -> Option<&mut document_format::GddV1> {
self.history.storage_mut()
@@ -3848,7 +3859,7 @@ impl DocumentMessageHandler {
]
}
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration, history_graph_open: bool) {
let mut widgets = vec![
IconButton::new("PlaybackToStart", 24)
.tooltip_label("Restart Animation")
@@ -3933,6 +3944,14 @@ impl DocumentMessageHandler {
widgets.extend([
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextButton::new("History")
.icon("HistoryUndo")
.tooltip_label(if history_graph_open { "Hide the history graph" } else { "Show the history graph" })
.tooltip_description("Every step and branch of the document's history, drawn over the viewport.")
.tooltip_shortcut(action_shortcut!(HistoryMessageDiscriminant::GraphOverlayToggle))
.on_update(|_| HistoryMessage::GraphOverlayToggle.into())
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("Node Graph")
.icon(if self.graph_view_overlay_open { "GraphViewOpen" } else { "GraphViewClosed" })
.hover_icon(if self.graph_view_overlay_open { "GraphViewClosed" } else { "GraphViewOpen" })
@@ -19,7 +19,7 @@ use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::edit_target::{EditTarget, ResolvedEditTarget};
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
use crate::messages::tool::common_functionality::utility_functions::{make_path_editable_is_allowed, name_layer_action};
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position;
@@ -450,10 +450,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return;
};
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: selected_nodes.selected_nodes().cloned().collect::<Vec<_>>(),
delete_children,
});
let node_ids: Vec<NodeId> = selected_nodes.selected_nodes().cloned().collect();
let layers = node_ids.iter().filter(|node_id| network_interface.is_layer(node_id, selection_network_path)).count();
if !node_ids.is_empty() {
responses.add(match (layers == node_ids.len(), node_ids.len()) {
(true, _) => name_layer_action("Deleted", layers),
(false, 1) => DocumentMessage::NameInteraction { action: "Deleted a node".into() },
(false, count) => DocumentMessage::NameInteraction {
action: format!("Deleted {count} nodes"),
},
});
}
responses.add(NodeGraphMessage::DeleteNodes { node_ids, delete_children });
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::SendGraph);
@@ -0,0 +1,184 @@
//! Tints what a step changed onto a close-up of the document, colored by how the layer under each changed pixel changed.
use super::utility_types::Pixels;
use glam::{DVec2, UVec2};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
Added,
Removed,
Changed,
}
/// Where a layer's change shows, in document coordinates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChangedArea {
pub change: Change,
pub bounds: [DVec2; 2],
}
/// How far apart two premultiplied channels must be for a pixel to count as changed, out of 255.
const THRESHOLD: u8 = 16;
/// How much of a tint's color covers a changed pixel.
const TINT_STRENGTH: f32 = 0.6;
/// How opaque unchanged pixels stay, so the tints stand out.
const UNCHANGED_OPACITY: f32 = 0.35;
fn tint_color(change: Change) -> [u8; 3] {
match change {
Change::Added => [64, 200, 96],
Change::Removed => [232, 64, 64],
Change::Changed => [240, 176, 32],
}
}
/// The close-up `after` of `frame` with each pixel that differs from `before`, the whole document before the step
/// showing `before_frame`, tinted by the change of the area it falls in. A pixel that lost coverage shows as it was.
pub fn tint_changes(after: &Pixels, frame: [DVec2; 2], before: &Pixels, before_frame: [DVec2; 2], areas: &[ChangedArea]) -> Pixels {
let size = after.size;
let mut rgba = Vec::with_capacity(after.rgba.len());
for y in 0..size.y {
for x in 0..size.x {
let point = frame[0] + (DVec2::new(x as f64, y as f64) + 0.5) / size.as_dvec2() * (frame[1] - frame[0]);
let now = pixel(after, UVec2::new(x, y));
let then = sample(before, before_frame, point);
let shown = if differs(now, then) {
let lost = now[3] < then[3];
tint(if lost { then } else { now }, change_at(areas, point, lost))
} else {
[now[0], now[1], now[2], (now[3] as f32 * UNCHANGED_OPACITY) as u8]
};
rgba.extend_from_slice(&shown);
}
}
Pixels { size, rgba }
}
/// The area around every change, with a margin, at the thumbnails' aspect ratio. None when nothing changed.
pub fn close_up(areas: &[ChangedArea]) -> Option<[DVec2; 2]> {
/// The thumbnails' width over their height.
const ASPECT_RATIO: f64 = 1.5;
let [min, max] = areas.iter().map(|area| area.bounds).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])?;
let margin = ((max - min) * 0.15).max(DVec2::splat(4.));
let (min, max) = (min - margin, max + margin);
let size = max - min;
let size = if size.x >= size.y * ASPECT_RATIO {
DVec2::new(size.x, size.x / ASPECT_RATIO)
} else {
DVec2::new(size.y * ASPECT_RATIO, size.y)
};
let center = (min + max) / 2.;
Some([center - size / 2., center + size / 2.])
}
/// The change of the areas holding `point`, preferring a removal where the pixel lost coverage and an addition elsewhere.
fn change_at(areas: &[ChangedArea], point: DVec2, lost: bool) -> Change {
let holding = |change: Change| areas.iter().any(|area| area.change == change && contains(area.bounds, point));
let order = match lost {
true => [Change::Removed, Change::Changed, Change::Added],
false => [Change::Added, Change::Changed, Change::Removed],
};
order.into_iter().find(|&change| holding(change)).unwrap_or(Change::Changed)
}
fn contains(bounds: [DVec2; 2], point: DVec2) -> bool {
point.cmpge(bounds[0]).all() && point.cmple(bounds[1]).all()
}
fn pixel(pixels: &Pixels, at: UVec2) -> [u8; 4] {
let index = (at.y * pixels.size.x + at.x) as usize * 4;
pixels.rgba.get(index..index + 4).and_then(|pixel| pixel.try_into().ok()).unwrap_or([0; 4])
}
/// The pixel of `pixels`, which shows `frame`, at a document point, transparent outside it.
fn sample(pixels: &Pixels, frame: [DVec2; 2], point: DVec2) -> [u8; 4] {
let at = (point - frame[0]) / (frame[1] - frame[0]) * pixels.size.as_dvec2();
if at.cmplt(DVec2::ZERO).any() || at.cmpge(pixels.size.as_dvec2()).any() {
return [0; 4];
}
pixel(pixels, at.as_uvec2())
}
fn differs(a: [u8; 4], b: [u8; 4]) -> bool {
let premultiplied = |pixel: [u8; 4]| pixel.map(|channel| (channel as u16 * pixel[3] as u16 / 255) as u8);
let (a, b) = (premultiplied(a), premultiplied(b));
a.iter().zip(&b).any(|(a, b)| a.abs_diff(*b) > THRESHOLD) || a[3].abs_diff(b[3]) > THRESHOLD
}
fn tint(pixel: [u8; 4], change: Change) -> [u8; 4] {
let color = tint_color(change);
let mix = |channel: u8, tint: u8| (channel as f32 + (tint as f32 - channel as f32) * TINT_STRENGTH) as u8;
[mix(pixel[0], color[0]), mix(pixel[1], color[1]), mix(pixel[2], color[2]), pixel[3]]
}
#[cfg(test)]
mod tests {
use super::*;
const FRAME: [DVec2; 2] = [DVec2::ZERO, DVec2::new(4., 2.)];
const CLEAR: [u8; 4] = [0; 4];
const WHITE: [u8; 4] = [255; 4];
/// A 4×2 image of the given pixels, row by row.
fn image(pixels: [[u8; 4]; 8]) -> Pixels {
Pixels {
size: UVec2::new(4, 2),
rgba: pixels.concat(),
}
}
fn left_half(change: Change) -> ChangedArea {
ChangedArea {
change,
bounds: [DVec2::ZERO, DVec2::new(2., 2.)],
}
}
#[test]
fn what_stayed_fades_and_what_came_is_tinted_as_added() {
let before = image([CLEAR; 8]);
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Added)]);
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Added));
assert_eq!(pixel(&tinted, UVec2::new(3, 1))[3], 0, "transparent pixels that stayed stay transparent");
let unchanged = tint_changes(&after, FRAME, &after, FRAME, &[]);
assert_eq!(pixel(&unchanged, UVec2::new(0, 0))[3], (255. * UNCHANGED_OPACITY) as u8);
}
#[test]
fn what_went_shows_as_it_was_tinted_as_removed() {
let before = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
let after = image([CLEAR; 8]);
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Removed)]);
let removed = pixel(&tinted, UVec2::new(1, 1));
assert_eq!(removed, tint(WHITE, Change::Removed));
assert_eq!(removed[3], 255, "a removed pixel keeps the coverage it had");
}
#[test]
fn a_moved_layer_is_tinted_as_changed_where_it_was_and_where_it_is() {
let before = image([WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
let after = image([CLEAR, WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Changed)]);
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Changed), "where it was");
assert_eq!(pixel(&tinted, UVec2::new(1, 0)), tint(WHITE, Change::Changed), "where it is");
}
#[test]
fn the_close_up_samples_the_whole_document_before_at_its_own_scale() {
// The before image shows twice the area, so its left pixel column covers the close-up's left two
let before = image([WHITE, CLEAR, CLEAR, CLEAR, WHITE, CLEAR, CLEAR, CLEAR]);
let before_frame = [DVec2::ZERO, DVec2::new(8., 4.)];
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
let tinted = tint_changes(&after, FRAME, &before, before_frame, &[]);
assert_eq!(pixel(&tinted, UVec2::new(1, 0))[3], (255. * UNCHANGED_OPACITY) as u8, "still covered, so unchanged");
assert_eq!(pixel(&tinted, UVec2::new(2, 0))[3], 0);
}
}
@@ -5,12 +5,39 @@ use crate::messages::prelude::*;
pub enum HistoryMessage {
Refresh,
Tick,
Expand { id: String, expanded: bool },
Expand {
id: String,
expanded: bool,
},
LoadMore,
GoBack { id: String },
RemoveStep { id: String },
BringBack { id: String },
Follow { id: Option<String> },
Rename { id: String, label: String },
Tag { id: String, tag: String, on: bool },
GoBack {
id: String,
},
RemoveStep {
id: String,
},
BringBack {
id: String,
},
Follow {
id: Option<String>,
},
Rename {
id: String,
label: String,
},
Tag {
id: String,
tag: String,
on: bool,
},
GraphOverlay {
open: bool,
},
GraphOverlayToggle,
Captured {
document_id: DocumentId,
step: document_graph_storage::TimeStamp,
capture: Option<Box<super::utility_types::DocumentCapture>>,
},
}
File diff suppressed because it is too large. Load diff
@@ -1,3 +1,4 @@
mod changes;
mod history_message;
mod history_message_handler;
pub mod utility_types;
@@ -1,5 +1,36 @@
//! What the History panel shows, as the frontend receives it, and the changes it asks of the head's line.
use glam::DVec2;
use graph_craft::document::NodeId;
use std::collections::HashMap;
/// The document as rendered once a step is done, for the History panel to show and compare.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentCapture {
/// The whole document.
pub image: CaptureImage,
/// The document area `image` shows.
pub frame: [DVec2; 2],
/// The area asked for in detail, and its image.
pub detail: Option<([DVec2; 2], CaptureImage)>,
/// The proto node giving each layer's own content, whose ID changes with that content.
pub layer_sources: HashMap<NodeId, NodeId>,
}
/// A capture rendered like the layer thumbnails: pixels from Vello, or an SVG for the frontend to draw when the GPU is unavailable.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum CaptureImage {
Pixels(Pixels),
Svg(String),
}
/// Straight RGBA pixels, row by row.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Pixels {
pub size: glam::UVec2,
pub rgba: Vec<u8>,
}
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum LineChange {
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
@@ -19,8 +50,8 @@ pub struct HistoryPanelState {
pub progress: Vec<HistoryProgressRow>,
pub more: bool,
pub following: Option<String>,
/// In a session, a head move affects everyone.
pub session: bool,
/// Others are connected, so authors, whether work is in history yet and head moves concern them too.
pub collaborating: bool,
}
/// One interaction, a run of deltas that undo takes back together.
@@ -48,6 +79,17 @@ pub struct HistoryRow {
pub head: bool,
pub expanded: bool,
pub details: Vec<HistoryDeltaRow>,
/// How the document looked once this step was done, if the panel was open to capture it.
pub thumbnail: Option<HistoryThumbnail>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryThumbnail {
/// The ID the frontend received the whole document's image under.
pub whole: String,
/// The ID of a close-up of what the step changed, tinted by how, when the step before was captured too.
pub detail: Option<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -63,10 +105,42 @@ pub struct HistoryDeltaRow {
pub id: String,
pub label: String,
pub author: String,
pub color: String,
pub mine: bool,
pub time: Option<f64>,
}
/// Every step in history as a tree on first parents, for the history graph drawn over the viewport.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryGraphState {
pub nodes: Vec<HistoryGraphNode>,
/// The widest column plus one.
pub width: f64,
/// The deepest step's depth plus one.
pub depth: usize,
}
/// One interaction, placed in the tree.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryGraphNode {
/// The rev closing the interaction, in decimal.
pub id: String,
pub label: String,
/// The column, in step widths from the left. A parent sits centred over its children.
pub x: f64,
/// Steps from the root.
pub depth: usize,
pub parent: Option<String>,
/// Steps joined into this one by a merge.
pub merged: Vec<String>,
pub head: bool,
pub undone: bool,
/// Off the head's line and not undone.
pub abandoned: bool,
pub thumbnail: Option<HistoryThumbnail>,
}
/// A person with unretired work in the room's hot log.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -79,4 +153,5 @@ pub struct HistoryProgressRow {
pub ops: usize,
/// Still being made, not closed and waiting.
pub open: bool,
pub thumbnail: Option<HistoryThumbnail>,
}
@@ -144,6 +144,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
documents: &mut self.documents,
active_document_id: self.active_document_id,
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
executor: &self.executor,
};
self.history.process_message(message, responses, context);
}
@@ -1141,7 +1142,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
PortfolioMessage::UpdateDocumentWidgets => {
if let Some(document) = self.active_document() {
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time);
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time, self.history.graph_open());
}
}
PortfolioMessage::UpdateOpenDocumentsList => {
@@ -1176,6 +1177,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PrevDocument,
));
common.extend(actions!(IngestMessageDiscriminant; Import));
common.extend(self.history.actions());
}
common
@@ -17,6 +17,16 @@ use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType};
use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape};
/// Names the open interaction after what a tool did to `count` layers, such as "Moved 2 layers".
pub fn name_layer_action(verb: &str, count: usize) -> DocumentMessage {
let action = match count {
0 => verb.to_string(),
1 => format!("{verb} a layer"),
count => format!("{verb} {count} layers"),
};
DocumentMessage::NameInteraction { action }
}
/// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable.
pub fn should_extend(document: &DocumentMessageHandler, goal: DVec2, tolerance: f64, layers: impl Iterator<Item = LayerNodeIdentifier>) -> Option<(LayerNodeIdentifier, PointId, DVec2)> {
closest_point(document, goal, tolerance, layers, |_| false)
@@ -1976,6 +1976,7 @@ impl Fsm for PenToolFsmState {
}
(PenToolFsmState::Ready, PenToolMessage::DragStart { append_to_selected }) => {
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Drew a path segment".into() });
tool_data.handle_mode = HandleMode::Free;
// Get the closest point and the segment it is on
@@ -2015,6 +2016,7 @@ impl Fsm for PenToolFsmState {
// Each segment placement is its own history step, spanning from this click through the release that finalizes it
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Drew a path segment".into() });
// Merge two layers if the point is connected to the end point of another path
@@ -22,7 +22,9 @@ use crate::messages::tool::common_functionality::shape_editor::SelectionShapeTyp
use crate::messages::tool::common_functionality::snap_session::{BoxFeatures, FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView, snapping_hints};
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
use crate::messages::tool::common_functionality::transformation_cage::*;
use crate::messages::tool::common_functionality::utility_functions::{push_nearest_anchors, resize_bounds, rotate_bounds, skew_bounds, text_bounding_box, transforming_transform_cage};
use crate::messages::tool::common_functionality::utility_functions::{
name_layer_action, push_nearest_anchors, resize_bounds, rotate_bounds, skew_bounds, text_bounding_box, transforming_transform_cage,
};
use glam::DMat2;
use graph_craft::document::NodeId;
use graphene_std::Color;
@@ -1746,6 +1748,10 @@ impl Fsm for SelectToolFsmState {
// Deselect layer if not snap dragging
responses.add(DocumentMessage::EndTransaction);
tool_data.axis_align = false;
if has_dragged {
let verb = if tool_data.non_duplicated_layers.is_some() { "Duplicated" } else { "Moved" };
responses.add(name_layer_action(verb, tool_data.layers_dragging.len()));
}
if !has_dragged && input.keyboard.key(remove_from_selection) && tool_data.layer_selected_on_start.is_none() {
// When you click on the layer with remove from selection key (shift) pressed, we deselect all nodes that are children.
@@ -1832,6 +1838,14 @@ impl Fsm for SelectToolFsmState {
) => {
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction };
if !drag_too_small {
responses.add(match self {
SelectToolFsmState::DraggingPivot => DocumentMessage::NameInteraction { action: "Moved the pivot".into() },
SelectToolFsmState::RotatingBounds => name_layer_action("Rotated", tool_data.layers_dragging.len()),
SelectToolFsmState::SkewingBounds { .. } => name_layer_action("Skewed", tool_data.layers_dragging.len()),
_ => name_layer_action("Resized", tool_data.layers_dragging.len()),
});
}
tool_data.pivot_before_drag = None;
let pivot_gizmo = tool_data.pivot_gizmo();
@@ -1100,6 +1100,7 @@ impl Fsm for ShapeToolFsmState {
) && clicked_on_shape_endpoints(layer, document, input, tool_data)
{
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Moved a line end".into() });
let moving = Moving {
layers: vec![layer],
@@ -1166,6 +1167,11 @@ impl Fsm for ShapeToolFsmState {
tool_data.data.start(snap_session, SnapView::new(document, *document_id, input), drawn);
responses.add(DocumentMessage::StartTransaction);
let shape = format!("{:?}", tool_data.current_shape).to_lowercase();
let article = if shape.starts_with(['a', 'e', 'i', 'o', 'u']) { "an" } else { "a" };
responses.add(DocumentMessage::NameInteraction {
action: format!("Drew {article} {shape}"),
});
let node = match tool_data.current_shape {
ShapeType::Polygon => Polygon::create_node(tool_options.vertices),
@@ -548,6 +548,7 @@ impl TextToolData {
self.layer = layer;
if self.load_layer_text_node(document, fonts).is_some() {
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Edited text".into() });
self.set_editing(true, fonts, responses);
@@ -567,6 +568,7 @@ impl TextToolData {
fn new_text(&mut self, document: &DocumentMessageHandler, editing_text: EditingText, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
self.new_text = String::new();
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Added text".into() });
self.layer = LayerNodeIdentifier::new_unchecked(NodeId::new());
@@ -765,6 +767,7 @@ impl Fsm for TextToolFsmState {
if dragging_bounds.is_some() {
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Resized a text box".into() });
// Set the original transform
if let Some(id) = selected {
@@ -11,7 +11,7 @@ use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
use crate::messages::tool::common_functionality::snap_session::{BoxFeatures, FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView};
use crate::messages::tool::common_functionality::transformation_cage::MIN_FEATURE_TRAVEL;
use crate::messages::tool::common_functionality::utility_functions::{is_almost_colinear, push_nearest_anchors};
use crate::messages::tool::common_functionality::utility_functions::{is_almost_colinear, name_layer_action, push_nearest_anchors};
use crate::messages::tool::tool_messages::path_tool::MAX_SNAPPING_POINTS;
use crate::messages::tool::tool_messages::select_tool;
use crate::messages::tool::tool_messages::tool_prelude::Key;
@@ -321,6 +321,12 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
// Messages
TransformLayerMessage::ApplyTransformOperation { final_transform } => {
let verb = match self.transform_operation {
TransformOperation::Grabbing(_) => Some("Moved"),
TransformOperation::Rotating(_) => Some("Rotated"),
TransformOperation::Scaling(_) => Some("Scaled"),
TransformOperation::None => None,
};
selected.original_transforms.clear();
self.typing.clear();
if final_transform {
@@ -337,6 +343,12 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
} else {
update_colinear_handles(&selected_layers, document, responses);
responses.add(DocumentMessage::EndTransaction);
if let Some(verb) = verb {
responses.add(match using_path_tool {
true => DocumentMessage::NameInteraction { action: format!("{verb} points") },
false => name_layer_action(verb, selected_layers.len()),
});
}
responses.add(ToolMessage::UpdateHints);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
+24 -1
View File
@@ -81,7 +81,16 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
Thumbnails {
responses: VecDeque<FrontendMessage>,
document_id: DocumentId,
},
DocumentCapture {
document_id: DocumentId,
step: document_graph_storage::TimeStamp,
/// `None` when a newer graph replaced the one the request was for, so it can be asked again.
capture: Option<Box<crate::messages::portfolio::history::utility_types::DocumentCapture>>,
},
InspectResult(Box<InspectResult>),
}
@@ -203,6 +212,18 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view");
}
/// Asks for the document as rendered once what was submitted before has run, for the History panel's `step`, with the area `detail` close up.
/// Returns false when the runtime doesn't hold the document's graph as it is now, so nothing was asked.
pub fn submit_document_capture(&self, document: &DocumentMessageHandler, document_id: DocumentId, step: document_graph_storage::TimeStamp, detail: Option<[DVec2; 2]>) -> bool {
if self.node_graph_document != Some(document_id) || self.node_graph_hash != document.network_interface.network_hash() {
return false;
}
self.sender
.send(GraphRuntimeRequest::CaptureDocument { document_id, step, detail })
.expect("Failed to send the capture request");
true
}
/// Updates the network to monitor all inputs. Useful for the testing.
#[cfg(test)]
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
@@ -664,6 +685,7 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses);
}
}
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
}
}
@@ -682,6 +704,7 @@ impl NodeGraphExecutor {
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
_ => {}
}
}
+27 -1
View File
@@ -46,6 +46,8 @@ pub struct NodeRuntime {
pending_export: Option<ExecutionRequest>,
pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>,
/// The step the History panel wants the document captured for, once what is pending has run.
pending_capture: Option<(DocumentId, document_graph_storage::TimeStamp, Option<[DVec2; 2]>)>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
@@ -82,6 +84,12 @@ pub enum GraphRuntimeRequest {
layers: HashSet<NodeId>,
document_id: DocumentId,
},
CaptureDocument {
document_id: DocumentId,
step: document_graph_storage::TimeStamp,
/// The area to render close up as well.
detail: Option<[DVec2; 2]>,
},
/// The full path from the root network to the node the Data panel inspects, or empty for none.
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
@@ -131,6 +139,7 @@ impl NodeRuntime {
pending_export: None,
pending_eyedropper: None,
pending_thumbnails: None,
pending_capture: None,
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
@@ -169,7 +178,15 @@ impl NodeRuntime {
let mut graph = None;
for request in self.receiver.try_iter() {
match request {
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
GraphRuntimeRequest::GraphUpdate(update) => {
graph = Some(update);
// The graph may be another document's, or show a later step than the one asked for
if let Some((document_id, step, _)) = self.pending_capture.take() {
self.sender
.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture: None })
.expect("Failed to send response");
}
}
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
self.pending_export = Some(request);
@@ -184,6 +201,7 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
GraphRuntimeRequest::CaptureDocument { document_id, step, detail } => self.pending_capture = Some((document_id, step, detail)),
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
Some(update) => update.node_to_inspect = node_to_inspect,
@@ -273,6 +291,14 @@ impl NodeRuntime {
if let Some(viewport) = viewport {
texture = self.run_viewport(viewport).await;
}
if let Some((document_id, step, detail)) = self.pending_capture.take()
&& let Some(network) = &self.old_graph
&& let Some(capture) = self.thumbnails.capture_document(network, &self.executor, &self.editor_api, detail).await
{
let capture = Some(Box::new(capture));
self.sender.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture }).expect("Failed to send response");
}
}
(self.editor_wake)();
@@ -1,5 +1,6 @@
use super::evaluated_output;
use crate::messages::frontend::FrontendMessage;
use crate::messages::portfolio::history::utility_types::{CaptureImage, DocumentCapture, Pixels};
#[cfg(feature = "gpu")]
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
@@ -224,22 +225,58 @@ impl Thumbnails {
}
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
let bounds = content.bounds();
let footprint = Footprint {
transform: DAffine2::from_translation(bounds[0]),
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
quality: RenderQuality::Full,
};
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
content.graphic().render_svg(&mut render, &render_params);
render.format_svg(bounds[0], bounds[1]);
self.show_svg(layer, content.svg(), responses).await;
}
self.show_svg(layer, render.svg.to_svg_string(), responses).await;
/// Renders the whole document as the network's export gives it, and the area `detail` close up, the way layer
/// thumbnails are rendered, along with what each layer currently shows.
pub async fn capture_document(&self, network: &NodeNetwork, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, detail: Option<[DVec2; 2]>) -> Option<DocumentCapture> {
let content = match network.exports.first().and_then(|export| network.input_source(&[], export)) {
Some(source) => {
let &(content_node, _) = executor.tree().source_map().get(source.as_slice())?;
ThumbnailContent::evaluate(executor, content_node)?
}
// Nothing reaches the export, so the document shows nothing
None => ThumbnailContent::Graphics(List::default()),
};
let frame = content.bounds();
let frames: Vec<[DVec2; 2]> = std::iter::once(frame).chain(detail).collect();
let mut images: Vec<CaptureImage> = match self.render_frames_with_vello(&content, &frames, editor_api).await {
Some(pixels) => pixels.into_iter().map(CaptureImage::Pixels).collect(),
None => frames.iter().map(|&frame| CaptureImage::Svg(content.svg_of(frame))).collect(),
};
let detail_image = (images.len() > 1).then(|| images.pop()).flatten();
Some(DocumentCapture {
image: images.pop()?,
frame,
detail: detail.zip(detail_image),
layer_sources: self.sources.clone(),
})
}
/// Renders each frame of the content into a cell the size of a layer thumbnail, giving none if Vello is unavailable.
#[cfg(feature = "gpu")]
async fn render_frames_with_vello(&self, content: &ThumbnailContent, frames: &[[DVec2; 2]], editor_api: &PlatformEditorApi) -> Option<Vec<Pixels>> {
let executor = editor_api.application_io.as_ref()?.gpu_executor()?;
let cell_size = cell_size(self.scale);
let size = UVec2::new(cell_size.x * frames.len() as u32, cell_size.y);
let texture = executor.render_vello(size, DAffine2::IDENTITY, &mut |scene| atlas::draw_frames(scene, cell_size, content, frames));
let texture = texture.inspect_err(|error| log::error!("Failed to render the document capture: {error}")).ok()?;
let raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8();
let cell = |index: usize| Pixels {
size: cell_size,
rgba: atlas::cell_pixels(&pixels, size.x, cell_size, UVec2::new(index as u32 * cell_size.x, 0)),
};
Some((0..frames.len()).map(cell).collect())
}
#[cfg(not(feature = "gpu"))]
async fn render_frames_with_vello(&self, _content: &ThumbnailContent, _frames: &[[DVec2; 2]], _editor_api: &PlatformEditorApi) -> Option<Vec<Pixels>> {
None
}
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
@@ -344,6 +381,28 @@ impl ThumbnailContent {
}
}
fn svg(&self) -> String {
self.svg_of(self.bounds())
}
/// The SVG of the area `bounds`.
fn svg_of(&self, bounds: [DVec2; 2]) -> String {
let footprint = Footprint {
transform: DAffine2::from_translation(bounds[0]),
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
quality: RenderQuality::Full,
};
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
self.graphic().render_svg(&mut render, &render_params);
render.format_svg(bounds[0], bounds[1]);
render.svg.to_svg_string()
}
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] {
let bounds = match self {
@@ -445,6 +504,7 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
#[cfg(test)]
mod tests {
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
use crate::messages::portfolio::history::utility_types::CaptureImage;
use crate::test_utils::test_prelude::*;
use glam::UVec2;
use graph_craft::document::NodeId;
@@ -467,6 +527,27 @@ mod tests {
editor.runtime.executor.tree().source_map().get(path).map(|(id, _)| *id)
}
#[tokio::test]
async fn a_document_capture_shows_the_document_and_what_each_layer_shows() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
compile_and_run(&mut editor).await;
let runtime = &editor.runtime;
let network = runtime.old_graph.as_ref().expect("The document should have compiled");
let capture = runtime.thumbnails.capture_document(network, &runtime.executor, &runtime.editor_api, None).await;
let capture = capture.expect("The document should render");
match &capture.image {
CaptureImage::Pixels(pixels) => assert!(pixels.rgba.chunks(4).any(|pixel| pixel[3] > 0), "The rectangle should be drawn"),
CaptureImage::Svg(svg) => assert!(svg.contains("<path"), "The rectangle should be drawn: {svg}"),
}
assert!(capture.layer_sources.contains_key(&layer), "The rectangle's layer should have its content");
let [min, max] = capture.frame;
assert!(min.cmple(DVec2::ZERO).all() && max.cmpge(DVec2::splat(10.)).all(), "The frame {min} to {max} should hold the rectangle");
}
#[tokio::test]
async fn a_merge_layer_shows_its_content_and_another_layer_its_output() {
let mut editor = EditorTestUtils::create();
@@ -1,5 +1,5 @@
use super::{ThumbnailContent, cell_size};
use glam::{DAffine2, UVec2};
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::document::NodeId;
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
use graphene_std::renderer::{RenderOutputType, RenderParams};
@@ -43,44 +43,57 @@ impl ThumbnailAtlasLayout {
}
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
let atlas_row_length = self.size().x as usize * 4;
let row_length = self.cell_size.x as usize * 4;
let origin = self.cell_origin(index).as_usizevec2();
(origin.y..origin.y + self.cell_size.y as usize)
.filter_map(|row| {
let start = row * atlas_row_length + origin.x * 4;
atlas_pixels.get(start..start + row_length)
})
.flatten()
.copied()
.collect()
cell_pixels(atlas_pixels, self.size().x, self.cell_size, self.cell_origin(index))
}
}
/// The pixels of the cell at `origin` in an atlas `atlas_width` pixels wide, row by row.
pub fn cell_pixels(atlas_pixels: &[u8], atlas_width: u32, cell_size: UVec2, origin: UVec2) -> Vec<u8> {
let atlas_row_length = atlas_width as usize * 4;
let row_length = cell_size.x as usize * 4;
let origin = origin.as_usizevec2();
(origin.y..origin.y + cell_size.y as usize)
.filter_map(|row| {
let start = row * atlas_row_length + origin.x * 4;
atlas_pixels.get(start..start + row_length)
})
.flatten()
.copied()
.collect()
}
/// Draws the content of each layer in the layout centered within its cell.
pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout, contents: &HashMap<NodeId, ThumbnailContent>) {
for (index, layer) in layout.layers.iter().enumerate() {
let Some(content) = contents.get(layer) else { continue };
draw_cell(scene, layout.cell_origin(index), layout.cell_size, content, content.bounds());
}
}
/// Draws the area `frame` of the content into each cell of a row of them, one per frame.
pub fn draw_frames(scene: &mut VelloSceneBuilder, cell_size: UVec2, content: &ThumbnailContent, frames: &[[DVec2; 2]]) {
for (index, &frame) in frames.iter().enumerate() {
draw_cell(scene, UVec2::new(index as u32 * cell_size.x, 0), cell_size, content, frame);
}
}
fn draw_cell(scene: &mut VelloSceneBuilder, origin: UVec2, cell_size: UVec2, content: &ThumbnailContent, frame: [DVec2; 2]) {
let render_params = RenderParams {
footprint: Footprint::BOUNDLESS,
render_output_type: RenderOutputType::Vello,
thumbnail: true,
..Default::default()
};
let cell_size = layout.cell_size.as_dvec2();
let (origin, cell_size) = (origin.as_dvec2(), cell_size.as_dvec2());
let [min, max] = frame;
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
for (index, layer) in layout.layers.iter().enumerate() {
let Some(content) = contents.get(layer) else { continue };
let origin = layout.cell_origin(index).as_dvec2();
let [min, max] = content.bounds();
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
// The clip also limits content filling the whole scene, like a background, to the cell
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
content.graphic().render_to_vello(scene, transform, &render_params);
scene.pop_layer();
}
// The clip also limits content filling the whole scene, like a background, to the cell
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
content.graphic().render_to_vello(scene, transform, &render_params);
scene.pop_layer();
}
/// The RGBA pixels with runs of fully transparent ones left out, which most of a thumbnail's margins are.
@@ -5,6 +5,7 @@
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import Graph from "/src/components/views/Graph.svelte";
import HistoryGraph from "/src/components/views/HistoryGraph.svelte";
import RemoteCursor from "/src/components/views/RemoteCursor.svelte";
import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte";
import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte";
@@ -12,6 +13,7 @@
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { AppWindowStore } from "/src/stores/app-window";
import type { DocumentStore } from "/src/stores/document";
import type { HistoryStore } from "/src/stores/history";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageBody } from "/src/subscriptions-router";
import { fillChoiceColor, createSRgba8, sRgba8FromCSS } from "/src/utility-functions/colors";
@@ -31,6 +33,7 @@
const editor = getContext<EditorWrapper>("editor");
const appWindow = getContext<AppWindowStore>("appWindow");
const document = getContext<DocumentStore>("document");
const historyGraphOpen = getContext<HistoryStore>("history").graphOpen;
const remoteCursors = document.remoteCursorsStore;
// Interactive text editing
@@ -768,6 +771,9 @@
<div class="graph-view" class:open={$document.graphViewOverlayOpen} style:--fade-artwork={`${$document.fadeArtwork}%`} data-graph>
<Graph />
</div>
{#if $historyGraphOpen}
<HistoryGraph />
{/if}
</LayoutCol>
<LayoutCol class="ruler-or-scrollbar right-scrollbar">
<ScrollbarInput
+57 -22
View File
@@ -2,6 +2,7 @@
import { getContext, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import HistoryShot from "/src/components/views/HistoryShot.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
@@ -11,6 +12,7 @@
const editor = getContext<EditorWrapper>("editor");
const history = getContext<HistoryStore>("history");
const thumbnails = history.thumbnails;
// Relative times age while the panel stays open
let now = Date.now();
@@ -31,6 +33,9 @@
return new Date(ms).toLocaleDateString();
}
// Alone, the newest step not yet in history is where the document is
$: pendingHead = !$history.collaborating && $history.progress.length > 0;
function count(n: number, one: string, many: string): string {
return `${n} ${n === 1 ? one : many}`;
}
@@ -67,28 +72,41 @@
</LayoutRow>
{/if}
<LayoutCol class="body" scrollableY={true}>
{#each $history.progress as row}
<div class="row progress">
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
{#each $history.progress as row, index}
<!-- Alone, work not yet in history is shown as an ordinary step -->
<div class="row" class:head={pendingHead && index === 0}>
<span class="gutter"></span>
{#if $history.collaborating}
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
{:else}
<span class="rail"><span class="dot"></span></span>
{/if}
{#if row.thumbnail}<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />{/if}
<div class="text">
<span class="label">{row.label || (row.open ? "In progress" : "Waiting to enter history")}</span>
<span class="meta">
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
· {count(row.ops, "change", "changes")}
· {row.open ? "in progress" : "not yet in history"}
{#if $history.collaborating}<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span> ·{/if}
{count(row.ops, "change", "changes")}
{#if $history.collaborating}· {row.open ? "in progress" : "not yet in history"}{/if}
</span>
</div>
{#if pendingHead && index === 0}<span class="marker">Now</span>{/if}
</div>
{/each}
{#each $history.rows as row (row.id)}
<div class="row" class:head={row.head} class:undone={row.undone} class:abandoned={row.abandoned}>
<button
class="expand"
class:expanded={row.expanded}
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
></button>
<span class="rail"><span class="dot" style:background={row.color}></span></span>
<div class="row" class:head={row.head && !pendingHead} class:undone={row.undone} class:abandoned={row.abandoned}>
{#if row.deltas > 1 || row.thumbnail?.detail}
<button
class="expand"
class:expanded={row.expanded}
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
></button>
{:else}
<span class="gutter"></span>
{/if}
<span class="rail"><span class="dot" style:background={$history.collaborating || !row.mine ? row.color : undefined}></span></span>
{#if row.thumbnail}<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />{/if}
<div class="text">
{#if renamingId === row.id}
<span class="editing" use:focusInput on:focusout={() => (renamingId = undefined)}>
@@ -98,9 +116,9 @@
<span class="label" class:named={row.named}>{row.label}</span>
{/if}
<span class="meta">
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
{#if row.time}· {when(row.time, now)}{/if}
· {count(row.deltas, "change", "changes")}
{#if $history.collaborating || !row.mine}<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span> ·{/if}
{#if row.time}{when(row.time, now)} ·{/if}
{count(row.deltas, "change", "changes")}
</span>
{#if row.tags.length > 0 || taggingId === row.id}
<span class="tags">
@@ -139,7 +157,7 @@
icon="HistoryUndo"
size={16}
tooltipLabel="Go back to here"
tooltipDescription={$history.session
tooltipDescription={$history.collaborating
? "Move everyone's document back to this step. The steps since stay as a branch."
: "Move the document back to this step. The steps since stay as a branch."}
action={() => editor.goBackToHistoryInteraction(row.id)}
@@ -154,19 +172,27 @@
/>
{/if}
</span>
{#if row.head}<span class="marker">Now</span>{/if}
{#if row.head && !pendingHead}<span class="marker">Now</span>{/if}
{#if row.undone}<span class="marker">Undone</span>{/if}
{#if row.abandoned}<span class="marker">Branch</span>{/if}
</div>
{#if row.expanded}
{#if row.thumbnail?.detail}
<div class="row comparison" class:undone={row.undone}>
<span class="gutter"></span>
<span class="rail"></span>
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} large={true} />
</div>
{/if}
{#each row.details as delta (delta.id)}
<div class="row delta" class:undone={row.undone}>
<span class="gutter"></span>
<span class="rail"><span class="tick"></span></span>
<div class="text">
<span class="label">{delta.label}</span>
<span class="meta">
<span class="author">{delta.author}</span>
{#if delta.time}· {when(delta.time, now)}{/if}
{#if $history.collaborating || !delta.mine}<span class="author">{delta.author}</span>{/if}
{#if delta.time}{$history.collaborating || !delta.mine ? "· " : ""}{when(delta.time, now)}{/if}
</span>
</div>
</div>
@@ -217,10 +243,14 @@
&.delta {
min-height: 24px;
padding-left: 28px;
font-size: 11px;
}
&.comparison {
padding-top: 4px;
padding-bottom: 4px;
}
.actions {
flex: 0 0 auto;
display: flex;
@@ -250,6 +280,10 @@
}
}
.gutter {
flex: 0 0 16px;
}
.expand {
flex: 0 0 auto;
width: 16px;
@@ -288,6 +322,7 @@
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-8-uppergray);
&.hollow {
background: none;
@@ -0,0 +1,240 @@
<script lang="ts">
import { getContext, tick } from "svelte";
import HistoryShot from "/src/components/views/HistoryShot.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { HistoryStore } from "/src/stores/history";
import type { EditorWrapper, HistoryGraphNode } from "/wrapper/pkg/graphite_wasm_wrapper";
const editor = getContext<EditorWrapper>("editor");
const history = getContext<HistoryStore>("history");
const graph = history.graph;
const thumbnails = history.thumbnails;
// Each step's card and the room around it
const NODE_WIDTH = 168;
const NODE_HEIGHT = 44;
const COLUMN = 184;
const ROW = 72;
const PADDING = 24;
let body: HTMLDivElement | undefined;
let scrolledToHead = false;
$: byId = new Map($graph.nodes.map((node) => [node.id, node]));
$: head = $graph.nodes.find((node) => node.head);
$: if (head && !scrolledToHead) scrollToHead();
function left(node: HistoryGraphNode): number {
return PADDING + node.x * COLUMN;
}
function top(node: HistoryGraphNode): number {
return PADDING + node.depth * ROW;
}
// From the bottom of the parent's card to the top of the child's
function edge(parent: HistoryGraphNode, child: HistoryGraphNode): string {
const [x1, y1] = [left(parent) + NODE_WIDTH / 2, top(parent) + NODE_HEIGHT];
const [x2, y2] = [left(child) + NODE_WIDTH / 2, top(child)];
const middle = (y1 + y2) / 2;
return `M ${x1} ${y1} C ${x1} ${middle}, ${x2} ${middle}, ${x2} ${y2}`;
}
function onHeadLine(node: HistoryGraphNode): boolean {
return !node.undone && !node.abandoned;
}
function tooltip(node: HistoryGraphNode): string {
if (node.head) return "Where the document is now";
if (node.undone) return "Redo up to here";
if (node.abandoned) return "Show this branch in the History panel";
return "Go back to here";
}
function choose(node: HistoryGraphNode) {
if (node.abandoned) editor.followHistoryBranch(node.id);
else if (!node.head) editor.goBackToHistoryInteraction(node.id);
}
async function scrollToHead() {
scrolledToHead = true;
await tick();
body?.querySelector("[data-head]")?.scrollIntoView({ block: "center", inline: "center" });
}
</script>
<!-- Pointer presses and wheel scrolls stay here rather than reaching the viewport's tools beneath -->
<div class="history-graph" on:pointerdown|stopPropagation on:wheel|stopPropagation>
<div class="header">
<TextLabel>History</TextLabel>
<IconButton icon="CloseX" size={16} tooltipLabel="Hide the history graph" action={() => editor.setHistoryGraphOpen(false)} />
</div>
<div class="body" bind:this={body}>
{#if $graph.nodes.length === 0}
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
{/if}
<div class="canvas" style:width={`${PADDING * 2 + Math.max(0, $graph.width - 1) * COLUMN + NODE_WIDTH}px`} style:height={`${PADDING * 2 + $graph.depth * ROW}px`}>
<svg class="edges">
{#each $graph.nodes as node (node.id)}
{@const parent = node.parent ? byId.get(node.parent) : undefined}
{#if parent}
<path d={edge(parent, node)} class:head-line={onHeadLine(node)} class:undone={node.undone} />
{/if}
{#each node.merged as merged}
{@const other = byId.get(merged)}
{#if other}<path d={edge(other, node)} class="merge" />{/if}
{/each}
{/each}
</svg>
{#each $graph.nodes as node (node.id)}
<div
class="node"
class:head={node.head}
class:head-line={onHeadLine(node)}
class:undone={node.undone}
class:abandoned={node.abandoned}
style:left={`${left(node)}px`}
style:top={`${top(node)}px`}
style:width={`${NODE_WIDTH}px`}
style:height={`${NODE_HEIGHT}px`}
data-head={node.head || undefined}
>
<button class="step" data-tooltip-label={tooltip(node)} on:click={() => choose(node)}>
{#if node.thumbnail}<HistoryShot thumbnail={node.thumbnail} images={$thumbnails} />{/if}
<span class="label">{node.label}</span>
</button>
{#if node.abandoned}
<IconButton
icon="HistoryRedo"
size={16}
tooltipLabel="Bring back"
tooltipDescription="Do this step again on top of the current line."
action={() => editor.bringBackHistoryInteraction(node.id)}
/>
{/if}
{#if node.head}<span class="marker">Now</span>{/if}
</div>
{/each}
</div>
</div>
</div>
<style lang="scss">
.history-graph {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
background: var(--color-2-mildblack);
.header {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
padding: 4px 8px;
border-bottom: 1px solid var(--color-4-dimgray);
}
.body {
flex: 1 1 0;
overflow: auto;
position: relative;
> .text-label {
position: absolute;
padding: 16px;
}
}
.canvas {
position: relative;
}
.edges {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
path {
fill: none;
stroke: var(--color-5-dullgray);
stroke-width: 2;
&.head-line {
stroke: var(--color-e-nearwhite);
}
&.undone {
stroke-dasharray: 4 3;
}
&.merge {
stroke-dasharray: 2 4;
}
}
}
.node {
position: absolute;
box-sizing: border-box;
display: flex;
align-items: center;
gap: 2px;
padding: 0 4px 0 0;
border-radius: 4px;
border: 1px solid var(--color-4-dimgray);
background: var(--color-3-darkgray);
&.head-line {
border-color: var(--color-8-uppergray);
}
&.head {
border-color: var(--color-e-nearwhite);
background: var(--color-4-dimgray);
}
&.undone,
&.abandoned {
.step {
opacity: 0.6;
}
}
.step {
flex: 1 1 0;
min-width: 0;
height: 100%;
display: flex;
align-items: center;
gap: 6px;
padding: 0 0 0 6px;
border: none;
background: none;
color: var(--color-e-nearwhite);
text-align: left;
cursor: pointer;
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.marker {
flex: 0 0 auto;
font-size: 10px;
line-height: 14px;
padding: 0 4px;
border-radius: 2px;
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
}
</style>
@@ -0,0 +1,56 @@
<script lang="ts">
import type { HistoryThumbnail } from "/wrapper/pkg/graphite_wasm_wrapper";
export let thumbnail: HistoryThumbnail;
// The images the frontend received, by ID
export let images: Record<string, string>;
export let large = false;
</script>
<span class="history-shot" class:large>
<span class="image" data-tooltip-label="The document once this step was done">
{#if images[thumbnail.whole]}<img src={images[thumbnail.whole]} alt="" />{/if}
</span>
{#if thumbnail.detail}
<span class="image" data-tooltip-label="What this step changed, close up" data-tooltip-description="Green was added, red removed, and yellow changed.">
{#if images[thumbnail.detail]}<img src={images[thumbnail.detail]} alt="" />{/if}
</span>
{/if}
</span>
<style lang="scss">
.history-shot {
flex: 0 0 auto;
display: flex;
gap: 2px;
.image {
width: 36px;
height: 24px;
border-radius: 2px;
overflow: hidden;
background-image: var(--color-transparent-checkered-background);
background-size: var(--color-transparent-checkered-background-size-mini);
background-position: var(--color-transparent-checkered-background-position-mini);
background-repeat: var(--color-transparent-checkered-background-repeat);
}
&.large {
gap: 4px;
.image {
// The size captures are rendered at, like layer thumbnails
width: 72px;
height: 48px;
background-size: var(--color-transparent-checkered-background-size);
background-position: var(--color-transparent-checkered-background-position);
}
}
img {
display: block;
width: 100%;
height: 100%;
}
}
</style>
+77 -4
View File
@@ -1,18 +1,70 @@
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { HistoryGraphState, HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
export type HistoryStore = ReturnType<typeof createHistoryStore>;
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, session: false };
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, collaborating: false };
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<HistoryPanelState> = import.meta.hot?.data?.store || writable<HistoryPanelState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store;
// The captured images by the ID rows name them with, sent once each
const thumbnails: Writable<Record<string, string>> = import.meta.hot?.data?.thumbnails || writable<Record<string, string>>({});
// The history graph drawn over the viewport, sent only while it is open
const graph: Writable<HistoryGraphState> = import.meta.hot?.data?.graph || writable<HistoryGraphState>({ nodes: [], width: 0, depth: 0 });
const graphOpen: Writable<boolean> = import.meta.hot?.data?.graphOpen || writable<boolean>(false);
if (import.meta.hot) {
import.meta.hot.data.store = store;
import.meta.hot.data.thumbnails = thumbnails;
import.meta.hot.data.graph = graph;
import.meta.hot.data.graphOpen = graphOpen;
}
const { subscribe, set } = store;
// The most recent images kept, oldest dropped first. Each step has a whole image and maybe a close-up, so twice as many as the editor keeps captures
const MAX_THUMBNAILS = 600;
// The size an SVG capture is drawn at, twice the largest a capture is shown
const RASTER_WIDTH = 144;
const RASTER_HEIGHT = 96;
// Kept as a small PNG rather than the pixels themselves
function encodePixels(pixels: Uint8Array, width: number, height: number): string {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(pixels), width, height), 0, 0);
return canvas.toDataURL("image/png");
}
// Without the GPU a capture comes as an SVG, which can embed whole images, so it is kept as a small PNG, or as the SVG when the browser can't draw it
async function rasterize(svg: string): Promise<string> {
// An SVG drawn as an image needs an intrinsic size, which the capture's only gives as a view box
const sized = svg.replace("<svg ", `<svg width="${RASTER_WIDTH}" height="${RASTER_HEIGHT}" `);
const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(sized)}`;
try {
const image = new Image();
image.src = url;
await image.decode();
const canvas = document.createElement("canvas");
canvas.width = RASTER_WIDTH;
canvas.height = RASTER_HEIGHT;
canvas.getContext("2d")?.drawImage(image, 0, 0, RASTER_WIDTH, RASTER_HEIGHT);
return canvas.toDataURL("image/png");
} catch {
return url;
}
}
function keepThumbnail(id: string, url: string) {
thumbnails.update((images) => {
const ids = Object.keys(images);
const kept = ids.length < MAX_THUMBNAILS ? images : Object.fromEntries(ids.slice(ids.length - MAX_THUMBNAILS + 1).map((id) => [id, images[id]]));
return { ...kept, [id]: url };
});
}
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
@@ -23,7 +75,24 @@ export function createHistoryStore(subscriptions: SubscriptionsRouter) {
set(data.state);
});
return { subscribe };
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnail", async (data) => {
const url = await rasterize(data.svg);
keepThumbnail(data.id, url);
});
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnailPixels", (data) => {
keepThumbnail(data.id, encodePixels(data.pixels, data.width, data.height));
});
subscriptions.subscribeFrontendMessage("UpdateHistoryGraph", (data) => {
graph.set(data.graph);
});
subscriptions.subscribeFrontendMessage("UpdateHistoryGraphOverlay", (data) => {
graphOpen.set(data.open);
});
return { subscribe, thumbnails: { subscribe: thumbnails.subscribe }, graph: { subscribe: graph.subscribe }, graphOpen: { subscribe: graphOpen.subscribe } };
}
export function destroyHistoryStore() {
@@ -31,5 +100,9 @@ export function destroyHistoryStore() {
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnail");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnailPixels");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryGraph");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryGraphOverlay");
subscriptionsRouter = undefined;
}
+5
View File
@@ -300,6 +300,11 @@ mod editor_commands {
HistoryMessage::Tag { id, tag, on }.into()
}
/// Show or hide the history graph over the viewport
fn set_history_graph_open(open: bool) -> Message {
HistoryMessage::GraphOverlay { open }.into()
}
fn split_panel_group(target_group: u64, direction: Ts<DockingSplitDirection>, tabs: Vec<Ts<PanelType>>, active_tab_index: usize) -> Message {
WorkspaceMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),