Compare commits

..
Author SHA1 Message Date
Dennis Kobert e1e9ed9660 Merge branch 'master' into fix-colinear-handles-extension 2026-11-06 22:26:29 +01:00
Ramayen c88d9d366f Add a test suite for Pen tool offsets (#4823)
Add Pen tool tests for joining paths across groups, artboards, and boolean layers
2026-11-06 19:39:56 +00:00
e45a397abf Create the matching Read node when dropping a Map node onto a wire (#4925)
* Create the matching Read node when dropping a Map node onto a wire

Co-authored-by: Ankit-cs <[email protected]>
Co-authored-by: shubhtrek <[email protected]>
2026-11-06 17:26:02 +01:00
James LindsayandDennis Kobert b40c57d200 Bump the Rust dependencies (#4605)
* Bump rust dependencies

* Update more dependencies

---------

Co-authored-by: Dennis Kobert <[email protected]>
2026-11-05 23:49:21 +00:00
Keavon Chambers 1d3ebc5454 Add an acknowledgments section to the project readme and website donation page 2026-11-05 15:36:41 -08:00
James Lindsay db32addcb0 Update the Tsify dependency (#4600) 2026-11-05 13:29:36 -08:00
Timon 045cdfd5ee Resend only node positions while dragging nodes in the graph (#4921) 2026-11-05 13:29:08 -08:00
Dennis Kobert 1d6b93a6d1 Test all workspace members in CI and remove broken test (#4924) 2026-11-05 13:29:07 -08:00
Dennis Kobert baced334ec Add graphene-cli host, join and watch (#4893)
* Add graphene-cli host, join and watch

* Trim the live CLI to the migrating opener, the graph output it renders and fewer comments

* Log a failed session transport, exit the watcher cleanly, recover a lost surface and clear answered resource requests
2026-11-05 13:29:07 -08:00
Dennis Kobert 4c4e0ba39b Fix clippy warnings (#4923) 2026-11-05 13:29:07 -08:00
Dennis Kobert fbbae5876b Move graph-craft migrations into extra module (#4916) 2026-11-05 13:29:07 -08:00
Dennis Kobert fba33376bc Show other peers' pointers in collaborative editing (#4892) 2026-11-05 13:29:07 -08:00
Dennis Kobert a8104cf230 Add live sessions and the Session panel (#4891)
* Add live sessions and the Session panel

* Move comment

* Address the review findings on joining, guest undo, failed history steps and the panel layout

* Keep the undo note of a failed redo and let a promoted guest undo its unanswered step

* Drop the workspace layout version
2026-11-05 13:28:15 -08:00
Dennis Kobert 778e979c41 Keep in-memory resources when storage mounts after an edit (#4922) 2026-11-05 13:28:15 -08:00
Harshith Jeevan 5ee999b847 Fix a crash when previewing a node with no output (#4899) 2026-11-05 13:28:15 -08:00
Keavon Chambers 9044a9c09a New node: 'Iterate' (#4919) 2026-11-04 18:34:41 -08:00
Keavon Chambers a1ff88ae30 New node: 'Open Ends' (#4918)
* Fix large branching paths freezing the editor

* New node: 'Open Ends' and make 'Vector to Points' keep point attributes
2026-11-04 18:15:57 -08:00
Keavon Chambers d96f03fe90 Rework the 'Math' expression family as 'Math Function' / 'Math Formula', and add 'Math Running' / 'Math Aggregate' (#4917)
* Rename 'Math f(x)' and 'Math f(…)' to 'Math Function' and 'Math Formula'

* Move the lone operator mode of 'Math Formula' into a new 'Math Aggregate' node

* New node: 'Math Running'
2026-11-04 17:18:09 -08:00
Dennis Kobert 708cca339d Move the document and compiler tests into dedicated test modules (#4915) 2026-11-03 19:48:07 +01:00
Timon 6e9208c004 Add save with history preference (#4913)
* Add save with history preference

* Export resources only history names
2026-11-03 15:56:02 +00:00
Dennis Kobert 412979278e Move the compiler passes out of document.rs into a compiler module (#4914) 2026-11-03 16:56:20 +01:00
Dennis Kobert 7f7262c3cd Reconcile the interface with storage, undo hot steps (#4890) 2026-11-03 12:34:58 +01:00
Timon 8206b4cc88 Fix 'Combine Paths' hashing differently across platforms (#4911) 2026-11-02 22:50:39 +00:00
Dennis Kobert b05af55d50 Mint a fresh peer when the user changes (#4889) 2026-11-02 22:53:38 +01:00
Timon 39b8d23a34 Desktop: Confine CEF disk and network more (#4910) 2026-11-02 20:05:09 +00:00
Shubh Pingale 314e9f7866 Merge branch 'upstream/master' into fix-colinear-handles-extension 2026-10-21 20:08:30 +05:30
Shubh Pingale 69d3b465d6 Verify colinearity with is_almost_colinear and add get_handle_at helper 2026-10-14 20:39:02 +05:30
Shubh Pingale 49412afedf Extract get_anchor_near and get_segment_between helpers; add single-segment colinear handle test
Address review nits from 0HyperCube:

- Extract repeated point-lookup into a reusable get_anchor_near helper

- Extract repeated segment-lookup into a reusable get_segment_between helper

- Add test verifying single-segment anchors preserve colinear handles
2026-10-14 20:36:43 +05:30
Shubh Pingale 9efed51d8b Assert new segment handle remains at the anchor 2026-10-14 20:36:43 +05:30
Shubh Pingale 9f444bc964 Add test for extending from points connected to multiple segments 2026-10-14 20:36:43 +05:30
Shubh Pingale e8356e6efa Fix #4618: Prevent colinear handles when extending from points connected to multiple segments 2026-10-14 20:36:43 +05:30
145 changed files with 5855 additions and 5940 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
https://github.com/Keavon/graphite-branded-assets/archive/70b260c21afad29140bbc63ddab952fec3dd024c.tar.gz
5b05e7f4449b5f962755542e9b156891bbf2e0a87b7fc90798b8352d9225757d
+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.127",
"WASM_BINDGEN_CLI_VERSION": "0.2.129",
"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.127"
WASM_BINDGEN_CLI_VERSION: "0.2.129"
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.127"
WASM_BINDGEN_CLI_VERSION: "0.2.129"
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.127"
WASM_BINDGEN_CLI_VERSION: "0.2.129"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
+5 -16
View File
@@ -174,23 +174,12 @@ jobs:
env:
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: cargo test --all-features
# The plain `cargo test` above only covers the workspace's default members, which leave these out
- name: 🧪 Run document migration tests
env:
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
run: >-
cargo test --all-features
--package migration-core
--package migration-runner
--package migration-formats
--package migration-nodes
--package migration-snapshot
--package document-graph-storage
--package document-format
--package graphene-cli
--package regression
cargo test --workspace --all-features
--exclude 'graphite-desktop*'
--exclude third-party-licenses
&& cargo test --package third-party-licenses
# Render the documents of the regression corpus and compare them with their reference images
regression-corpus:
+1 -1
View File
@@ -22,7 +22,7 @@ let
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_127
pkgs.wasm-bindgen-cli_0_2_129
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_127
pkgs.wasm-bindgen-cli_0_2_129
deps.cargoAbout
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
Generated
+1979 -2369
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 = "0.2"
ctor = "1.0"
convert_case = "0.12"
titlecase = "3.6"
fancy-regex = "0.18.0"
fancy-regex = "0.20.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.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 = "=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-futures = "0.4"
js-sys = "=0.3.104"
web-sys = { version = "=0.3.104", features = [
js-sys = "=0.3.106"
web-sys = { version = "=0.3.106", 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.47"
usvg = "0.49"
simplecss = "0.2"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
parley = { version = "0.12", default-features = false, features = ["std"] }
skrifa = "0.44"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
rand_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.22"
base64 = "0.23"
blake3 = "1.5"
mmap-io = { version = "0.9", features = ["hugepages"] }
mmap-io = { version = "1.0", 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.4"
num-derive = "0.5"
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "2.0", default-features = false, features = [
syn = { version = "3.0", default-features = false, features = [
"full",
"derive",
"parsing",
@@ -262,14 +262,14 @@ syn = { version = "2.0", default-features = false, features = [
lyon_geom = "1.0"
delaunator = "1.0"
robust = "1.2"
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
petgraph = { version = "0.8", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.7", features = ["html_reports"] }
gungraun = { version = "0.18" }
ndarray = "0.16"
ollev = "0.1.1"
dirs = "6.0"
criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" }
ndarray = "0.17"
ollev = "0.1.2"
dirs = "7.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.10"
spin = "0.12"
clap = "4.5"
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
linesweeper = "0.4"
lzma-rust2 = { version = "0.25", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.29"
linesweeper = "0.5"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
zip = { version = "9", default-features = false }
[workspace.lints]
+10 -2
View File
@@ -1,5 +1,3 @@
<a href="https://graphite.art/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/9366c148-4405-484f-909a-9a3526eb9209">
@@ -83,3 +81,13 @@ 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::Rng;
use rand::RngExt;
use rfd::AsyncFileDialog;
use std::fs;
use std::io::Read;
-8
View File
@@ -45,11 +45,3 @@ pub(crate) fn app_resources_dir() -> PathBuf {
ensure_dir_exists(&path);
path
}
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
pub(crate) fn delete_old_cef_browser_directory() {
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
if old_browser_dir.is_dir() {
let _ = std::fs::remove_dir_all(&old_browser_dir);
}
}
-3
View File
@@ -74,9 +74,6 @@ pub fn start() -> ExitCode {
dirs::clear_dir(&ui::temp_dir_root());
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
dirs::delete_old_cef_browser_directory();
// Must be called before event loop initialization or native window integrations will break
App::init();
+2 -1
View File
@@ -28,12 +28,13 @@ wgpu-sync = { workspace = true }
winit = { workspace = true, features = ["serde"] }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
rand = { workspace = true, features = ["thread_rng"] }
cef = { workspace = true }
bytemuck = { workspace = true, optional = true }
ipc-channel = "0.22"
ipc-channel = "0.23"
# Linux-specific dependencies
[target.'cfg(target_os = "linux")'.dependencies]
+1 -1
View File
@@ -8,7 +8,7 @@ const APP_DIRECTORY_NAME: &str = "graphite";
const APP_DIRECTORY_NAME: &str = "Graphite";
pub(crate) fn app_tmp_dir() -> PathBuf {
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
let path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join(APP_DIRECTORY_NAME).join("ui");
if let Err(e) = fs::create_dir_all(&path) {
tracing::error!("Failed to create temp directory at {path:?}: {e}");
}
@@ -48,6 +48,10 @@ impl ImplApp for BrowserProcessAppImpl {
cmd.append_switch(Some(&"disable-default-apps".into()));
cmd.append_switch(Some(&"disable-breakpad".into()));
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
cmd.append_switch_with_value(
Some(&"host-resolver-rules".into()),
Some(&"MAP * ~NOTFOUND, EXCLUDE fonts.googleapis.com, EXCLUDE fonts.gstatic.com".into()),
);
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
let disabled_features_switch = Some(&"disable-features".into());
-1
View File
@@ -27,7 +27,6 @@ wgpu-executor = { workspace = true }
wgpu = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
dirs = { workspace = true }
image = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+1 -1
View File
@@ -36,7 +36,7 @@ impl Archive for Zip {
if !entry.is_file() {
continue;
}
let name = entry.name().to_string();
let name = entry.name().map_err(zip_err)?.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(0, len)
file.as_slice_bytes(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(0, len) {
match self.0.as_slice_bytes(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
+13
View File
@@ -181,6 +181,19 @@ impl<L: Layout> Gdd<L> {
}
export_session.embed_resource_sources(links_to_promote)?;
// If the export includes history, also embed every resource referenced by the history.
if options.include_history {
let current: std::collections::HashSet<ResourceHash> = export_session.registry().resources.values().filter_map(|entry| entry.hash).collect();
for hash in export_session.all_referenced_resource_hashes() {
if current.contains(&hash) || working_copy_hashes.contains(&hash) {
continue;
}
if let Some(resource) = byte_store.load(hash).await {
embedded_bytes.push((hash, resource));
}
}
}
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
let mut session_state = self.exported_session_state(&export_session);
+10 -5
View File
@@ -111,6 +111,9 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
#[cfg(feature = "network")]
pub(crate) remote_changes: network::RemoteChanges,
/// The step a guest asked the host to undo, with the head it asked under. A repeat waits until the head moves.
#[cfg(feature = "network")]
pub(crate) undo_requested: Option<(document_graph_storage::Rev, Option<document_graph_storage::Rev>)>,
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
pub(crate) own_last_staged_ms: Option<f64>,
pub(crate) own_staged_since_tick: bool,
@@ -175,6 +178,8 @@ impl<L: Layout> Gdd<L> {
pending_persist: PendingPersist::default(),
#[cfg(feature = "network")]
remote_changes: network::RemoteChanges::default(),
#[cfg(feature = "network")]
undo_requested: None,
interactions_seen: Default::default(),
own_last_staged_ms: None,
own_staged_since_tick: false,
@@ -232,16 +237,16 @@ impl<L: Layout> Gdd<L> {
Self::open_in_with(working, layout, byte_store, host).await
}
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
/// Reads the manifest without opening the copy, which may be another writer's.
pub async fn read_manifest(working: &AnyContainer, layout: &L) -> Result<Manifest, Error> {
Ok(io::read_single(working, layout.manifest_basename(), MANIFEST_CODEC).await?)
}
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
///
/// # Errors
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs::default()).await
}
+1
View File
@@ -86,6 +86,7 @@ impl<L: Layout> Gdd<L> {
/// Drop the connection but keep the document shared, so a reopen reconnects. A host first retires every closed
/// interaction with no ops still on their way.
pub fn disconnect(&mut self) {
self.undo_requested = None;
let closed = self.contiguous_interactions();
if let Err(error) = self.retire_interactions(&closed) {
log::error!("Retiring before leaving failed: {error}");
+6 -17
View File
@@ -427,7 +427,13 @@ impl<L: Layout> Gdd<L> {
let Some(rev) = self.session.latest_own_interaction() else {
return Ok(None);
};
// A peer promoted to host drops the step itself, so an unanswered request no longer blocks it
let asked = (!self.retires_locally()).then_some((rev, self.session.head_rev()));
if asked.is_some() && self.undo_requested == asked {
return Ok(None);
}
self.drop_step(rev)?;
self.undo_requested = asked;
Ok(Some(rev))
}
@@ -452,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> {
-6
View File
@@ -137,12 +137,6 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
fn clone(&self) -> Self {
Self(self.0.clone(), self.1.clone())
}
}
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
Box::pin(async move {
+40
View File
@@ -538,6 +538,46 @@ fn export_materializes_embedded_resource_from_byte_store() {
});
}
/// An export with history carries the bytes of a resource only history still names, so undoing its removal
/// after a reopen finds them, even when they live in the byte store rather than the working copy.
#[test]
fn export_with_history_carries_history_only_resources() {
use document_format::{ExportFormat, ExportOptions};
use document_graph_storage::NoMetadata;
use graph_craft::application_io::resource::ResourceStorage;
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
futures::executor::block_on(async {
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
let payload = b"bytes of a removed resource";
let hash = ResourceHash::from(&payload[..]);
let byte_store = empty_byte_store();
byte_store.store(payload);
let mut resources = ResourceRegistry::new();
let id = ResourceId::new();
resources.push_source_back(&id, DataSource::Embedded);
resources.resolve(&id, hash);
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
gdd.commit_from_runtime(&graph_craft::document::NodeNetwork::default(), &NoMetadata, &ResourceRegistry::new(), &byte_store)
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
assert!(!gdd.registry().resources.contains_key(&id), "the resource should only be named by history");
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
let archive = gdd
.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &byte_store, None)
.await
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
.await
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
assert!(reopened.has_resource(&hash).await, "history-only bytes should travel with the export");
});
}
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
+2 -11
View File
@@ -2,7 +2,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout, ResourceProxy};
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{PeerId, UserId};
use graph_craft::application_io::resource::ResourceHash;
use graph_craft::document::NodeNetwork;
@@ -10,7 +10,7 @@ use peer_transport::{Room, SyncTarget};
pub use document_format::Error as FormatError;
pub use document_graph_storage::to_runtime::ConversionError;
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
@@ -58,10 +58,6 @@ impl LiveDocument {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
@@ -101,17 +97,12 @@ impl LiveDocument {
&mut self.gdd
}
/// Async because proto-node declarations are resources.
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
let declarations = self.gdd.declarations(&self.gdd).await;
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
Ok(network)
}
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
self.gdd.resource_proxy()
}
pub fn leave(&mut self) {
self.gdd.leave();
}
+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)]
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = #core::ctor))]
fn register() {
#core::#register(#migration);
}
+1
View File
@@ -2,4 +2,5 @@
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod graphene_core;
mod math_nodes;
mod raster_nodes;
@@ -0,0 +1,107 @@
use migration_core::{Node, Target, decl, literal_of, migration};
use serde::{Deserialize, Serialize};
const EXPRESSION: usize = 1;
/// Frozen mirror of the `TaggedValue` variant this migration reads.
#[derive(Serialize, Deserialize)]
enum Tagged {
String(String),
}
/// The lone operators 'Math f(…)' applied across its items, in every spelling its classifier read when the node was split.
const OPERATORS: &[&str] = &["+", "-", "*", "/", "^", "&&", "∧", "||", "∨", "<", "<=", "≤", ">", ">=", "≥", "==", "!=", "≠"];
/// The variadic functions 'Math f(…)' called with all its items when given a lone name, also spelled with a leading `\`.
const FUNCTIONS: &[&str] = &[
"hypot",
"min",
"max",
"mean",
"median",
"variance",
"variancepop",
"stdev",
"stdevpop",
"geomean",
"harmmean",
"rms",
"mode",
"count",
"xor",
"gcd",
"lcm",
];
/// 'Math f(…)' split by the kind of string it held: a lone operator or function name, which it applied across its items, moves to
/// 'Math Aggregate', and an expression stays as 'Math Formula'. A wired string can't be read before it runs, so it stays an expression.
#[migration("math_nodes::MathFNode"@1 => "math_nodes::MathFormulaNode"@2)]
pub fn math_formula_from_math_f(node: &Node, target: &mut Target) {
let Some(slot) = node.inputs().get(EXPRESSION) else { return };
let Some(Tagged::String(expression)) = literal_of::<Tagged>(&slot.input) else { return };
let token = expression.trim();
let function = token.strip_prefix('\\').unwrap_or(token);
if OPERATORS.contains(&token) || FUNCTIONS.contains(&function) {
target.set(decl!("math_nodes::MathAggregateNode"@1));
}
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{Declaration, NodeInput, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const MATH_F: Declaration = decl!("math_nodes::MathFNode"@1);
fn contract() -> SourceContract {
// Only the items can read another 'Math f(…)', since the expression and output type don't take its number
SourceContract {
reads_own_output: |slot| slot == 0,
..SourceContract::new(3, |random, slot| match slot {
EXPRESSION => literal(Tagged::String(["+", "a * b", "\\max", " ≤ ", "min(a, b)"][random.below(5)].to_string())),
_ => literal(random.below(4) as f64),
})
}
}
fn migrated_declaration(expression: NodeInput) -> Option<Declaration> {
let mut fixture = Fixture::new(&MathFormulaFromMathF);
let anchor = fixture.add(MATH_F, vec![literal(1.), expression, literal(0.)]);
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
fixture.declaration_of(&migrated, anchor)
}
#[test]
fn rewrites_history() {
check_commutation(&MathFormulaFromMathF, &contract());
check_undo(&MathFormulaFromMathF, &contract());
}
#[test]
fn lone_operators_and_functions_become_aggregates() {
let aggregate = Some(decl!("math_nodes::MathAggregateNode"@1));
let formula = Some(decl!("math_nodes::MathFormulaNode"@2));
let expression = |text: &str| literal(Tagged::String(text.to_string()));
assert_eq!(migrated_declaration(expression("+")), aggregate);
assert_eq!(migrated_declaration(expression(" ≠ ")), aggregate);
assert_eq!(migrated_declaration(expression("max")), aggregate);
assert_eq!(migrated_declaration(expression("\\mean")), aggregate);
assert_eq!(migrated_declaration(expression("a + b")), formula);
assert_eq!(migrated_declaration(expression("max(a, b)")), formula);
assert_eq!(migrated_declaration(expression("")), formula);
}
#[test]
fn a_wired_expression_becomes_a_formula() {
let mut fixture = Fixture::new(&MathFormulaFromMathF);
let source = fixture.add(MATH_F, vec![literal(1.), literal(Tagged::String("+".to_string())), literal(0.)]);
let anchor = fixture.add(MATH_F, vec![literal(1.), NodeInput::Node { id: source, index: 0 }, literal(0.)]);
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("math_nodes::MathFormulaNode"@2)));
assert_eq!(fixture.declaration_of(&migrated, source), Some(decl!("math_nodes::MathAggregateNode"@1)));
}
}
@@ -0,0 +1,4 @@
//! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f;
mod renames;
@@ -0,0 +1,5 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
+1 -1
View File
@@ -13,7 +13,7 @@ publish.workspace = true
[dependencies]
core-types = { workspace = true }
document-graph-storage = { workspace = true }
matchbox_socket = "0.14.0"
matchbox_socket = "0.15.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
+20
View File
@@ -405,6 +405,12 @@ impl Replica {
}
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
if let Some(recipients) = self.owed_resources.get_mut(&hash) {
recipients.remove(&to);
if recipients.is_empty() {
self.owed_resources.remove(&hash);
}
}
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
}
@@ -1126,4 +1132,18 @@ mod tests {
host.poll(&mut session);
assert!(host.owed_resources.is_empty(), "nothing is owed to a link that closed");
}
#[test]
fn an_answered_request_is_owed_no_more() {
let (mut network, mut host, host_link, mut session) = hosted_room();
let mut bare = connect_bare_peer(&mut network, &mut host, &mut session);
let hash = ResourceHash::from(b"bytes".as_slice());
bare.send(host_link, &hello(0)).unwrap();
bare.send(host_link, &SyncPacket::ResourceRequest(vec![hash])).unwrap();
network.deliver_all();
host.poll(&mut session);
host.send_resource(bare.id(), hash, b"bytes".to_vec()).unwrap();
assert!(host.owed_resources.is_empty());
}
}
+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<Box<[u8]>> {
fn frames(bytes: &[u8]) -> Vec<Packet> {
// 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), Box::new([FRAME_FINAL, 7])));
lock(&inbox).packets.push_back((peer(1), Packet::from_static(&[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;
@@ -330,6 +330,29 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
let save_with_history_description = "
Include the document's edit history in saved files. Only applies with \"Save as .gdd\" enabled.\n\
\n\
*Default: Off.*
"
.trim();
let save_with_history_checkbox_id = CheckboxId::new();
let save_with_history = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.save_with_history)
.tooltip_label("Save with History")
.tooltip_description(save_with_history_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveWithHistory { enabled: checkbox_input.checked }.into())
.for_label(save_with_history_checkbox_id)
.widget_instance(),
TextLabel::new("Save with History")
.tooltip_label("Save with History")
.tooltip_description(save_with_history_description)
.for_checkbox(save_with_history_checkbox_id)
.widget_instance(),
];
let validate_description = "
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
\n\
@@ -353,7 +376,7 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
rows.extend_from_slice(&[header, save_as_gdd, save_with_history, validate_storage_round_trip]);
}
// =============
@@ -33,18 +33,18 @@ impl LayoutHolder for DocumentsOpenElsewhereDialog {
]),
];
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
let label = TextLabel::new(name.clone()).widget_instance();
let button = TextButton::new(if shared { "Join in This Tab" } else { "Open a Copy" })
.on_update(move |_| {
let followup = if shared {
PortfolioMessage::JoinStoredSession { source }
} else {
PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }
};
DialogMessage::CloseAndThen { followups: vec![followup.into()] }.into()
})
.widget_instance();
LayoutGroup::row(vec![label, Separator::new(SeparatorStyle::Unrelated).widget_instance(), button])
let button = |label: &str, followup: Box<dyn Fn() -> PortfolioMessage + Send + Sync>| {
TextButton::new(label)
.on_update(move |_| DialogMessage::CloseAndThen { followups: vec![followup().into()] }.into())
.widget_instance()
};
let mut widgets = vec![TextLabel::new(name.clone()).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance()];
// A copy stays possible, since joining needs the other tab to be connected
if shared {
widgets.push(button("Join in This Tab", Box::new(move || PortfolioMessage::JoinStoredSession { source })));
}
widgets.push(button("Open a Copy", Box::new(move || PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() })));
LayoutGroup::row(widgets)
}));
Layout(rows)
@@ -196,9 +196,6 @@ pub enum FrontendMessage {
UpdateDocumentCursors {
cursors: Vec<FrontendRemoteCursor>,
},
UpdateHistoryPanel {
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
},
UpdateNodeGraphCursors {
cursors: Vec<FrontendRemoteCursor>,
},
@@ -25,7 +25,7 @@ pub enum SessionStatus {
Disconnected,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PersistedState {
pub documents: Vec<DocumentInfo>,
@@ -62,7 +62,7 @@ pub enum RenderStatus {
Panic,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum FileType {
#[default]
@@ -99,7 +99,7 @@ impl MessageHandler<FutureMessage, ()> for FutureMessageHandler {
}));
}
FutureMessage::Drain => {
while let Ok(Some(message)) = self.results_receiver.try_next() {
while let Ok(message) = self.results_receiver.try_recv() {
responses.push_back(message);
}
}
@@ -118,7 +118,7 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
};
// The reply carries the source it read, so the frontend can drop one that a later keystroke has outdated
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.operator_only);
let completions = caret.map(|caret| math_expression_completions(&source, caret, asked));
responses.add(FrontendMessage::UpdateMathExpressionAnalysis {
widget_id,
@@ -371,9 +371,9 @@ impl LayoutMessageHandler {
};
// The widget is resent as stored, so its tokens and errors must be for its new value rather than its old one
let accepts_reducers = math_expression_input.accepts_reducers;
let error = math_expression_error(update_value, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, accepts_reducers);
let operator_only = math_expression_input.operator_only;
let error = math_expression_error(update_value, operator_only);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, operator_only);
math_expression_input.tokens = tokens;
math_expression_input.tooltips = tooltips;
math_expression_input.errors = math_expression_error_ranges(update_value, error.as_ref());
@@ -24,7 +24,7 @@ impl core::fmt::Display for WidgetId {
macro_rules! define_layout_target {
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LayoutTarget {
@@ -16,13 +16,16 @@ fn utf16_offsets(source: &str) -> Vec<u32> {
units
}
/// Why a math expression fails to parse, or `None` when it parses. Where the node applies a lone operator or function name like
/// `+` or `min` across its items, that counts as valid too.
pub fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<ParseError> {
/// Why a math expression fails to parse, or `None` when it parses. Where the node takes only a lone operator or function name like
/// `+` or `min` to apply across its items, anything else is the error instead.
pub fn math_expression_error(expression: &str, operator_only: bool) -> Option<ParseError> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
if expression.trim().is_empty() {
return None;
}
if operator_only {
return math_parser::reducer::reducer_error(expression);
}
math_parser::ast::Node::try_parse_from_str(expression).err()
}
@@ -143,11 +146,11 @@ pub struct MathExpressionTokens {
}
/// The tokens of a math expression for the frontend to color and typeset, with the parser's byte offsets converted to code units.
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
pub fn math_expression_tokens(source: &str, operator_only: bool) -> MathExpressionTokens {
let units = utf16_offsets(source);
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
let tokens = math_parser::highlight::highlight(source, accepts_reducers).into_iter().map(|token| {
let tokens = math_parser::highlight::highlight(source, operator_only).into_iter().map(|token| {
let tooltip = token.tooltip.map(|tooltip| MathExpressionTooltip {
label: tooltip.label,
form: tooltip.form,
@@ -502,9 +502,9 @@ pub struct MathExpressionInput {
pub tooltips: Vec<MathExpressionTooltip>,
/// The stretches of the value its parse errors point at, which the frontend underlines.
pub errors: Vec<MathExpressionRange>,
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
/// Whether the value is a lone operator or function name like `+` or `max`, applied across a list, rather than an expression.
#[serde(skip)]
pub accepts_reducers: bool,
pub operator_only: bool,
pub disabled: bool,
// Tooltips
@@ -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(),
@@ -141,7 +141,15 @@ impl DocumentHistory {
if self.legacy_undo_stack.is_empty() {
return false;
}
let note = if let Some(ops) = self.retract_storage_interaction() {
// A failed retract may already have taken the step back, so no older step is undone after it
let retracted = match self.retract_storage_interaction() {
Ok(retracted) => retracted,
Err(error) => {
log::error!("Taking the storage interaction back failed: {error}");
return false;
}
};
let note = if let Some(ops) = retracted {
UndoNote::Retracted(ops)
} else if in_session && let Some(rev) = self.undo_retired_step() {
UndoNote::Dropped(rev)
@@ -169,16 +177,19 @@ impl DocumentHistory {
return false;
};
let redone = match &note {
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
UndoNote::Dropped(rev) => self.redo_retired_step(*rev),
UndoNote::Cursor => true,
};
if !redone {
// The note stays paired with its redo snapshot
self.undo_notes.push(note);
return false;
}
if let Some(snapshot) = self.pop_redo() {
self.push_undo(snapshot);
}
match note {
UndoNote::Retracted(ops) => self.restage_ops(ops),
UndoNote::Dropped(rev) => {
self.redo_retired_step(rev);
}
UndoNote::Cursor => {}
}
true
}
@@ -196,18 +207,16 @@ impl DocumentHistory {
self.undo_notes.drain(..evicted);
}
fn retract_storage_interaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
self.storage.as_mut()?.retract_interaction().unwrap_or_else(|error| {
log::error!("Taking the storage interaction back failed: {error}");
None
})
fn retract_storage_interaction(&mut self) -> Result<Option<Vec<document_graph_storage::RegistryDelta>>, document_format::Error> {
match self.storage.as_mut() {
Some(storage) => storage.retract_interaction(),
None => Ok(None),
}
}
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.restage_ops(ops) {
log::error!("Staging the redone step failed: {error}");
}
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) -> bool {
let Some(storage) = self.storage.as_mut() else { return false };
storage.restage_ops(ops).inspect_err(|error| log::error!("Staging the redone step failed: {error}")).is_ok()
}
fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
@@ -222,29 +231,8 @@ impl DocumentHistory {
}
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) -> bool {
self.change_line(|storage| storage.redo_retired_step(rev), "Redoing the dropped step failed")
}
pub fn drop_step(&mut self, rev: document_graph_storage::Rev) -> bool {
self.change_line(|storage| storage.drop_step(rev), "Removing the step failed")
}
pub fn move_head_to(&mut self, rev: document_graph_storage::Rev) -> bool {
self.change_line(|storage| storage.move_head(rev), "Moving the head failed")
}
fn change_line(&mut self, change: impl FnOnce(&mut document_format::GddV1) -> Result<(), document_format::Error>, failure: &str) -> bool {
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
return false;
};
change(storage).inspect_err(|error| log::error!("{failure}: {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();
let Some(storage) = self.storage.as_mut() else { return false };
storage.redo_retired_step(rev).inspect_err(|error| log::error!("Redoing the dropped step failed: {error}")).is_ok()
}
pub fn retire_storage_interaction(&mut self) {
@@ -56,17 +56,6 @@ pub enum DocumentMessage {
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
HistoryMoveHead {
rev: document_graph_storage::Rev,
},
/// Drops a retired interaction and mints the later ones again on its parent.
HistoryRemoveStep {
rev: document_graph_storage::Rev,
},
HistoryRestoreStep {
rev: document_graph_storage::Rev,
},
DocumentStructureChanged,
DrawArtboardOverlays {
context: OverlayContext,
@@ -473,27 +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::HistoryMoveHead { rev } => self.apply_history_action(
document_id,
|history| history.move_head_to(rev),
&resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
responses,
),
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(
document_id,
|history| history.drop_step(rev),
&resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
responses,
),
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(
document_id,
|history| history.redo_retired_step(rev),
&resource_storage.resources_mut(),
preferences.validate_storage_round_trip,
responses,
),
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
self.network_interface.load_structure();
@@ -1275,6 +1254,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
let save_as_gdd = preferences.save_as_gdd;
let include_history = preferences.save_with_history;
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
let name = format!("{}.{}", self.name.clone(), extension);
@@ -1310,7 +1290,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportOptions {
include_history: false,
include_history,
..Default::default()
},
export_load_handle.as_ref(),
@@ -2224,6 +2204,7 @@ impl DocumentMessageHandler {
document.apply_stored_document_settings(storage.view_settings());
document.set_storage(storage, declarations, byte_store);
document.refresh_resource_registry();
document
}
@@ -2460,7 +2441,6 @@ impl DocumentMessageHandler {
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
storage.set_byte_store(byte_store);
self.history.set_storage(storage, declarations);
self.refresh_resource_registry();
}
pub(crate) fn end_storage_interaction(&mut self) {
@@ -3018,32 +2998,6 @@ impl DocumentMessageHandler {
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Performs a History panel action in storage and drops the legacy snapshots, which are off the head's line.
fn apply_history_action(
&mut self,
document_id: DocumentId,
action: impl FnOnce(&mut DocumentHistory) -> bool,
byte_store: &dyn ResourceStorage,
validate: bool,
responses: &mut VecDeque<Message>,
) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
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 !action(&mut self.history) {
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() {
@@ -1394,8 +1394,8 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
"math_expression_or_reducer".to_string(),
// Like `math_expression`, but taking only a lone operator or function name like `+` or `min` to apply across the node's items
"math_operator".to_string(),
Box::new(|node_id, index, context| {
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![LayoutGroup::row(node_inspector::math_expression_widget(info, true))])
@@ -208,6 +208,7 @@ pub enum NodeGraphMessage {
SendWires,
UpdateVisibleNodes,
SendGraph,
SendNodePositions,
SetInputValue {
node_id: NodeId,
input_index: usize,
@@ -131,9 +131,9 @@ pub struct NodeGraphMessageHandler {
reordering_export: Option<usize>,
/// The end index of the moved connector
end_index: Option<usize>,
/// Used to keep track of what nodes are sent to the front end so that only visible ones are sent to the frontend
frontend_nodes: Vec<NodeId>,
/// Used to keep track of what wires are sent to the front end so the old ones can be removed
/// The nodes the frontend currently knows about
frontend_nodes: Vec<FrontendNode>,
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
frontend_wires: HashSet<(NodeId, usize)>,
evaluation_errors: Vec<NodeEvaluationError>,
}
@@ -650,6 +650,7 @@ 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);
@@ -2017,7 +2018,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let document_bbox: [DVec2; 2] = viewport_bbox.map(|p| network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(p));
let mut nodes = Vec::new();
for node_id in &self.frontend_nodes {
for node_id in self.frontend_nodes.iter().map(|node| &node.id) {
let Some(node_bbox) = network_interface.node_bounding_box(node_id, breadcrumb_network_path) else {
log::error!("Could not get bbox for node: {node_id:?}");
continue;
@@ -2052,9 +2053,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(InspectorMessage::Refresh);
responses.add(EventMessage::GraphChanged);
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes });
self.frontend_nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
@@ -2071,6 +2071,36 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.update_node_graph_hints(responses);
}
}
NodeGraphMessage::SendNodePositions => {
if breadcrumb_network_path != selection_network_path || !graph_view_overlay_open {
return;
}
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { return };
let same_nodes = network.nodes.len() == self.frontend_nodes.len() && self.frontend_nodes.iter().all(|node| network.nodes.contains_key(&node.id));
if !same_nodes {
responses.add(NodeGraphMessage::SendGraph);
return;
}
for node in &mut self.frontend_nodes {
if let Some(position) = network_interface.position(&node.id, breadcrumb_network_path) {
node.position = position.into();
}
}
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateLayerWidths {
layer_widths,
chain_widths,
has_left_input_wire,
});
responses.add(NodeGraphMessage::UpdateImportsExports);
}
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
@@ -2134,12 +2164,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
if graph_view_overlay_open {
responses.add(NodeGraphMessage::SendGraph);
if !rubber_band {
responses.add(NodeGraphMessage::SendGraph);
}
responses.add(DocumentMessage::RenderRulers);
responses.add(DocumentMessage::RenderScrollbars);
}
}
NodeGraphMessage::ShiftSelectedNodesByAmount { mut graph_delta, rubber_band, glide } => {
let moved = graph_delta != IVec2::ZERO;
while graph_delta != IVec2::ZERO {
match graph_delta.x.cmp(&0) {
Ordering::Greater => {
@@ -2183,6 +2216,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
responses.add(NodeGraphMessage::SendWires);
if rubber_band && moved {
responses.add(NodeGraphMessage::SendNodePositions);
}
}
NodeGraphMessage::ToggleSelectedAsLayersOrNodes => {
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
@@ -3410,7 +3446,8 @@ impl NodeGraphMessageHandler {
.exports
.iter()
.any(|export| matches!(export, NodeInput::Node { node_id: export_node_id, .. } if *export_node_id == node_id));
if selection_is_not_already_the_output && no_other_selections {
let has_outputs = network_interface.number_of_outputs(&node_id, breadcrumb_network_path) > 0;
if selection_is_not_already_the_output && no_other_selections && has_outputs {
let button = TextButton::new("Preview")
.icon("FrameAll")
.tooltip_label("Preview")
@@ -481,16 +481,16 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
}
/// A math expression's typeset text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, operator_only: bool) -> Vec<WidgetInstance> {
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
return text_widget(parameter_widgets_info);
};
let error = math_expression_error(expression, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
let error = math_expression_error(expression, operator_only);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, operator_only);
let input = MathExpressionInput::new(expression.clone())
.tokens(tokens)
.tooltips(tooltips)
.accepts_reducers(accepts_reducers)
.operator_only(operator_only)
.errors(math_expression_error_ranges(expression, error.as_ref()))
.on_update(parameter_widgets_info.update_value(|x: &MathExpressionInput| TaggedValue::String(x.value.clone())))
.on_commit(commit_value)
@@ -500,7 +500,7 @@ pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo,
// padded to a checkbox's 16px so the field lines up with the rows around it
let icon = match &error {
Some(error) => IconLabel::new("Warning")
.tooltip_label("Invalid Math Expression")
.tooltip_label(if operator_only { "Invalid Operator" } else { "Invalid Math Expression" })
.tooltip_description(math_expression_error_description(error)),
None => IconLabel::new("Empty12px"),
};
@@ -3942,12 +3942,13 @@ mod tests {
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
assert!(math_expression_error(expression, accepts_reducers).is_none(), "`{expression}`");
for (expression, operator_only) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true), (" ≤ ", true)] {
assert!(math_expression_error(expression, operator_only).is_none(), "`{expression}`");
}
assert!(math_expression_error("2 +", false).is_some());
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert!(math_expression_error("+", false).is_some(), "a lone operator is an error where the node takes an expression");
assert!(math_expression_error("a + b", true).is_some(), "an expression is an error where the node takes a lone operator");
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
}
@@ -664,6 +664,39 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
}
}
#[tokio::test]
async fn pasted_image_resource_survives_inserting_a_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.handle_message(paste_named_image()).await;
editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER)).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let document = editor.active_document();
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
}
#[tokio::test]
async fn pasted_image_resource_survives_storage_mounting_after_the_paste() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(paste_named_image()).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
let document = editor.active_document();
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
}
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
@@ -4,6 +4,7 @@ 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::*;
@@ -3532,3 +3533,121 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
"The evaluated network should fall back to the document's own export"
);
}
#[tokio::test]
async fn cannot_preview_node_without_outputs() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
let network_interface = &mut editor.active_document_mut().network_interface;
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
// Attempting to toggle preview on a node without outputs should not enable previewing
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,4 +1,9 @@
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.
@@ -1155,6 +1160,41 @@ 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`.
///
@@ -1575,3 +1615,30 @@ 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)
})
}
@@ -1408,8 +1408,10 @@ impl NodeNetworkInterface {
let primary_output = RootNode { node_id: toggle_id, output_index: 0 };
let previewing = if self.previewing(network_path).previews(toggle_id) || self.root_node(network_path) == Some(primary_output) {
Previewing::No
} else {
} else if self.number_of_outputs(&toggle_id, network_path) > 0 {
Previewing::Yes { previewed: primary_output }
} else {
return;
};
self.set_previewing(previewing, network_path);
}
@@ -376,6 +376,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_math_nodes::LogicalOrNode",
],
},
NodeReplacement {
node: graphene_std::math_nodes::math_function::IDENTIFIER,
aliases: &["math_nodes::MathFxNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::max::IDENTIFIER,
aliases: &["graphene_math_nodes::MaxNode", "graphene_core::ops::MaxNode"],
@@ -1266,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
}
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
}
}
}
}
@@ -1384,8 +1392,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
}
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math f(x)"
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math f(…)", which reads the pair as `a` and `b`.
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math Function"
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math Formula", which reads the pair as `a` and `b`.
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
.network_interface
.document_network()
@@ -1416,7 +1424,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.is_some();
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
// The rewritten "Math Function" expression, or `None` when only the Extend + "Math Formula" form can preserve the node's meaning
let inline_b_constant = match operand_b.as_value() {
Some(TaggedValue::Number(constant)) => Some(*constant),
_ => None,
@@ -1436,8 +1444,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
};
if let Some(fx_expression) = fx_expression {
// "Math f(x)": forward the old `A` input and the rewritten expression; the old `B` input is dropped
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER)) else {
// "Math Function": forward the old `A` input and the rewritten expression; the old `B` input is dropped
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
@@ -1451,7 +1459,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::String(fx_expression), false), network_path);
} else {
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
// "Extend" joins the two operands into the list "Math Formula" reads; an unwired constant operand becomes a one-item list value
let as_list_input = |input: &NodeInput| match input.as_value() {
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
_ => input.clone(),
@@ -1461,7 +1469,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
};
let extend_template = extend_definition.default_node_template();
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_f::IDENTIFIER)) else {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_formula::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
@@ -1854,6 +1862,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
migrate_assign_colors_nodes(document);
migrate_math_f_nodes(document);
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
migrate_copy_to_points_nodes(document);
@@ -1976,10 +1985,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
let mut inputs_count = node.inputs.len();
// The expression nodes gained an output-type input, a type witness the Inspector edits. A node from before it
// takes the definition's default choice, Number, which is the output type every such node had.
let expression_node_identifiers = [graphene_std::math_nodes::math_fx::IDENTIFIER, graphene_std::math_nodes::math_f::IDENTIFIER];
if expression_node_identifiers.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && inputs_count == 2 {
// The expression nodes gained an output-type input, a type witness the Inspector edits. A node from before it takes the definition's
// default choice, Number, which is the output type every such node had. Math f(…) nodes get it as `migrate_math_f` splits them.
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER) && inputs_count == 2 {
let definition = resolve_document_node_type(&reference)?;
let mut template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut template);
@@ -3840,6 +3848,46 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
Some(())
}
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter(|(_, node, _)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::MathFNode")))
.map(|(node_id, _, path)| (*node_id, path))
.collect();
for (node_id, network_path) in math_f_nodes {
migrate_math_f(&node_id, &network_path, document);
}
}
/// Rebuilds a removed Math f(…) node as Math Aggregate if its string was a lone operator or function name it applied across its items, or as
/// Math Formula otherwise, including when the string is wired, since a wired string can't be read before it runs.
fn migrate_math_f(node_id: &NodeId, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
use graphene_std::math_nodes::{math_aggregate, math_formula};
let old_node = document.network_interface.document_node(node_id, network_path)?;
let applies_operator = matches!(
old_node.inputs.get(1).and_then(|input| input.as_value()),
Some(TaggedValue::String(expression)) if math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()
);
let identifier = if applies_operator { math_aggregate::IDENTIFIER } else { math_formula::IDENTIFIER };
let mut node_template = resolve_proto_node_type(identifier)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
reset_default_display_name(document, node_id, network_path, "Math f(…)");
// The items, string, and output type keep their places, where a node from before the output type takes its default, Number
for (index, input) in old_inputs.into_iter().enumerate().take(3) {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
Some(())
}
/// Splits each removed Assign Colors node into the Vary Fill Colors and Vary Stroke Colors nodes its Fill and Stroke toggles call for.
fn migrate_assign_colors_nodes(document: &mut DocumentMessageHandler) {
let assign_colors_nodes: Vec<(NodeId, Vec<NodeId>)> = document
@@ -4556,7 +4604,7 @@ mod tests {
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
@@ -4591,7 +4639,7 @@ mod tests {
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
@@ -4614,8 +4662,44 @@ mod tests {
assert_eq!(outward_wires.as_deref(), Some([InputConnector::node_at_index(node_id, 0)].as_slice()));
}
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
// Math f(…) either applied a lone operator across its items or evaluated an expression over them, which are now two nodes
#[test]
fn math_f_nodes_split_into_aggregate_and_formula() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use graphene_std::math_nodes::{math_aggregate, math_formula};
let migrated_implementation = |inputs: Vec<NodeInput>| {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::MathFNode")),
inputs,
..Default::default()
},
&[],
);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&node_id];
assert_eq!(node.inputs.len(), 3, "the output type is kept, or added to a node from before it");
match &node.implementation {
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
other => panic!("expected a proto node implementation, got {other:?}"),
}
};
let items = || NodeInput::value(TaggedValue::None, false);
let expression = |text: &str| NodeInput::value(TaggedValue::String(text.into()), false);
let output_type = || NodeInput::value(TaggedValue::Number(0.), false);
assert_eq!(migrated_implementation(vec![items(), expression(" max "), output_type()]), math_aggregate::IDENTIFIER);
assert_eq!(migrated_implementation(vec![items(), expression("+")]), math_aggregate::IDENTIFIER);
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
}
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
#[test]
fn old_math_nodes_split_into_the_expression_node_pair() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
@@ -4666,7 +4750,7 @@ mod tests {
.expect("an Extend node should be spliced in")
};
// A static expression that never reads `B` becomes "Math f(x)" with `A` renamed to `x` and the `B` input dropped
// A static expression that never reads `B` becomes "Math Function" with `A` renamed to `x` and the `B` input dropped
{
let inputs = vec![
NodeInput::node(source_a_id, 0),
@@ -4676,7 +4760,7 @@ mod tests {
let mut document = build_document("math_nodes::MathNode", inputs);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_function::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.len(),
@@ -4698,7 +4782,7 @@ mod tests {
let mut document = build_document("graphene_core::ops::MathNode", inputs);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_function::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
@@ -4717,7 +4801,7 @@ mod tests {
let mut document = build_document("math_nodes::MathNode", inputs);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_formula::IDENTIFIER);
let extend_id = find_extend(&document);
let network = document.network_interface.document_network();
assert_eq!(network.nodes[&math_id].inputs.first(), Some(&NodeInput::node(extend_id, 0)));
@@ -4739,7 +4823,7 @@ mod tests {
let mut document = build_document("math_nodes::MathNode", inputs);
migrate(&mut document);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_formula::IDENTIFIER);
let extend_id = find_extend(&document);
let network = document.network_interface.document_network();
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
@@ -143,6 +143,10 @@ pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_
/// Joins the session of a stored document another tab holds, as a document and peer of this tab's own.
pub(super) async fn join_stored_session(store: DocumentStoreHandle, source: DocumentId) -> Message {
let manifest = async {
// Opening a missing key creates it, and the other tab may have closed the document since
if !store.list().await.map_err(|error| error.to_string())?.contains(&document_key(source)) {
return Err("the other tab closed it".to_string());
}
let container = store.open(document_key(source)).await.map_err(|error| error.to_string())?;
GddV1::read_manifest(&container, &GddV1Layout).await.map_err(|error| error.to_string())
}
@@ -1,16 +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 },
}
@@ -1,508 +0,0 @@
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow};
use crate::messages::portfolio::document::DocumentMessageHandler;
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
use crate::messages::portfolio::sync::now_ms;
use crate::messages::prelude::*;
use document_format::GddV1;
use document_graph_storage::{Delta, HistoryMetadata, HotOpId, PeerId, RegistryDelta, Rev, Session, Subject, UserId, rev_attr};
use peer_transport::RemotePeer;
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
#[derive(ExtractField)]
pub struct HistoryMessageContext<'a> {
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
pub active_document_id: Option<DocumentId>,
pub panel_open: bool,
}
/// Sends the History panel the active document's history and turns its actions into head moves.
#[derive(Debug, Default, ExtractField)]
pub struct HistoryMessageHandler {
ticking: bool,
expanded: HashSet<Rev>,
limit: usize,
following: Option<Rev>,
last_sent: Option<u64>,
}
/// How many interactions each request adds.
const PAGE: usize = 100;
#[message_handler_data]
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
fn process_message(&mut self, message: HistoryMessage, responses: &mut VecDeque<Message>, mut context: HistoryMessageContext) {
match message {
HistoryMessage::Refresh => {
if !self.ticking {
self.ticking = true;
responses.add(BroadcastMessage::SubscribeEvent {
on: EventMessage::AnimationFrame,
send: Box::new(HistoryMessage::Tick.into()),
});
}
self.send(&context, responses, true);
}
HistoryMessage::Tick => {
if context.panel_open {
self.send(&context, responses, false);
}
}
HistoryMessage::Expand { id, expanded } => {
if let Some(rev) = parse_rev(&id) {
match expanded {
true => self.expanded.insert(rev),
false => self.expanded.remove(&rev),
};
}
self.send(&context, responses, true);
}
HistoryMessage::LoadMore => {
self.limit = self.limit.max(PAGE) + PAGE;
self.send(&context, responses, true);
}
HistoryMessage::Follow { id } => {
self.following = id.as_deref().and_then(parse_rev);
self.send(&context, responses, true);
}
HistoryMessage::GoBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(0)) => {}
// A session moves the head for everyone at once. Alone, undo each interaction to keep undo in step
Some(Place::Line(steps)) => match gdd.role().is_some() {
true => responses.add(DocumentMessage::HistoryMoveHead { rev }),
false => (0..steps).for_each(|_| responses.add(DocumentMessage::Undo)),
},
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"),
}
}
HistoryMessage::RemoveStep { id } => {
if let Some(rev) = parse_rev(&id) {
responses.add(DocumentMessage::HistoryRemoveStep { rev });
}
}
HistoryMessage::BringBack { id } => {
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
match place(gdd.session(), rev) {
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
Some(Place::Line(_)) => {}
None => responses.add(DocumentMessage::HistoryRestoreStep { rev }),
}
}
HistoryMessage::Rename { id, label } => {
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
if let Err(error) = gdd.record(Subject::Rev(rev), rev_attr::LABEL, serde_json::Value::from(label.trim()), now_ms()) {
log::warn!("Naming the step failed: {error}");
}
self.send(&context, responses, true);
}
HistoryMessage::Tag { id, tag, on } => {
let tag = tag.trim();
if tag.is_empty() {
return;
}
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
if let Err(error) = gdd.record(Subject::Rev(rev), &format!("{}{tag}", rev_attr::TAG_PREFIX), serde_json::Value::Bool(on), now_ms()) {
log::warn!("Tagging the step failed: {error}");
}
self.send(&context, responses, true);
}
}
}
advertise_actions!(HistoryMessageDiscriminant;);
}
impl HistoryMessageHandler {
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>, force: bool) {
let Some(gdd) = active_storage(context) else {
if force || self.last_sent.is_some() {
self.last_sent = None;
responses.add(FrontendMessage::UpdateHistoryPanel { state: HistoryPanelState::default() });
}
return;
};
if self.following.is_some_and(|tip| gdd.session().delta(tip).is_none()) {
self.following = None;
}
let limit = self.limit.max(PAGE);
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following);
if !force && self.last_sent == Some(fingerprint) {
return;
}
self.last_sent = Some(fingerprint);
let state = panel_state(gdd, limit, &self.expanded, self.following);
responses.add(FrontendMessage::UpdateHistoryPanel { state });
}
}
fn active_storage<'a>(context: &'a HistoryMessageContext) -> Option<&'a GddV1> {
context.active_document_id.and_then(|id| context.documents.get(&id)).and_then(|document| document.storage())
}
fn active_storage_mut<'a>(context: &'a mut HistoryMessageContext) -> Option<&'a mut GddV1> {
context.active_document_id.and_then(|id| context.documents.get_mut(&id)).and_then(|document| document.storage_mut())
}
fn parse_rev(id: &str) -> Option<Rev> {
id.parse::<u128>().ok().and_then(Rev::new)
}
/// Where an interaction sits relative to the head.
enum Place {
/// On the head's line, this many interactions back.
Line(usize),
/// Undone above the head, this many redos forward.
Undone(usize),
}
fn place(session: &Session, rev: Rev) -> Option<Place> {
let head = session.head_rev();
let (kept, _) = line(session, head, None, usize::MAX);
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
return Some(Place::Line(steps));
}
// The stack's first entry is the farthest undone, so its line holds every undone step
let checkpoint = *session.redo_stack().first()?;
let (undone, _) = line(session, Some(checkpoint), head, usize::MAX);
let groups = interactions(&undone);
let index = groups.iter().position(|group| group[0].id == rev)?;
Some(Place::Undone(groups.len() - index))
}
/// A hash of the panel's inputs, cheap enough for every frame.
fn fingerprint(document_id: Option<DocumentId>, gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> u64 {
let session = gdd.session();
let mut hasher = std::collections::hash_map::DefaultHasher::new();
document_id.hash(&mut hasher);
session.history_len().hash(&mut hasher);
session.head_rev().hash(&mut hasher);
session.redo_stack().hash(&mut hasher);
session.hot_log().len().hash(&mut hasher);
gdd.role().is_some().hash(&mut hasher);
for remote in gdd.peers() {
remote.user.hash(&mut hasher);
remote.name.hash(&mut hasher);
}
for fact in gdd.metadata().facts() {
fact.subject.hash(&mut hasher);
fact.key.hash(&mut hasher);
fact.stamp.hash(&mut hasher);
}
limit.hash(&mut hasher);
expanded.len().hash(&mut hasher);
following.hash(&mut hasher);
hasher.finish()
}
fn panel_state(gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
let session = gdd.session();
let people = People {
session,
metadata: gdd.metadata(),
peers: gdd.peers().collect(),
};
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
for delta in session.history() {
for parent in delta.all_parents() {
children.entry(parent).or_default().push(delta.id);
}
}
let head = session.head_rev();
let (head_line, _) = line(session, head, None, usize::MAX);
let head_line_revs: HashSet<Rev> = head_line.iter().map(|delta| delta.id).collect();
let undone = match (following, session.redo_stack().first()) {
(None, Some(&checkpoint)) => line(session, Some(checkpoint), head, usize::MAX).0,
_ => Vec::new(),
};
let (shown, more) = line(session, following.or(head), None, limit);
let on_line: HashSet<Rev> = undone.iter().chain(&shown).map(|delta| delta.id).collect();
let view = View {
children: &children,
on_line: &on_line,
head_line: &head_line_revs,
head,
people: &people,
expanded,
session,
metadata: gdd.metadata(),
};
let undone_rows = interactions(&undone).into_iter().map(|group| view.row(&group, true));
let shown_rows = interactions(&shown).into_iter().map(|group| view.row(&group, false));
let rows = undone_rows.chain(shown_rows).collect();
// Open interactions first, then closed ones waiting to retire, newest first
let hot_log = session.hot_log();
let closed = session.closed_interactions();
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|interaction| interaction.ops.iter().copied()).collect();
let mut open_by_peer: Vec<(PeerId, Vec<&RegistryDelta>)> = Vec::new();
for hot_op in hot_log.iter().filter(|hot_op| !in_closed.contains(&hot_op.id())) {
match open_by_peer.iter_mut().find(|(peer, _)| *peer == hot_op.timestamp.peer) {
Some((_, ops)) => ops.push(&hot_op.op),
None => open_by_peer.push((hot_op.timestamp.peer, vec![&hot_op.op])),
}
}
let mut progress: Vec<HistoryProgressRow> = open_by_peer.into_iter().map(|(peer, ops)| progress_row(&people, peer, &ops, true)).collect();
for interaction in closed.iter().rev() {
let ids: HashSet<HotOpId> = interaction.ops.iter().copied().collect();
let ops: Vec<&RegistryDelta> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).map(|hot_op| &hot_op.op).collect();
progress.push(progress_row(&people, interaction.author, &ops, false));
}
HistoryPanelState {
rows,
progress,
more,
following: following.map(|tip| tip.to_string()),
session: gdd.role().is_some(),
}
}
/// The deltas from `from` back along first parents to `until` (exclusive) or the root, newest first. Stops after
/// `limit` interaction ends, and the flag says whether it did.
fn line(session: &Session, from: Option<Rev>, until: Option<Rev>, limit: usize) -> (Vec<Delta>, bool) {
let mut deltas = Vec::new();
let mut ends = 0;
let mut current = from;
while let Some(rev) = current
&& Some(rev) != until
{
let Some(delta) = session.delta(rev) else { break };
if delta.is_interaction_end() {
if ends == limit {
return (deltas, true);
}
ends += 1;
}
deltas.push(delta.clone());
current = delta.parent;
}
(deltas, false)
}
/// Groups a newest-first line into interactions. Newest deltas without an end, retired mid-interaction, form their own.
fn interactions(deltas: &[Delta]) -> Vec<Vec<&Delta>> {
let mut groups: Vec<Vec<&Delta>> = Vec::new();
for delta in deltas {
match groups.last_mut() {
Some(group) if !delta.is_interaction_end() => group.push(delta),
_ => groups.push(vec![delta]),
}
}
groups
}
struct View<'a> {
children: &'a HashMap<Rev, Vec<Rev>>,
on_line: &'a HashSet<Rev>,
head_line: &'a HashSet<Rev>,
head: Option<Rev>,
people: &'a People<'a>,
expanded: &'a HashSet<Rev>,
session: &'a Session,
metadata: &'a HistoryMetadata,
}
impl View<'_> {
fn row(&self, group: &[&Delta], undone: bool) -> HistoryRow {
let closing = group[0];
let person = self.people.person(closing.author);
let branches = group
.iter()
.flat_map(|delta| self.children.get(&delta.id).into_iter().flatten())
.filter(|child| !self.on_line.contains(child))
.map(|&child| self.branch(child))
.collect();
let is_expanded = self.expanded.contains(&closing.id);
let details = match is_expanded {
true => group
.iter()
.map(|delta| {
let author = self.people.person(delta.author);
HistoryDeltaRow {
id: delta.id.to_string(),
label: describe(&delta.kind),
author: author.name,
color: author.color,
time: delta.retired_at().map(|ms| ms as f64),
}
})
.collect(),
false => Vec::new(),
};
let given = self.metadata.rev_label(closing.id);
HistoryRow {
id: closing.id.to_string(),
label: given.map(str::to_string).unwrap_or_else(|| summarize(group.iter().map(|delta| &delta.kind))),
named: given.is_some(),
tags: self.metadata.rev_tags(closing.id).into_iter().map(str::to_string).collect(),
author: person.name,
anonymous: person.anonymous,
mine: person.mine,
color: person.color,
time: group.iter().find_map(|delta| delta.retired_at()).map(|ms| ms as f64),
deltas: group.len(),
branches,
undone,
abandoned: !undone && !self.head_line.contains(&closing.id),
head: Some(closing.id) == self.head,
expanded: is_expanded,
details,
}
}
fn branch(&self, first: Rev) -> HistoryBranch {
let mut tip = first;
while let Some(&next) = self.children.get(&tip).and_then(|children| children.first()) {
tip = next;
}
let (newest, _) = line(self.session, Some(tip), None, 1);
let label = self
.metadata
.rev_label(tip)
.map(str::to_string)
.unwrap_or_else(|| interactions(&newest).first().map(|group| summarize(group.iter().map(|delta| &delta.kind))).unwrap_or_default());
HistoryBranch { id: tip.to_string(), label }
}
}
fn progress_row(people: &People, peer: PeerId, ops: &[&RegistryDelta], open: bool) -> HistoryProgressRow {
let person = people.person(peer);
HistoryProgressRow {
label: summarize(ops.iter().copied()),
author: person.name,
anonymous: person.anonymous,
mine: person.mine,
color: person.color,
ops: ops.len(),
open,
}
}
/// One line for a run of changes, most frequent kind first. Peer registrations and markers are named only when alone.
fn summarize<'a>(kinds: impl IntoIterator<Item = &'a RegistryDelta>) -> String {
let is_bookkeeping = |kind: &RegistryDelta| matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Meta);
let mut kinds: Vec<&RegistryDelta> = kinds.into_iter().collect();
if kinds.iter().any(|kind| !is_bookkeeping(kind)) {
kinds.retain(|kind| !is_bookkeeping(kind));
}
let mut counts: Vec<(String, usize)> = Vec::new();
for kind in kinds {
let label = describe(kind);
match counts.iter_mut().find(|(known, _)| *known == label) {
Some((_, count)) => *count += 1,
None => counts.push((label, 1)),
}
}
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
let mut parts: Vec<String> = counts
.iter()
.take(2)
.map(|(label, count)| match count {
1 => label.clone(),
count => format!("{label} ×{count}"),
})
.collect();
if counts.len() > 2 {
parts.push(format!("{} more", counts.len() - 2));
}
parts.join(", ")
}
fn describe(kind: &RegistryDelta) -> String {
match kind {
RegistryDelta::AddNode { .. } => "Added a node".into(),
RegistryDelta::RemoveNode { .. } => "Removed a node".into(),
RegistryDelta::ChangeNodeInput { .. } => "Changed an input".into(),
RegistryDelta::SetNodeInputs { .. } => "Set a node's inputs".into(),
RegistryDelta::SetNodeImplementation { .. } => "Changed what a node does".into(),
RegistryDelta::ChangeNodeAttribute { delta, .. } => format!("Set node {}", delta.key),
RegistryDelta::ChangeNodeInputAttribute { delta, .. } => format!("Set input {}", delta.key),
RegistryDelta::SetNetworkExport { .. } => "Changed an export".into(),
RegistryDelta::ChangeNetworkAttribute { delta, .. } => format!("Set network {}", delta.key),
RegistryDelta::AddNetwork { .. } => "Added a network".into(),
RegistryDelta::RemoveNetwork { .. } => "Removed a network".into(),
RegistryDelta::AddResource { .. } => "Added a resource".into(),
RegistryDelta::SetResourceHash { .. } => "Updated a resource".into(),
RegistryDelta::RemoveResource { .. } => "Removed a resource".into(),
RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => "Changed where a resource comes from".into(),
RegistryDelta::RegisterPeer { .. } => "Joined the document".into(),
RegistryDelta::ChangeDocumentAttribute { delta } => format!("Set document {}", delta.key),
RegistryDelta::Merge { .. } => "Joined two lines of work".into(),
RegistryDelta::Meta => "Marked a step".into(),
RegistryDelta::Other(_) => "Changed something".into(),
}
}
/// Names and colours authors by user id. The document's record wins, then the announced name, then the stand-in.
struct People<'a> {
session: &'a Session,
metadata: &'a HistoryMetadata,
peers: Vec<&'a RemotePeer>,
}
struct Person {
name: String,
anonymous: bool,
mine: bool,
color: String,
}
impl People<'_> {
fn person(&self, peer: PeerId) -> Person {
// A peer that never registered is its own user
let user = self.session.user_of(peer).unwrap_or(UserId(peer.0));
let recorded = self.metadata.user_name(user).map(str::to_string);
let announced = || self.peers.iter().find(|remote| remote.user == user && !remote.name.is_empty()).map(|remote| remote.name.clone());
let (name, anonymous) = match recorded.or_else(announced) {
Some(name) => (name, false),
None => (anonymous_name(user), true),
};
Person {
name,
anonymous,
mine: self.session.is_mine(peer),
color: user_color(user),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Undoing pushes each step's head, so undone steps must be read from the first entry.
#[test]
fn every_undone_step_stays_on_the_panel() {
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::GddV1Layout;
use document_graph_storage::{Network, NetworkId};
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into()).expect("create");
for id in 1..=3 {
let network = Network::default();
gdd.stage_ops([RegistryDelta::AddNetwork { id: NetworkId(id), network }]).expect("stage");
gdd.retire_pending_interaction().expect("retire");
}
gdd.undo().expect("undo");
gdd.undo().expect("undo");
assert_eq!(panel_state(&gdd, PAGE, &HashSet::new(), None).rows.len(), 3);
}
#[test]
fn a_run_of_only_markers_is_named_by_them() {
let register = RegistryDelta::RegisterPeer { peer: PeerId(1), user: UserId(1) };
let merge = RegistryDelta::Merge { extra_parents: Vec::new() };
assert_eq!(summarize([&RegistryDelta::Meta, &RegistryDelta::Meta]), "Marked a step ×2");
assert_eq!(summarize([&register, &RegistryDelta::Meta]), "Joined the document, Marked a step");
assert_eq!(summarize([&RegistryDelta::Meta, &merge, &register]), "Joined two lines of work");
}
}
@@ -1,8 +0,0 @@
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,72 +0,0 @@
//! What the History panel shows, as the frontend receives it.
/// 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>,
/// In a session, a head move affects everyone.
pub session: 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>,
}
#[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 color: String,
pub time: Option<f64>,
}
/// 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,
}
@@ -206,7 +206,7 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
/// Determine the size of an SVG file (the viewBox is already applied by the SVG importer so can be ignored)
fn svg_canvas(svg: &str) -> Option<(IVec2, IVec2)> {
usvg::Tree::from_str(&svg, &usvg::Options::default()).ok().map(|tree| {
usvg::Tree::from_str(svg, &usvg::Options::default()).ok().map(|tree| {
let size = tree.size();
(glam::IVec2::ZERO, glam::IVec2::new(size.width().round() as i32, size.height().round() as i32))
})
@@ -13,7 +13,7 @@ use std::path::Path;
const SNIFFED_TEXT_LENGTH: usize = 4096;
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
pub enum IngestAction {
Open,
/// Open a distributed file such as a demo artwork as a copy with its own session room.
-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,14 +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,
};
self.history.process_message(message, responses, context);
}
PortfolioMessage::Sync(message) => {
let context = SyncMessageContext {
documents: &mut self.documents,
@@ -431,14 +422,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PortfolioMessage::LoadPersistedState { state } => {
if let Some(layout) = state.workspace_layout {
self.workspace.panel_layout = layout;
// Add the Session panel beside the Inspector, unless the user closed it
let panel_layout = &mut self.workspace.panel_layout;
if !panel_layout.is_panel_present(PanelType::Session) && !panel_layout.was_closed(PanelType::Session) {
match panel_layout.find_panel(PanelType::Inspector).and_then(|group_id| panel_layout.panel_group_mut(group_id)) {
Some(group) => group.tabs.push(PanelType::Session),
None => panel_layout.restore_panel(PanelType::Session),
}
}
responses.add(WorkspaceMessage::UpdatePanelsLayout);
// Refill panels whose content was lost when the layout load remounted their frontend components
@@ -1201,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};
@@ -37,6 +37,8 @@ pub struct SyncMessageContext<'a> {
#[derive(Debug, Default, ExtractField)]
pub struct SyncMessageHandler {
pending_joins: HashMap<DocumentId, SessionToken>,
/// Rooms joined by link until the host's state arrives, since the document's own id names another room.
joined: HashMap<DocumentId, SessionToken>,
polling: bool,
incoming: HashMap<DocumentId, (u32, Incoming)>,
connections: u32,
@@ -78,6 +80,12 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
if gdd.role().is_some() {
return;
}
if gdd.is_shared() {
// A reconnect leaves the clipboard and the panels alone
let Some(gdd) = document.storage_mut() else { return };
self.connect_document(document_id, gdd, preferences, responses);
return;
}
document.stage_name_attribute();
let Some(gdd) = document.storage_mut() else { return };
self.host(document_id, gdd, preferences, responses);
@@ -115,6 +123,7 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
return;
}
announce_name(gdd, &preferences.user_name);
self.joined.insert(document_id, token);
self.attach(document_id, incoming, driver, responses);
refresh_session_views(responses);
} else if gdd.is_shared() && gdd.role().is_none() {
@@ -130,6 +139,7 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
};
gdd.leave();
self.detach(document_id);
self.joined.remove(&document_id);
refresh_session_views(responses);
}
SyncMessage::Fork => {
@@ -139,6 +149,7 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
let Some(gdd) = document.storage_mut() else { return };
gdd.leave();
self.detach(document_id);
self.joined.remove(&document_id);
// The room derives from the manifest's document id, so a fresh id is a fresh room
if let Err(error) = gdd.update_manifest(|manifest| manifest.document_id = generate_uuid()) {
log::error!("Forking the session failed: {error}");
@@ -168,14 +179,14 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
}
SyncMessage::Poll => {
let cursor = active_cursor(documents, active_document_id, ipp, viewport, tools);
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, None, responses);
}
SyncMessage::Wake { document_id, generation } => {
if !self.is_current(document_id, generation) {
return;
}
let cursor = active_cursor(documents, active_document_id, ipp, viewport, tools);
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, Some(document_id), responses);
// The poll drained the inbox, so the next arrival wakes the next poll
self.arm(document_id, responses);
}
@@ -219,7 +230,7 @@ impl SyncMessageHandler {
}
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
let token = SessionToken::for_document(gdd.manifest().document_id);
let token = self.joined.get(&document_id).copied().unwrap_or_else(|| SessionToken::for_document(gdd.manifest().document_id));
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
let incoming = room.incoming();
if let Err(error) = gdd.connect(room, UserId(preferences.user_id)) {
@@ -249,6 +260,7 @@ impl SyncMessageHandler {
self.reconnect_at.remove(&document_id);
self.retry_at.remove(&document_id);
self.undecided_since.remove(&document_id);
self.decoding.retain(|&(id, _)| id != document_id);
}
fn is_current(&self, document_id: DocumentId, generation: u32) -> bool {
@@ -277,6 +289,8 @@ impl SyncMessageHandler {
});
}
/// Polls `only`, or every document when it is `None`.
#[allow(clippy::too_many_arguments)]
fn poll(
&mut self,
documents: &mut HashMap<DocumentId, DocumentMessageHandler>,
@@ -284,9 +298,10 @@ impl SyncMessageHandler {
resources: ResourcesHandle,
preferences: &PreferencesMessageHandler,
active_cursor: Option<CursorPosition>,
only: Option<DocumentId>,
responses: &mut VecDeque<Message>,
) {
for (&document_id, document) in documents.iter_mut() {
for (&document_id, document) in documents.iter_mut().filter(|(id, _)| only.is_none_or(|only| only == **id)) {
let cursor = (Some(document_id) == active_document_id).then(|| active_cursor.clone()).flatten();
self.poll_document(document_id, document, &resources, preferences, cursor, responses);
}
@@ -337,7 +352,9 @@ impl SyncMessageHandler {
None => return,
Some(Role::Undecided) => {
let since = *self.undecided_since.entry(document_id).or_insert_with(now_ms);
if now_ms() - since >= ROLE_GRACE_MS && gdd.decide_role().is_some() {
// A joiner holds nothing yet, so it waits for a host instead of taking the room
let may_host = !self.joined.contains_key(&document_id);
if may_host && now_ms() - since >= ROLE_GRACE_MS && gdd.decide_role().is_some() {
self.undecided_since.remove(&document_id);
refresh_session_views(responses);
}
@@ -370,6 +387,7 @@ impl SyncMessageHandler {
match event {
Event::Synced => {
log::debug!("Synced with the host, applying its state");
self.joined.remove(&document_id);
refresh_session_views(responses);
self.dirty.insert(document_id);
self.fit_after_sync.insert(document_id);
@@ -397,10 +415,7 @@ impl SyncMessageHandler {
refresh_session_views(responses);
}
Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses),
Event::MetadataChanged => {
refresh_session_views(responses);
responses.add(HistoryMessage::Refresh);
}
Event::MetadataChanged => refresh_session_views(responses),
Event::CursorMoved { .. } => {}
}
}
@@ -414,11 +429,11 @@ impl SyncMessageHandler {
self.dirty.remove(&document_id);
continue;
};
let Some(gdd) = document.storage() else { continue };
let missing = SyncTarget::missing_resources(gdd).len();
if self.retry_at.get(&document_id).is_some_and(|&due| now_ms() < due) {
continue;
}
let Some(gdd) = document.storage() else { continue };
let missing = SyncTarget::missing_resources(gdd).len();
let transaction = document.network_interface.transaction_status();
if missing > 0 || transaction != TransactionStatus::Finished {
self.wait(document_id, format!("missing {missing} transaction {transaction:?}"));
@@ -500,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()
+5 -12
View File
@@ -3,7 +3,7 @@ const DOCUMENT_PANEL_SHARE: f64 = 0.8;
/// Proportional share for each side when neither (or both) contain the document panel.
const EQUAL_PANEL_SHARE: f64 = 0.5;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
Welcome,
@@ -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]
}
}
@@ -44,7 +42,7 @@ impl PanelType {
pub struct PanelGroupId(pub u64);
/// Which edge of a panel group to split on when docking a dragged panel.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum DockingSplitDirection {
Left,
@@ -256,10 +254,6 @@ impl WorkspacePanelLayout {
});
}
pub fn was_closed(&self, panel_type: PanelType) -> bool {
self.saved_positions.iter().any(|saved| saved.panel_type == panel_type)
}
/// Restore a panel to its previous position if available, otherwise to its default position.
pub fn restore_panel(&mut self, panel_type: PanelType) {
let saved = self.saved_positions.iter().find(|s| s.panel_type == panel_type).copied();
@@ -309,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
@@ -340,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 {
@@ -39,6 +39,9 @@ pub enum PreferencesMessage {
SaveAsGdd {
enabled: bool,
},
SaveWithHistory {
enabled: bool,
},
ToggleShowStoragePreferences,
UserName {
name: String,
@@ -23,6 +23,7 @@ pub struct PreferencesMessageHandler {
pub disable_ui_acceleration: bool,
pub validate_storage_round_trip: bool,
pub save_as_gdd: bool,
pub save_with_history: bool,
pub show_storage_preferences: bool,
/// This person's id across documents. A decimal string, since the browser's JSON loses 64-bit precision.
#[serde(with = "u64_as_string")]
@@ -59,6 +60,7 @@ impl Default for PreferencesMessageHandler {
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
validate_storage_round_trip: false,
save_as_gdd: false,
save_with_history: false,
show_storage_preferences: false,
user_id: crate::application::generate_uuid(),
user_name: String::new(),
@@ -99,8 +101,10 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
responses.add(ToolMessage::RefreshToolShelf);
}
PreferencesMessage::ResetToDefaults => {
// The identity isn't a setting, and documents would record the cleared name
let preferences = Self {
user_id: self.user_id,
user_name: self.user_name.clone(),
..Self::default()
};
responses.add(PreferencesMessage::Load { preferences });
@@ -147,6 +151,9 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
PreferencesMessage::SaveAsGdd { enabled } => {
self.save_as_gdd = enabled;
}
PreferencesMessage::SaveWithHistory { enabled } => {
self.save_with_history = enabled;
}
PreferencesMessage::ToggleShowStoragePreferences => {
self.show_storage_preferences = !self.show_storage_preferences;
responses.add(MenuBarMessage::SendLayout);
-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};
@@ -1478,7 +1478,9 @@ impl PenToolData {
/// Perform extension of an existing path
fn extend_existing_path(&mut self, document: &DocumentMessageHandler, layer: LayerNodeIdentifier, point: PointId, position: DVec2) {
let vector: Option<VectorGeometry> = document.network_interface.compute_modified_vector(layer);
let (handle_start, in_segment) = if let Some(vector) = &vector {
let (handle_start, in_segment) = if let Some(vector) = &vector
&& vector.connected_count(point) <= 1
{
vector
.segment_iter()
.find_map(|(segment_id, bezier, start, end)| {
@@ -2496,13 +2498,30 @@ impl Fsm for PenToolFsmState {
#[cfg(test)]
mod test_pen_tool {
use super::is_almost_colinear;
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;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId};
use graphene_std::vector::{SegmentId, VectorGeometry};
use glam::{DAffine2, DVec2};
use graphene_std::vector::misc::{BooleanOperation, HandleId, ManipulatorPointId};
use graphene_std::vector::{PointId, 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)> {
@@ -2565,6 +2584,267 @@ 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] {
@@ -3145,6 +3425,37 @@ mod test_pen_tool {
assert!(leaving.distance(handle) < 1e-6, "the joining segment's handle is at {leaving}");
}
/// Finds the point ID whose viewport position is within tolerance of `target`.
fn get_anchor_near(vector: &VectorGeometry, layer_to_viewport: DAffine2, target: DVec2) -> PointId {
vector
.anchors()
.find(|&(_id, pos)| layer_to_viewport.transform_point2(pos).distance(target) < 1e-6)
.map(|(id, _pos)| id)
.unwrap_or_else(|| panic!("No anchor found near {target}"))
}
/// Finds the segment that connects two given point IDs (in either direction).
fn get_segment_between(vector: &VectorGeometry, point_a: PointId, point_b: PointId) -> SegmentId {
vector
.segment_ids()
.into_iter()
.find(|&segment| {
let start = vector.segment_start_from_id(segment);
let end = vector.segment_end_from_id(segment);
(start == Some(point_a) && end == Some(point_b)) || (start == Some(point_b) && end == Some(point_a))
})
.unwrap_or_else(|| panic!("No segment found between the given anchors"))
}
/// Finds the handle position on `segment` that corresponds to `point`.
fn get_handle_at(vector: &VectorGeometry, segment: SegmentId, point: PointId) -> Option<DVec2> {
if vector.segment_start_from_id(segment) == Some(point) {
vector.position_of(ManipulatorPointId::PrimaryHandle(segment))
} else {
vector.position_of(ManipulatorPointId::EndHandle(segment))
}
}
#[tokio::test]
async fn an_anchor_moved_with_space_lands_on_a_corner_and_carries_its_handles_along() {
let mut editor = EditorTestUtils::create();
@@ -3432,4 +3743,83 @@ mod test_pen_tool {
let stroke = position(graphene_std::vector_nodes::stroke::IDENTIFIER).expect("The path should have a Stroke node");
assert!(transform > fill && transform > stroke, "the Transform should be upstream of the Fill and Stroke in {chain:?}");
}
#[tokio::test]
async fn extending_from_anchor_with_multiple_segments_does_not_create_colinear_handle() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// 1. Draw a path through A, B, and C with curved handles dragged out at B
click_pen(&mut editor, A).await;
let handle = B + DVec2::new(50., 0.);
editor.drag_path(&[B, handle], ModifierKeys::empty()).await;
click_pen(&mut editor, C).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 3, 2);
// 2. Extend from anchor B to D by clicking on B and then D (without dragging)
click_pen(&mut editor, B).await;
click_pen(&mut editor, D).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 4, 3);
// 3. Verify the new branch leaving B does not create a mirrored/colinear handle
let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let b_id = get_anchor_near(&vector, layer_to_viewport, B);
let d_id = get_anchor_near(&vector, layer_to_viewport, D);
let bd_segment = get_segment_between(&vector, b_id, d_id);
if let Some(handle_pos) = get_handle_at(&vector, bd_segment, b_id) {
let handle_pos = layer_to_viewport.transform_point2(handle_pos);
assert!(handle_pos.distance(B) < 1e-4, "Handle at B for the new segment should remain at the anchor");
}
}
#[tokio::test]
async fn extending_from_anchor_with_single_segment_uses_colinear_handle() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// 1. Draw a single segment A→B with a curved handle dragged out at B
click_pen(&mut editor, A).await;
let handle = B + DVec2::new(50., 0.);
editor.drag_path(&[B, handle], ModifierKeys::empty()).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 2, 1);
// 2. Extend from B to C by clicking B then C (only one segment is attached to B)
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
editor.press(Key::Enter, ModifierKeys::empty()).await;
assert_path_shape(&editor, 3, 2);
// 3. Verify the new segment leaving B carries a mirrored/colinear handle
let (layer, vector) = drawn_path(&editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let b_id = get_anchor_near(&vector, layer_to_viewport, B);
let c_id = get_anchor_near(&vector, layer_to_viewport, C);
let bc_segment = get_segment_between(&vector, b_id, c_id);
let a_id = get_anchor_near(&vector, layer_to_viewport, A);
let ab_segment = get_segment_between(&vector, a_id, b_id);
let existing_handle_at_b = get_handle_at(&vector, ab_segment, b_id).expect("Segment AB should have a handle at B");
let existing_handle_pos = layer_to_viewport.transform_point2(existing_handle_at_b);
let new_handle_at_b = get_handle_at(&vector, bc_segment, b_id).expect("The new segment should have a handle at B");
let new_handle_pos = layer_to_viewport.transform_point2(new_handle_at_b);
// When only one segment is connected, the handle should not collapse to the
// anchor, and must be colinear with the existing handle at B.
assert!(
new_handle_pos.distance(B) > 1e-4,
"Handle at B should not collapse to the anchor when only one segment is connected (got {new_handle_pos})"
);
assert!(
is_almost_colinear(B, existing_handle_pos, new_handle_pos),
"New handle should be colinear with the existing handle at B (existing: {existing_handle_pos}, new: {new_handle_pos})"
);
}
}
+1 -1
View File
@@ -448,7 +448,7 @@ impl NodeGraphExecutor {
let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
while let Some(response) = results.next() {
for response in results.by_ref() {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse {
+1 -1
View File
@@ -114,7 +114,7 @@ impl EditorTestUtils {
return Ok(result);
}
}
return Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")));
Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")))
}
pub async fn handle_message(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
-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();
@@ -1,405 +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 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");
// 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();
}
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;
}
</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}
<div class="row progress">
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
<div class="text">
<span class="label">{row.label || (row.open ? "In progress" : "Waiting to enter history")}</span>
<span class="meta">
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
· {count(row.ops, "change", "changes")}
· {row.open ? "in progress" : "not yet in history"}
</span>
</div>
</div>
{/each}
{#each $history.rows as row (row.id)}
<div class="row" class:head={row.head} class:undone={row.undone} class:abandoned={row.abandoned}>
<button
class="expand"
class:expanded={row.expanded}
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
></button>
<span class="rail"><span class="dot" style:background={row.color}></span></span>
<div class="text">
{#if renamingId === row.id}
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
{:else}
<span class="label" class:named={row.named}>{row.label}</span>
{/if}
<span class="meta">
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
{#if row.time}· {when(row.time, now)}{/if}
· {count(row.deltas, "change", "changes")}
</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}
<TextInput value="" placeholder="Tag name" narrow={true} on:commitText={({ detail }) => commitTag(row.id, detail)} />
{/if}
</span>
{/if}
{#if row.branches.length > 0}
<span class="branches">
{#each row.branches as branch (branch.id)}
<button class="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="small" data-tooltip-label="Name this step" on:click={() => (renamingId = renamingId === row.id ? undefined : row.id)}>Name</button>
<button class="small" data-tooltip-label="Tag this step" on:click={() => (taggingId = taggingId === row.id ? undefined : 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.session ? "Move everyone's document back to this step. The steps since stay as a branch." : "Undo up to this step."}
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}<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}
{#each row.details as delta (delta.id)}
<div class="row delta" class:undone={row.undone}>
<span class="rail"><span class="tick"></span></span>
<div class="text">
<span class="label">{delta.label}</span>
<span class="meta">
<span class="author">{delta.author}</span>
{#if delta.time}· {when(delta.time, now)}{/if}
</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;
padding-left: 28px;
font-size: 11px;
}
.actions {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 2px;
visibility: hidden;
.small {
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);
}
}
}
&:hover .actions {
visibility: visible;
}
.expand {
flex: 0 0 auto;
width: 16px;
height: 16px;
padding: 0;
border: none;
background: none;
position: relative;
cursor: pointer;
&::after {
content: "";
position: absolute;
left: 5px;
top: 4px;
border: 4px solid transparent;
border-left: 5px solid var(--color-8-uppergray);
}
&.expanded::after {
left: 3px;
top: 6px;
border: 4px solid transparent;
border-top: 5px solid var(--color-8-uppergray);
}
&:hover::after {
border-left-color: var(--color-e-nearwhite);
}
&.expanded:hover::after {
border-left-color: transparent;
border-top-color: var(--color-e-nearwhite);
}
}
.rail {
flex: 0 0 12px;
display: flex;
justify-content: center;
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
&.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 {
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;
max-width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
&:hover {
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
}
}
.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);
}
}
.more {
display: flex;
justify-content: center;
padding: 8px;
}
}
</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,
+12 -4
View File
@@ -228,6 +228,7 @@ import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-tra
import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg";
import NodeIsNonzero from "/../branding/assets/16x16-nodes/node-is-nonzero.svg";
import NodeItemAtIndex from "/../branding/assets/16x16-nodes/node-item-at-index.svg";
import NodeIterate from "/../branding/assets/16x16-nodes/node-iterate.svg";
import NodeJitterPoints from "/../branding/assets/16x16-nodes/node-jitter-points.svg";
import NodeLeastCommonMultiple from "/../branding/assets/16x16-nodes/node-least-common-multiple.svg";
import NodeLerp from "/../branding/assets/16x16-nodes/node-lerp.svg";
@@ -247,8 +248,10 @@ import NodeMandelbrot from "/../branding/assets/16x16-nodes/node-mandelbrot.svg"
import NodeMapPoints from "/../branding/assets/16x16-nodes/node-map-points.svg";
import NodeMap from "/../branding/assets/16x16-nodes/node-map.svg";
import NodeMask from "/../branding/assets/16x16-nodes/node-mask.svg";
import NodeMathF from "/../branding/assets/16x16-nodes/node-math-f.svg";
import NodeMathFx from "/../branding/assets/16x16-nodes/node-math-fx.svg";
import NodeMathAggregate from "/../branding/assets/16x16-nodes/node-math-aggregate.svg";
import NodeMathFormula from "/../branding/assets/16x16-nodes/node-math-formula.svg";
import NodeMathFunction from "/../branding/assets/16x16-nodes/node-math-function.svg";
import NodeMathRunning from "/../branding/assets/16x16-nodes/node-math-running.svg";
import NodeMax from "/../branding/assets/16x16-nodes/node-max.svg";
import NodeMaximum from "/../branding/assets/16x16-nodes/node-maximum.svg";
import NodeMedianFilter from "/../branding/assets/16x16-nodes/node-median-filter.svg";
@@ -270,6 +273,7 @@ import NodeNumbersToVec2 from "/../branding/assets/16x16-nodes/node-numbers-to-v
import NodeOffsetPath from "/../branding/assets/16x16-nodes/node-offset-path.svg";
import NodeOffsetPoints from "/../branding/assets/16x16-nodes/node-offset-points.svg";
import NodeOpacity from "/../branding/assets/16x16-nodes/node-opacity.svg";
import NodeOpenEnds from "/../branding/assets/16x16-nodes/node-open-ends.svg";
import NodeOriginsToPolyline from "/../branding/assets/16x16-nodes/node-origins-to-polyline.svg";
import NodePackStrips from "/../branding/assets/16x16-nodes/node-pack-strips.svg";
import NodePassthrough from "/../branding/assets/16x16-nodes/node-passthrough.svg";
@@ -506,6 +510,7 @@ export const ICON_16X16_NODES = {
NodeInvertTransform: { svg: NodeInvertTransform, size: 16 },
NodeIsNonzero: { svg: NodeIsNonzero, size: 16 },
NodeItemAtIndex: { svg: NodeItemAtIndex, size: 16 },
NodeIterate: { svg: NodeIterate, size: 16 },
NodeJitterPoints: { svg: NodeJitterPoints, size: 16 },
NodeLeastCommonMultiple: { svg: NodeLeastCommonMultiple, size: 16 },
NodeLerp: { svg: NodeLerp, size: 16 },
@@ -525,8 +530,10 @@ export const ICON_16X16_NODES = {
NodeMap: { svg: NodeMap, size: 16 },
NodeMapPoints: { svg: NodeMapPoints, size: 16 },
NodeMask: { svg: NodeMask, size: 16 },
NodeMathF: { svg: NodeMathF, size: 16 },
NodeMathFx: { svg: NodeMathFx, size: 16 },
NodeMathAggregate: { svg: NodeMathAggregate, size: 16 },
NodeMathFormula: { svg: NodeMathFormula, size: 16 },
NodeMathFunction: { svg: NodeMathFunction, size: 16 },
NodeMathRunning: { svg: NodeMathRunning, size: 16 },
NodeMax: { svg: NodeMax, size: 16 },
NodeMaximum: { svg: NodeMaximum, size: 16 },
NodeMedianFilter: { svg: NodeMedianFilter, size: 16 },
@@ -548,6 +555,7 @@ export const ICON_16X16_NODES = {
NodeOffsetPath: { svg: NodeOffsetPath, size: 16 },
NodeOffsetPoints: { svg: NodeOffsetPoints, size: 16 },
NodeOpacity: { svg: NodeOpacity, size: 16 },
NodeOpenEnds: { svg: NodeOpenEnds, size: 16 },
NodeOriginsToPolyline: { svg: NodeOriginsToPolyline, size: 16 },
NodePackStrips: { svg: NodePackStrips, size: 16 },
NodePassthrough: { svg: NodePassthrough, size: 16 },
-35
View File
@@ -1,35 +0,0 @@
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
export type HistoryStore = ReturnType<typeof createHistoryStore>;
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, session: false };
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<HistoryPanelState> = import.meta.hot?.data?.store || writable<HistoryPanelState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, set } = store;
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
destroyHistoryStore();
subscriptionsRouter = subscriptions;
subscriptions.subscribeFrontendMessage("UpdateHistoryPanel", (data) => {
set(data.state);
});
return { subscribe };
}
export function destroyHistoryStore() {
const subscriptions = subscriptionsRouter;
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
subscriptionsRouter = undefined;
}
+16 -54
View File
@@ -7,6 +7,8 @@
use crate::editor_wrapper::EditorWrapper;
use graphite_proc_macros::editor_commands;
use serde::{Deserialize, Serialize};
#[cfg(target_family = "wasm")]
use tsify::Ts;
use tsify::Tsify;
#[cfg(target_family = "wasm")]
use wasm_bindgen::prelude::*;
@@ -94,7 +96,7 @@ mod editor_commands {
}
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
fn widget_value_update(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let update = LayoutMessage::WidgetValueUpdate {
layout_target,
@@ -111,7 +113,7 @@ mod editor_commands {
}
/// Commit the value of a given UI widget to the history
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
fn widget_value_commit(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>) -> Message {
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id: WidgetId(widget_id),
@@ -121,7 +123,7 @@ mod editor_commands {
}
/// Update the value of a given UI widget, and commit it to the history
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
fn widget_value_commit_and_update(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let mut messages: Vec<Message> = vec![
LayoutMessage::WidgetValueCommit {
@@ -147,13 +149,13 @@ mod editor_commands {
}
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
fn widget_value_drag_drop(layout_target: Ts<LayoutTarget>, widget_id: u64) -> Message {
let widget_id = WidgetId(widget_id);
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
}
/// Hand a file dropped on a UI widget to the widget's file drop callback
fn widget_value_file_drop(layout_target: LayoutTarget, widget_id: u64, name: String, mime_type: String, data: Vec<u8>) -> Message {
fn widget_value_file_drop(layout_target: Ts<LayoutTarget>, widget_id: u64, name: String, mime_type: String, data: Vec<u8>) -> Message {
let widget_id = WidgetId(widget_id);
let file = DroppedFile { name, mime_type, data };
LayoutMessage::WidgetValueFileDrop { layout_target, widget_id, file }.into()
@@ -161,7 +163,7 @@ mod editor_commands {
/// Tokenizes a math expression widget's text as it is typed, for the reply to color and typeset it, and offers names to finish
/// the one at the caret, where the caret is given. Unless they're `asked` for, names are offered only once part of one is typed.
fn analyze_math_expression(layout_target: LayoutTarget, widget_id: u64, source: String, caret: Option<u32>, asked: bool) -> Message {
fn analyze_math_expression(layout_target: Ts<LayoutTarget>, widget_id: u64, source: String, caret: Option<u32>, asked: bool) -> Message {
LayoutMessage::AnalyzeMathExpression {
layout_target,
widget_id: WidgetId(widget_id),
@@ -257,48 +259,11 @@ mod editor_commands {
}
/// Bring a panel to the front, reopening it if closed
fn focus_panel(panel_type: PanelType) -> Message {
fn focus_panel(panel_type: Ts<PanelType>) -> Message {
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()
}
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
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),
direction,
@@ -478,7 +443,7 @@ mod editor_commands {
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
fn update_primary_color(color: SRGBA8) -> Message {
fn update_primary_color(color: Ts<SRGBA8>) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
@@ -487,7 +452,7 @@ mod editor_commands {
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
fn update_secondary_color(color: SRGBA8) -> Message {
fn update_secondary_color(color: Ts<SRGBA8>) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
@@ -496,7 +461,7 @@ mod editor_commands {
}
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
fn open_color_picker(initial_value: FillChoiceSRGBA8, allow_none: bool, disabled: bool) -> Message {
fn open_color_picker(initial_value: Ts<FillChoiceSRGBA8>, allow_none: bool, disabled: bool) -> Message {
ColorPickerMessage::Open {
initial_value: FillChoice::from(&initial_value.0),
allow_none,
@@ -511,7 +476,7 @@ mod editor_commands {
}
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
fn update_gradient_stop_color(color: SRGBA8) -> Message {
fn update_gradient_stop_color(color: Ts<SRGBA8>) -> Message {
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
}
@@ -703,12 +668,12 @@ mod editor_commands {
}
/// The pixels of an export that `TriggerExportImage` had the frontend rasterize, which the editor encodes and saves as the chosen file type
fn save_rasterized_export(name: String, file_type: FileType, width: u32, height: u32, data: Vec<u8>) -> Message {
fn save_rasterized_export(name: String, file_type: Ts<FileType>, width: u32, height: u32, data: Vec<u8>) -> Message {
PortfolioMessage::SaveRasterizedExport { name, file_type, width, height, data }.into()
}
/// A file headed for a known action, picked in the dialog that `TriggerBrowse` opened
fn ingest_picked(name: String, mime_type: String, data: Vec<u8>, action: IngestAction) -> Message {
fn ingest_picked(name: String, mime_type: String, data: Vec<u8>, action: Ts<IngestAction>) -> Message {
IngestMessage::Ingest {
data,
action,
@@ -926,7 +891,6 @@ mod editor_commands {
#[cfg(feature = "editor")]
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct FillChoiceSRGBA8(
/// Concrete wasm boundary form of the generic [`FillChoice`], since a `#[wasm_bindgen]` argument's TS declaration names its type without the generic's argument.
#[tsify(type = "FillChoice<SRGBA8>")]
@@ -936,7 +900,6 @@ pub struct FillChoiceSRGBA8(
pub type FillChoiceSRGBA8 = Any;
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct Any(#[tsify(type = "any")] serde_json::Value);
impl Any {
#[cfg(feature = "editor")]
@@ -962,6 +925,5 @@ editor_proxy_types! {
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
PanelType = editor::messages::portfolio::utility_types::PanelType;
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
SRGBA8 = graphene_std::color::SRGBA8;
}
+8 -1
View File
@@ -250,7 +250,14 @@ impl EditorWrapper {
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
#[cfg(all(feature = "web", not(feature = "native")))]
#[wasm_bindgen(js_name = loadPersistedState)]
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
pub fn load_persisted_state(&self, state: tsify::Ts<editor::messages::frontend::utility_types::PersistedState>) {
let state = match state.to_rust() {
Ok(state) => state,
Err(e) => {
log::error!("Cannot convert state to type utility_types::PersistedState: {e:?}");
return;
}
};
self.dispatch(PersistentStateMessage::LoadState { state });
}
#[cfg(feature = "native")]
+1 -1
View File
@@ -30,7 +30,7 @@ glam = ["dep:glam"]
dyn-any-derive = { path = "derive", optional = true }
# Optional dependencies
glam = { version = "0.33", optional = true, default-features = false, features = ["all-types"] }
glam = { version = "0.34", optional = true, default-features = false, features = ["all-types"] }
reqwest = { version = "0.13", optional = true, default-features = false }
[package.metadata.docs.rs]
+3 -3
View File
@@ -213,13 +213,13 @@ unsafe impl<T: StaticTypeSized> StaticType for [T] {
type Static = [<T as StaticTypeSized>::Static];
}
unsafe impl StaticType for dyn for<'i> DynAny<'_> + '_ {
unsafe impl StaticType for dyn DynAny<'_> + '_ {
type Static = dyn DynAny<'static>;
}
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + Sync + '_ {
unsafe impl StaticType for dyn DynAny<'_> + Send + Sync + '_ {
type Static = dyn DynAny<'static> + Send + Sync;
}
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + '_ {
unsafe impl StaticType for dyn DynAny<'_> + Send + '_ {
type Static = dyn DynAny<'static> + Sync;
}
unsafe impl<T: StaticTypeSized> StaticType for dyn core::future::Future<Output = T> + Send + Sync + '_ {
+1
View File
@@ -18,6 +18,7 @@ workspace = true
thiserror = "2.0"
num-complex = "0.4"
unicode-ident = "1.0"
# This is intentionally not upgraded since the cache API was removed for soundness https://codeberg.org/zesterer/chumsky/pulls/980
chumsky = { version = "0.10", default-features = false, features = ["std", "unstable"] }
[dev-dependencies]
+6
View File
@@ -17,6 +17,12 @@ impl ParseError {
pub fn messages(&self) -> &[ErrorMessage] {
&self.0
}
/// The error of a source that should be a lone operator or function name but isn't, spanning the given range of it.
pub(crate) fn lone_reducer_expected(span: Range<usize>) -> Self {
let message = ErrorMessage::from_prose("Expected a lone operator like `+` or a function name like `max`");
Self(vec![ErrorMessage { span: Some(span), ..message }])
}
}
impl fmt::Display for ParseError {
+162 -10
View File
@@ -1,10 +1,11 @@
use crate::ast::BinaryOp;
use crate::constants::{Builtin, BuiltinFunction, builtin_function};
use crate::context::ValueProvider;
use crate::context::{NothingMap, ValueProvider};
use crate::executer::settle_matrix;
use crate::lexer::{Lexer, Token};
use crate::matrix::Matrix;
use crate::object::Object;
use crate::parser::ParseError;
use crate::value::{Number, Value};
use std::cmp::Ordering;
use std::collections::HashSet;
@@ -80,6 +81,17 @@ pub fn classify_reducer(source: &str, bindings: impl ValueProvider) -> Option<Re
})
}
/// Why an input string isn't a lone reducer token, for a host input taking only one, or `None` when it is one or is blank.
pub fn reducer_error(source: &str) -> Option<ParseError> {
if source.trim().is_empty() || classify_reducer(source, NothingMap).is_some() {
return None;
}
// The whole source is wrong rather than any part of it, so the error spans all of it but the whitespace around it
let start = source.len() - source.trim_start().len();
Some(ParseError::lone_reducer_expected(start..source.trim_end().len()))
}
impl Reducer {
/// Evaluates this reducer across the given items, or `None` for an ill-formed application, like a NaN item, a fold of an
/// empty list under an operator with no identity element, or an indeterminate result, since no operation produces NaN.
@@ -87,8 +99,69 @@ impl Reducer {
if items.iter().any(|Value::Number(number)| number.is_nan()) {
return None;
}
let Value::Number(result) = self.evaluate_unsettled(items)?;
(!result.is_nan()).then(|| Value::Number(result.canonical()))
settle(self.evaluate_unsettled(items)?)
}
/// Evaluates this reducer across each leading run of the items, the first item alone, then the first two, and so on, giving for
/// each run exactly what [`Self::evaluate`] gives for it. Once a fold step fails, every longer run fails with it.
pub fn evaluate_running(&self, items: &[Value]) -> Vec<Option<Value>> {
// A NaN item makes every run containing it ill-formed
let valid_count = items.iter().position(|Value::Number(number)| number.is_nan()).unwrap_or(items.len());
let valid_items = &items[..valid_count];
// Items take canonical form first, as in `evaluate_unsettled`
let numbers = valid_items.iter().map(|Value::Number(number)| number.canonical());
let mut results: Vec<Option<Value>> = match self {
// O(n) by folding each item into the previous run's result
Reducer::FoldLeft(op) => {
let mut accumulated: Option<Number> = None;
numbers
.enumerate()
.map(|(index, item)| {
accumulated = match index {
// A lone item meets no operator, so logic checks it is a truth value here
0 if matches!(op, BinaryOp::And | BinaryOp::Or) => item.as_bool().map(|_| item),
0 => Some(item),
_ => accumulated.and_then(|accumulated| accumulated.binary_op(*op, item)),
};
accumulated.and_then(|accumulated| settle(Value::Number(accumulated)))
})
.collect()
}
// O(n) by checking only the newest adjacent pair against the previous run's result
Reducer::ChainAdjacent(op) => {
let mut satisfied = Some(true);
let mut previous = None;
numbers
.map(|number| {
if let Some(previous) = previous {
satisfied = satisfied.and_then(|satisfied| adjacent_holds(*op, previous, number).map(|holds| satisfied && holds));
}
previous = Some(number);
satisfied.and_then(|satisfied| settle(Value::from_bool(satisfied)))
})
.collect()
}
// O(n) by keeping the set of items seen so far
Reducer::ChainDistinct => {
let mut seen = HashSet::new();
let mut distinct = true;
numbers
.map(|number| {
distinct &= seen.insert(CanonicalBits::of(number));
settle(Value::from_bool(distinct))
})
.collect()
}
// O(n²) since `^` groups from the right and a variadic builtin reads its whole list, so no run builds on a shorter one's result
Reducer::FoldRight(_) | Reducer::Function { .. } => (1..=valid_count).map(|count| self.evaluate(&valid_items[..count])).collect(),
};
results.resize(items.len(), None);
results
}
fn evaluate_unsettled(&self, items: &[Value]) -> Option<Value> {
@@ -138,13 +211,7 @@ impl Reducer {
match self {
Reducer::FoldLeft(op) => {
let combine: fn(Matrix, Matrix) -> Option<Matrix> = match op {
BinaryOp::Add => |a, b| Some(a + b),
BinaryOp::Sub => |a, b| Some(a - b),
BinaryOp::Mul => |a, b| Some(a.compose(b)),
BinaryOp::Div => |a, b| Some(a.compose(b.inverse()?)),
_ => return None,
};
let combine = matrix_fold_step(*op)?;
let mut iter = items.iter().copied();
let Some(first) = iter.next() else {
@@ -161,6 +228,60 @@ impl Reducer {
Reducer::FoldRight(_) | Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => None,
}
}
/// Evaluates this reducer across each leading run of the matrices, the first alone, then the first two, and so on, giving for
/// each run exactly what [`Self::evaluate_matrices`] gives for it. Under `*`, each result is where that many steps end up.
pub fn evaluate_running_matrices(&self, items: &[Matrix]) -> Vec<Option<Object>> {
// A NaN item makes every run containing it ill-formed
let valid_count = items.iter().position(|matrix| matrix.is_nan()).unwrap_or(items.len());
let valid_items = &items[..valid_count];
let mut results: Vec<Option<Object>> = match self {
// O(n) by folding each matrix into the previous run's result
Reducer::FoldLeft(op) => match matrix_fold_step(*op) {
Some(combine) => {
let mut accumulated: Option<Matrix> = None;
valid_items
.iter()
.enumerate()
.map(|(index, &matrix)| {
accumulated = match index {
0 => Some(matrix),
_ => accumulated.and_then(|accumulated| settle_matrix(combine(accumulated, matrix)?).ok()),
};
accumulated.map(Object::from)
})
.collect()
}
None => Vec::new(),
},
// O(n²) since a matrix function is an opaque function of its whole list
Reducer::Function { over_matrices, .. } => (1..=valid_count).map(|count| over_matrices.and_then(|function| function(&valid_items[..count]))).collect(),
Reducer::FoldRight(_) | Reducer::ChainAdjacent(_) | Reducer::ChainDistinct => Vec::new(),
};
results.resize(items.len(), None);
results
}
}
/// A reducer's result in canonical form, or `None` for an indeterminate result, since no operation produces NaN.
fn settle(Value::Number(result): Value) -> Option<Value> {
(!result.is_nan()).then(|| Value::Number(result.canonical()))
}
/// How a fold combines its running matrix with the next one: `*` and `/` compose in list order, while `+` and `-` are pointwise.
/// Any other operator has no action across matrices.
fn matrix_fold_step(op: BinaryOp) -> Option<fn(Matrix, Matrix) -> Option<Matrix>> {
Some(match op {
BinaryOp::Add => |a, b| Some(a + b),
BinaryOp::Sub => |a, b| Some(a - b),
BinaryOp::Mul => |a, b| Some(a.compose(b)),
BinaryOp::Div => |a, b| Some(a.compose(b.inverse()?)),
_ => return None,
})
}
/// Whether every adjacent pair of items satisfies the chain's relation: true over zero or one items, since no pair exists to fail
@@ -430,4 +551,35 @@ mod tests {
}
assert_eq!(reduce("+", &[scale, Matrix::IDENTITY.translated(Quaternion::splat(f64::NAN))]), None);
}
#[test]
fn running_results_match_each_leading_run() {
// Between them, the lists hold repeats, descents, a zero divisor, a NaN, and items that aren't truth values
let lists: [&[f64]; 6] = [&[3., 1., 4., 1., 5.], &[2., 0., 3.], &[1., 1., 0., 1.], &[0.5, 2., -1., 2.], &[1., f64::NAN, 2.], &[]];
for source in ["+", "-", "*", "/", "&&", "||", "^", "<", "<=", "==", "!=", "min", "max", "mean", "count"] {
let reducer = classify_reducer(source, NothingMap).unwrap();
for list in lists {
let items: Vec<Value> = list.iter().map(|&item| Value::from_f64(item)).collect();
let expected: Vec<Option<Value>> = (1..=items.len()).map(|count| reducer.evaluate(&items[..count])).collect();
assert_eq!(reducer.evaluate_running(&items), expected, "`{source}` over {list:?}");
}
}
}
#[test]
fn running_matrix_results_match_each_leading_run() {
let scale = Matrix::scale(Quaternion::new(2., 0., 0., 0.));
let shift = Matrix::IDENTITY.translated(Quaternion::I);
let nan = Matrix::IDENTITY.translated(Quaternion::splat(f64::NAN));
// Between them, the lists hold a singular divisor and a NaN
let lists: [&[Matrix]; 4] = [&[scale, shift, scale, shift], &[shift, Matrix::ZERO, scale], &[scale, nan, shift], &[]];
for source in ["*", "/", "+", "-", "mean", "count", "<", "min"] {
let reducer = classify_reducer(source, NothingMap).unwrap();
for (list_index, list) in lists.into_iter().enumerate() {
let expected: Vec<Option<Object>> = (1..=list.len()).map(|count| reducer.evaluate_matrices(&list[..count])).collect();
assert_eq!(reducer.evaluate_running_matrices(list), expected, "`{source}` over list {list_index}");
}
}
}
}
@@ -149,7 +149,7 @@ struct MmappedBytes(MemoryMappedFile);
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice(0, len) {
match self.0.as_slice_bytes(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
@@ -0,0 +1,446 @@
use crate::document::value::TaggedValue;
use crate::document::*;
use core_types::{ProtoNodeIdentifier, concrete};
use rustc_hash::FxHashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
/// Hash two IDs together, returning a new ID that is always consistent for two input IDs in a specific order.
/// This is used during [`NodeNetwork::flatten`] in order to ensure consistent yet non-conflicting IDs for inner networks.
fn merge_ids(a: NodeId, b: NodeId) -> NodeId {
let mut hasher = DefaultHasher::new();
a.hash(&mut hasher);
b.hash(&mut hasher);
NodeId(hasher.finish())
}
impl DocumentNode {
/// Locate the input that is a [`NodeInput::Import`] at index `offset` and replace it with a [`NodeInput::Node`].
pub fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize) {
let (index, _) = self
.inputs
.iter()
.enumerate()
.nth(offset)
.unwrap_or_else(|| panic!("no network input found for {self:#?} and offset: {offset}"));
self.inputs[index] = NodeInput::Node { node_id, output_index };
}
}
impl NodeNetwork {
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and finding monitor nodes.
///
/// Table entries are not visited, since each instance gets its paths when [`Self::flatten`] copies the entry.
pub fn generate_node_paths(&mut self, prefix: &[NodeId]) {
let definitions = std::mem::take(&mut self.definitions);
self.generate_node_paths_with(prefix, &definitions);
self.definitions = definitions;
}
fn generate_node_paths_with(&mut self, prefix: &[NodeId], definitions: &FxHashMap<NetworkId, NodeNetwork>) {
for (node_id, node) in &mut self.nodes {
let mut new_path = prefix.to_vec();
if !self.generated {
new_path.push(*node_id);
}
if let DocumentNodeImplementation::Network(network) = &mut node.implementation {
network.generate_node_paths_with(new_path.as_slice(), definitions);
}
if node.original_location.path.is_some() {
log::warn!("Attempting to overwrite node path");
} else {
node.original_location.path = Some(new_path);
let output_count = output_count_in(&node.implementation, definitions).unwrap_or(1);
node.original_location.dependants = vec![Vec::new(); output_count];
}
}
}
/// A copy of table entry `id` for the instance at `instance_path`, with its node paths and dependant slots in place.
fn instantiate_definition(&self, id: NetworkId, instance_path: &[NodeId]) -> Option<NodeNetwork> {
let mut instance = self.definitions.get(&id)?.clone();
instance.generate_node_paths_with(instance_path, &self.definitions);
Some(instance)
}
pub fn populate_dependants(&mut self) {
let mut dep_changes = Vec::new();
for (node_id, node) in &mut self.nodes {
let len = node.original_location.dependants.len();
let output_count = output_count_in(&node.implementation, &self.definitions).unwrap_or(len);
node.original_location.dependants.extend(vec![vec![]; output_count.max(len) - len]);
for input in &node.inputs {
if let NodeInput::Node { node_id: dep_id, output_index, .. } = input {
dep_changes.push((*dep_id, *output_index, *node_id));
}
}
}
// println!("{:#?}", self.nodes.get(&NodeId(1)));
for (dep_id, output_index, node_id) in dep_changes {
let node = self.nodes.get_mut(&dep_id).expect("Encountered invalid node id");
let len = node.original_location.dependants.len();
// One must be added to the index to find the length because indexing in rust starts from 0.
node.original_location.dependants.extend(vec![vec![]; (output_index + 1).max(len) - len]);
// println!("{node_id} {output_index} {}", node.implementation.output_count());
node.original_location.dependants[output_index].push(node_id);
}
}
/// Replace all references in any node of `old_input` with `new_input`
fn replace_node_inputs(&mut self, node_id: NodeId, old_input: (NodeId, usize), new_input: (NodeId, usize)) {
let Some(node) = self.nodes.get_mut(&node_id) else { return };
node.inputs.iter_mut().for_each(|input| {
if let NodeInput::Node { node_id: input_id, output_index, .. } = input
&& (*input_id, *output_index) == old_input
{
(*input_id, *output_index) = new_input;
}
});
}
/// Replace all references in any node of `old_output` with `new_output`
fn replace_network_outputs(&mut self, old_output: &NodeInput, new_output: &NodeInput) {
for output in self.exports.iter_mut() {
if *output == *old_output {
*output = new_output.clone();
}
}
}
/// Removes unused nodes from the graph. Returns a list of booleans which represent if each of the inputs have been retained.
pub fn remove_dead_nodes(&mut self, number_of_inputs: usize) -> Vec<bool> {
// Take all the nodes out of the nodes list
let mut old_nodes = std::mem::take(&mut self.nodes);
let mut stack = self
.exports
.iter()
.filter_map(|output| if let NodeInput::Node { node_id, .. } = output { Some(*node_id) } else { None })
.collect::<Vec<_>>();
while let Some(node_id) = stack.pop() {
let Some((node_id, mut document_node)) = old_nodes.remove_entry(&node_id) else {
continue;
};
// Remove dead nodes from child networks
if let DocumentNodeImplementation::Network(network) = &mut document_node.implementation {
// Remove inputs to the parent node if they have been removed from the child
let mut retain_inputs = network.remove_dead_nodes(document_node.inputs.len()).into_iter();
document_node.inputs.retain(|_| retain_inputs.next().unwrap_or(true))
}
// Visit all nodes that this node references
stack.extend(
document_node
.inputs
.iter()
.filter_map(|input| if let NodeInput::Node { node_id, .. } = input { Some(node_id) } else { None }),
);
// Add the node back to the list of nodes
self.nodes.insert(node_id, document_node);
}
// Remove references to nodes that have been deleted
for node in self.nodes.values_mut() {
for dependants in &mut node.original_location.dependants {
dependants.retain(|dependant| !old_nodes.contains_key(dependant));
}
}
// Check if inputs are used and store for return value
let mut are_inputs_used = vec![false; number_of_inputs];
for node in &self.nodes {
for node_input in &node.1.inputs {
if let NodeInput::Import { import_index, .. } = node_input
&& let Some(is_used) = are_inputs_used.get_mut(*import_index)
{
*is_used = true;
}
}
}
are_inputs_used
}
/// Remove all nodes that contain [`DocumentNodeImplementation::Network`] by moving the nested nodes into the parent network.
pub fn flatten(&mut self, node_id: NodeId) {
self.flatten_with_fns(node_id, merge_ids, NodeId::new)
}
/// Remove all nodes that contain [`DocumentNodeImplementation::Network`] by moving the nested nodes into the parent network.
pub fn flatten_with_fns(&mut self, node_id: NodeId, map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy, gen_id: impl Fn() -> NodeId + Copy) {
let Some((id, mut node)) = self.nodes.remove_entry(&node_id) else {
warn!("The node which was supposed to be flattened does not exist in the network, id {node_id} network {self:#?}");
return;
};
// If the node is hidden, replace it with a passthrough node
let passthrough_node = DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER);
if !node.visible && node.implementation != passthrough_node {
node.implementation = passthrough_node;
// A node without inputs has nothing to pass through, so it passes through the unit value instead
if node.inputs.is_empty() {
node.inputs.push(NodeInput::value(TaggedValue::None, false));
}
// Keep only the primary input, which the passthrough forwards
let removed_inputs = node.inputs.split_off(1);
// Remove the dependants on the ignored inputs
for removed_input in removed_inputs {
if let NodeInput::Node { node_id, output_index } = removed_input
&& let Some(former_dependency) = self.nodes.get_mut(&node_id)
// Ensure that the other node inputs do not also reference the dependency
&& !node.inputs.iter().any(|input| matches!(input, NodeInput::Node { node_id: other, .. } if *other == node_id))
{
former_dependency.original_location.dependants[output_index].retain(|&dependant| dependant != id);
}
}
// Removing the passthrough later splices its input into its consumers, which accept only node wires, so an unwired input becomes a value node
let path = node.original_location.path.clone().unwrap_or_default();
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id);
node.call_argument = concrete!(());
self.nodes.insert(id, node);
return;
}
let path = node.original_location.path.clone().unwrap_or_default();
// Replace value inputs with dedicated value nodes
if node.implementation != DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")) {
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, gen_id, map_ids, id);
}
if let DocumentNodeImplementation::Definition(definition) = node.implementation {
let Some(instance) = self.instantiate_definition(definition, &path) else {
log::error!("Node {id} names definition {definition:?}, which the definitions table lacks");
self.nodes.insert(id, node);
return;
};
node.implementation = DocumentNodeImplementation::Network(instance);
}
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
// If the node is not a network, it is a primitive node and can be inserted into the network as is.
assert!(!self.nodes.contains_key(&id), "Trying to insert a node into the network caused an id conflict");
self.nodes.insert(id, node);
return;
};
debug_assert!(
node.compile_metadata.is_none(),
"Network {id} should not have compile metadata: {compile_metadata:#?}",
compile_metadata = node.compile_metadata
);
// Replace value and reflection imports with value nodes, added inside nested network
Self::replace_value_inputs_with_nodes(
&mut inner_network.exports,
&mut inner_network.nodes,
node.original_location.path.as_ref().unwrap_or(&vec![]),
gen_id,
map_ids,
id,
);
// Connect all network inputs to either the parent network nodes, or newly created value nodes for the parent node.
inner_network.map_ids(|inner_id| map_ids(id, inner_id));
inner_network.populate_dependants();
let new_nodes = inner_network.nodes.keys().cloned().collect::<Vec<_>>();
for (key, value) in inner_network.scope_injections.into_iter() {
match self.scope_injections.entry(key) {
std::collections::hash_map::Entry::Occupied(o) => {
log::warn!("Found duplicate scope injection for key {}, ignoring", o.key());
}
std::collections::hash_map::Entry::Vacant(v) => {
v.insert(value);
}
}
}
// Match the document node input and the inputs of the inner network
for (nested_node_id, mut nested_node) in inner_network.nodes.into_iter() {
for (nested_input_index, nested_input) in nested_node.clone().inputs.iter().enumerate() {
if let NodeInput::Import { import_index, .. } = nested_input {
let parent_input = node
.inputs
.get(*import_index)
.unwrap_or_else(|| panic!("Import index {import_index} of network node implementation {:?} should always exist", nested_node.implementation));
match *parent_input {
// If the input to self is a node, connect the corresponding output of the inner network to it
NodeInput::Node { node_id, output_index } => {
nested_node.populate_first_network_input(node_id, output_index, nested_input_index);
let input_node = self.nodes.get_mut(&node_id).unwrap_or_else(|| panic!("Unable to find input node {node_id:?}"));
input_node.original_location.dependants[output_index].push(nested_node_id);
}
NodeInput::Import { import_index, .. } => {
let parent_input_index = import_index;
let Some(NodeInput::Import { import_index, .. }) = nested_node.inputs.get_mut(nested_input_index) else {
log::error!("Nested node should have a network input");
continue;
};
*import_index = parent_input_index;
}
NodeInput::Value { .. } => unreachable!("Value inputs should have been replaced with value nodes"),
NodeInput::Scope(_) => unreachable!("Scope inputs should have been resolved by resolve_scope_inputs_recursive before flattening"),
NodeInput::Reflection(_) => unreachable!("Reflection inputs should have been replaced with value nodes"),
}
}
}
self.nodes.insert(nested_node_id, nested_node);
}
// Remove the newly flattened node from the dependants
for parent_input in &node.inputs {
if let NodeInput::Node { node_id, output_index } = *parent_input
&& let Some(input_node) = self.nodes.get_mut(&node_id)
{
input_node.original_location.dependants[output_index].retain(|&dependant| dependant != id);
}
}
// TODO: Add support for flattening exports that are NodeInput::Import (https://github.com/GraphiteEditor/Graphite/issues/1762)
self.replace_node_with_its_exports(id, &node.original_location, &inner_network.exports);
for node_id in new_nodes {
self.flatten_with_fns(node_id, map_ids, gen_id);
}
}
/// Connect all nodes that were previously connected to this node to the nodes of the inner network
fn replace_node_with_its_exports(&mut self, id: NodeId, original_location: &OriginalLocation, exports: &[NodeInput]) {
for (i, export) in exports.iter().enumerate() {
if let NodeInput::Node { node_id, output_index, .. } = &export {
for deps in &original_location.dependants {
for dep in deps {
self.replace_node_inputs(*dep, (id, i), (*node_id, *output_index));
}
}
if let Some(new_output_node) = self.nodes.get_mut(node_id) {
for dep in &original_location.dependants[i] {
new_output_node.original_location.dependants[*output_index].push(*dep);
}
// Remove references from dependants on wrapper
new_output_node.original_location.dependants[*output_index].retain(|&dependant| dependant != id);
}
}
self.replace_network_outputs(&NodeInput::node(id, i), export);
}
}
#[inline(never)]
fn replace_value_inputs_with_nodes(
inputs: &mut [NodeInput],
collection: &mut FxHashMap<NodeId, DocumentNode>,
path: &[NodeId],
gen_id: impl Fn() -> NodeId + Copy,
map_ids: impl Fn(NodeId, NodeId) -> NodeId + Copy,
id: NodeId,
) {
// Replace value exports and imports with value nodes, added inside the nested network
for export in inputs {
let previous_export = std::mem::replace(export, NodeInput::import(concrete!(()), 0));
let (tagged_value, exposed) = match previous_export {
NodeInput::Value { tagged_value, exposed } => (tagged_value, exposed),
NodeInput::Reflection(reflect) => match reflect {
DocumentNodeMetadata::DocumentNodePath => (TaggedValue::NodeIdPath(core_types::list::NodeIdPath::from(path.to_vec())).into(), false),
DocumentNodeMetadata::SourceId => (TaggedValue::SourceId(core_types::SourceId::from_path(path)).into(), false),
},
previous_export => {
*export = previous_export;
continue;
}
};
let value_node_id = gen_id();
let merged_node_id = map_ids(id, value_node_id);
let mut original_location = OriginalLocation {
path: Some(path.to_vec()),
dependants: vec![vec![id]],
..Default::default()
};
if let Some(path) = &mut original_location.path {
path.push(value_node_id);
}
collection.insert(
merged_node_id,
DocumentNode {
inputs: vec![NodeInput::Value { tagged_value, exposed }],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location,
..Default::default()
},
);
*export = NodeInput::Node {
node_id: merged_node_id,
output_index: 0,
};
}
}
fn remove_passthrough_node(&mut self, passthrough_id: NodeId) {
let node = self.nodes.remove(&passthrough_id).unwrap_or_else(|| panic!("Node with id {passthrough_id} does not exist"));
let implementation = &node.implementation;
assert!(
matches!(implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::passthrough::IDENTIFIER),
"remove_passthrough_node was given a node {implementation:?} and id {passthrough_id:?}",
);
assert_eq!(node.inputs.len(), 1, "Passthrough node has more than one input");
// Consider the upstream node (the input to the passthrough)
if let NodeInput::Node {
node_id: upstream_node_id,
output_index: upstream_output_index,
..
} = node.inputs[0]
&& let Some(upstream_node) = self.nodes.get_mut(&upstream_node_id)
{
let dependants_of_upstream = &mut upstream_node.original_location.dependants[upstream_output_index];
// Add our dependants to the list of dependants
dependants_of_upstream.extend(node.original_location.dependants[0].iter().copied());
// Remove ourselves from the list of dependants
dependants_of_upstream.retain(|&dependant| dependant != passthrough_id);
};
// Check if the passthrough output is connected to a network export
for node_input in self.exports.iter_mut() {
if matches!(node_input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) {
*node_input = node.inputs[0].clone();
}
}
// Look at all downstream nodes
for &dependant_id in &node.original_location.dependants[0] {
let Some(dependant_node) = self.nodes.get_mut(&dependant_id) else {
error!("remove_passthrough_node got a dependant id {dependant_id:?} that did not exist in the network\n{self:#?}");
continue;
};
for input in dependant_node.inputs.iter_mut() {
if matches!(input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) {
*input = node.inputs[0].clone();
}
}
}
}
/// Strips out all [`graphene_core::ops::PassthroughNode`]s.
pub fn remove_all_passthrough_nodes(&mut self) {
let passthrough_nodes = self
.nodes
.iter()
.filter(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(ident) if ident == &graphene_core::ops::passthrough::IDENTIFIER))
.map(|(id, _)| *id)
.collect::<Vec<_>>();
for id in passthrough_nodes {
self.remove_passthrough_node(id);
}
}
}
@@ -0,0 +1,310 @@
use crate::document::document_tests::add_network;
use crate::document::value::TaggedValue;
use crate::document::*;
use crate::proto::{ConstructionArgs, ProtoNetwork};
use core_types::{ProtoNodeIdentifier, concrete};
use std::sync::atomic::AtomicU64;
/// Generates IDs from a counter all tests share, so the IDs a test gets depend on what else runs in parallel.
fn gen_node_id() -> NodeId {
static NODE_ID: AtomicU64 = AtomicU64::new(4);
NodeId(NODE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst))
}
#[test]
fn flatten_add() {
let mut network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [(
NodeId(1),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::Network(add_network()),
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
network.populate_dependants();
// A counter of its own, since the expected network names the nodes by the IDs it generates
let next_id = AtomicU64::new(4);
let gen_id = || NodeId(next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst));
network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_id);
let expected = flatten_add_expected();
println!("{expected:#?}");
println!("{network:#?}");
assert_eq!(expected, network);
}
fn flatten_add_expected() -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(11), 0)],
nodes: [
(
NodeId(10),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::node(NodeId(14), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
original_location: OriginalLocation {
dependants: vec![vec![NodeId(11)]],
..Default::default()
},
..Default::default()
},
),
(
NodeId(14),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(4)]),
dependants: vec![vec![NodeId(10)]],
..Default::default()
},
..Default::default()
},
),
(
NodeId(11),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(10), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")),
original_location: OriginalLocation {
dependants: vec![vec![]],
..Default::default()
},
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
fn two_node_passthrough() -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)],
nodes: [
(
NodeId(1),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(i64), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
..Default::default()
},
),
(
NodeId(2),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(i64), 1)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
fn output_duplicate(network_outputs: Vec<NodeInput>, result_node_input: NodeInput) -> NodeNetwork {
let mut network = NodeNetwork {
exports: network_outputs,
nodes: [
(
NodeId(1),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Number(1.), false), NodeInput::value(TaggedValue::Number(2.), false)],
implementation: DocumentNodeImplementation::Network(two_node_passthrough()),
..Default::default()
},
),
(
NodeId(2),
DocumentNode {
inputs: vec![result_node_input],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
let _new_ids = 101..;
network.populate_dependants();
network.flatten_with_fns(NodeId(1), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), || NodeId(10000));
network.validate_dependants();
network.flatten_with_fns(NodeId(2), |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), || NodeId(10001));
network.validate_dependants();
network.remove_dead_nodes(0);
network.validate_dependants();
network
}
#[test]
fn simple_duplicate() {
let result = output_duplicate(vec![NodeInput::node(NodeId(1), 0)], NodeInput::node(NodeId(1), 0));
println!("{result:#?}");
result.validate_dependants();
assert_eq!(result.exports.len(), 1, "The number of outputs should remain as 1");
assert_eq!(result.exports[0], NodeInput::node(NodeId(11), 0), "The outer network output should be from a duplicated inner network");
let mut ids = result.nodes.keys().copied().collect::<Vec<_>>();
ids.sort();
assert_eq!(ids, vec![NodeId(11), NodeId(10010)], "Should only contain passthrough and values");
}
fn passthrough_network() -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(10), 0)],
nodes: [
(
NodeId(1),
DocumentNode {
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(5), 0); 3],
..Default::default()
}),
..Default::default()
},
),
(
NodeId(10),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(1), 2)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
..Default::default()
},
),
(
NodeId(11),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(10), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("add")),
..Default::default()
},
),
(
NodeId(12),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(10), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("double")),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
#[test]
fn remove_passthrough_node() {
let mut network = passthrough_network();
network.generate_node_paths(&[]);
network.populate_dependants();
network.remove_all_passthrough_nodes();
assert_eq!(network.nodes.len(), 3);
let mut generator_dependants = network.nodes.get(&NodeId(1)).unwrap().original_location.dependants[2].clone();
generator_dependants.sort();
generator_dependants.dedup();
assert_eq!(generator_dependants, vec![NodeId(11), NodeId(12)]);
let add_inputs = &network.nodes.get(&NodeId(11)).unwrap().inputs;
assert_eq!(add_inputs, &vec![NodeInput::node(NodeId(1), 2); 2]);
let double_inputs = &network.nodes.get(&NodeId(12)).unwrap().inputs;
assert_eq!(double_inputs, &vec![NodeInput::node(NodeId(1), 2); 1]);
assert_eq!(&network.exports, &vec![NodeInput::node(NodeId(1), 2), NodeInput::node(NodeId(11), 0), NodeInput::node(NodeId(1), 2)]);
network.validate_dependants();
}
/// A hidden node with nothing wired into it (a layer chain's first node, or a generator) feeding a node with several inputs.
fn hidden_source_network(source_inputs: Vec<NodeInput>) -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
(
NodeId(1),
DocumentNode {
inputs: source_inputs,
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Source")),
visible: false,
..Default::default()
},
),
(
NodeId(2),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(2.), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::Consumer")),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
// Flattens and strips passthroughs as the compiler does, then resolves the proto nodes, where an unwired input would panic
fn compile_hidden_source(mut network: NodeNetwork) -> ProtoNetwork {
network.generate_node_paths(&[]);
network.populate_dependants();
let ids: Vec<_> = network.nodes.keys().copied().collect();
ids.into_iter()
.for_each(|id| network.flatten_with_fns(id, |self_id, inner_id| NodeId(self_id.0 * 10 + inner_id.0), gen_node_id));
network.remove_all_passthrough_nodes();
network.into_proto_networks().next().expect("The network should give a proto network")
}
#[test]
fn hidden_node_with_an_unwired_input_passes_its_value() {
let proto_network = compile_hidden_source(hidden_source_network(vec![NodeInput::value(TaggedValue::Number(1.), true)]));
// The consumer's first input is now a value node holding the hidden node's unwired value
let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain");
let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else {
panic!("The consumer should take node inputs")
};
let value_node = proto_network
.nodes
.iter()
.find(|(id, _)| *id == inputs[0])
.map(|(_, node)| node)
.expect("The consumer's first input should be a node");
assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::Number(1.)));
}
#[test]
fn hidden_node_without_inputs_passes_the_unit_value() {
let proto_network = compile_hidden_source(hidden_source_network(vec![]));
let consumer = proto_network.nodes.iter().find(|(id, _)| *id == NodeId(2)).map(|(_, node)| node).expect("The consumer should remain");
let ConstructionArgs::Nodes(inputs) = &consumer.construction_args else {
panic!("The consumer should take node inputs")
};
let value_node = proto_network
.nodes
.iter()
.find(|(id, _)| *id == inputs[0])
.map(|(_, node)| node)
.expect("The consumer's first input should be a node");
assert!(matches!(&value_node.construction_args, ConstructionArgs::Value(value) if **value == TaggedValue::None));
}
@@ -0,0 +1,148 @@
use crate::document::value::TaggedValue;
use crate::document::*;
use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
use core_types::{ProtoNodeIdentifier, generic};
impl DocumentNode {
pub(crate) fn resolve_proto_node(self) -> ProtoNode {
let DocumentNodeImplementation::ProtoNode(identifier) = self.implementation else {
unreachable!("tried to resolve not flattened node on resolved node {self:?}");
};
assert!(!self.inputs.iter().any(|input| matches!(input, NodeInput::Import { .. })), "received non-resolved input");
let mut construction_args = ConstructionArgs::Nodes(vec![]);
// If we have one input of the type value, set it as the construction args
if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Value(tagged_value.clone());
}
if let ConstructionArgs::Nodes(nodes) = &mut construction_args {
nodes.extend(self.inputs.iter().map(|input| match input {
NodeInput::Node { node_id, .. } => *node_id,
_ => unreachable!(),
}));
}
ProtoNode {
identifier,
call_argument: self.call_argument,
construction_args,
original_location: self.original_location,
skip_deduplication: self.skip_deduplication,
compile_metadata: self.compile_metadata.unwrap_or_default(),
upstream_context_features: Default::default(),
}
}
}
impl NodeNetwork {
/// Converts the `DocumentNode`s with a `DocumentNodeImplementation::Extract` into a `ClonedNode` that returns
/// the `DocumentNode` specified by the single `NodeInput::Node`.
/// The referenced node is removed from the network, and any `NodeInput::Node`s used by the referenced node are replaced with a generically typed network input.
pub fn resolve_extract_nodes(&mut self) {
let mut extraction_nodes = self
.nodes
.iter()
.filter(|(_, node)| matches!(node.implementation, DocumentNodeImplementation::Extract))
.map(|(id, node)| (*id, node.clone()))
.collect::<Vec<_>>();
self.nodes.retain(|_, node| !matches!(node.implementation, DocumentNodeImplementation::Extract));
for (_, node) in &mut extraction_nodes {
assert_eq!(node.inputs.len(), 1);
let NodeInput::Node { node_id, output_index, .. } = node.inputs.pop().unwrap() else {
panic!("Extract node has no input, inputs: {:?}", node.inputs);
};
assert_eq!(output_index, 0);
// TODO: check if we can read lambda checking?
let mut input_node = self.nodes.remove(&node_id).unwrap();
node.implementation = DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode"));
if let Some(input) = input_node.inputs.get_mut(0) {
*input = match &input {
NodeInput::Node { .. } => NodeInput::import(generic!(T), 0),
ni => NodeInput::import(ni.ty(), 0),
};
}
for input in input_node.inputs.iter_mut() {
if let NodeInput::Node { .. } = input {
*input = NodeInput::import(generic!(T), 0)
}
}
node.inputs = vec![NodeInput::value(TaggedValue::DocumentNode(input_node), false)];
}
self.nodes.extend(extraction_nodes);
}
/// Creates a proto network for evaluating each output of this network.
pub fn into_proto_networks(self) -> impl Iterator<Item = ProtoNetwork> {
#[cfg(test)]
self.validate_dependants();
let nodes: Vec<_> = self.nodes.into_iter().map(|(id, node)| (id, node.resolve_proto_node())).collect();
// Create a network to evaluate each output
if self.exports.len() == 1
&& let NodeInput::Node { node_id, .. } = self.exports[0]
{
return vec![ProtoNetwork {
inputs: Vec::new(),
output: node_id,
nodes,
}]
.into_iter();
}
// Create a network to evaluate each output
let networks: Vec<_> = self
.exports
.into_iter()
.filter_map(move |output| {
if let NodeInput::Node { node_id, .. } = output {
Some(ProtoNetwork {
inputs: Vec::new(), // Inputs field is not used. Should be deleted
// inputs: vec![input_node.expect("Set node should always exist")],
// inputs: self.imports.clone(),
output: node_id,
nodes: nodes.clone(),
})
} else {
None
}
})
.collect();
networks.into_iter()
}
/// Ensure the cached list of dependants exactly matches the real list of dependants
#[cfg(test)]
pub(crate) fn validate_dependants(&self) {
use std::collections::{HashMap, HashSet};
let mut dependants = HashMap::<NodeId, Vec<HashSet<NodeId>>>::new();
for (&id, node) in self.nodes.iter() {
dependants.insert(id, vec![HashSet::new(); node.implementation.output_count()]);
}
for (&id, node) in self.nodes.iter() {
for input in &node.inputs {
if let NodeInput::Node { node_id, output_index } = *input {
dependants.get_mut(&node_id).unwrap()[output_index].insert(id);
}
}
}
for (&id, node) in self.nodes.iter() {
for output_index in 0..node.implementation.output_count() {
let real_dependants = &dependants.get(&id).unwrap()[output_index];
let listed_dependants = node.original_location.dependants.get(output_index).map_or_default(|d| d.iter().copied().collect::<HashSet<_>>());
assert_eq!(
real_dependants, &listed_dependants,
"real {:?} should equal listed {:?} for output index {} in id {:?} in network:\n{:#?}",
real_dependants, listed_dependants, output_index, id, self
);
}
}
}
}
@@ -0,0 +1,165 @@
use crate::document::value::TaggedValue;
use crate::document::*;
use crate::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
use core_types::{Context, ProtoNodeIdentifier, concrete};
#[test]
fn extract_node() {
let passthrough_node = DocumentNode {
inputs: vec![],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::ops::passthrough::IDENTIFIER),
..Default::default()
};
// TODO: Extend test cases to test nested network
let mut extraction_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
passthrough_node.clone(),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::Extract,
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
};
extraction_network.resolve_extract_nodes();
assert_eq!(extraction_network.nodes.len(), 1);
let inputs = extraction_network.nodes.get(&NodeId(1)).unwrap().inputs.clone();
assert_eq!(inputs.len(), 1);
assert!(matches!(&inputs[0].as_value(), &Some(TaggedValue::DocumentNode(network), ..) if network == &passthrough_node));
}
#[test]
fn resolve_proto_node_add() {
let document_node = DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
call_argument: concrete!(i64),
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
..Default::default()
};
let proto_node = document_node.resolve_proto_node();
let reference = ProtoNode {
identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"),
call_argument: concrete!(i64),
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
..Default::default()
};
assert_eq!(proto_node, reference);
}
#[test]
fn resolve_flatten_add_as_proto_network() {
let construction_network = ProtoNetwork {
inputs: Vec::new(),
output: NodeId(11),
nodes: [
(
NodeId(10),
ProtoNode {
identifier: ProtoNodeIdentifier::new("core_types::structural::ConsNode"),
call_argument: concrete!(i64),
construction_args: ConstructionArgs::Nodes(vec![NodeId(14)]),
original_location: OriginalLocation {
path: Some(vec![NodeId(1), NodeId(0)]),
dependants: vec![vec![NodeId(11)]],
..Default::default()
},
..Default::default()
},
),
(
NodeId(11),
ProtoNode {
identifier: ProtoNodeIdentifier::new("core_types::ops::AddPairNode"),
call_argument: concrete!(Context),
construction_args: ConstructionArgs::Nodes(vec![NodeId(10)]),
original_location: OriginalLocation {
path: Some(vec![NodeId(1), NodeId(1)]),
dependants: vec![vec![]],
..Default::default()
},
..Default::default()
},
),
(
NodeId(14),
ProtoNode {
identifier: ProtoNodeIdentifier::new("core_types::value::ClonedNode"),
call_argument: concrete!(core_types::Context),
construction_args: ConstructionArgs::Value(TaggedValue::Integer(2).into()),
original_location: OriginalLocation {
path: Some(vec![NodeId(1), NodeId(4)]),
dependants: vec![vec![NodeId(10)]],
..Default::default()
},
..Default::default()
},
),
]
.into_iter()
.collect(),
};
let mut network = flat_network();
network.populate_dependants();
let mut resolved_network = network.into_proto_networks().collect::<Vec<_>>();
resolved_network[0].nodes.sort_unstable_by_key(|(id, _)| *id);
println!("{:#?}", resolved_network[0]);
println!("{construction_network:#?}");
pretty_assertions::assert_eq!(resolved_network[0], construction_network);
}
fn flat_network() -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(11), 0)],
nodes: [
(
NodeId(10),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(14), 0)],
call_argument: concrete!(i64),
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(1), NodeId(0)]),
..Default::default()
},
..Default::default()
},
),
(
NodeId(14),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(1), NodeId(4)]),
..Default::default()
},
..Default::default()
},
),
(
NodeId(11),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(10), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")),
original_location: OriginalLocation {
path: Some(vec![NodeId(1), NodeId(1)]),
..Default::default()
},
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
@@ -0,0 +1,10 @@
mod flatten;
mod lowering;
mod scope;
#[cfg(test)]
mod flatten_tests;
#[cfg(test)]
mod lowering_tests;
#[cfg(test)]
mod scope_tests;
@@ -0,0 +1,261 @@
use crate::document::value::TaggedValue;
use crate::document::*;
use core_types::{Cow, Type};
use rustc_hash::{FxHashMap, FxHashSet};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
/// Every table entry, each listed after the entries its nodes name. O(entries + nodes).
fn definitions_children_first(definitions: &FxHashMap<NetworkId, NodeNetwork>) -> Vec<NetworkId> {
fn visit_network(network: &NodeNetwork, definitions: &FxHashMap<NetworkId, NodeNetwork>, visited: &mut FxHashSet<NetworkId>, order: &mut Vec<NetworkId>) {
for node in network.nodes.values() {
match &node.implementation {
DocumentNodeImplementation::Definition(id) => visit_definition(*id, definitions, visited, order),
DocumentNodeImplementation::Network(nested) => visit_network(nested, definitions, visited, order),
_ => {}
}
}
}
fn visit_definition(id: NetworkId, definitions: &FxHashMap<NetworkId, NodeNetwork>, visited: &mut FxHashSet<NetworkId>, order: &mut Vec<NetworkId>) {
if !visited.insert(id) {
return;
}
if let Some(definition) = definitions.get(&id) {
visit_network(definition, definitions, visited, order);
}
order.push(id);
}
let mut ids: Vec<NetworkId> = definitions.keys().copied().collect();
ids.sort();
let mut visited = FxHashSet::default();
let mut order = Vec::with_capacity(ids.len());
for id in ids {
visit_definition(id, definitions, &mut visited, &mut order);
}
order
}
impl NodeNetwork {
/// Resolves each scope input to the node injecting it, adding imports to carry it into nested networks.
///
/// Each table entry is resolved once per scope context, children first: the keys an entry does not inject become its imports,
/// and every node naming the entry gets a matching scope input that its own network then resolves, so the nearest injection wins.
/// An entry reached from contexts that give a key different types is specialized into one entry per context.
pub fn resolve_scope_inputs(&mut self) {
let mut free_keys = FxHashMap::default();
for id in definitions_children_first(&self.definitions) {
let Some(definition) = self.definitions.get(&id) else { continue };
let keys = definition.free_scope_keys(&free_keys);
free_keys.insert(id, keys);
}
let originals = std::mem::take(&mut self.definitions);
let mut specializer = ScopeSpecializer {
originals: &originals,
free_keys: &free_keys,
base_signatures: FxHashMap::default(),
contexts: FxHashMap::default(),
specialized: FxHashMap::default(),
};
let root_chain = self.scope_injections.clone();
specializer.specialize(self, &root_chain);
let ScopeSpecializer {
contexts,
specialized: mut definitions,
..
} = specializer;
let mut import_counts = FxHashMap::default();
for network in std::iter::once(&*self).chain(definitions.values()) {
network.collect_instance_input_counts(&mut import_counts);
}
let mut forwarded: FxHashMap<NetworkId, Vec<NodeInput>> = FxHashMap::default();
for id in definitions_children_first(&definitions) {
let (Some(definition), Some(context)) = (definitions.get_mut(&id), contexts.get(&id)) else {
continue;
};
definition.append_forwarded_scopes(&forwarded);
// Stands in for an instance's inputs, so the forwarded keys become imports after the existing ones
let import_count = import_counts.get(&id).copied().unwrap_or_default();
let mut instance_inputs = vec![NodeInput::value(TaggedValue::None, false); import_count];
let outside = ScopeChain { scopes: context, parent: None };
definition.resolve_scope_inputs_impl(Some(&outside), &mut instance_inputs);
forwarded.insert(id, instance_inputs.split_off(import_count));
}
self.append_forwarded_scopes(&forwarded);
self.definitions = definitions;
let mut leftover = Vec::new();
self.resolve_scope_inputs_impl(None, &mut leftover);
assert!(leftover.is_empty(), "Unresolved scope keys at top level: {leftover:?}");
}
/// The scope keys this network reads, directly or through the networks it contains, without injecting them itself.
fn free_scope_keys(&self, entry_keys: &FxHashMap<NetworkId, FxHashSet<String>>) -> FxHashSet<String> {
let mut keys = FxHashSet::default();
for node in self.nodes.values() {
keys.extend(node.inputs.iter().filter_map(|input| match input {
NodeInput::Scope(key) => Some(key.to_string()),
_ => None,
}));
match &node.implementation {
DocumentNodeImplementation::Definition(id) => keys.extend(entry_keys.get(id).into_iter().flatten().cloned()),
DocumentNodeImplementation::Network(nested) => keys.extend(nested.free_scope_keys(entry_keys)),
_ => {}
}
}
keys.retain(|key| !self.scope_injections.contains_key(key));
keys
}
fn collect_instance_input_counts(&self, counts: &mut FxHashMap<NetworkId, usize>) {
for node in self.nodes.values() {
match &node.implementation {
DocumentNodeImplementation::Definition(id) => {
counts.entry(*id).or_insert(node.inputs.len());
}
DocumentNodeImplementation::Network(nested) => nested.collect_instance_input_counts(counts),
_ => {}
}
}
}
fn append_forwarded_scopes(&mut self, forwarded: &FxHashMap<NetworkId, Vec<NodeInput>>) {
for node in self.nodes.values_mut() {
match &mut node.implementation {
DocumentNodeImplementation::Definition(id) => node.inputs.extend(forwarded.get(id).into_iter().flatten().cloned()),
DocumentNodeImplementation::Network(nested) => nested.append_forwarded_scopes(forwarded),
_ => {}
}
}
}
fn resolve_scope_inputs_impl(&mut self, parent: Option<&ScopeChain<'_>>, network_inputs: &mut Vec<NodeInput>) {
let scope_chain = ScopeChain {
scopes: &self.scope_injections,
parent,
};
for node in self.nodes.values_mut() {
let DocumentNodeImplementation::Network(network) = &mut node.implementation else { continue };
network.resolve_scope_inputs_impl(Some(&scope_chain), &mut node.inputs);
}
let mut key_to_idx: FxHashMap<Cow<'static, str>, usize> = FxHashMap::default();
for node in self.nodes.values_mut() {
for input in node.inputs.iter_mut() {
let NodeInput::Scope(key) = input else { continue };
*input = match scope_chain.lookup(key) {
ScopeChainLookup::Current(node_id, _ty) => NodeInput::node(*node_id, 0),
ScopeChainLookup::Parent(_node_id, ty) => {
let import_index = *key_to_idx.entry(key.clone()).or_insert_with(|| {
let index = network_inputs.len();
network_inputs.push(NodeInput::Scope(key.clone()));
index
});
NodeInput::Import {
import_type: ty.clone(),
import_index,
}
}
ScopeChainLookup::None => panic!("Scope key `{key}` not found in any ancestor scope_injections"),
};
}
}
}
}
type ScopeInjections = FxHashMap<String, (NodeId, Type)>;
/// Gives every instance the entry matching the scope types its context provides, copying an entry for each further context.
struct ScopeSpecializer<'a> {
originals: &'a FxHashMap<NetworkId, NodeNetwork>,
free_keys: &'a FxHashMap<NetworkId, FxHashSet<String>>,
/// The signature of the first context reaching each original entry, which keeps the entry's ID.
base_signatures: FxHashMap<NetworkId, Vec<(String, Type)>>,
/// The injections each specialized entry resolves its free keys against.
contexts: FxHashMap<NetworkId, ScopeInjections>,
specialized: FxHashMap<NetworkId, NodeNetwork>,
}
impl ScopeSpecializer<'_> {
/// Points every instance in `network` at its specialization, where `chain` holds the nearest injection of every key visible in `network`.
fn specialize(&mut self, network: &mut NodeNetwork, chain: &ScopeInjections) {
let mut node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
node_ids.sort();
for node_id in node_ids {
let Some(node) = network.nodes.get_mut(&node_id) else { continue };
match &mut node.implementation {
DocumentNodeImplementation::Definition(id) => *id = self.specialization(*id, chain),
DocumentNodeImplementation::Network(nested) => {
let mut nested_chain = chain.clone();
nested_chain.extend(nested.scope_injections.iter().map(|(key, injection)| (key.clone(), injection.clone())));
self.specialize(nested, &nested_chain);
}
_ => {}
}
}
}
fn specialization(&mut self, id: NetworkId, chain: &ScopeInjections) -> NetworkId {
let Some(original) = self.originals.get(&id) else { return id };
let context: ScopeInjections = self.free_keys.get(&id).into_iter().flatten().filter_map(|key| Some((key.clone(), chain.get(key)?.clone()))).collect();
let mut signature: Vec<(String, Type)> = context.iter().map(|(key, (_, ty))| (key.clone(), ty.clone())).collect();
signature.sort_by(|(a, _), (b, _)| a.cmp(b));
let base_signature = self.base_signatures.entry(id).or_insert_with(|| signature.clone());
let specialized_id = if *base_signature == signature { id } else { specialized_network_id(id, &signature) };
if self.contexts.contains_key(&specialized_id) {
return specialized_id;
}
let mut body = original.clone();
let mut inner_chain = context.clone();
inner_chain.extend(body.scope_injections.iter().map(|(key, injection)| (key.clone(), injection.clone())));
self.contexts.insert(specialized_id, context);
self.specialize(&mut body, &inner_chain);
self.specialized.insert(specialized_id, body);
specialized_id
}
}
fn specialized_network_id(id: NetworkId, signature: &[(String, Type)]) -> NetworkId {
let mut hasher = DefaultHasher::new();
"scope specialization".hash(&mut hasher);
id.hash(&mut hasher);
signature.hash(&mut hasher);
NetworkId(hasher.finish())
}
struct ScopeChain<'a> {
scopes: &'a ScopeInjections,
parent: Option<&'a ScopeChain<'a>>,
}
enum ScopeChainLookup<'a> {
Current(&'a NodeId, &'a Type),
Parent(&'a NodeId, &'a Type),
None,
}
impl ScopeChain<'_> {
fn lookup(&'_ self, key: &str) -> ScopeChainLookup<'_> {
self.scopes
.get(key)
.map(|(id, ty)| ScopeChainLookup::Current(id, ty))
.or_else(|| {
self.parent.and_then(|parent| match parent.lookup(key) {
ScopeChainLookup::Current(id, ty) | ScopeChainLookup::Parent(id, ty) => Some(ScopeChainLookup::Parent(id, ty)),
ScopeChainLookup::None => None,
})
})
.unwrap_or(ScopeChainLookup::None)
}
}
@@ -0,0 +1,128 @@
use crate::document::document_tests::{ADD, add_network};
use crate::document::value::TaggedValue;
use crate::document::*;
use core_types::{ProtoNodeIdentifier, Type, concrete};
/// Two instances of `ADD`, one of them through another entry, with a scope input inside the entry it names.
fn shared_instances_with_a_scope_input() -> NodeNetwork {
let outer = NetworkId(2);
let mut add = add_network();
add.nodes.get_mut(&NodeId(1)).unwrap().inputs.push(NodeInput::scope("injected"));
let node = |implementation, inputs| DocumentNode {
implementation,
inputs,
..Default::default()
};
let value = |number| NodeInput::value(TaggedValue::Integer(number), false);
let outer_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: [(NodeId(10), node(DocumentNodeImplementation::Definition(ADD), vec![NodeInput::import(concrete!(i64), 0), value(2)]))]
.into_iter()
.collect(),
..Default::default()
};
let injected = node(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode")), vec![value(7)]);
NodeNetwork {
exports: vec![NodeInput::node(NodeId(11), 0)],
nodes: [
(NodeId(10), node(DocumentNodeImplementation::Definition(outer), vec![value(1)])),
(NodeId(11), node(DocumentNodeImplementation::Definition(ADD), vec![NodeInput::node(NodeId(10), 0), value(3)])),
(NodeId(20), injected),
]
.into_iter()
.collect(),
scope_injections: [("injected".to_string(), (NodeId(20), concrete!(i64)))].into_iter().collect(),
definitions: [(ADD, add), (outer, outer_network)].into_iter().collect(),
..Default::default()
}
}
/// A root instance of `ADD` and one inside `group`, which shadows the root's `injected` with a node of type `shadowing_type`.
fn shadowed_scope_input(shadowing_type: Type) -> NodeNetwork {
let group = NetworkId(2);
let mut add = add_network();
add.nodes.get_mut(&NodeId(1)).unwrap().inputs.push(NodeInput::scope("injected"));
let node = |implementation| DocumentNode { implementation, ..Default::default() };
let identity = || node(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode")));
let group_network = NodeNetwork {
nodes: [(NodeId(10), node(DocumentNodeImplementation::Definition(ADD))), (NodeId(21), identity())].into_iter().collect(),
scope_injections: [("injected".to_string(), (NodeId(21), shadowing_type))].into_iter().collect(),
..Default::default()
};
NodeNetwork {
nodes: [
(NodeId(10), node(DocumentNodeImplementation::Definition(group))),
(NodeId(11), node(DocumentNodeImplementation::Definition(ADD))),
(NodeId(20), identity()),
]
.into_iter()
.collect(),
scope_injections: [("injected".to_string(), (NodeId(20), concrete!(i64)))].into_iter().collect(),
definitions: [(ADD, add), (group, group_network)].into_iter().collect(),
..Default::default()
}
}
fn scope_import_types(network: &NodeNetwork) -> Vec<Type> {
let mut types: Vec<Type> = network
.definitions
.values()
.filter_map(|definition| match definition.nodes.get(&NodeId(1))?.inputs.last()? {
NodeInput::Import { import_type, .. } => Some(import_type.clone()),
_ => None,
})
.collect();
types.sort_by_key(|ty| format!("{ty:?}"));
types
}
#[test]
fn the_nearest_injection_resolves_a_scope_input() {
let mut network = shadowed_scope_input(concrete!(i64));
network.resolve_scope_inputs();
assert_eq!(scope_import_types(&network), vec![concrete!(i64)], "a shadowing injection of the same type shares the entry");
assert_eq!(network.nodes[&NodeId(11)].inputs.last(), Some(&NodeInput::node(NodeId(20), 0)));
assert_eq!(network.definitions[&NetworkId(2)].nodes[&NodeId(10)].inputs.last(), Some(&NodeInput::node(NodeId(21), 0)));
}
#[test]
fn a_shadowing_injection_of_another_type_specializes_the_entry() {
let mut network = shadowed_scope_input(concrete!(f64));
network.resolve_scope_inputs();
assert_eq!(scope_import_types(&network), vec![concrete!(i64), concrete!(f64)]);
let DocumentNodeImplementation::Definition(root_instance) = network.nodes[&NodeId(11)].implementation else {
panic!()
};
let DocumentNodeImplementation::Definition(group_instance) = network.definitions[&NetworkId(2)].nodes[&NodeId(10)].implementation else {
panic!()
};
assert_ne!(root_instance, group_instance);
assert_eq!(network.definitions[&NetworkId(2)].nodes[&NodeId(10)].inputs.last(), Some(&NodeInput::node(NodeId(21), 0)));
}
#[test]
fn a_table_compiles_like_its_inlined_network() {
let table = shared_instances_with_a_scope_input();
let mut inlined = table.clone();
inlined.inline_definitions().unwrap();
// Flattening gives value nodes random IDs, which their paths carry, so only the other paths are compared
let compile = |network| {
let mut compiled = crate::graphene_compiler::Compiler {}.compile_single(network).expect("the network compiles").network;
let mut paths: Vec<_> = compiled
.nodes
.iter()
.filter(|(_, node)| node.identifier != ProtoNodeIdentifier::new("core_types::value::ClonedNode"))
.map(|(_, node)| node.original_location.path.clone())
.collect();
paths.sort();
compiled.nodes.iter_mut().for_each(|(_, node)| node.original_location = OriginalLocation::default());
(compiled, paths)
};
assert_eq!(compile(table), compile(inlined));
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,252 @@
use super::*;
pub(crate) fn add_network() -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
..Default::default()
},
),
(
NodeId(1),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
#[test]
fn map_ids() {
let mut network = add_network();
network.map_ids(|id| NodeId(id.0 + 1));
let mapped_add = NodeNetwork {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
(
NodeId(1),
DocumentNode {
inputs: vec![NodeInput::import(concrete!(i64), 0), NodeInput::import(concrete!(i64), 1)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::structural::ConsNode")),
..Default::default()
},
),
(
NodeId(2),
DocumentNode {
inputs: vec![NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
assert_eq!(network, mapped_add);
}
#[test]
fn output_source_follows_exports_imports_and_hidden_nodes() {
let proto_node = |inputs: Vec<NodeInput>| DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::AddPairNode")),
..Default::default()
};
let network_node = |input: NodeInput, network: NodeNetwork| DocumentNode {
inputs: vec![input],
implementation: DocumentNodeImplementation::Network(network),
..Default::default()
};
// Network 2 passes its import through to its export, network 3 exports its inner node 0, and node 4 is hidden
let passing_network = NodeNetwork {
exports: vec![NodeInput::import(concrete!(i64), 0)],
..Default::default()
};
let wrapping_network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [(NodeId(0), proto_node(vec![NodeInput::import(concrete!(i64), 0)]))].into_iter().collect(),
..Default::default()
};
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(4), 0)],
nodes: [
(NodeId(1), proto_node(vec![NodeInput::value(TaggedValue::Integer(1), false)])),
(NodeId(2), network_node(NodeInput::node(NodeId(1), 0), passing_network)),
(NodeId(3), network_node(NodeInput::node(NodeId(2), 0), wrapping_network)),
(
NodeId(4),
DocumentNode {
visible: false,
..proto_node(vec![NodeInput::node(NodeId(3), 0)])
},
),
]
.into_iter()
.collect(),
..Default::default()
};
assert_eq!(network.output_source(&[NodeId(1)], 0), Some(vec![NodeId(1)]));
assert_eq!(
network.output_source(&[NodeId(2)], 0),
Some(vec![NodeId(1)]),
"A network passing its import through gives what's wired to it"
);
assert_eq!(network.output_source(&[NodeId(3)], 0), Some(vec![NodeId(3), NodeId(0)]), "A network gives what its export is wired to");
assert_eq!(network.output_source(&[NodeId(4)], 0), Some(vec![NodeId(3), NodeId(0)]), "A hidden node gives its primary input");
assert_eq!(network.input_source(&[NodeId(3)], &NodeInput::import(concrete!(i64), 0)), Some(vec![NodeId(1)]));
assert_eq!(network.output_source(&[NodeId(5)], 0), None);
}
fn node_with(implementation: DocumentNodeImplementation) -> DocumentNode {
DocumentNode { implementation, ..Default::default() }
}
fn network_with(nodes: impl IntoIterator<Item = (NodeId, DocumentNodeImplementation)>, definitions: impl IntoIterator<Item = (NetworkId, NodeNetwork)>) -> NodeNetwork {
NodeNetwork {
exports: vec![NodeInput::node(NodeId(10), 0)],
nodes: nodes.into_iter().map(|(id, implementation)| (id, node_with(implementation))).collect(),
definitions: definitions.into_iter().collect(),
..Default::default()
}
}
pub(crate) const ADD: NetworkId = NetworkId(1);
fn two_add_instances() -> NodeNetwork {
network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(ADD)), (NodeId(11), DocumentNodeImplementation::Definition(ADD))],
[(ADD, add_network())],
)
}
#[test]
fn definitions_inline_into_copies_of_their_network() {
let mut network = two_add_instances();
network.inline_definitions().unwrap();
let inlined = network_with(
[
(NodeId(10), DocumentNodeImplementation::Network(add_network())),
(NodeId(11), DocumentNodeImplementation::Network(add_network())),
],
[],
);
assert_eq!(network, inlined);
}
#[test]
fn lifted_networks_inline_back_to_the_original() {
let nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(add_network()))], []);
let original = network_with(
[
(NodeId(10), DocumentNodeImplementation::Network(nested)),
(NodeId(11), DocumentNodeImplementation::Network(add_network())),
],
[],
);
let mut network = original.clone();
let lifted = network.lift_nested_networks();
assert_eq!(lifted.len(), 3);
assert_eq!(network.definitions.len(), 3);
let all_nodes = std::iter::once(&network).chain(network.definitions.values()).flat_map(|network| network.nodes.values());
assert!(all_nodes.into_iter().all(|node| !matches!(node.implementation, DocumentNodeImplementation::Network(_))));
let outermost: Vec<_> = lifted.iter().filter(|lifted| lifted.containing.is_none()).map(|lifted| lifted.node_id).collect();
assert_eq!(outermost.len(), 2);
assert!(lifted.iter().position(|entry| entry.containing.is_some()) > lifted.iter().position(|entry| entry.containing.is_none()));
network.inline_definitions().unwrap();
assert_eq!(network, original);
}
#[test]
fn definitions_referencing_definitions_inline_transitively() {
let outer = NetworkId(2);
let mut network = network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(outer))],
[(ADD, add_network()), (outer, network_with([(NodeId(10), DocumentNodeImplementation::Definition(ADD))], []))],
);
network.inline_definitions().unwrap();
let inner = network_with([(NodeId(10), DocumentNodeImplementation::Network(add_network()))], []);
assert_eq!(network, network_with([(NodeId(10), DocumentNodeImplementation::Network(inner))], []));
}
#[test]
fn invalid_definition_tables_are_rejected() {
let (first, second) = (NetworkId(2), NetworkId(3));
let mut cyclic = network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(first))],
[
(first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])),
(second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])),
],
);
assert_eq!(cyclic.validate_definitions(), Err(DefinitionError::Cycle(vec![first, second])));
assert_eq!(cyclic.inline_definitions(), Err(DefinitionError::Cycle(vec![first, second])));
let mut missing = network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], []);
assert_eq!(missing.validate_definitions(), Err(DefinitionError::Missing(first)));
assert_eq!(missing.inline_definitions(), Err(DefinitionError::Missing(first)));
let mut nested = network_with([(NodeId(10), DocumentNodeImplementation::Network(two_add_instances()))], []);
assert_eq!(nested.validate_definitions(), Err(DefinitionError::NestedTable));
assert_eq!(nested.inline_definitions(), Err(DefinitionError::NestedTable));
assert_eq!(two_add_instances().validate_definitions(), Ok(()));
}
#[test]
fn edits_through_one_instance_reach_every_instance() {
let mut network = two_add_instances();
let added = node_with(DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::ops::IdentityNode")));
network.nested_network_mut(&[NodeId(10)]).unwrap().nodes.insert(NodeId(2), added.clone());
assert_eq!(network.nested_network(&[NodeId(11)]).unwrap().nodes.get(&NodeId(2)), Some(&added));
assert_eq!(network.locate(&[NodeId(11)]), Some(Some(ADD)));
assert_eq!(network.implementation_output_count(&DocumentNodeImplementation::Definition(ADD)), 1);
}
#[test]
fn definition_edits_change_the_network_hash() {
let mut network = two_add_instances();
let before = network.current_hash();
network.definitions.get_mut(&ADD).unwrap().exports.push(NodeInput::node(NodeId(0), 0));
assert_ne!(network.current_hash(), before);
}
#[test]
fn recursive_nodes_visit_each_definition_once() {
let network = two_add_instances();
let body_paths = network.recursive_nodes().map(|(_, _, path)| path).filter(|path| !path.is_empty()).collect::<Vec<_>>();
assert_eq!(body_paths.len(), add_network().nodes.len());
assert!(body_paths.windows(2).all(|pair| pair[0] == pair[1]));
let (first, second) = (NetworkId(2), NetworkId(3));
let cyclic = network_with(
[(NodeId(10), DocumentNodeImplementation::Definition(first))],
[
(first, network_with([(NodeId(10), DocumentNodeImplementation::Definition(second))], [])),
(second, network_with([(NodeId(10), DocumentNodeImplementation::Definition(first))], [])),
],
);
assert_eq!(cyclic.recursive_nodes().count(), 3);
}
@@ -0,0 +1,183 @@
use super::*;
// TODO: Eventually remove this document upgrade code
#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)]
/// Represents the implementation of a node, which can be a nested [`NodeNetwork`], a proto [`ProtoNodeIdentifier`], or `Extract`.
pub enum OldDocumentNodeImplementation {
Network(OldNodeNetwork),
#[serde(alias = "Unresolved")]
ProtoNode(ProtoNodeIdentifier),
Extract,
}
// TODO: Eventually remove this document upgrade code
#[derive(Debug, serde::Deserialize)]
#[serde(untagged)]
pub enum NodeExportVersions {
OldNodeInput(NodeOutput),
NodeInput(NodeInput),
}
// TODO: Eventually remove this document upgrade code
#[derive(Debug, serde::Deserialize)]
pub struct NodeOutput {
pub node_id: NodeId,
pub node_output_index: usize,
}
// TODO: Eventually remove this document upgrade code
pub(super) fn deserialize_exports<'de, D>(deserializer: D) -> Result<Vec<NodeInput>, D::Error>
where
D: serde::Deserializer<'de>,
{
use serde::Deserialize;
let node_input_versions = Vec::<NodeExportVersions>::deserialize(deserializer)?;
// Convert Vec<NodeOutput> to Vec<NodeInput>
let inputs = node_input_versions
.into_iter()
.map(|node_input_version| {
let node_output = match node_input_version {
NodeExportVersions::OldNodeInput(node_output) => node_output,
NodeExportVersions::NodeInput(node_input) => return node_input,
};
NodeInput::node(node_output.node_id, node_output.node_output_index)
})
.collect();
Ok(inputs)
}
/// An instance of a [`DocumentNodeDefinition`] that has been instantiated in a [`NodeNetwork`].
/// Currently, when an instance is made, it lives all on its own without any lasting connection to the definition.
/// But we will want to change it in the future so it merely references its definition.
#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)]
pub struct OldDocumentNode {
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the node definition's name is displayed to the user in italics.
/// Ensure the click target in the encapsulating network is updated when this is modified by using network.update_click_target(node_id).
#[serde(default)]
pub alias: String,
// TODO: Replace this name with a reference to the [`DocumentNodeDefinition`] node definition to use the name from there instead.
/// The name of the node definition, as originally set by [`DocumentNodeDefinition`], used to display in the UI and to display the appropriate Inspector layout.
#[serde(deserialize_with = "migrate_layer_to_merge")]
pub name: String,
/// The inputs to a node, which are either:
/// - From other nodes within this graph [`NodeInput::Node`],
/// - A constant value [`NodeInput::Value`],
/// - A [`NodeInput::Import`] which specifies that this input is from outside the graph, which is resolved in the graph flattening step in the case of nested networks.
///
/// In the root network, it is resolved when evaluating the borrow tree.
/// Ensure the click target in the encapsulating network is updated when the inputs cause the node shape to change (currently only when exposing/hiding an input) by using network.update_click_target(node_id).
#[cfg_attr(target_family = "wasm", serde(alias = "outputs"))]
pub inputs: Vec<NodeInput>,
pub manual_composition: Option<Type>,
// TODO: Remove once this references its definition instead (see above TODO).
/// Indicates to the UI if a primary output should be drawn for this node.
/// True for most nodes, but the Split Channels node is an example of a node that has multiple secondary outputs but no primary output.
#[serde(default = "return_true")]
pub has_primary_output: bool,
// A nested document network or a proto-node identifier.
pub implementation: OldDocumentNodeImplementation,
/// User chosen state for displaying this as a left-to-right node or bottom-to-top layer. Ensure the click target in the encapsulating network is updated when the node changes to a layer by using network.update_click_target(node_id).
#[serde(default)]
pub is_layer: bool,
/// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step.
#[serde(default = "return_true")]
pub visible: bool,
/// Represents the lock icon for locking/unlocking the node in the graph UI. When locked, a node cannot be moved in the graph UI.
#[serde(default)]
pub locked: bool,
/// Metadata about the node including its position in the graph UI. Ensure the click target in the encapsulating network is updated when the node moves by using network.update_click_target(node_id).
pub metadata: OldDocumentNodeMetadata,
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
#[serde(default)]
pub skip_deduplication: bool,
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
#[serde(skip)]
pub original_location: OriginalLocation,
}
// TODO: Eventually remove this document upgrade code
#[derive(Clone, Debug, PartialEq, Default, Hash, DynAny, serde::Serialize, serde::Deserialize)]
/// Metadata about the node including its position in the graph UI
pub struct OldDocumentNodeMetadata {
pub position: IVec2,
}
// TODO: Eventually remove this document upgrade code
#[derive(Clone, Copy, Debug, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
/// Root Node is the "default" export for a node network. Used by document metadata, displaying UI-only "Export" node, and for restoring the default preview node.
pub struct OldRootNode {
pub id: NodeId,
pub output_index: usize,
}
// TODO: Eventually remove this document upgrade code
#[derive(PartialEq, Debug, Clone, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum OldPreviewing {
/// If there is a node to restore the connection to the export for, then it is stored in the option.
/// Otherwise, nothing gets restored and the primary export is disconnected.
Yes { root_node_to_restore: Option<OldRootNode> },
#[default]
No,
}
// TODO: Eventually remove this document upgrade code
#[derive(Clone, Debug, DynAny, serde::Serialize, serde::Deserialize)]
/// A network (subgraph) of nodes containing each [`DocumentNode`] and its ID, as well as list mapping each export to its connected node, or a value if disconnected
pub struct OldNodeNetwork {
/// The list of data outputs that are exported from this network to the parent network.
/// Each export is a reference to a node within this network, paired with its output index, that is the source of the network's exported data.
#[serde(alias = "outputs", deserialize_with = "deserialize_exports")] // TODO: Eventually remove this alias document upgrade code
pub exports: Vec<NodeInput>,
/// The list of all nodes in this network.
//cfg_attr(feature = "serde", #[serde(serialize_with = "core_types::vector::serialize_hashmap", deserialize_with = "core_types::vector::deserialize_hashmap"))]
pub nodes: HashMap<NodeId, OldDocumentNode>,
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
#[serde(default)]
pub previewing: OldPreviewing,
/// Temporary fields to store metadata for "Import"/"Export" UI-only nodes, eventually will be replaced with lines leading to edges
#[serde(default = "default_import_metadata")]
pub imports_metadata: (NodeId, IVec2),
#[serde(default = "default_export_metadata")]
pub exports_metadata: (NodeId, IVec2),
/// A network may expose nodes as constants which can by used by other nodes using a `NodeInput::Scope(key)`.
#[serde(default)]
//cfg_attr(feature = "serde", #[serde(serialize_with = "core_types::vector::serialize_hashmap", deserialize_with = "core_types::vector::deserialize_hashmap"))]
pub scope_injections: HashMap<String, (NodeId, Type)>,
}
// TODO: Eventually remove this document upgrade code
fn migrate_layer_to_merge<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<String, D::Error> {
let mut s: String = serde::Deserialize::deserialize(deserializer)?;
if s == "Layer" {
s = "Merge".to_string();
}
Ok(s)
}
// TODO: Eventually remove this document upgrade code
fn default_import_metadata() -> (NodeId, IVec2) {
(NodeId::new(), IVec2::new(-25, -4))
}
// TODO: Eventually remove this document upgrade code
fn default_export_metadata() -> (NodeId, IVec2) {
(NodeId::new(), IVec2::new(8, -4))
}
pub(super) fn migrate_call_argument<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Type, D::Error> {
use serde::Deserialize;
#[derive(serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
enum CallArg {
New(Type),
Old(Option<Type>),
}
Ok(match CallArg::deserialize(deserializer)? {
CallArg::New(ty) => ty,
CallArg::Old(ty) => ty.unwrap_or_default(),
})
}
Loaded 100 of 145 files, more files were not shown because too many files have changed in this diff. Show more