Compare commits

..
Author SHA1 Message Date
Dennis Kobert 96a8e72fcf Fix Vivid Light burning and dodging the source by the backdrop instead of the backdrop by the source 2026-11-05 22:57:24 +00:00
Dennis Kobert 21910d242f Address review comments on the GPU raster kernels 2026-11-05 22:57:24 +00:00
Dennis Kobert c22fb0ec3a Add an Image to Channels GPU node for GPU rasters, since a multi-output struct can't be generic over its raster 2026-11-05 13:30:23 -08:00
Dennis Kobert 312dc1529b Version the nodes that gained GPU rasters and add their migrations 2026-11-05 13:30:23 -08:00
Dennis Kobert ccc32d6104 Test that CPU rasters stay on the CPU without a GPU, Eager opts into it, and a footprint-dependent raster warns at Dehaze 2026-11-05 13:30:22 -08:00
Dennis Kobert ba4b4812e7 Add an Eager node that uploads a raster so the nodes after it run on the GPU 2026-11-05 13:30:22 -08:00
Dennis Kobert 1642bf38ce Report a raster kernel's GPU failures and oversized outputs rather than saying a GPU is required 2026-11-05 13:30:22 -08:00
Dennis Kobert 6684bd279f Mark the Dehaze node as footprint invariant 2026-11-05 13:30:21 -08:00
Dennis Kobert 181c8e461c Fall back to half-float rasters where the GPU can't render full floats 2026-11-05 13:30:20 -08:00
Dennis Kobert 2e57be5aa1 Let list and render nodes carry GPU rasters 2026-11-05 13:30:19 -08:00
Dennis Kobert 7d6718dc67 Embed GPU rasters in SVG output by downloading them first 2026-11-05 13:30:19 -08:00
Dennis Kobert 49ecb3e695 Give GPU rasters an empty default 2026-11-05 13:30:19 -08:00
Dennis Kobert 73aeeee4d6 Run Dehaze and Image Color Palette on GPU rasters 2026-11-05 13:30:16 -08:00
Dennis Kobert 5cfe68dd32 Run raster nodes on GPU rasters through hand-written WGSL kernels 2026-11-05 13:30:15 -08:00
196 changed files with 8208 additions and 7181 deletions

No files matched your search

+1 -1
View File
@@ -12,7 +12,7 @@
},
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
"containerEnv": {
"WASM_BINDGEN_CLI_VERSION": "0.2.129",
"WASM_BINDGEN_CLI_VERSION": "0.2.127",
"CARGO_ABOUT_VERSION": "0.9.2",
"BINARYEN_VERSION": "130",
"CARGO_BINSTALL_VERSION": "1.23.0"
+3 -3
View File
@@ -62,7 +62,7 @@ jobs:
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
SCCACHE_VERSION: "v0.19.0"
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
steps:
@@ -348,7 +348,7 @@ jobs:
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
@@ -617,7 +617,7 @@ jobs:
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
+1 -1
View File
@@ -22,7 +22,7 @@ let
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_129
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.rustc
+1 -1
View File
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_129
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
Generated
+2360 -1968
View File
File diff suppressed because it is too large. Load diff
+26 -26
View File
@@ -147,10 +147,10 @@ web-time = "1.1"
env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "1.0"
ctor = "0.2"
convert_case = "0.12"
titlecase = "3.6"
fancy-regex = "0.20.0"
fancy-regex = "0.18.0"
unicode-segmentation = "1.13.2"
indoc = "2.0.5"
derivative = "2.2"
@@ -176,10 +176,10 @@ wgpu = { version = "30.0", default-features = false, features = [
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.129" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.127" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.106"
web-sys = { version = "=0.3.106", features = [
js-sys = "=0.3.104"
web-sys = { version = "=0.3.104", features = [
"Document",
"DomRect",
"Element",
@@ -210,25 +210,25 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
usvg = "0.49"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.12", default-features = false, features = ["std"] }
skrifa = "0.44"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
rand_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.23"
base64 = "0.22"
blake3 = "1.5"
mmap-io = { version = "1.0", features = ["hugepages"] }
mmap-io = { version = "0.9", features = ["hugepages"] }
image = { version = "0.25", default-features = false, features = [
"png",
"jpeg",
@@ -245,10 +245,10 @@ image = { version = "0.25", default-features = false, features = [
pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.5"
num-derive = "0.4"
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "3.0", default-features = false, features = [
syn = { version = "2.0", default-features = false, features = [
"full",
"derive",
"parsing",
@@ -262,14 +262,14 @@ syn = { version = "3.0", default-features = false, features = [
lyon_geom = "1.0"
delaunator = "1.0"
robust = "1.2"
petgraph = { version = "0.8", default-features = false, features = ["graphmap"] }
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" }
ndarray = "0.17"
ollev = "0.1.2"
dirs = "7.0"
criterion = { version = "0.7", features = ["html_reports"] }
gungraun = { version = "0.18" }
ndarray = "0.16"
ollev = "0.1.1"
dirs = "6.0"
cef = "156"
cef-dll-sys = "156"
include_dir = "0.7"
@@ -277,14 +277,14 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.17"
open = "5.3"
spin = "0.12"
spin = "0.10"
clap = "4.5"
qrcodegen = "1.8"
lzma-rust2 = { version = "0.25", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.29"
linesweeper = "0.5"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "9", default-features = false }
zip = { version = "8", default-features = false }
[workspace.lints]
+2 -10
View File
@@ -1,3 +1,5 @@
<a href="https://graphite.art/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/9366c148-4405-484f-909a-9a3526eb9209">
@@ -81,13 +83,3 @@ Are you a graphics programmer or Rust developer? Graphite aims to be one of the
## License
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
## Acknowledgments
We're grateful to these programs and organizations for the grants and services that help make Graphite possible.
[<img width="600" alt="European Commission, NGI Zero, and NLnet Foundation" src="https://github.com/user-attachments/assets/d5b3c623-710a-4809-916b-263e80c28184" />](https://nlnet.nl/commonsfund/)
[<img width="600" alt="Google Summer of Code" src="https://github.com/user-attachments/assets/37284dfe-fccd-4abd-904c-1165ff36da53" />](https://summerofcode.withgoogle.com/)
[<img width="300" alt="CI Powered by Blacksmith" src="https://github.com/user-attachments/assets/72bd48c2-ab21-4aed-b0a5-d440a8662128" />](https://www.blacksmith.sh/)
+1 -1
View File
@@ -1,4 +1,4 @@
use rand::RngExt;
use rand::Rng;
use rfd::AsyncFileDialog;
use std::fs;
use std::io::Read;
+1 -1
View File
@@ -34,7 +34,7 @@ serde_json = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
cef = { workspace = true }
bytemuck = { workspace = true, optional = true }
ipc-channel = "0.23"
ipc-channel = "0.22"
# Linux-specific dependencies
[target.'cfg(target_os = "linux")'.dependencies]
+1 -1
View File
@@ -36,7 +36,7 @@ impl Archive for Zip {
if !entry.is_file() {
continue;
}
let name = entry.name().map_err(zip_err)?.to_string();
let name = entry.name().to_string();
validate_path(&name)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
+2 -2
View File
@@ -91,7 +91,7 @@ impl MmappedBytes {
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
let len = file.len();
file.as_slice_bytes(0, len)
file.as_slice(0, len)
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
Ok(Self(file))
}
@@ -105,7 +105,7 @@ impl MmappedBytes {
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice_bytes(0, len) {
match self.0.as_slice(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
-22
View File
@@ -400,11 +400,6 @@ 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 {
@@ -463,23 +458,6 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer asks the retirer.
#[cfg(feature = "network")]
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
if self.retires_locally() {
let (moved, touched) = self.session.move_head_to(rev)?;
self.remote_changes.touched.extend(touched);
self.persist_registry_snapshot()?;
self.persist_session_state()?;
if let Some(replica) = &mut self.network {
replica.broadcast_head_move(moved)?;
}
} else if let Some(replica) = &mut self.network {
replica.request_move(rev)?;
}
Ok(())
}
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
#[cfg(feature = "network")]
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
@@ -74,6 +74,4 @@ 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,14 +55,6 @@ 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,7 +10,6 @@ pub mod ids;
pub mod model;
mod prior;
pub mod registry;
mod repair;
pub mod resources;
mod schema;
pub mod session;
@@ -50,7 +49,6 @@ 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
@@ -1,273 +0,0 @@
//! 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 });
}
}
}
+11 -149
View File
@@ -24,8 +24,6 @@ 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 {
@@ -49,7 +47,6 @@ impl Session {
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
action: None,
}
}
@@ -339,7 +336,6 @@ impl Session {
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
action: None,
}
}
@@ -390,10 +386,6 @@ 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();
@@ -438,70 +430,23 @@ 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. Each copied interaction ends with the
// repairs it needs on the changed line.
// Minted on a scratch fold first, so a failing copy changes nothing.
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 (copy, _) in copies.iter().zip(&sources).filter(|(_, (original, _))| original.is_none()) {
touched.record(&copy.kind);
}
for copy in &copies {
for (original, copy) in newest_first[..position].iter().rev().zip(&mut copies) {
self.document.history.push(copy.clone());
}
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 {
self.carry_attributes(original, copy.id);
if let Some(carried) = self.document.history.get(copy.id) {
*copy = carried.clone();
}
@@ -614,8 +559,7 @@ 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, and the graph is repaired where that
/// left it broken (see [`repair_ops`](crate::repair::repair_ops)). Returns the new revs.
/// original stamps, so a field someone wrote since keeps the newer value. 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();
@@ -627,32 +571,10 @@ impl Session {
originals.push(delta);
}
originals.reverse();
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();
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
for (original, &rev) in originals.iter().zip(&revs) {
let closes = original.id == dropped;
self.carry_attributes_closing(original, rev, closing.filter(|_| closes));
self.carry_attributes(original, rev);
}
revs.extend(repaired);
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
}
@@ -708,7 +630,6 @@ 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
@@ -722,22 +643,9 @@ 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();
@@ -934,14 +842,9 @@ 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)
}
@@ -992,57 +895,16 @@ impl Session {
}
}
/// 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);
}
/// 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);
}
for (key, value) in original.attributes.live() {
let moved = closing.filter(|_| key == INTERACTION_END || key == ACTION);
self.document.history.annotate(moved.unwrap_or(copy), key, value.value.clone(), value.timestamp);
self.document.history.annotate(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,37 +597,3 @@ 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]);
}
@@ -1,427 +0,0 @@
//! 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()));
}
+1 -1
View File
@@ -244,7 +244,7 @@ fn registration(core: &TokenStream2, register: TokenStream2, migration: TokenStr
quote! {
use #core::ctor::ctor;
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = #core::ctor))]
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register() {
#core::#register(#migration);
}
+5
View File
@@ -4,3 +4,8 @@
mod graphene_core;
mod math_nodes;
mod raster_nodes;
/// The scope input of nodes that came to take the GPU pipeline, the identifier frozen as it was when they did.
fn raster_kernel_pipeline() -> migration_core::NodeInput {
migration_core::NodeInput::Scope("raster_nodes::raster_kernel::RasterKernelPipelineNode".into())
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::BlackAndWhiteNode"@1 => @2)]
pub fn black_and_white_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlackAndWhiteV1, &contract());
check_undo(&BlackAndWhiteV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::filter::BlurNode"@1 => @2)]
pub fn blur_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BlurV1, &contract());
check_undo(&BlurV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::BrightnessContrastNode"@1 => @2)]
pub fn brightness_contrast_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&BrightnessContrastV1, &contract());
check_undo(&BrightnessContrastV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ChannelMixerNode"@1 => @2)]
pub fn channel_mixer_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(19, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ChannelMixerV1, &contract());
check_undo(&ChannelMixerV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::ChannelsToImageNode"@1 => @2)]
pub fn channels_to_image_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ChannelsToImageV1, &contract());
check_undo(&ChannelsToImageV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ColorBalanceNode"@1 => @2)]
pub fn color_balance_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(12, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorBalanceV1, &contract());
check_undo(&ColorBalanceV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ColorLookupNode"@1 => @2)]
pub fn color_lookup_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorLookupV1, &contract());
check_undo(&ColorLookupV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => @2)]
pub fn color_overlay_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ColorOverlayV1, &contract());
check_undo(&ColorOverlayV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::CurvesNode"@1 => @2)]
pub fn curves_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&CurvesV1, &contract());
check_undo(&CurvesV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::dehaze::DehazeNode"@1 => @2)]
pub fn dehaze_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DehazeV1, &contract());
check_undo(&DehazeV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::DesaturateNode"@1 => @2)]
pub fn desaturate_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&DesaturateV1, &contract());
check_undo(&DesaturateV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ExposureNode"@1 => @2)]
pub fn exposure_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ExposureV1, &contract());
check_undo(&ExposureV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => @2)]
pub fn extend_image_to_bounds_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ExtendImageToBoundsV1, &contract());
check_undo(&ExtendImageToBoundsV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::GammaCorrectionNode"@1 => @2)]
pub fn gamma_correction_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&GammaCorrectionV1, &contract());
check_undo(&GammaCorrectionV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::GradientMapNode"@1 => @2)]
pub fn gradient_map_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&GradientMapV1, &contract());
check_undo(&GradientMapV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::HueSaturationNode"@1 => @2)]
pub fn hue_saturation_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(51, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&HueSaturationV1, &contract());
check_undo(&HueSaturationV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::image_color_palette::ImageColorPaletteNode"@1 => @2)]
pub fn image_color_palette_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ImageColorPaletteV1, &contract());
check_undo(&ImageColorPaletteV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::InvertNode"@1 => @2)]
pub fn invert_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&InvertV1, &contract());
check_undo(&InvertV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::LevelsNode"@1 => @2)]
pub fn levels_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(27, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&LevelsV1, &contract());
check_undo(&LevelsV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
pub fn make_opaque_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MakeOpaqueV1, &contract());
check_undo(&MakeOpaqueV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::std_nodes::MaskNode"@1 => @2)]
pub fn mask_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MaskV1, &contract());
check_undo(&MaskV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
pub fn median_filter_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MedianFilterV1, &contract());
check_undo(&MedianFilterV1, &contract());
}
}
@@ -1,4 +1,31 @@
//! Migrations of the nodes in `raster_nodes`.
mod black_and_white_v1;
mod blur_v1;
mod brightness_contrast_v1;
mod channel_mixer_v1;
mod channels_to_image_v1;
mod color_balance_v1;
mod color_lookup_v1;
mod color_overlay_v1;
mod curves_v1;
mod dehaze_v1;
mod desaturate_v1;
mod exposure_v1;
mod extend_image_to_bounds_v1;
mod gamma_correction_v1;
mod gradient_map_v1;
mod hue_saturation_v1;
mod image_color_palette_v1;
mod invert_v1;
mod levels_v1;
mod make_opaque_v1;
mod mask_v1;
mod median_filter_v1;
mod mix_colors_from_mix_node;
mod photo_filter_v1;
mod posterize_v1;
mod renames;
mod selective_color_v1;
mod threshold_v1;
mod vibrance_v1;
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::PhotoFilterNode"@1 => @2)]
pub fn photo_filter_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PhotoFilterV1, &contract());
check_undo(&PhotoFilterV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::PosterizeNode"@1 => @2)]
pub fn posterize_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PosterizeV1, &contract());
check_undo(&PosterizeV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::SelectiveColorNode"@1 => @2)]
pub fn selective_color_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(39, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&SelectiveColorV1, &contract());
check_undo(&SelectiveColorV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::ThresholdNode"@1 => @2)]
pub fn threshold_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&ThresholdV1, &contract());
check_undo(&ThresholdV1, &contract());
}
}
@@ -0,0 +1,25 @@
use crate::raster_kernel_pipeline;
use migration_core::{Inputs, migration};
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
#[migration("raster_nodes::adjustments::VibranceNode"@1 => @2)]
pub fn vibrance_v1(inputs: &mut Inputs) {
inputs.push(raster_kernel_pipeline());
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::literal;
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&VibranceV1, &contract());
check_undo(&VibranceV1, &contract());
}
}
+1 -1
View File
@@ -13,7 +13,7 @@ publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.15.0"
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
+2 -2
View File
@@ -14,7 +14,7 @@ const FRAME_FINAL: u8 = 1;
const FRAME_MORE: u8 = 0;
/// Split a packet into `[flag][bytes]` chunks, the last carrying [`FRAME_FINAL`] so no length prefix is needed.
fn frames(bytes: &[u8]) -> Vec<Packet> {
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// Chunking an empty packet would yield no frame at all.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
@@ -258,7 +258,7 @@ mod tests {
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
lock(&inbox).packets.push_back((peer(1), Packet::from_static(&[FRAME_FINAL, 7])));
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
-1
View File
@@ -307,7 +307,6 @@ impl Dispatcher {
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
@@ -8,7 +8,6 @@ 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;
@@ -167,12 +166,6 @@ 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,
@@ -384,7 +377,6 @@ 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 {
@@ -396,7 +388,6 @@ 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;
}
@@ -196,27 +196,6 @@ pub enum FrontendMessage {
UpdateDocumentCursors {
cursors: Vec<FrontendRemoteCursor>,
},
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>,
},
@@ -99,7 +99,7 @@ impl MessageHandler<FutureMessage, ()> for FutureMessageHandler {
}));
}
FutureMessage::Drain => {
while let Ok(message) = self.results_receiver.try_recv() {
while let Ok(Some(message)) = self.results_receiver.try_next() {
responses.push_back(message);
}
}
@@ -345,7 +345,6 @@ 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),
@@ -25,7 +25,6 @@ pub struct MenuBarMessageHandler {
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub session_panel_open: bool,
pub history_panel_open: bool,
pub layers_panel_open: bool,
pub inspector_open: bool,
pub focus_document: bool,
@@ -694,11 +693,6 @@ impl LayoutHolder for MenuBarMessageHandler {
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("History")
.label("History")
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
.disabled(self.focus_document),
],
])
.widget_instance(),
@@ -18,7 +18,7 @@ use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -944,9 +944,15 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({} x {})", self.data().width(), self.data().height())
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
if self.is_empty() {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
@@ -7,7 +7,6 @@ use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRe
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, StagingError, construct_batch};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
use crate::messages::portfolio::history::utility_types::LineChange;
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
@@ -236,26 +235,6 @@ impl DocumentHistory {
storage.redo_retired_step(rev).inspect_err(|error| log::error!("Redoing the dropped step failed: {error}")).is_ok()
}
/// Returns whether storage made the change.
pub fn change_line(&mut self, rev: document_graph_storage::Rev, change: LineChange) -> bool {
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
return false;
};
let result = match change {
LineChange::MoveHead => storage.move_head(rev),
LineChange::Remove => storage.drop_step(rev),
LineChange::Restore => storage.redo_retired_step(rev),
};
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok()
}
/// Forgets the legacy snapshots once the head has moved off their line.
pub fn clear_legacy(&mut self) {
self.legacy_undo_stack.clear();
self.legacy_redo_stack.clear();
self.undo_notes.clear();
}
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
@@ -56,10 +56,6 @@ pub enum DocumentMessage {
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
ChangeHistoryLine {
rev: document_graph_storage::Rev,
change: crate::messages::portfolio::history::utility_types::LineChange,
},
DocumentStructureChanged,
DrawArtboardOverlays {
context: OverlayContext,
@@ -131,10 +127,6 @@ 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,
},
@@ -24,7 +24,6 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::history::utility_types::LineChange;
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::edit_target::EditTarget;
@@ -36,7 +35,7 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_container::AnyContainer;
use document_graph_storage::{Declarations, Rev};
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceStorage};
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
@@ -474,14 +473,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
}
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
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();
@@ -1049,7 +1040,6 @@ 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);
@@ -1111,7 +1101,6 @@ 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);
@@ -2443,10 +2432,6 @@ 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()
@@ -3013,26 +2998,6 @@ impl DocumentMessageHandler {
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Makes a History panel change in storage and drops the legacy snapshots, which are off the head's line.
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, validate: bool, responses: &mut VecDeque<Message>) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort);
self.stage_edits_outside_transaction(byte_store, validate);
self.history.retire_storage_interaction();
let stored_name = self.stored_name().map(str::to_string);
if !self.history.change_line(rev, change) {
return;
}
self.history.clear_legacy();
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
responses.add(OverlaysMessage::Draw);
responses.add(EventMessage::SelectionChanged);
}
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
if let Some(gdd) = self.history.storage_mut() {
@@ -3859,7 +3824,7 @@ impl DocumentMessageHandler {
]
}
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration, history_graph_open: bool) {
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
let mut widgets = vec![
IconButton::new("PlaybackToStart", 24)
.tooltip_label("Restart Animation")
@@ -3944,14 +3909,6 @@ 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, name_layer_action};
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
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,18 +450,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return;
};
responses.add(DocumentMessage::AddTransaction);
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::DeleteNodes {
node_ids: selected_nodes.selected_nodes().cloned().collect::<Vec<_>>(),
delete_children,
});
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::SendGraph);
@@ -658,7 +650,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
insert_node_input_index,
} => {
network_interface.insert_node_between(&node_id, &input_connector, insert_node_input_index, selection_network_path);
network_interface.connect_read_node_to_map(&node_id, selection_network_path);
}
NodeGraphMessage::InsertDotOnWire { node_id, input_connector, x, y } => {
network_interface.insert_dot_on_wire(node_id, &input_connector, IVec2::new(x, y), selection_network_path);
@@ -4,7 +4,6 @@ use super::{
};
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::test_utils::test_prelude::*;
@@ -3548,106 +3547,3 @@ async fn cannot_preview_node_without_outputs() {
network_interface.toggle_preview(custom_node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
}
fn map_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)
}
async fn layer_with_chain_and_unwired_map(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId) {
let (layer, near, ..) = layer_with_chain(editor).await;
editor
.active_document_mut()
.network_interface
.create_wire(&OutputConnector::primary_output(layer), &InputConnector::Export(0), &[]);
editor.handle_message(NodeGraphMessage::RunDocumentGraph).await;
let map = editor.create_node_by_name_at(map_definition(), 0, 30).await;
(layer, near, map)
}
async fn drop_map_onto_chain(editor: &mut EditorTestUtils, layer: NodeId, map: NodeId) {
editor
.handle_message(NodeGraphMessage::InsertNodeBetween {
node_id: map,
input_connector: InputConnector::layer_secondary_input(layer),
insert_node_input_index: 0,
})
.await;
}
#[tokio::test]
async fn dropping_a_map_node_onto_a_wire_feeds_it_the_matching_read_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, near, map) = layer_with_chain_and_unwired_map(&mut editor).await;
drop_map_onto_chain(&mut editor, layer, map).await;
let network_interface = &editor.active_document().network_interface;
let Some(NodeInput::Node { node_id: read_node, .. }) = network_interface.input_from_connector(&InputConnector::node_at_index(map, 1), &[]).cloned() else {
panic!("The Map node's mapped input should be fed by a new node");
};
assert_eq!(
network_interface.reference(&read_node, &[]),
Some(DefinitionIdentifier::ProtoNode(graphene_std::context::read_vector::IDENTIFIER))
);
let map_position = network_interface.position(&map, &[]).unwrap();
let near_position = network_interface.position(&near, &[]).unwrap();
let near_bottom = near_position.y + network_interface.node_height(&near, &[]) as i32;
let read_node_position = network_interface.position(&read_node, &[]).unwrap();
assert_eq!(read_node_position.x, map_position.x - crate::consts::NODE_CHAIN_WIDTH);
assert!(
read_node_position.y > near_bottom,
"The Read node should sit below the Map node's content source rather than overlap it"
);
assert_invariants(&editor, "after dropping a Map node onto a wire");
}
#[test]
fn map_content_types_resolve_to_the_read_node_of_their_element() {
use super::layout::read_node_for_content;
use super::resolved_types::TypeSource;
use graph_craft::{item, list};
use graphene_std::context::{read_graphic, read_number, read_vector};
use graphene_std::list::Bundle;
use graphene_std::text_nodes::read_string;
use graphene_std::{Graphic, Vector};
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(Vector))), Some(read_vector::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::Compiled(item!(Graphic))), Some(read_graphic::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(f64))), Some(read_number::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::TaggedValue(list!(String))), Some(read_string::IDENTIFIER));
assert_eq!(read_node_for_content(&TypeSource::Compiled(item!(Bundle<Vector>))), Some(read_vector::IDENTIFIER));
assert_eq!(
read_node_for_content(&TypeSource::Compiled(list!(i64))),
None,
"Read Number yields f64, which a Map over integers can't take"
);
assert_eq!(read_node_for_content(&TypeSource::Compiled(list!(bool))), None);
assert_eq!(read_node_for_content(&TypeSource::Unknown), None);
}
#[tokio::test]
async fn dropping_a_map_node_onto_a_wire_keeps_its_wired_mapped_input() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, _, map) = layer_with_chain_and_unwired_map(&mut editor).await;
let mapped_source = NodeId::new();
let read_vector = resolve_proto_node_type(graphene_std::context::read_vector::IDENTIFIER).unwrap().default_node_template();
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.insert_node(mapped_source, read_vector, &[]);
network_interface.create_wire(&OutputConnector::primary_output(mapped_source), &InputConnector::node_at_index(map, 1), &[]);
let node_count = editor.active_document().network_interface.document_network().nodes.len();
drop_map_onto_chain(&mut editor, layer, map).await;
let network_interface = &editor.active_document().network_interface;
assert_eq!(
network_interface.input_from_connector(&InputConnector::node_at_index(map, 1), &[]),
Some(&NodeInput::node(mapped_source, 0))
);
assert_eq!(network_interface.document_network().nodes.len(), node_count);
}
@@ -1,9 +1,4 @@
use super::resolved_types::TypeSource;
use super::*;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::style::Gradient;
use graphene_std::{Color, Graphic};
impl NodeNetworkInterface {
/// The top left corner of a node in node graph grid coordinates.
@@ -1160,41 +1155,6 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node_at_index(*node_id, insert_node_input_index), network_path);
}
/// Feeds an unconnected Map node's mapped input with the Read node matching the element type of its content.
pub fn connect_read_node_to_map(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
if self.reference(node_id, network_path) != Some(DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)) {
return;
}
let mapped_input = InputConnector::node_at_index(*node_id, 1);
if !matches!(self.input_from_connector(&mapped_input, network_path), Some(NodeInput::Value { .. })) {
return;
}
let Some(content_source) = self.upstream_output_connector(&InputConnector::primary_input(*node_id), network_path) else {
return;
};
let Some(mut read_node_template) = read_node_for_content(&self.output_type(&content_source, network_path))
.and_then(resolve_proto_node_type)
.map(|definition| definition.default_node_template())
else {
return;
};
let Some(map_position) = self.position(node_id, network_path) else {
return;
};
let below_content_source = content_source
.node_id()
.and_then(|source| Some(self.position(&source, network_path)?.y + self.node_height(&source, network_path) as i32 + 1));
let read_node_position = IVec2::new(map_position.x - NODE_CHAIN_WIDTH, below_content_source.unwrap_or(map_position.y + 2));
read_node_template.node_type_metadata = NodeTypePersistentMetadata::node(read_node_position);
let read_node_id = NodeId::new();
self.insert_node(read_node_id, read_node_template, network_path);
self.create_wire(&OutputConnector::primary_output(read_node_id), &mapped_input, network_path);
}
/// Inserts the freshly-created `node_id` onto the wire feeding `input_connector`: the previous upstream becomes the
/// new node's primary (index 0) input, and the new node feeds `input_connector`.
///
@@ -1615,30 +1575,3 @@ impl NodeNetworkInterface {
self.layer_chain(layer, network_path) == intended_chain
}
}
/// The Read node yielding each element of a Map node's content, unbundling a whole-list `Item<Bundle<T>>` wire to its `T`.
pub(super) fn read_node_for_content(content_type: &TypeSource) -> Option<ProtoNodeIdentifier> {
use graphene_std::context::{read_color, read_gradient, read_graphic, read_number, read_raster, read_vector};
use graphene_std::text_nodes::read_string;
let bundle_element = content_type.compiled_nested_type().and_then(Type::bundle_element_name);
let element_type = content_type.compiled_element_type()?;
[
(concrete!(Vector), read_vector::IDENTIFIER),
(concrete!(Graphic), read_graphic::IDENTIFIER),
(concrete!(Raster<CPU>), read_raster::IDENTIFIER),
(concrete!(Color), read_color::IDENTIFIER),
(concrete!(Gradient), read_gradient::IDENTIFIER),
(concrete!(f64), read_number::IDENTIFIER),
(concrete!(String), read_string::IDENTIFIER),
]
.into_iter()
.find_map(|(candidate, read_node)| {
let matches = match (bundle_element, &candidate) {
(Some(bundle_element), Type::Concrete(descriptor)) => descriptor.name == bundle_element,
_ => candidate == *element_type,
};
matches.then_some(read_node)
})
}
@@ -3519,6 +3519,49 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
let raster_kernel_pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
let raster_kernel_nodes = {
use graphene_std::raster_nodes::adjustments::*;
[
desaturate::IDENTIFIER,
gamma_correction::IDENTIFIER,
make_opaque::IDENTIFIER,
brightness_contrast::IDENTIFIER,
levels::IDENTIFIER,
curves::IDENTIFIER,
black_and_white::IDENTIFIER,
hue_saturation::IDENTIFIER,
invert::IDENTIFIER,
threshold::IDENTIFIER,
gradient_map::IDENTIFIER,
vibrance::IDENTIFIER,
channel_mixer::IDENTIFIER,
selective_color::IDENTIFIER,
posterize::IDENTIFIER,
exposure::IDENTIFIER,
color_balance::IDENTIFIER,
photo_filter::IDENTIFIER,
color_lookup::IDENTIFIER,
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
graphene_std::raster_nodes::filter::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
]
};
if raster_kernel_nodes.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && !node.inputs.contains(&raster_kernel_pipeline) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let value_inputs = node_template.inputs.iter().position(|input| *input == raster_kernel_pipeline)?;
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().take(value_inputs).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
if let Some(definition) = resolve_document_node_type(&reference) {
@@ -4478,7 +4521,8 @@ mod tests {
let desaturate_node = node(1);
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method]);
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
let brightness_contrast = node(2);
assert_eq!(
@@ -1,184 +0,0 @@
//! 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);
}
}
@@ -1,43 +0,0 @@
use crate::messages::prelude::*;
#[impl_message(Message, PortfolioMessage, History)]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum HistoryMessage {
Refresh,
Tick,
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,
},
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,9 +0,0 @@
mod changes;
mod history_message;
mod history_message_handler;
pub mod utility_types;
#[doc(inline)]
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
#[doc(inline)]
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
@@ -1,157 +0,0 @@
//! 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.
MoveHead,
/// Drops a retired interaction and mints the later ones again on its parent.
Remove,
/// Does a step off the line again on top of it.
Restore,
}
/// The panel's content, newest first. The head's line with undone interactions above it, or a followed branch's line.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryPanelState {
pub rows: Vec<HistoryRow>,
/// Work not yet in history. One row per person's open work and per closed interaction waiting to retire.
pub progress: Vec<HistoryProgressRow>,
pub more: bool,
pub following: Option<String>,
/// 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.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryRow {
/// The rev closing the interaction, in decimal.
pub id: String,
pub label: String,
pub named: bool,
pub tags: Vec<String>,
pub author: String,
/// `author` is a stand-in.
pub anonymous: bool,
pub mine: bool,
pub color: String,
/// Milliseconds since the Unix epoch, if the retirer recorded it.
pub time: Option<f64>,
pub deltas: usize,
/// Branches off the shown line, each by its tip.
pub branches: Vec<HistoryBranch>,
pub undone: bool,
/// On a followed branch, off the head's line.
pub abandoned: bool,
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))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryBranch {
pub id: String,
pub label: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryDeltaRow {
pub id: String,
pub label: String,
pub author: 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)]
pub struct HistoryProgressRow {
pub label: String,
pub author: String,
pub anonymous: bool,
pub mine: bool,
pub color: String,
pub ops: usize,
/// Still being made, not closed and waiting.
pub open: bool,
pub thumbnail: Option<HistoryThumbnail>,
}
-1
View File
@@ -7,7 +7,6 @@ pub mod document_migration;
pub mod document_storage_io;
pub mod failed_documents;
pub mod fonts;
pub mod history;
pub mod ingest;
pub mod persistent_state;
pub mod sync;
@@ -1,5 +1,4 @@
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
use super::history::HistoryMessage;
use super::persistent_state::PersistentStateMessage;
use super::sync::SyncMessage;
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
@@ -23,8 +22,6 @@ pub enum PortfolioMessage {
#[child]
PersistentState(PersistentStateMessage),
#[child]
History(HistoryMessage),
#[child]
Sync(SyncMessage),
#[child]
Workspace(WorkspaceMessage),
@@ -60,7 +60,6 @@ pub struct PortfolioMessageHandler {
persistent_state: PersistentStateMessageHandler,
pub fonts: FontsMessageHandler,
ingest: IngestMessageHandler,
history: HistoryMessageHandler,
sync: SyncMessageHandler,
pub executor: NodeGraphExecutor,
pub selection_mode: SelectionMode,
@@ -139,15 +138,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
};
self.ingest.process_message(message, responses, context);
}
PortfolioMessage::History(message) => {
let context = HistoryMessageContext {
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);
}
PortfolioMessage::Sync(message) => {
let context = SyncMessageContext {
documents: &mut self.documents,
@@ -1142,7 +1132,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, self.history.graph_open());
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time);
}
}
PortfolioMessage::UpdateOpenDocumentsList => {
@@ -1177,7 +1167,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PrevDocument,
));
common.extend(actions!(IngestMessageDiscriminant; Import));
common.extend(self.history.actions());
}
common
@@ -1195,7 +1184,6 @@ impl PortfolioMessageHandler {
persistent_state: Default::default(),
fonts: Default::default(),
ingest: Default::default(),
history: Default::default(),
sync: Default::default(),
executor,
selection_mode: Default::default(),
@@ -4,6 +4,5 @@ mod sync_message_handler;
#[doc(inline)]
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
pub(crate) use sync_message_handler::now_ms;
#[doc(inline)]
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
@@ -515,7 +515,7 @@ fn load_resource_future(document_id: DocumentId, to: TransportPeerId, hash: Reso
future.into()
}
pub(crate) fn now_ms() -> f64 {
fn now_ms() -> f64 {
#[cfg(target_arch = "wasm32")]
{
js_sys::Date::now()
@@ -13,7 +13,6 @@ pub enum PanelType {
Inspector,
Data,
Session,
History,
}
impl From<String> for PanelType {
@@ -25,7 +24,6 @@ impl From<String> for PanelType {
"Inspector" | "Properties" => PanelType::Inspector,
"Data" => PanelType::Data,
"Session" => PanelType::Session,
"History" => PanelType::History,
_ => panic!("Unknown panel type: {value}"),
}
}
@@ -33,7 +31,7 @@ impl From<String> for PanelType {
impl PanelType {
pub fn non_document_panels() -> &'static [PanelType] {
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session, PanelType::History]
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session]
}
}
@@ -305,11 +303,10 @@ impl WorkspacePanelLayout {
/// - Data: below the document in the left column (root child 0)
/// - Inspector: top of the right column (root child 1)
/// - Layers: bottom of the right column (root child 1)
/// - Session, History: a tab beside the Inspector or Layers, otherwise placed like that panel
/// - Session: a tab in the Inspector's group, otherwise placed like the Inspector
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
let beside = match panel_type {
PanelType::Session => Some(PanelType::Inspector),
PanelType::History => Some(PanelType::Layers),
_ => None,
};
if let Some(beside) = beside
@@ -336,7 +333,7 @@ impl WorkspacePanelLayout {
let (root_child_index, insert_at_end) = match panel_type {
PanelType::Data => (0, true), // Left column, after document
PanelType::Inspector | PanelType::Session => (1, false), // Right column, at top
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
PanelType::Layers => (1, true), // Right column, at bottom
_ => (1, true),
};
@@ -35,7 +35,6 @@ pub enum WorkspaceMessage {
},
ToggleDataPanelOpen,
ToggleSessionPanelOpen,
ToggleHistoryPanelOpen,
ToggleInspectorOpen,
ToggleLayersPanelOpen,
UpdatePanelsLayout,
@@ -296,14 +296,6 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
let panel_type = PanelType::Session;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::ToggleHistoryPanelOpen => {
if self.panel_layout.focus_document {
return;
}
let panel_type = PanelType::History;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::UpdatePanelsLayout => {
let panel_layout = match self.panel_layout.focus_document {
true => self.panel_layout.document_only_layout(),
@@ -420,7 +412,7 @@ impl WorkspaceMessageHandler {
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
PanelType::Data => &[LayoutTarget::DataPanel, LayoutTarget::DataPanelContext, LayoutTarget::DataPanelPath],
PanelType::Session => &[LayoutTarget::SessionPanel],
PanelType::Document | PanelType::Welcome | PanelType::History => return,
PanelType::Document | PanelType::Welcome => return,
};
for &layout_target in targets {
@@ -449,9 +441,6 @@ impl WorkspaceMessageHandler {
PanelType::Session => {
responses.add(SyncMessage::RefreshPanel);
}
PanelType::History => {
responses.add(HistoryMessage::Refresh);
}
PanelType::Document | PanelType::Welcome => {
// Re-send the welcome screen buttons layout to repopulate after a remount
if has_no_documents {
-1
View File
@@ -33,7 +33,6 @@ pub use crate::messages::portfolio::document::resource::{ResourceMessage, Resour
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
pub use crate::messages::portfolio::failed_documents::{FailedDocumentsMessage, FailedDocumentsMessageContext, FailedDocumentsMessageDiscriminant, FailedDocumentsMessageHandler};
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
pub use crate::messages::portfolio::history::{HistoryMessage, HistoryMessageContext, HistoryMessageDiscriminant, HistoryMessageHandler};
pub use crate::messages::portfolio::ingest::{IngestMessage, IngestMessageContext, IngestMessageDiscriminant, IngestMessageHandler};
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
pub use crate::messages::portfolio::sync::{SyncMessage, SyncMessageContext, SyncMessageDiscriminant, SyncMessageHandler};
@@ -17,16 +17,6 @@ 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,7 +1976,6 @@ 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
@@ -2016,7 +2015,6 @@ 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
@@ -2500,28 +2498,12 @@ impl Fsm for PenToolFsmState {
mod test_pen_tool {
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::tool::common_functionality::snap_session::WAKE_DWELL_ON_APPROACH;
use crate::test_utils::EditorTestUtils;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, DVec2};
use graphene_std::vector::misc::{BooleanOperation, HandleId, ManipulatorPointId};
use glam::DAffine2;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId};
use graphene_std::vector::{SegmentId, VectorGeometry};
fn assert_expected_anchors(editor: &EditorTestUtils, expected_anchors: &[DVec2]) {
let (layer, vector) = drawn_path(editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let mut viewport_points: Vec<DVec2> = vector.anchor_positions().into_iter().map(|pos| layer_to_viewport.transform_point2(pos)).collect();
for (expected_index, &expected_position) in expected_anchors.iter().enumerate() {
let Some(viewport_index) = viewport_points.iter().position(|viewport| viewport.distance_squared(expected_position) < 1e-10) else {
panic!("The expected anchor index {expected_index} and position {expected_position} was not found in the actual anchors {viewport_points:?}");
};
viewport_points.remove(viewport_index);
}
assert!(viewport_points.is_empty(), "Viewport point(s) were not matched: {viewport_points:?}");
}
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> {
let document = editor.active_document();
@@ -2583,267 +2565,6 @@ mod test_pen_tool {
const C: DVec2 = DVec2::new(200., 200.);
const D: DVec2 = DVec2::new(100., 200.);
async fn create_a_rectangle() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
// Draw a rectangle not at the origin (so will end up with a non-identity transform)
editor.draw_rect(A.x, A.y, C.x, C.y).await;
editor
}
/// Using the path tool to merge layers (by setting the endpoint to an anchor of another layer) should produce only expected anchor positions.
#[tokio::test]
async fn merging_layers_simple() {
let mut editor = create_a_rectangle().await;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle
click_pen(&mut editor, B).await;
// Validate that these anchors are the only ones that exist
let expected_anchors = [A, B, C, D, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_two_pen_paths() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Create First Pen path
click_pen(&mut editor, A).await;
click_pen(&mut editor, C).await;
// Abort the first pen process
editor.handle_message(ToolMessage::Pen(PenToolMessage::Abort)).await;
// Create a second pen stroke
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
// Validate that these anchors are the only ones that exist
let expected_anchors = [A, B, C];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_group_with_offset() {
let mut editor = create_a_rectangle().await;
// Group rectangle
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group = editor.active_document().metadata().all_layers().next().unwrap();
let offset = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group,
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle (offset by the group transform)
click_pen(&mut editor, B + offset).await;
let expected_anchors = [A + offset, B + offset, C + offset, D + offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_different_groups_with_offsets() {
let mut editor = create_a_rectangle().await;
// Group rectangle into Group 1
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group1 = editor.active_document().metadata().all_layers().next().unwrap();
let offset1 = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group1,
transform: DAffine2::from_translation(offset1),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Nest Group 1 inside Group 2 with a different offset
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group2 = editor.active_document().metadata().all_layers().next().unwrap();
let offset2 = DVec2::new(30., -20.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group2,
transform: DAffine2::from_translation(offset2),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
let total_offset = offset1 + offset2;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle (offset by the nested group transforms)
click_pen(&mut editor, B + total_offset).await;
let expected_anchors = [A + total_offset, B + total_offset, C + total_offset, D + total_offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_artboard_with_offset() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let offset = DVec2::new(60., 70.);
editor.drag_tool(ToolType::Artboard, 0., 0., 500., 500., ModifierKeys::empty()).await;
let artboard = editor.active_document().metadata().all_layers().next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard,
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x + offset.x, A.y + offset.y, C.x + offset.x, C.y + offset.y).await;
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
click_pen(&mut editor, B + offset).await;
let expected_anchors = [A + offset, B + offset, C + offset, D + offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_artboards_with_different_offsets() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Create first artboard with offset
editor.drag_tool(ToolType::Artboard, 0., 0., 400., 400., ModifierKeys::empty()).await;
let artboard1 = editor.active_document().metadata().all_layers().next().unwrap();
let offset1 = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard1,
transform: DAffine2::from_translation(offset1),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Draw rectangle in first artboard
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x + offset1.x, A.y + offset1.y, C.x + offset1.x, C.y + offset1.y).await;
// Create second artboard with different offset
let offset2 = DVec2::new(-30., 40.);
let artboard2_origin = DVec2::new(600., 600.);
editor
.drag_tool(
ToolType::Artboard,
artboard2_origin.x,
artboard2_origin.y,
artboard2_origin.x + 400.,
artboard2_origin.y + 400.,
ModifierKeys::empty(),
)
.await;
let artboard2 = editor.active_document().metadata().all_layers().next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard2,
transform: DAffine2::from_translation(offset2),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Start pen in second artboard
let pen_start = artboard2_origin + offset2 + DVec2::new(50., 50.);
click_pen(&mut editor, pen_start).await;
// Connect to anchor B of the rectangle in the first artboard
click_pen(&mut editor, B + offset1).await;
let expected_anchors = [A + offset1, B + offset1, C + offset1, D + offset1, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
async fn test_boolean_operation(operation: BooleanOperation) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x, A.y, C.x, C.y).await;
editor.draw_rect(150., 150., 250., 250.).await;
// Select both rectangles and create boolean operation layer
let layers: Vec<_> = editor.active_document().metadata().all_layers().collect();
editor
.handle_message(NodeGraphMessage::SelectedNodesSet {
nodes: layers.iter().map(|l| l.to_node()).collect(),
})
.await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::BooleanOperation(operation),
})
.await;
let bool_layer = editor.active_document().metadata().all_layers().next().unwrap();
let bool_vector = editor.active_document().network_interface.compute_modified_vector(bool_layer).expect("Boolean layer vector");
let bool_to_viewport = editor.active_document().metadata().transform_to_viewport(bool_layer);
let mut expected_anchors: Vec<DVec2> = bool_vector.anchor_positions().into_iter().map(|pos| bool_to_viewport.transform_point2(pos)).collect();
// Connect pen to one of the anchors of the boolean operation
let connect_anchor = expected_anchors[0];
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
click_pen(&mut editor, connect_anchor).await;
expected_anchors.push(pen_start);
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_with_different_boolean_outputs() {
for operation in [BooleanOperation::Union, BooleanOperation::SubtractFront, BooleanOperation::Intersect, BooleanOperation::Difference] {
test_boolean_operation(operation).await;
}
}
#[tokio::test]
async fn enter_or_esc_after_a_single_click_leaves_no_layer() {
for key in [Key::Enter, Key::Escape] {
@@ -22,9 +22,7 @@ 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::{
name_layer_action, push_nearest_anchors, resize_bounds, rotate_bounds, skew_bounds, text_bounding_box, transforming_transform_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 glam::DMat2;
use graph_craft::document::NodeId;
use graphene_std::Color;
@@ -1748,10 +1746,6 @@ 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.
@@ -1838,14 +1832,6 @@ 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,7 +1100,6 @@ 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],
@@ -1167,11 +1166,6 @@ 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,7 +548,6 @@ 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);
@@ -568,7 +567,6 @@ 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());
@@ -767,7 +765,6 @@ 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 {
@@ -1199,32 +1196,6 @@ mod test_text_tool {
(metadata.transform_to_viewport(layer) * frame * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()
}
#[tokio::test]
async fn a_word_longer_than_the_max_width_breaks_to_stay_within_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
provide_fonts(&mut editor).await;
let layer = LayerNodeIdentifier::new_unchecked(NodeId::new());
let typesetting = TypesettingConfig {
max_width: Some(100.),
..Default::default()
};
editor
.handle_message(GraphOperationMessage::NewTextLayer {
id: layer.to_node(),
text: "Supercalifragilisticexpialidocious".into(),
font: Font::default(),
typesetting,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let [min, max] = editor.active_document().metadata().bounding_box_document(layer).expect("the text should have bounds");
assert!(max.x - min.x <= 100. + 1e-6, "the text is {} wide, wider than its max width of 100", max.x - min.x);
}
#[tokio::test]
async fn a_text_box_stretched_by_its_right_edge_to_near_the_edge_of_a_rectangle_lands_on_it() {
let mut editor = EditorTestUtils::create();
@@ -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, name_layer_action, push_nearest_anchors};
use crate::messages::tool::common_functionality::utility_functions::{is_almost_colinear, 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,12 +321,6 @@ 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 {
@@ -343,12 +337,6 @@ 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);
}
+69 -24
View File
@@ -81,16 +81,7 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
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>>,
},
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
InspectResult(Box<InspectResult>),
}
@@ -212,18 +203,6 @@ 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> {
@@ -685,7 +664,6 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses);
}
}
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
}
}
@@ -704,7 +682,6 @@ 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 }),
_ => {}
}
}
@@ -1259,3 +1236,71 @@ mod test {
}
}
}
#[cfg(test)]
mod raster_path_tests {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graphene_std::list::Item;
use graphene_std::raster_nodes::adjustments::invert;
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_nodes::std_nodes::eager;
use graphene_std::raster_types::{CPU, Raster};
/// A document whose image feeds `nodes` in turn, ending in the export.
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) {
editor.new_document().await;
editor.create_raster_image(Image::new(4, 4, color), None).await;
let image = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
.map(|(id, _)| *id)
.expect("the pasted image should be an Image node");
let mut previous = OutputConnector::node(image, 0);
for (index, identifier) in nodes.iter().enumerate() {
let id: NodeId = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
let input = InputConnector::node_at_index(id, 0);
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
previous = OutputConnector::node(id, 0);
}
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
}
#[tokio::test]
async fn an_image_reaches_a_filter_as_a_cpu_raster() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[median_filter::IDENTIFIER]).await;
let instrumented = editor.eval_graph_until_finished().await.expect("the image should render through Median");
let _: Item<Raster<CPU>> = instrumented
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
.next()
.expect("the image should arrive at Median as a CPU raster");
}
#[tokio::test]
async fn an_image_feeding_dehaze_renders() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should render through Dehaze");
}
#[tokio::test]
async fn an_image_uploaded_by_eager_renders_through_a_kernel() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[eager::IDENTIFIER, invert::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should render through Eager and Invert");
}
}
+1 -27
View File
@@ -46,8 +46,6 @@ 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>,
@@ -84,12 +82,6 @@ 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),
@@ -139,7 +131,6 @@ impl NodeRuntime {
pending_export: None,
pending_eyedropper: None,
pending_thumbnails: None,
pending_capture: None,
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
@@ -178,15 +169,7 @@ impl NodeRuntime {
let mut graph = None;
for request in self.receiver.try_iter() {
match request {
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::GraphUpdate(update) => graph = Some(update),
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);
@@ -201,7 +184,6 @@ 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,
@@ -291,14 +273,6 @@ 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,6 +1,5 @@
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};
@@ -225,58 +224,22 @@ impl Thumbnails {
}
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
self.show_svg(layer, content.svg(), 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 bounds = content.bounds();
let footprint = Footprint {
transform: DAffine2::from_translation(bounds[0]),
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
quality: RenderQuality::Full,
};
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 render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
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(),
})
}
let mut render = SvgRender::new();
content.graphic().render_svg(&mut render, &render_params);
render.format_svg(bounds[0], bounds[1]);
/// 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
self.show_svg(layer, render.svg.to_svg_string(), responses).await;
}
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
@@ -381,28 +344,6 @@ 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 {
@@ -504,7 +445,6 @@ 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;
@@ -527,27 +467,6 @@ 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, DVec2, UVec2};
use glam::{DAffine2, UVec2};
use graph_craft::document::NodeId;
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
use graphene_std::renderer::{RenderOutputType, RenderParams};
@@ -43,57 +43,44 @@ impl ThumbnailAtlasLayout {
}
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
cell_pixels(atlas_pixels, self.size().x, self.cell_size, self.cell_origin(index))
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()
}
}
/// 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 (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);
let cell_size = layout.cell_size.as_dvec2();
// 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();
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 RGBA pixels with runs of fully transparent ones left out, which most of a thumbnail's margins are.
+27 -9
View File
@@ -66,22 +66,30 @@ impl EditorTestUtils {
}
/// Submit an evaluation to the executor, run the runtime, and process the results.
/// With `instrument`, the graph is compiled with the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
///
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
async fn eval_graph_once(&mut self) -> Result<Instrumented, TestGraphError> {
async fn eval_graph_once(&mut self, instrument: bool) -> Result<Option<Instrumented>, TestGraphError> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
let instrumented = if instrument {
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
Some(instrumented)
} else {
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_node_graph_evaluation failed\n\n{e}")));
}
None
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
}
self.runtime.update();
self.runtime.run().await;
@@ -105,10 +113,20 @@ impl EditorTestUtils {
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
let instrumented = self.eval_graph_repeatedly(true).await?;
Ok(instrumented.expect("an instrumented evaluation returns its monitors"))
}
/// Like [`Self::eval_graph_until_finished`], but compiles the graph without monitors so that it can contain asynchronous nodes.
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), TestGraphError> {
self.eval_graph_repeatedly(false).await.map(|_| ())
}
async fn eval_graph_repeatedly(&mut self, instrument: bool) -> Result<Option<Instrumented>, TestGraphError> {
const MAX_ITERATIONS: usize = 16;
for _iteration in 0..MAX_ITERATIONS {
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
let result = self.eval_graph_once().await?;
let result = self.eval_graph_once(instrument).await?;
// If there have been no other executions queued (other than the one we just queued ourselves above) then finish
if execution_id + 1 >= self.portfolio_message_handler().executor.current_execution_id() {
return Ok(result);
-3
View File
@@ -12,7 +12,6 @@
import { createDialogStore, destroyDialogStore } from "/src/stores/dialog";
import { createDocumentStore, destroyDocumentStore } from "/src/stores/document";
import { createFullscreenStore, destroyFullscreenStore } from "/src/stores/fullscreen";
import { createHistoryStore, destroyHistoryStore } from "/src/stores/history";
import { createMathExpressionStore, destroyMathExpressionStore } from "/src/stores/math-expression";
import { createNodeGraphStore, destroyNodeGraphStore } from "/src/stores/node-graph";
import { createPortfolioStore, destroyPortfolioStore } from "/src/stores/portfolio";
@@ -32,7 +31,6 @@
document: createDocumentStore(subscriptions),
fullscreen: createFullscreenStore(subscriptions),
nodeGraph: createNodeGraphStore(subscriptions),
history: createHistoryStore(subscriptions),
portfolio: createPortfolioStore(subscriptions, editor),
appWindow: createAppWindowStore(subscriptions),
colorPicker: createColorPickerStore(subscriptions),
@@ -63,7 +61,6 @@
destroyDocumentStore();
destroyFullscreenStore();
destroyNodeGraphStore();
destroyHistoryStore();
destroyPortfolioStore();
destroyAppWindowStore();
destroyColorPickerStore();
@@ -5,7 +5,6 @@
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";
@@ -13,7 +12,6 @@
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";
@@ -33,7 +31,6 @@
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
@@ -771,9 +768,6 @@
<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
@@ -1,437 +0,0 @@
<script lang="ts">
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";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { HistoryStore } from "/src/stores/history";
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
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();
const clock = setInterval(() => (now = Date.now()), 15_000);
onDestroy(() => clearInterval(clock));
// Relative for the past week, a date before that
function when(ms: number | undefined, now: number): string {
if (ms === undefined) return "";
const seconds = Math.max(0, Math.round((now - ms) / 1000));
if (seconds < 45) return "just now";
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes} min ago`;
const hours = Math.round(minutes / 60);
if (hours < 24) return `${hours} h ago`;
const days = Math.round(hours / 24);
if (days < 7) return days === 1 ? "yesterday" : `${days} days ago`;
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}`;
}
function authorLabel(row: { author: string; mine: boolean }): string {
return row.mine ? `${row.author} (you)` : row.author;
}
let renamingId: string | undefined = undefined;
let taggingId: string | undefined = undefined;
function commitName(id: string, label: string) {
editor.renameHistoryInteraction(id, label);
renamingId = undefined;
}
function commitTag(id: string, tag: string) {
if (tag.trim()) editor.tagHistoryInteraction(id, tag, true);
taggingId = undefined;
}
// The inputs open focused and close once focus leaves them, committed or not
function focusInput(node: HTMLElement) {
const input = node.querySelector("[data-input-element]");
if (input instanceof HTMLElement) input.focus();
}
</script>
<LayoutCol class="history-panel">
{#if $history.following}
<LayoutRow class="following">
<TextLabel>Viewing a branch</TextLabel>
<TextButton label="Back to now" action={() => editor.followHistoryBranch(undefined)} />
</LayoutRow>
{/if}
<LayoutCol class="body" scrollableY={true}>
{#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">
{#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 && !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)}>
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
</span>
{:else}
<span class="label" class:named={row.named}>{row.label}</span>
{/if}
<span class="meta">
{#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">
{#each row.tags as tag (tag)}
<span class="tag">{tag}<button class="remove" data-tooltip-label="Remove the tag" on:click={() => editor.tagHistoryInteraction(row.id, tag, false)}>×</button></span>
{/each}
{#if taggingId === row.id}
<span class="editing" use:focusInput on:focusout={() => (taggingId = undefined)}>
<TextInput value="" placeholder="Tag name" narrow={true} on:commitText={({ detail }) => commitTag(row.id, detail)} />
</span>
{/if}
</span>
{/if}
{#if row.branches.length > 0}
<span class="branches">
{#each row.branches as branch (branch.id)}
<button class="chip branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button>
{/each}
</span>
{/if}
</div>
<span class="actions">
<button class="chip" data-tooltip-label="Name this step" on:click={() => (renamingId = row.id)}>Name</button>
<button class="chip" data-tooltip-label="Tag this step" on:click={() => (taggingId = row.id)}>Tag</button>
{#if row.undone || row.abandoned}
<IconButton
icon="HistoryRedo"
size={16}
tooltipLabel="Bring back"
tooltipDescription={row.undone ? "Redo up to and including this step." : "Do this step again on top of the current line."}
action={() => editor.bringBackHistoryInteraction(row.id)}
/>
{:else}
{#if !row.head}
<IconButton
icon="HistoryUndo"
size={16}
tooltipLabel="Go back to here"
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)}
/>
{/if}
<IconButton
icon="Trash"
size={16}
tooltipLabel="Remove this step"
tooltipDescription="Take this step out and keep the ones after it."
action={() => editor.removeHistoryInteraction(row.id)}
/>
{/if}
</span>
{#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">
{#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>
{/each}
{/if}
{/each}
{#if $history.more}
<div class="more">
<TextButton label="Show older" action={() => editor.loadMoreHistory()} />
</div>
{/if}
{#if $history.rows.length === 0 && $history.progress.length === 0}
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
{/if}
</LayoutCol>
</LayoutCol>
<style lang="scss">
.history-panel {
flex-grow: 1;
padding: 4px 0;
.following {
flex: 0 0 auto;
align-items: center;
justify-content: space-between;
padding: 0 8px 4px 8px;
}
.row {
display: flex;
align-items: center;
min-height: 32px;
padding: 2px 8px 2px 4px;
gap: 6px;
&.head {
background: var(--color-3-darkgray);
}
&.undone,
&.abandoned {
.rail,
.text {
opacity: 0.6;
}
}
&.delta {
min-height: 24px;
font-size: 11px;
}
&.comparison {
padding-top: 4px;
padding-bottom: 4px;
}
.actions {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 2px;
visibility: hidden;
}
&:hover .actions,
&:focus-within .actions {
visibility: visible;
}
.chip {
font-size: 11px;
line-height: 14px;
padding: 0 4px;
border: none;
border-radius: 2px;
background: var(--color-4-dimgray);
color: var(--color-c-brightgray);
cursor: pointer;
&:hover {
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
.gutter {
flex: 0 0 16px;
}
.expand {
flex: 0 0 auto;
width: 16px;
height: 16px;
padding: 0;
border: none;
background: none;
position: relative;
cursor: pointer;
color: var(--color-8-uppergray);
&:hover {
color: var(--color-e-nearwhite);
}
&::after {
content: "";
position: absolute;
left: 5px;
top: 4px;
border: 4px solid transparent;
border-left: 5px solid currentColor;
}
&.expanded::after {
transform: rotate(90deg);
}
}
.rail {
flex: 0 0 12px;
display: flex;
justify-content: center;
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-8-uppergray);
&.hollow {
background: none;
border: 2px solid;
width: 6px;
height: 6px;
}
}
.tick {
width: 4px;
height: 4px;
border-radius: 50%;
background: var(--color-6-lowergray);
}
}
.text {
flex: 1 1 0;
min-width: 0;
display: flex;
flex-direction: column;
line-height: 16px;
.label {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.meta {
color: var(--color-a-softgray);
font-size: 11px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
.anonymous {
font-style: italic;
}
}
.label.named {
font-weight: 600;
}
.tags {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
margin-top: 2px;
.tag {
display: inline-flex;
align-items: center;
gap: 2px;
font-size: 11px;
line-height: 14px;
padding: 0 2px 0 4px;
border-radius: 2px;
background: var(--color-accent-hover);
color: var(--color-f-white);
.remove {
border: none;
background: none;
color: inherit;
padding: 0 2px;
cursor: pointer;
line-height: 14px;
}
}
}
.branches {
display: flex;
flex-wrap: wrap;
gap: 4px;
margin-top: 2px;
.branch {
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
}
.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);
}
}
.editing {
display: contents;
}
.more {
display: flex;
justify-content: center;
padding: 8px;
}
}
</style>
@@ -1,240 +0,0 @@
<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>
@@ -1,56 +0,0 @@
<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>
@@ -4,7 +4,6 @@
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import Data from "/src/components/panels/Data.svelte";
import Document from "/src/components/panels/Document.svelte";
import History from "/src/components/panels/History.svelte";
import Inspector from "/src/components/panels/Inspector.svelte";
import Layers from "/src/components/panels/Layers.svelte";
import Session from "/src/components/panels/Session.svelte";
@@ -19,7 +18,6 @@
Welcome,
Document,
Layers,
History,
Inspector,
Data,
Session,
+2
View File
@@ -377,6 +377,7 @@ import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg";
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
import NodeUploadTexture from "/../branding/assets/16x16-nodes/node-upload-texture.svg";
import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg";
import NodeVaryStrokeColors from "/../branding/assets/16x16-nodes/node-vary-stroke-colors.svg";
import NodeVec2ToNumbers from "/../branding/assets/16x16-nodes/node-vec2-to-numbers.svg";
@@ -659,6 +660,7 @@ export const ICON_16X16_NODES = {
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
NodeUngroup: { svg: NodeUngroup, size: 16 },
NodeUnweld: { svg: NodeUnweld, size: 16 },
NodeUploadTexture: { svg: NodeUploadTexture, size: 16 },
NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 },
NodeVaryRotations: { svg: NodeVaryRotations, size: 16 },
NodeVaryScales: { svg: NodeVaryScales, size: 16 },
-108
View File
@@ -1,108 +0,0 @@
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
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, 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);
// 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) {
destroyHistoryStore();
subscriptionsRouter = subscriptions;
subscriptions.subscribeFrontendMessage("UpdateHistoryPanel", (data) => {
set(data.state);
});
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() {
const subscriptions = subscriptionsRouter;
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnail");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnailPixels");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryGraph");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryGraphOverlay");
subscriptionsRouter = undefined;
}
-42
View File
@@ -263,48 +263,6 @@ mod editor_commands {
WorkspaceMessage::FocusPanel { panel_type }.into()
}
/// Show or hide an interaction's deltas
fn expand_history_interaction(id: String, expanded: bool) -> Message {
HistoryMessage::Expand { id, expanded }.into()
}
fn load_more_history() -> Message {
HistoryMessage::LoadMore.into()
}
fn go_back_to_history_interaction(id: String) -> Message {
HistoryMessage::GoBack { id }.into()
}
/// Remove one interaction and keep the later ones
fn remove_history_interaction(id: String) -> Message {
HistoryMessage::RemoveStep { id }.into()
}
/// Redo an undone interaction, or reapply an abandoned one
fn bring_back_history_interaction(id: String) -> Message {
HistoryMessage::BringBack { id }.into()
}
/// Show a branch's line, or the head's line when `id` is `None`
fn follow_history_branch(id: Option<String>) -> Message {
HistoryMessage::Follow { id }.into()
}
/// Name an interaction. An empty label removes the name
fn rename_history_interaction(id: String, label: String) -> Message {
HistoryMessage::Rename { id, label }.into()
}
fn tag_history_interaction(id: String, tag: String, on: bool) -> Message {
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),
+1 -1
View File
@@ -30,7 +30,7 @@ glam = ["dep:glam"]
dyn-any-derive = { path = "derive", optional = true }
# Optional dependencies
glam = { version = "0.34", optional = true, default-features = false, features = ["all-types"] }
glam = { version = "0.33", optional = true, default-features = false, features = ["all-types"] }
reqwest = { version = "0.13", optional = true, default-features = false }
[package.metadata.docs.rs]
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more