Compare commits

..
156 changed files with 5059 additions and 8909 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/70b260c21afad29140bbc63ddab952fec3dd024c.tar.gz
5b05e7f4449b5f962755542e9b156891bbf2e0a87b7fc90798b8352d9225757d
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
+1 -1
View File
@@ -12,7 +12,7 @@
},
// NOTICE: keep these tool versions in sync with `.github/workflows/build.yml`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
"containerEnv": {
"WASM_BINDGEN_CLI_VERSION": "0.2.129",
"WASM_BINDGEN_CLI_VERSION": "0.2.127",
"CARGO_ABOUT_VERSION": "0.9.2",
"BINARYEN_VERSION": "130",
"CARGO_BINSTALL_VERSION": "1.23.0"
+3 -3
View File
@@ -62,7 +62,7 @@ jobs:
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
SCCACHE_VERSION: "v0.19.0"
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
steps:
@@ -348,7 +348,7 @@ jobs:
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
@@ -617,7 +617,7 @@ jobs:
env:
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.129"
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
CARGO_BINSTALL_VERSION: "1.23.0"
+16 -5
View File
@@ -174,12 +174,23 @@ jobs:
env:
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
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
# 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"
run: >-
cargo test --workspace --all-features
--exclude 'graphite-desktop*'
--exclude third-party-licenses
&& cargo test --package third-party-licenses
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
# 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_129
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.rustc
+1 -1
View File
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
pkgs.lld
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_129
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
Generated
+2363 -1973
View File
File diff suppressed because it is too large. Load diff
+26 -26
View File
@@ -147,10 +147,10 @@ web-time = "1.1"
env_logger = "0.11"
log = "0.4"
bitflags = { version = "2.4", features = ["serde"] }
ctor = "1.0"
ctor = "0.2"
convert_case = "0.12"
titlecase = "3.6"
fancy-regex = "0.20.0"
fancy-regex = "0.18.0"
unicode-segmentation = "1.13.2"
indoc = "2.0.5"
derivative = "2.2"
@@ -176,10 +176,10 @@ wgpu = { version = "30.0", default-features = false, features = [
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
wasm-bindgen = "=0.2.129" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen = "=0.2.127" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned in `.github/workflows/build.yml`, `.devcontainer/devcontainer.json`, `.nix/dev.nix`, `.nix/pkgs/graphite.nix`, and `tools/cargo-run/src/requirements.rs`. We pin this version because wasm-bindgen upgrades may break various things.
wasm-bindgen-futures = "0.4"
js-sys = "=0.3.106"
web-sys = { version = "=0.3.106", features = [
js-sys = "=0.3.104"
web-sys = { version = "=0.3.104", features = [
"Document",
"DomRect",
"Element",
@@ -210,25 +210,25 @@ tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-mult
# Linebender ecosystem (BEGIN)
kurbo = { version = "0.13", features = ["serde"] }
vello_gpu = { version = "0.3", default-features = false, features = ["wgpu", "full_image_support"] }
usvg = "0.49"
usvg = "0.47"
simplecss = "0.2"
parley = { version = "0.12", default-features = false, features = ["std"] }
skrifa = "0.44"
parley = { version = "0.9", default-features = false, features = ["std"] }
skrifa = "0.42"
polycool = "0.4"
color = "0.3"
# Linebender ecosystem (END)
rand = { version = "0.10", default-features = false, features = ["std_rng"] }
rand_chacha = "0.10"
glam = { version = "0.34", default-features = false, features = [
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
"all-types",
] }
base64 = "0.23"
base64 = "0.22"
blake3 = "1.5"
mmap-io = { version = "1.0", features = ["hugepages"] }
mmap-io = { version = "0.9", features = ["hugepages"] }
image = { version = "0.25", default-features = false, features = [
"png",
"jpeg",
@@ -245,10 +245,10 @@ image = { version = "0.25", default-features = false, features = [
pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.5"
num-derive = "0.4"
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "3.0", default-features = false, features = [
syn = { version = "2.0", default-features = false, features = [
"full",
"derive",
"parsing",
@@ -262,14 +262,14 @@ syn = { version = "3.0", default-features = false, features = [
lyon_geom = "1.0"
delaunator = "1.0"
robust = "1.2"
petgraph = { version = "0.8", default-features = false, features = ["graphmap"] }
petgraph = { version = "0.7", default-features = false, features = ["graphmap"] }
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" }
ndarray = "0.17"
ollev = "0.1.2"
dirs = "7.0"
criterion = { version = "0.7", features = ["html_reports"] }
gungraun = { version = "0.18" }
ndarray = "0.16"
ollev = "0.1.1"
dirs = "6.0"
cef = "156"
cef-dll-sys = "156"
include_dir = "0.7"
@@ -277,14 +277,14 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
rfd = "0.17"
open = "5.3"
spin = "0.12"
spin = "0.10"
clap = "4.5"
qrcodegen = "1.8"
lzma-rust2 = { version = "0.25", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.29"
linesweeper = "0.5"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "9", default-features = false }
zip = { version = "8", default-features = false }
[workspace.lints]
+2 -10
View File
@@ -1,3 +1,5 @@
<a href="https://graphite.art/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/user-attachments/assets/9366c148-4405-484f-909a-9a3526eb9209">
@@ -81,13 +83,3 @@ Are you a graphics programmer or Rust developer? Graphite aims to be one of the
## License
Graphite's source code is dual-licensed under your choice of either the [MIT license](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), at your option, unless otherwise noted within the repository. By submitting code for inclusion in the project, you agree to license your contributions under both licenses, and that you have the authority to do so.
## Acknowledgments
We're grateful to these programs and organizations for the grants and services that help make Graphite possible.
[<img width="600" alt="European Commission, NGI Zero, and NLnet Foundation" src="https://github.com/user-attachments/assets/d5b3c623-710a-4809-916b-263e80c28184" />](https://nlnet.nl/commonsfund/)
[<img width="600" alt="Google Summer of Code" src="https://github.com/user-attachments/assets/37284dfe-fccd-4abd-904c-1165ff36da53" />](https://summerofcode.withgoogle.com/)
[<img width="300" alt="CI Powered by Blacksmith" src="https://github.com/user-attachments/assets/72bd48c2-ab21-4aed-b0a5-d440a8662128" />](https://www.blacksmith.sh/)
+1 -1
View File
@@ -1,4 +1,4 @@
use rand::RngExt;
use rand::Rng;
use rfd::AsyncFileDialog;
use std::fs;
use std::io::Read;
+8
View File
@@ -45,3 +45,11 @@ 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,6 +74,9 @@ 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();
+1 -2
View File
@@ -28,13 +28,12 @@ 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.23"
ipc-channel = "0.22"
# 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 = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join(APP_DIRECTORY_NAME).join("ui");
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
if let Err(e) = fs::create_dir_all(&path) {
tracing::error!("Failed to create temp directory at {path:?}: {e}");
}
@@ -48,10 +48,6 @@ 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,6 +27,7 @@ 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().map_err(zip_err)?.to_string();
let name = entry.name().to_string();
validate_path(&name)?;
let size = checked_entry_size(&mut total_size, entry.size())?;
+2 -2
View File
@@ -91,7 +91,7 @@ impl MmappedBytes {
/// later degrading to the `&[]` fallback in [`AsRef::as_ref`], which cannot return an error.
pub fn new(file: mmap_io::mmap::MemoryMappedFile) -> Result<Self> {
let len = file.len();
file.as_slice_bytes(0, len)
file.as_slice(0, len)
.map_err(|error| ContainerError::Backend(format!("mmap slice of {:?} failed: {error}", file.path())))?;
Ok(Self(file))
}
@@ -105,7 +105,7 @@ impl MmappedBytes {
impl AsRef<[u8]> for MmappedBytes {
fn as_ref(&self) -> &[u8] {
let len = self.0.len();
match self.0.as_slice_bytes(0, len) {
match self.0.as_slice(0, len) {
Ok(slice) => slice,
Err(error) => {
log::error!("Failed to obtain mmap slice: {error}");
-13
View File
@@ -181,19 +181,6 @@ 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);
+5 -10
View File
@@ -111,9 +111,6 @@ 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,
@@ -178,8 +175,6 @@ 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,
@@ -237,16 +232,16 @@ impl<L: Layout> Gdd<L> {
Self::open_in_with(working, layout, byte_store, host).await
}
/// 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.
/// 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?)
}
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
Self::open_stored(working, layout, MigrationInputs::default()).await
}
-1
View File
@@ -86,7 +86,6 @@ 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}");
-11
View File
@@ -400,11 +400,6 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
/// Names this peer's open interaction. Closing it takes the name along.
pub fn name_interaction(&mut self, action: &str) {
self.session.name_interaction(action);
}
/// Undo this peer's latest hot interaction, here and on peers. `None` if it already retired.
pub fn retract_interaction(&mut self) -> Result<Option<Vec<RegistryDelta>>, Error> {
let Some(retraction) = self.session.retract_interaction()? else {
@@ -432,13 +427,7 @@ 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))
}
+6
View File
@@ -137,6 +137,12 @@ 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,46 +538,6 @@ 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"
@@ -74,6 +74,4 @@ pub mod delta {
/// Marks the last delta of a user interaction, so the undo cursor steps per-interaction, not per-delta. Also set on
/// the last hot op of an interaction.
pub const INTERACTION_END: &str = "interaction_end";
/// What the user did in an interaction, such as a tool action. Set on the last hot op and the last delta.
pub const ACTION: &str = "action";
}
-8
View File
@@ -55,14 +55,6 @@ impl Delta {
self.attributes.get(attr::delta::INTERACTION_END).is_some_and(|marker| marker.value == Value::Bool(true))
}
/// What the user did in the interaction this delta ends, if it was named.
pub fn action(&self) -> Option<&str> {
match &self.attributes.get(attr::delta::ACTION)?.value {
Value::Str(action) => Some(action),
_ => None,
}
}
/// Take over `original`'s annotations and retirement time, for a delta that replaces it in rewritten history.
pub fn carry_annotations(&mut self, original: &Delta) {
self.attributes = original.attributes.clone();
-2
View File
@@ -10,7 +10,6 @@ pub mod ids;
pub mod model;
mod prior;
pub mod registry;
mod repair;
pub mod resources;
mod schema;
pub mod session;
@@ -50,7 +49,6 @@ pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProje
mod tests {
mod bookkeeping;
mod crdt;
mod history_simulation;
mod projection;
mod round_trip;
mod sessions;
-273
View File
@@ -1,273 +0,0 @@
//! Repairs the graph after steps are replayed onto a line that changed since they were made, as bringing a step back
//! or removing one does. Replayed writes keep their stamps, so a slot written since keeps the newer value, which can
//! leave an input naming a removed node, two nodes on one, or a node nothing reaches any more.
//!
//! Nodes connected through their primary inputs form chains, like a stack of layers or a node feeding the next. Each
//! chain hangs off a head slot: an export, or an input past the primary one. The repair rebuilds every chain from the
//! order the line had before the replay and the order the replayed step left it in when it was made, so the step's
//! own changes land on the chains as they are now.
use crate::{NetworkId, NodeId, NodeInput, Registry, RegistryDelta};
use std::collections::{BTreeSet, HashMap, HashSet};
/// Each node's network and newest primary input anywhere in history, for nodes this line no longer or never had.
pub(crate) type KnownInputs = HashMap<NodeId, (NetworkId, NodeInput)>;
/// A slot that can name a node.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum Slot {
Input(NodeId, u32),
Export(NetworkId, u32),
}
/// A chain's nodes from its head down, and what the last one rests on.
struct Chain {
head: Slot,
nodes: Vec<NodeId>,
bottom: Option<NodeInput>,
}
/// The ops that repair `registry`, which is `before` with `replayed` folded in. `intended` is the document as the
/// replayed step left it when it was made, and `gone` the nodes it must not have, as those the step deleted.
/// - A node in `gone`, or in neither `before` nor `intended`, is removed. A newer write to a node revives it over an
/// older removal, as one made on the line since does over a deletion brought back.
/// - Every chain keeps the nodes it had before, in their order, except those the replayed step moved, which take
/// their place from `intended`, after the node they followed there. A node the step added lands the same way.
/// - A node on no chain any more, which was on one, goes back where it was.
/// - An input naming a removed node takes that node's primary input instead, as deleting a node reconnects what it
/// sat between. A node this line never had counts as removed, with the primary input `known` gives it.
pub(crate) fn repair_ops(before: &Registry, registry: &Registry, intended: &Registry, replayed: &[RegistryDelta], gone: &HashSet<NodeId>, known: &KnownInputs) -> Vec<RegistryDelta> {
let mut registry = registry.clone();
let mut ops = Vec::new();
let mut unwanted: Vec<NodeId> = registry
.node_instances
.keys()
.filter(|id| gone.contains(id) || (!before.node_instances.contains_key(id) && !intended.node_instances.contains_key(id)))
.copied()
.collect();
unwanted.sort();
for id in unwanted {
if let Some(snapshot) = registry.node_instances.remove(&id) {
ops.push(RegistryDelta::RemoveNode { id, snapshot });
}
}
let live = |id: &NodeId| registry.node_instances.contains_key(id);
let placed_by_step: HashSet<NodeId> = replayed.iter().flat_map(placed_nodes).filter(live).collect();
let heads: BTreeSet<Slot> = [before, &registry, intended].into_iter().flat_map(head_slots).filter(|&slot| owner_is_live(&registry, slot)).collect();
let was_in = |registry: &Registry| -> HashMap<NodeId, Slot> { heads.iter().flat_map(|&head| chain(registry, head).nodes.into_iter().map(move |id| (id, head))).collect() };
let (was_before, was_intended) = (was_in(before), was_in(intended));
// Where each node goes: where the step put it if it placed it, else where it was
let home = |id: &NodeId| match placed_by_step.contains(id) {
true => was_intended.get(id).or(was_before.get(id)),
false => was_before.get(id).or(was_intended.get(id)),
};
let mut chains = Vec::new();
let mut taken = HashSet::new();
for &head in &heads {
let owner = match head {
Slot::Input(owner, _) => Some(owner),
Slot::Export(..) => None,
};
let fits = |id: &NodeId| live(id) && Some(*id) != owner && home(id) == Some(&head);
let earlier = chain(before, head);
let wanted = chain(intended, head);
// A node the step placed counts as moved when it sits on the other side of a node both orders have
let common: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| live(id) && wanted.nodes.contains(id)).collect();
let rank = |order: &[NodeId], id: &NodeId| order.iter().position(|node| node == id);
let moved = |id: &NodeId| {
placed_by_step.contains(id)
&& common.contains(id)
&& common
.iter()
.any(|other| other != id && (rank(&earlier.nodes, id) < rank(&earlier.nodes, other)) != (rank(&wanted.nodes, id) < rank(&wanted.nodes, other)))
};
let mut nodes: Vec<NodeId> = earlier.nodes.iter().copied().filter(|id| fits(id) && !moved(id)).collect();
for (position, id) in wanted.nodes.iter().enumerate() {
if nodes.contains(id) || !fits(id) {
continue;
}
let after = wanted.nodes[..position].iter().rev().find_map(|above| nodes.iter().position(|node| node == above));
nodes.insert(after.map_or(0, |index| index + 1), *id);
}
// What the chain rests on, as long as nothing else sits on it
let bottom = [earlier.bottom, wanted.bottom].into_iter().flatten().find(|bottom| match bottom {
NodeInput::Node { id, .. } => live(id) && home(id).is_none(),
_ => true,
});
taken.extend(nodes.iter().copied());
chains.push(Chain { head, nodes, bottom });
}
for chain in &chains {
let mut slot = chain.head;
for &id in &chain.nodes {
set(&mut registry, &mut ops, slot, Some(on(id)));
slot = Slot::Input(id, 0);
}
if let Some(bottom) = &chain.bottom {
set(&mut registry, &mut ops, slot, Some(bottom.clone()));
} else if let Some(NodeInput::Node { id, .. }) = slot_value(&registry, slot)
&& (taken.contains(&id) || !registry.node_instances.contains_key(&id))
{
// Resting on a node another chain holds, or one gone, it rests on nothing instead
let cleared = match slot {
Slot::Export(..) => None,
Slot::Input(..) => reconnect(&registry, id, slot_network(&registry, slot), known).filter(|input| !matches!(input, NodeInput::Node { .. })),
};
if cleared.is_some() || matches!(slot, Slot::Export(..)) {
set(&mut registry, &mut ops, slot, cleared);
}
}
}
// Inputs off every chain still naming a removed node
for (slot, named) in slots(&registry) {
if registry.node_instances.contains_key(&named) {
continue;
}
let reconnected = reconnect(&registry, named, slot_network(&registry, slot), known).or_else(|| slot_value(before, slot).filter(|earlier| !names_missing(&registry, earlier)));
if reconnected.is_some() || matches!(slot, Slot::Export(..)) {
set(&mut registry, &mut ops, slot, reconnected);
}
}
ops
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
fn names_missing(registry: &Registry, input: &NodeInput) -> bool {
matches!(input, NodeInput::Node { id, .. } if !registry.node_instances.contains_key(id))
}
/// The nodes a write places in a slot, or adds.
fn placed_nodes(op: &RegistryDelta) -> Vec<NodeId> {
match op {
RegistryDelta::AddNode { id, .. } => vec![*id],
RegistryDelta::ChangeNodeInput { id, index, new_input } => {
let placed = match new_input {
NodeInput::Node { id: placed, .. } => Some(*placed),
_ => None,
};
(*index == 0).then_some(*id).into_iter().chain(placed).collect()
}
RegistryDelta::SetNetworkExport {
export: Some(NodeInput::Node { id, .. }),
..
} => vec![*id],
_ => Vec::new(),
}
}
/// Every slot naming a node, in a fixed order.
fn slots(registry: &Registry) -> Vec<(Slot, NodeId)> {
let mut slots = Vec::new();
for (&id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = slot.input {
slots.push((Slot::Input(id, index as u32), named));
}
}
}
for (&id, network) in &registry.networks {
for (index, slot) in network.exports.iter().enumerate() {
if let Some(NodeInput::Node { id: named, .. }) = slot.target {
slots.push((Slot::Export(id, index as u32), named));
}
}
}
slots.sort();
slots
}
/// The slots heading a chain: exports and inputs past the primary one, naming a node.
fn head_slots(registry: &Registry) -> impl Iterator<Item = Slot> + '_ {
slots(registry).into_iter().map(|(slot, _)| slot).filter(|slot| !matches!(slot, Slot::Input(_, 0)))
}
fn owner_is_live(registry: &Registry, slot: Slot) -> bool {
match slot {
Slot::Input(id, _) => registry.node_instances.contains_key(&id),
Slot::Export(id, _) => registry.networks.contains_key(&id),
}
}
/// The chain hanging off `head` in `registry`.
fn chain(registry: &Registry, head: Slot) -> Chain {
let mut nodes = Vec::new();
let mut below = slot_value(registry, head);
while let Some(NodeInput::Node { id, .. }) = below {
if nodes.contains(&id) || !registry.node_instances.contains_key(&id) {
return Chain { head, nodes, bottom: None };
}
nodes.push(id);
below = slot_value(registry, Slot::Input(id, 0));
}
Chain { head, nodes, bottom: below }
}
fn slot_network(registry: &Registry, slot: Slot) -> Option<NetworkId> {
match slot {
Slot::Input(id, _) => registry.node_instances.get(&id).map(|node| node.network),
Slot::Export(id, _) => Some(id),
}
}
fn slot_value(registry: &Registry, slot: Slot) -> Option<NodeInput> {
match slot {
Slot::Input(id, index) => registry.node_instances.get(&id)?.inputs.get(index as usize).map(|slot| slot.input.clone()),
Slot::Export(id, index) => registry.networks.get(&id)?.exports.get(index as usize)?.target.clone(),
}
}
/// What a removed node's primary input led to, through removed nodes, staying in `network`. None when the chain ends
/// at a node never seen or in another network.
fn reconnect(registry: &Registry, removed: NodeId, network: Option<NetworkId>, known: &KnownInputs) -> Option<NodeInput> {
let mut visited = HashSet::new();
let mut current = removed;
loop {
if !visited.insert(current) {
return None;
}
let (in_network, input) = match registry.removed_nodes.get(&current) {
Some(tombstone) => (tombstone.content.network, tombstone.content.inputs.first()?.input.clone()),
None => known.get(&current).cloned()?,
};
if Some(in_network) != network {
return None;
}
match input {
NodeInput::Node { id, .. } if !registry.node_instances.contains_key(&id) => current = id,
NodeInput::Node { id, .. } if Some(registry.node_instances[&id].network) != network => return None,
input => return Some(input),
}
}
}
/// Records the op setting `slot` to `input`, None clearing an export, and applies it to the scratch `registry`. Writes
/// nothing when the slot holds it already.
fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input: Option<NodeInput>) {
if slot_value(registry, slot) == input {
return;
}
match slot {
Slot::Input(id, index) => {
let Some(input) = input else { return };
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
slot.input = input.clone();
}
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
}
Slot::Export(id, index) => {
if let Some(slot) = registry.networks.get_mut(&id).and_then(|network| network.exports.get_mut(index as usize)) {
slot.target = input.clone();
}
ops.push(RegistryDelta::SetNetworkExport { id, index, export: input });
}
}
}
+11 -149
View File
@@ -24,8 +24,6 @@ pub struct Session {
/// What the ops this peer took back named. A retirement racing the take-back may still name them, and this peer may
/// hold the only copy, so they stay garbage collection roots for the life of the session.
taken_back_resources: HashSet<ResourceHash>,
/// What this peer's open interaction is doing, for its closing marker to carry.
action: Option<String>,
}
impl Session {
@@ -49,7 +47,6 @@ impl Session {
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
action: None,
}
}
@@ -339,7 +336,6 @@ impl Session {
remote_tips: HashMap::new(),
runtime_base: None,
taken_back_resources: HashSet::new(),
action: None,
}
}
@@ -390,10 +386,6 @@ impl Session {
return Ok(None);
}
self.runtime_base = None;
// The name belongs to the open interaction being taken back
if closed_before == own.len() {
self.action = None;
}
let (touched, taken) = self.document.retract_hot_ops(&ids);
self.taken_back_resources.extend(taken.iter().filter_map(|hot_op| hot_op.op.resource_hash()));
let ops = taken.into_iter().map(|hot_op| hot_op.op).filter(|op| !matches!(op, RegistryDelta::Meta)).collect();
@@ -438,70 +430,23 @@ impl Session {
}
let position = newest_first.iter().position(|delta| delta.id == undone).ok_or(CrdtError::NotFoundInHistory(undone))?;
// Minted on a scratch fold first, so a failing copy changes nothing. Each copied interaction ends with the
// repairs it needs on the changed line.
// Minted on a scratch fold first, so a failing copy changes nothing.
let mut scratch = self.fold_scratch_at(Some(base))?;
let mut copies = Vec::with_capacity(position);
// Per copy, the delta it carries attributes from, and the repair now closing that delta's interaction
let mut sources: Vec<(Option<&Delta>, Option<Rev>)> = Vec::with_capacity(position);
let mut parent = Some(base);
let mut replayed = Vec::new();
let mut before = scratch.working_registry.clone();
let known = self.known_inputs();
// What the removed step added must not come back through a later step writing to it
let gone: HashSet<NodeId> = newest_first[position..]
.iter()
.filter_map(|delta| match &delta.kind {
RegistryDelta::AddNode { id, .. } => Some(*id),
_ => None,
})
.collect();
for original in newest_first[..position].iter().rev() {
let reverse = crate::prior::capture(&scratch.working_registry, &original.kind);
scratch.apply_op_with(RegistryTarget::Working, original.kind.clone(), original.timestamp, ApplyMode::Idempotent)?;
let copy = Delta::new(parent, original.timestamp.peer, original.timestamp, original.kind.clone(), reverse);
parent = Some(copy.id);
copies.push(copy);
sources.push((Some(original), None));
replayed.push(original.kind.clone());
if !original.is_interaction_end() {
continue;
}
let closing_index = sources.len() - 1;
for op in crate::repair::repair_ops(
&before,
&scratch.working_registry,
&self.fold_scratch_at(Some(original.id))?.working_registry,
&std::mem::take(&mut replayed),
&gone,
&known,
) {
let reverse = crate::prior::capture(&scratch.working_registry, &op);
let timestamp = self.document.clock.tick();
scratch.apply_op_with(RegistryTarget::Working, op.clone(), timestamp, ApplyMode::Strict)?;
let repair = Delta::new(parent, original.author, timestamp, op, reverse);
parent = Some(repair.id);
sources[closing_index].1 = Some(repair.id);
copies.push(repair);
sources.push((None, None));
}
before = scratch.working_registry.clone();
}
let mut touched = Touched::default();
newest_first[position..].iter().for_each(|delta| touched.record(&delta.kind));
for (copy, _) in copies.iter().zip(&sources).filter(|(_, (original, _))| original.is_none()) {
touched.record(&copy.kind);
}
for copy in &copies {
for (original, copy) in newest_first[..position].iter().rev().zip(&mut copies) {
self.document.history.push(copy.clone());
}
for (&(original, closing), copy) in sources.iter().zip(&copies) {
if let Some(original) = original {
self.carry_attributes_closing(original, copy.id, closing);
}
}
for copy in &mut copies {
self.carry_attributes(original, copy.id);
if let Some(carried) = self.document.history.get(copy.id) {
*copy = carried.clone();
}
@@ -614,8 +559,7 @@ impl Session {
}
/// Mint a dropped interaction's deltas again on top of the line as one interaction. They keep their
/// original stamps, so a field someone wrote since keeps the newer value, and the graph is repaired where that
/// left it broken (see [`repair_ops`](crate::repair::repair_ops)). Returns the new revs.
/// original stamps, so a field someone wrote since keeps the newer value. Returns the new revs.
pub fn restore_interaction(&mut self, dropped: Rev) -> Result<Vec<Rev>, CrdtError> {
let base = self.interaction_start_parent(dropped, false).ok_or(CrdtError::NotUndoable(dropped))?;
let mut originals = Vec::new();
@@ -627,32 +571,10 @@ impl Session {
originals.push(delta);
}
originals.reverse();
let before = self.document.retired_snapshot.clone();
let mut revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
let replayed: Vec<RegistryDelta> = originals.iter().map(|delta| delta.kind.clone()).collect();
let deleted: HashSet<NodeId> = replayed
.iter()
.filter_map(|op| match op {
RegistryDelta::RemoveNode { id, .. } => Some(*id),
_ => None,
})
.collect();
let repairs = crate::repair::repair_ops(
&before,
&self.document.retired_snapshot,
&self.fold_scratch_at(Some(dropped))?.working_registry,
&replayed,
&deleted,
&self.known_inputs(),
);
let author = originals.last().map_or(self.document.peer, |delta| delta.author);
let repaired = self.commit_repairs(repairs, author)?;
let closing = repaired.last().copied();
let revs = self.commit_ops_authored_at(originals.iter().map(|delta| (delta.kind.clone(), Some(delta.timestamp))), true)?;
for (original, &rev) in originals.iter().zip(&revs) {
let closes = original.id == dropped;
self.carry_attributes_closing(original, rev, closing.filter(|_| closes));
self.carry_attributes(original, rev);
}
revs.extend(repaired);
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
}
@@ -708,7 +630,6 @@ impl Session {
/// Closes this peer's open interaction with a flagged [`RegistryDelta::Meta`] op. Returns the staged ops, a
/// re-registration possibly before the marker; empty when nothing is open.
pub fn end_interaction(&mut self) -> Result<Vec<HotOp>, CrdtError> {
let action = self.action.take();
let peer = self.document.peer;
let open = self
.document
@@ -722,22 +643,9 @@ impl Session {
}
let mut closing = Attributes::new();
closing.set(crate::attr::delta::INTERACTION_END, Value::Bool(true), TimeStamp::ORIGIN);
if let Some(action) = action {
closing.set(crate::attr::delta::ACTION, Value::Str(action), TimeStamp::ORIGIN);
}
self.stage_ops_with([(RegistryDelta::Meta, closing)], ApplyMode::Strict)
}
/// Names this peer's open interaction, replacing an earlier name. Closing it takes the name along.
pub fn name_interaction(&mut self, action: &str) {
self.action = Some(action.to_string());
}
/// The name this peer's open interaction will close with.
pub fn pending_action(&self) -> Option<&str> {
self.action.as_deref()
}
/// Every author's closed interactions in the hot log, the earliest closed first.
pub fn closed_interactions(&self) -> Vec<ClosedInteraction> {
let mut by_author: HashMap<PeerId, Vec<&HotOp>> = HashMap::new();
@@ -934,14 +842,9 @@ impl Session {
/// Retire one closed interaction, coarsened, marking its last delta as the interaction's end. Every op is retired,
/// the ones coarsening drops included. Returns the new revs.
pub fn retire_interaction(&mut self, interaction: &ClosedInteraction) -> Result<Vec<Rev>, CrdtError> {
let marker = interaction.ops.last().and_then(|&id| self.document.hot_log.iter().find(|hot_op| hot_op.id() == id));
let action = marker.and_then(|hot_op| hot_op.attributes.get(crate::attr::delta::ACTION)).cloned();
let revs = self.retire_hot_ops_with(&interaction.ops, true)?;
if let Some(&last) = revs.last() {
self.mark_interaction_end(last);
if let Some(action) = action {
self.document.history.annotate(last, crate::attr::delta::ACTION, action.value, action.timestamp);
}
}
Ok(revs)
}
@@ -992,57 +895,16 @@ impl Session {
}
}
/// Give a minted copy the attributes and retirement time of the delta it stands for, with what closes the interaction moved to `closing` when repairs minted after the copy now end it.
fn carry_attributes_closing(&mut self, original: &Delta, copy: Rev, closing: Option<Rev>) {
use crate::attr::delta::{ACTION, INTERACTION_END};
for rev in std::iter::once(copy).chain(closing) {
if let Some(wall_ms) = original.retired_at() {
self.document.history.set_retired_at(rev, wall_ms);
}
/// Give a minted copy the attributes and retirement time of the delta it stands for.
fn carry_attributes(&mut self, original: &Delta, copy: Rev) {
if let Some(wall_ms) = original.retired_at() {
self.document.history.set_retired_at(copy, wall_ms);
}
for (key, value) in original.attributes.live() {
let moved = closing.filter(|_| key == INTERACTION_END || key == ACTION);
self.document.history.annotate(moved.unwrap_or(copy), key, value.value.clone(), value.timestamp);
self.document.history.annotate(copy, key, value.value.clone(), value.timestamp);
}
}
/// Each node's network and newest primary input anywhere in history, branches included.
fn known_inputs(&self) -> crate::repair::KnownInputs {
let mut networks: HashMap<NodeId, NetworkId> = HashMap::new();
let mut inputs: HashMap<NodeId, (TimeStamp, crate::NodeInput)> = HashMap::new();
for delta in self.document.history.iter() {
let (id, input) = match &delta.kind {
RegistryDelta::AddNode { id, node } | RegistryDelta::RemoveNode { id, snapshot: node } => {
networks.insert(*id, node.network);
(*id, node.inputs.first().map(|slot| slot.input.clone()))
}
RegistryDelta::ChangeNodeInput { id, index: 0, new_input } => (*id, Some(new_input.clone())),
RegistryDelta::SetNodeInputs { id, inputs } => (*id, inputs.first().map(|slot| slot.input.clone())),
_ => continue,
};
let Some(input) = input else { continue };
if inputs.get(&id).is_none_or(|(newest, _)| *newest < delta.timestamp) {
inputs.insert(id, (delta.timestamp, input));
}
}
inputs.into_iter().filter_map(|(id, (_, input))| Some((id, (*networks.get(&id)?, input)))).collect()
}
/// Commit repair ops on top of the line, authored by whoever made the interaction they finish.
fn commit_repairs(&mut self, ops: Vec<RegistryDelta>, author: PeerId) -> Result<Vec<Rev>, CrdtError> {
let mut revs = Vec::with_capacity(ops.len());
for op in ops {
let reverse = crate::prior::capture(&self.document.retired_snapshot, &op);
let delta = Delta::new(self.document.head, author, self.document.clock.tick(), op, reverse);
self.document.apply_op_with(RegistryTarget::Retired, delta.kind.clone(), delta.timestamp, ApplyMode::Strict)?;
self.document.head = Some(delta.id);
revs.push(delta.id);
self.document.history.push(delta);
}
Ok(revs)
}
/// Low-level: set a local annotation attribute (e.g. a commit message) on a retired delta in place.
/// Excluded from the delta's content-addressed `Rev`, so identity is unchanged. Returns whether the
/// delta was found. The `Gdd` layer re-persists the affected history frame after calling this.
@@ -597,37 +597,3 @@ fn undo_takes_back_the_interaction_before_one_already_taken_back() {
twice.retract_interaction().unwrap().expect("a is hot and now the latest");
assert!(twice.hot_log().is_empty());
}
#[test]
fn an_interaction_keeps_its_name_into_history() {
let mut session = Session::with_peer(PeerId(1));
session.name_interaction("Stale");
session.end_interaction().unwrap();
session.stage_ops([set_attribute("a", 1)]).unwrap();
session.name_interaction("Move");
session.end_interaction().unwrap();
session.stage_ops([set_attribute("b", 1)]).unwrap();
session.end_interaction().unwrap();
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).unwrap();
}
let actions: Vec<Option<&str>> = session.history().filter(|delta| delta.is_interaction_end()).map(|delta| delta.action()).collect();
assert_eq!(actions, [Some("Move"), None], "a name set while nothing was open is dropped at the next close");
}
#[test]
fn a_taken_back_interaction_takes_its_name_along() {
let mut session = Session::with_peer(PeerId(1));
session.stage_ops([set_attribute("a", 1)]).unwrap();
session.name_interaction("Move");
session.retract_interaction().unwrap().expect("a is open and hot");
session.stage_ops([set_attribute("b", 1)]).unwrap();
session.end_interaction().unwrap();
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).unwrap();
}
let actions: Vec<Option<&str>> = session.history().filter(|delta| delta.is_interaction_end()).map(|delta| delta.action()).collect();
assert_eq!(actions, [None]);
}
@@ -1,427 +0,0 @@
//! Deterministic simulation of a layer stack edited the way the editor does, with every history operation the History
//! panel offers mixed in: undo, redo, going back, removing a step and bringing one back. After every operation the
//! document must still be a well-formed stack, the snapshot must be what history folds to, and a peer following the
//! head moves must hold the same document.
//!
//! Inspect one run with `SEED=<n> cargo test -p document-graph-storage history_simulation::inspect_seed -- --ignored --nocapture`.
use crate::{Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, ROOT_NETWORK, Registry, RegistryDelta, Rev, Session, UserId, Value};
use std::collections::HashSet;
/// What every layer's implementation names, so nodes need no proto-node declarations.
const LEAF: NetworkId = NetworkId(1);
/// A small xorshift generator, so a seed fixes the run.
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1)
}
fn below(&mut self, bound: usize) -> usize {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
(self.0 % bound as u64) as usize
}
fn pick<T: Copy>(&mut self, options: &[T]) -> Option<T> {
(!options.is_empty()).then(|| options[self.below(options.len())])
}
}
/// The layers from the top of the stack down, following each layer's first input.
fn stack(registry: &Registry) -> Vec<NodeId> {
let mut layers = Vec::new();
let mut below = registry.networks.get(&ROOT_NETWORK).and_then(|network| network.exports.first()).and_then(|slot| slot.target.clone());
while let Some(NodeInput::Node { id, .. }) = below {
if layers.contains(&id) || layers.len() > registry.node_instances.len() {
break;
}
layers.push(id);
below = registry.node_instances.get(&id).and_then(|node| node.inputs.first()).map(|slot| slot.input.clone());
}
layers
}
/// What feeds into `layer` from below.
fn below(registry: &Registry, layer: NodeId) -> NodeInput {
registry.node_instances[&layer].inputs[0].input.clone()
}
/// Points what sits directly above `layer`, a layer or the export, at `input`.
fn rewire_above(registry: &Registry, layer: NodeId, input: NodeInput) -> RegistryDelta {
let layers = stack(registry);
match layers.iter().position(|&id| id == layer) {
Some(0) | None => RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(input),
},
Some(position) => RegistryDelta::ChangeNodeInput {
id: layers[position - 1],
index: 0,
new_input: input,
},
}
}
fn on(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
fn value(number: usize) -> NodeInput {
NodeInput::Value {
value: Value::from(serde_json::json!(number)),
exposed: false,
}
}
/// One interaction's ops, as the editor would stage them for a random edit of the stack.
fn random_edit(random: &mut Random, session: &mut Session) -> Vec<RegistryDelta> {
let registry = session.registry().clone();
let layers = stack(&registry);
match random.below(10) {
// Draw a layer on top
0..=3 => {
let id = session.next_node_id();
let mut node = Node::new(ROOT_NETWORK, Implementation::Network(LEAF), 2);
node.inputs[0].input = layers.first().map_or_else(|| value(0), |&top| on(top));
node.inputs[1].input = value(random.below(100));
let mut ops = vec![
RegistryDelta::AddNode { id, node },
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(id)),
},
];
// The layer below moves into the stack under the new one, as the editor records with its position
if let Some(&below) = layers.first() {
ops.push(super::crdt::change_node_attribute(below, "position", serde_json::json!(random.below(100))));
}
ops
}
// Delete a layer, reconnecting what was above it to what was below
4..=5 => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
let snapshot = registry.node_instances[&layer].clone();
vec![rewire_above(&registry, layer, below(&registry, layer)), RegistryDelta::RemoveNode { id: layer, snapshot }]
}
// Move a layer to the top
6 => {
let Some(layer) = random.pick(&layers[layers.len().min(1)..]) else { return Vec::new() };
vec![
rewire_above(&registry, layer, below(&registry, layer)),
RegistryDelta::ChangeNodeInput {
id: layer,
index: 0,
new_input: on(layers[0]),
},
RegistryDelta::SetNetworkExport {
id: ROOT_NETWORK,
index: 0,
export: Some(on(layer)),
},
]
}
// Change a layer's value
_ => {
let Some(layer) = random.pick(&layers) else { return Vec::new() };
vec![RegistryDelta::ChangeNodeInput {
id: layer,
index: 1,
new_input: value(random.below(100)),
}]
}
}
}
/// The ops of an edit, short enough to read in a failing run's log.
fn summarize(ops: &[RegistryDelta]) -> String {
let short = |id: &NodeId| id.0 % 1000;
let input = |input: &NodeInput| match input {
NodeInput::Node { id, .. } => format!("{}", short(id)),
_ => "value".to_string(),
};
ops.iter()
.map(|op| match op {
RegistryDelta::AddNode { id, node } => format!("add {} on {}", short(id), input(&node.inputs[0].input)),
RegistryDelta::RemoveNode { id, .. } => format!("remove {}", short(id)),
RegistryDelta::ChangeNodeInput { id, index, new_input } => format!("{}.{index} = {}", short(id), input(new_input)),
RegistryDelta::SetNetworkExport { export, .. } => format!("export = {}", export.as_ref().map_or("none".to_string(), input)),
other => format!("{other:?}"),
})
.collect::<Vec<_>>()
.join(", ")
}
/// The revs closing each interaction on the head's line, newest first.
fn line_steps(session: &Session) -> Vec<Rev> {
let mut steps = Vec::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
if delta.is_interaction_end() {
steps.push(delta.id);
}
current = delta.parent;
}
steps
}
/// The revs closing interactions left behind on branches.
fn branch_steps(session: &Session) -> Vec<Rev> {
let line: HashSet<Rev> = {
let mut line = HashSet::new();
let mut current = session.head_rev();
while let Some(delta) = current.and_then(|rev| session.delta(rev)) {
line.insert(delta.id);
current = delta.parent;
}
line
};
let mut steps: Vec<Rev> = session
.history()
.filter(|delta| delta.is_interaction_end() && !line.contains(&delta.id))
.map(|delta| delta.id)
.collect();
steps.sort();
steps
}
/// The layers the interaction ending at `end` added and deleted, by what it did in all.
fn added_and_removed(session: &Session, end: Rev) -> (Vec<NodeId>, Vec<NodeId>) {
let (mut added, mut removed) = (Vec::new(), Vec::new());
let mut current = session.delta(end);
while let Some(delta) = current {
match &delta.kind {
RegistryDelta::AddNode { id, .. } => added.push(*id),
RegistryDelta::RemoveNode { id, .. } => removed.push(*id),
_ => {}
}
current = delta.parent.and_then(|parent| session.delta(parent)).filter(|parent| !parent.is_interaction_end());
}
let net = |these: &[NodeId], those: &[NodeId]| these.iter().filter(|id| !those.contains(id)).copied().collect();
(net(&added, &removed), net(&removed, &added))
}
/// The layers the step ending at `end` added that a newer deletion on its own line had taken again.
fn lost_on_its_line(session: &Session, end: Rev, added: &[NodeId]) -> HashSet<NodeId> {
let mut lost = HashSet::new();
let mut added_at = std::collections::HashMap::new();
let mut line = Vec::new();
let mut current = session.delta(end);
while let Some(delta) = current {
line.push(delta);
current = delta.parent.and_then(|parent| session.delta(parent));
}
for delta in &line {
if let RegistryDelta::AddNode { id, .. } = &delta.kind {
added_at.entry(*id).or_insert(delta.timestamp);
}
}
for delta in &line {
if let RegistryDelta::RemoveNode { id, .. } = &delta.kind
&& added.contains(id)
&& added_at.get(id).is_some_and(|stamp| *stamp < delta.timestamp)
{
lost.insert(*id);
}
}
lost
}
/// The layers live on the line just before the interaction ending at `end`.
fn live_before(session: &Session, end: Rev) -> HashSet<NodeId> {
let mut current = session.delta(end);
while let Some(delta) = current.filter(|delta| delta.id == end || !delta.is_interaction_end()) {
current = delta.parent.and_then(|parent| session.delta(parent));
}
let mut line = Vec::new();
while let Some(delta) = current {
line.push(delta.clone());
current = delta.parent.and_then(|parent| session.delta(parent));
}
line.reverse();
let replayed = Session::replay_from_history(PeerId(3), UserId(3), line, 0).expect("the line replays");
replayed.retired_registry().node_instances.keys().copied().collect()
}
/// Every layer input and the export name a live layer, nothing loops, and every layer is in the stack, so none is
/// left drawn by nothing.
fn assert_well_formed(context: &str, registry: &Registry) {
let exports = registry.networks.get(&ROOT_NETWORK).map(|network| network.exports.clone()).unwrap_or_default();
let export = exports.first().and_then(|slot| slot.target.clone());
if let Some(NodeInput::Node { id, .. }) = &export {
assert!(registry.node_instances.contains_key(id), "{context}: the export names {id:?}, which is gone");
}
for (id, node) in &registry.node_instances {
for (index, slot) in node.inputs.iter().enumerate() {
if let NodeInput::Node { id: named, .. } = &slot.input {
assert!(registry.node_instances.contains_key(named), "{context}: input {index} of {id:?} names {named:?}, which is gone");
}
}
}
let mut stacked_on = HashSet::new();
let primary_inputs = registry.node_instances.values().filter_map(|node| node.inputs.first()).map(|slot| &slot.input);
for input in primary_inputs.chain(export.iter()) {
if let NodeInput::Node { id, .. } = input {
assert!(stacked_on.insert(*id), "{context}: two layers or the export sit on {id:?}");
}
}
let layers = stack(registry);
let unique: HashSet<NodeId> = layers.iter().copied().collect();
assert_eq!(unique.len(), layers.len(), "{context}: the stack loops: {layers:?}");
let stray: Vec<&NodeId> = registry.node_instances.keys().filter(|id| !unique.contains(id)).collect();
assert!(stray.is_empty(), "{context}: layers {stray:?} are in no stack (stack {layers:?})");
}
fn assert_consistent(context: &str, session: &Session) {
assert!(session.hot_log().is_empty(), "{context}: everything retires before history changes");
assert!(session.registry().value_equal(session.retired_registry()), "{context}: working and snapshot differ");
let folded = session.snapshot_from_history().expect("history folds");
assert!(folded.value_equal(session.retired_registry()), "{context}: the snapshot is not what history folds to");
assert_well_formed(context, session.retired_registry());
}
/// Closes the open interaction and retires it as one step.
fn retire_step(session: &mut Session) {
session.end_interaction().expect("close");
for interaction in session.closed_interactions() {
session.retire_interaction(&interaction).expect("retire");
}
}
/// Brings `follower` up to the host's history and head, as the room does with what the host broadcasts.
fn catch_up(follower: &mut Session, host: &Session) {
let missing: Vec<_> = host.cloned_deltas().into_iter().filter(|delta| follower.delta(delta.id).is_none()).collect();
follower.follow(missing, host.head_rev()).expect("follow");
}
/// A peer that joins now and holds what the host holds.
fn fresh_follower(host: &Session) -> Session {
Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0)
}
fn simulate(seed: u64, steps: usize, log: &mut Vec<String>) -> Session {
let mut random = Random::new(seed);
let mut host = Session::with_identity(PeerId(1), UserId(1));
let networks = [
RegistryDelta::AddNetwork {
id: ROOT_NETWORK,
network: Network::default(),
},
RegistryDelta::AddNetwork {
id: LEAF,
network: Network::default(),
},
];
host.stage_ops(networks).expect("stage the networks");
retire_step(&mut host);
let mut follower = fresh_follower(&host);
for step in 0..steps {
let context = |what: &str, log: &[String]| format!("seed {seed}, step {step}, {what}\n{}", log.join("\n"));
match random.below(12) {
0..=5 => {
let ops = random_edit(&mut random, &mut host);
if ops.is_empty() {
continue;
}
log.push(format!("{step}: edit {}", summarize(&ops)));
host.stage_ops(ops).expect("stage");
retire_step(&mut host);
catch_up(&mut follower, &host);
}
6 if host.can_undo() => {
log.push(format!("{step}: undo"));
host.undo().expect("undo");
follower = fresh_follower(&host);
}
7 if host.can_redo() => {
log.push(format!("{step}: redo"));
host.redo().expect("redo");
follower = fresh_follower(&host);
}
8 => {
// Not the newest step, which going back to would leave everything as it is
let Some(target) = random.pick(&line_steps(&host)[1.min(line_steps(&host).len())..]) else {
continue;
};
log.push(format!("{step}: go back to {target:?}"));
let (moved, _) = host.move_head_to(target).expect("go back");
follower.apply_head_move(&moved).expect("follow the move");
}
9 => {
let steps = line_steps(&host);
// The first step adds the networks, which nothing can do without
let Some(target) = random.pick(&steps[..steps.len().saturating_sub(1)]) else { continue };
log.push(format!("{step}: remove {target:?}"));
let (mut added, _) = added_and_removed(&host, target);
// A layer the line had before the step stays
let earlier = live_before(&host, target);
added.retain(|id| !earlier.contains(id));
let (moved, _) = host.drop_interaction(target).expect("remove the step");
follower.apply_head_move(&moved).expect("follow the removal");
let kept: Vec<&NodeId> = added.iter().filter(|id| host.retired_registry().node_instances.contains_key(id)).collect();
assert!(kept.is_empty(), "{}", context(&format!("the removed step's layers {kept:?} are still there"), log));
}
10 | 11 => {
let Some(target) = random.pick(&branch_steps(&host)) else { continue };
log.push(format!("{step}: bring back {target:?}"));
let (mut added, removed) = added_and_removed(&host, target);
// A layer the line already had from this step and deleted since stays deleted
added.retain(|id| !host.retired_registry().removed_nodes.contains_key(id));
// As does one a newer deletion took on the step's own line
let lost = lost_on_its_line(&host, target, &added);
added.retain(|id| !lost.contains(id));
host.restore_interaction(target).expect("bring back");
catch_up(&mut follower, &host);
let registry = host.retired_registry();
let missing: Vec<&NodeId> = added.iter().filter(|id| !registry.node_instances.contains_key(id)).collect();
let kept: Vec<&NodeId> = removed.iter().filter(|id| registry.node_instances.contains_key(id)).collect();
assert!(missing.is_empty(), "{}", context(&format!("the brought back step's layers {missing:?} are missing"), log));
assert!(kept.is_empty(), "{}", context(&format!("the layers {kept:?} the brought back step deleted are still there"), log));
}
_ => continue,
}
let what = log.last().cloned().unwrap_or_default();
assert_consistent(&context(&what, log), &host);
assert_eq!(follower.head_rev(), host.head_rev(), "{}", context("the follower is on another head", log));
assert!(
follower.retired_registry().value_equal(host.retired_registry()),
"{}",
context("the follower holds another document", log)
);
}
host
}
#[test]
fn history_operations_keep_the_stack_whole_and_peers_converged() {
let seeds: u64 = std::env::var("SEEDS").ok().and_then(|seeds| seeds.parse().ok()).unwrap_or(200);
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
for seed in 0..seeds {
simulate(seed, steps, &mut Vec::new());
}
}
/// A seed fixes the run, so one that fails can be replayed.
#[test]
fn a_seed_fixes_the_history_run() {
let stacks = |seed| stack(simulate(seed, 60, &mut Vec::new()).retired_registry());
for seed in 0..5 {
assert_eq!(stacks(seed), stacks(seed), "seed {seed}");
}
}
#[test]
#[ignore]
fn inspect_seed() {
let seed = std::env::var("SEED").ok().and_then(|seed| seed.parse().ok()).unwrap_or(0);
let mut log = Vec::new();
let steps = std::env::var("STEPS").ok().and_then(|steps| steps.parse().ok()).unwrap_or(80);
let host = simulate(seed, steps, &mut log);
println!("{}\nstack {:?}", log.join("\n"), stack(host.retired_registry()));
}
+11 -2
View File
@@ -2,7 +2,7 @@
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_format::{GddV1, GddV1Layout, ResourceProxy};
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, SessionToken};
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
#[derive(Debug, thiserror::Error)]
pub enum LiveError {
@@ -58,6 +58,10 @@ impl LiveDocument {
self.token
}
pub fn role(&self) -> Option<Role> {
self.gdd.role()
}
pub fn is_synced(&self) -> bool {
self.gdd.is_synced()
}
@@ -97,12 +101,17 @@ 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(unsafe, crate_path = #core::ctor))]
#[cfg_attr(not(target_family = "wasm"), ctor)]
fn register() {
#core::#register(#migration);
}
-1
View File
@@ -2,5 +2,4 @@
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
mod graphene_core;
mod math_nodes;
mod raster_nodes;
@@ -1,107 +0,0 @@
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)));
}
}
@@ -1,4 +0,0 @@
//! Migrations of the nodes in `math_nodes`.
mod math_formula_from_math_f;
mod renames;
@@ -1,5 +0,0 @@
//! 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.15.0"
matchbox_socket = "0.14.0"
futures = { workspace = true }
log = { workspace = true }
serde = { workspace = true }
-20
View File
@@ -405,12 +405,6 @@ 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 })
}
@@ -1132,18 +1126,4 @@ 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<Packet> {
fn frames(bytes: &[u8]) -> Vec<Box<[u8]>> {
// Chunking an empty packet would yield no frame at all.
let chunks: Vec<&[u8]> = if bytes.is_empty() { vec![&[]] } else { bytes.chunks(CHUNK_BYTES).collect() };
@@ -258,7 +258,7 @@ mod tests {
assert_eq!(incoming.wait().now_or_never(), None, "nothing arrived yet");
lock(&inbox).packets.push_back((peer(1), Packet::from_static(&[FRAME_FINAL, 7])));
lock(&inbox).packets.push_back((peer(1), Box::new([FRAME_FINAL, 7])));
assert_eq!(incoming.wait().now_or_never(), Some(true), "an arrival resolves the wait");
assert_eq!(incoming.wait().now_or_never(), Some(true), "and keeps it resolved until the inbox is drained");
@@ -8,7 +8,6 @@ use crate::messages::portfolio::document::utility_types::network_interface;
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::common_functionality::utility_functions::name_layer_action;
use crate::messages::tool::utility_types::ToolType;
use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
@@ -167,12 +166,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
return;
}
responses.add(DocumentMessage::AddTransaction);
let nodes = deleted_with_children.len() + chain_nodes.len();
responses.add(match (layers.len() == nodes, nodes) {
(true, _) => name_layer_action("Cut", nodes),
(false, 1) => DocumentMessage::NameInteraction { action: "Cut a node".into() },
(false, count) => DocumentMessage::NameInteraction { action: format!("Cut {count} nodes") },
});
if !deleted_with_children.is_empty() {
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: deleted_with_children,
@@ -384,7 +377,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let mut added_nodes = false;
let pasted = entries.len();
for entry in entries.into_iter().rev() {
let new_ids: HashMap<_, _> = entry.nodes.iter().map(|(id, _)| (*id, NodeId::new())).collect();
let Some(&root_id) = new_ids.get(&NodeId(0)) else {
@@ -396,7 +388,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
if !added_nodes {
responses.add(DocumentMessage::DeselectAllLayers);
responses.add(DocumentMessage::AddTransaction);
responses.add(name_layer_action("Pasted", pasted));
added_nodes = true;
}
@@ -330,29 +330,6 @@ 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\
@@ -376,7 +353,7 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
rows.extend_from_slice(&[header, save_as_gdd, save_with_history, validate_storage_round_trip]);
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
}
// =============
@@ -33,18 +33,18 @@ impl LayoutHolder for DocumentsOpenElsewhereDialog {
]),
];
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
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)
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])
}));
Layout(rows)
@@ -199,24 +199,6 @@ pub enum FrontendMessage {
UpdateHistoryPanel {
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
},
UpdateHistoryGraph {
graph: crate::messages::portfolio::history::utility_types::HistoryGraphState,
},
UpdateHistoryGraphOverlay {
open: bool,
},
/// A History panel step's captured image as an SVG, sent when the GPU is unavailable, which the panel shows wherever a row names `id`.
UpdateHistoryThumbnail {
id: String,
svg: String,
},
/// A History panel step's captured image as straight RGBA pixels.
UpdateHistoryThumbnailPixels {
id: String,
width: u32,
height: u32,
pixels: serde_bytes::ByteBuf,
},
UpdateNodeGraphCursors {
cursors: Vec<FrontendRemoteCursor>,
},
@@ -25,7 +25,7 @@ pub enum SessionStatus {
Disconnected,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
#[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))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[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(message) = self.results_receiver.try_recv() {
while let Ok(Some(message)) = self.results_receiver.try_next() {
responses.push_back(message);
}
}
@@ -345,7 +345,6 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
//
// DocumentMessage
entry!(DoubleTap(Space); action_dispatch=DocumentMessage::GraphViewOverlayToggle),
entry!(KeyDown(KeyH); modifiers=[Alt], action_dispatch=HistoryMessage::GraphOverlayToggle),
entry!(KeyDownNoRepeat(Escape); action_dispatch=DocumentMessage::Escape),
entry!(KeyDown(Delete); action_dispatch=DocumentMessage::DeleteSelectedLayers),
entry!(KeyDown(Backspace); action_dispatch=DocumentMessage::DeleteSelectedLayers),
@@ -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.operator_only);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
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 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);
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);
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))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum LayoutTarget {
@@ -16,16 +16,13 @@ fn utf16_offsets(source: &str) -> Vec<u32> {
units
}
/// 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> {
/// 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> {
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
if expression.trim().is_empty() {
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
return None;
}
if operator_only {
return math_parser::reducer::reducer_error(expression);
}
math_parser::ast::Node::try_parse_from_str(expression).err()
}
@@ -146,11 +143,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, operator_only: bool) -> MathExpressionTokens {
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
let units = utf16_offsets(source);
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
let tokens = math_parser::highlight::highlight(source, operator_only).into_iter().map(|token| {
let tokens = math_parser::highlight::highlight(source, accepts_reducers).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 the value is a lone operator or function name like `+` or `max`, applied across a list, rather than an expression.
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
#[serde(skip)]
pub operator_only: bool,
pub accepts_reducers: bool,
pub disabled: bool,
// Tooltips
@@ -7,7 +7,6 @@ use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRe
use super::utility_types::network_interface::NodeNetworkInterface;
use super::utility_types::network_interface::editor_delta::{EditorDelta, StagingError, construct_batch};
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
use crate::messages::portfolio::history::utility_types::LineChange;
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
@@ -142,15 +141,7 @@ impl DocumentHistory {
if self.legacy_undo_stack.is_empty() {
return false;
}
// 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 {
let note = if let Some(ops) = self.retract_storage_interaction() {
UndoNote::Retracted(ops)
} else if in_session && let Some(rev) = self.undo_retired_step() {
UndoNote::Dropped(rev)
@@ -178,19 +169,16 @@ 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
}
@@ -208,16 +196,18 @@ impl DocumentHistory {
self.undo_notes.drain(..evicted);
}
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 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 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 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 undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
@@ -232,21 +222,22 @@ impl DocumentHistory {
}
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) -> bool {
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()
self.change_line(|storage| storage.redo_retired_step(rev), "Redoing the dropped step failed")
}
/// Returns whether storage made the change.
pub fn change_line(&mut self, rev: document_graph_storage::Rev, change: LineChange) -> bool {
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;
};
let result = match change {
LineChange::MoveHead => storage.move_head(rev),
LineChange::Remove => storage.drop_step(rev),
LineChange::Restore => storage.redo_retired_step(rev),
};
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok()
change(storage).inspect_err(|error| log::error!("{failure}: {error}")).is_ok()
}
/// Forgets the legacy snapshots once the head has moved off their line.
@@ -56,9 +56,16 @@ pub enum DocumentMessage {
DeselectAllLayers,
DocumentHistoryBackward,
DocumentHistoryForward,
ChangeHistoryLine {
/// 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,
change: crate::messages::portfolio::history::utility_types::LineChange,
},
DocumentStructureChanged,
DrawArtboardOverlays {
@@ -131,10 +138,6 @@ pub enum DocumentMessage {
PasteNodes {
nodes: Vec<(NodeId, NodeTemplate)>,
},
/// Names the open interaction for the History panel, such as after the transaction a tool starts.
NameInteraction {
action: String,
},
MoveSelectedLayersToGroup {
parent: LayerNodeIdentifier,
},
@@ -24,7 +24,6 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, FlowType, InputConnector, NodeTemplate, OutputConnector, ReconcileError, Reconciled};
use crate::messages::portfolio::history::utility_types::LineChange;
use crate::messages::portfolio::utility_types::PanelType;
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::edit_target::EditTarget;
@@ -36,7 +35,7 @@ use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::NodeGraphExecutor;
use document_container::AnyContainer;
use document_graph_storage::{Declarations, Rev};
use document_graph_storage::Declarations;
use glam::{DAffine2, DVec2};
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceStorage};
use graph_craft::document::value::{TaggedValue, deserialize_replacing_null_floats_with_zero};
@@ -474,14 +473,27 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
}
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::ChangeHistoryLine { rev, change } => {
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), preferences.validate_storage_round_trip, responses)
}
DocumentMessage::NameInteraction { action } => {
if let Some(storage) = self.history.storage_mut() {
storage.name_interaction(&action);
}
}
DocumentMessage::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();
@@ -1049,7 +1061,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Added an image".into() });
let layer = graph_modification_utils::new_image_layer(data, layer_node_id, layer_parent, responses);
@@ -1111,7 +1122,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Added an SVG".into() });
let layer = graph_modification_utils::new_svg_layer(svg, transform, !place_at_origin, layer_node_id, layer_parent, responses);
@@ -1265,7 +1275,6 @@ 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);
@@ -1301,7 +1310,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportOptions {
include_history,
include_history: false,
..Default::default()
},
export_load_handle.as_ref(),
@@ -2215,7 +2224,6 @@ impl DocumentMessageHandler {
document.apply_stored_document_settings(storage.view_settings());
document.set_storage(storage, declarations, byte_store);
document.refresh_resource_registry();
document
}
@@ -2443,10 +2451,6 @@ impl DocumentMessageHandler {
self.history.storage()
}
pub fn declarations(&self) -> &document_graph_storage::Declarations {
self.history.declarations()
}
/// Mutable access to the `Gdd` working copy.
pub fn storage_mut(&mut self) -> Option<&mut document_format::GddV1> {
self.history.storage_mut()
@@ -2456,6 +2460,7 @@ 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) {
@@ -3013,17 +3018,23 @@ impl DocumentMessageHandler {
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Makes a History panel change in storage and drops the legacy snapshots, which are off the head's line.
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, validate: bool, responses: &mut VecDeque<Message>) {
/// 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;
}
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort);
self.stage_edits_outside_transaction(byte_store, validate);
self.history.retire_storage_interaction();
let stored_name = self.stored_name().map(str::to_string);
if !self.history.change_line(rev, change) {
if !action(&mut self.history) {
return;
}
self.history.clear_legacy();
@@ -3859,7 +3870,7 @@ impl DocumentMessageHandler {
]
}
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration, history_graph_open: bool) {
pub fn update_document_widgets(&self, responses: &mut VecDeque<Message>, animation_is_playing: bool, time: Duration) {
let mut widgets = vec![
IconButton::new("PlaybackToStart", 24)
.tooltip_label("Restart Animation")
@@ -3944,14 +3955,6 @@ impl DocumentMessageHandler {
widgets.extend([
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextButton::new("History")
.icon("HistoryUndo")
.tooltip_label(if history_graph_open { "Hide the history graph" } else { "Show the history graph" })
.tooltip_description("Every step and branch of the document's history, drawn over the viewport.")
.tooltip_shortcut(action_shortcut!(HistoryMessageDiscriminant::GraphOverlayToggle))
.on_update(|_| HistoryMessage::GraphOverlayToggle.into())
.widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextButton::new("Node Graph")
.icon(if self.graph_view_overlay_open { "GraphViewOpen" } else { "GraphViewClosed" })
.hover_icon(if self.graph_view_overlay_open { "GraphViewClosed" } else { "GraphViewOpen" })
@@ -1394,8 +1394,8 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
// 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(),
// 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(),
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,7 +208,6 @@ pub enum NodeGraphMessage {
SendWires,
UpdateVisibleNodes,
SendGraph,
SendNodePositions,
SetInputValue {
node_id: NodeId,
input_index: usize,
@@ -19,7 +19,7 @@ use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
use crate::messages::tool::common_functionality::edit_target::{EditTarget, ResolvedEditTarget};
use crate::messages::tool::common_functionality::graph_modification_utils::get_clip_mode;
use crate::messages::tool::common_functionality::utility_functions::{make_path_editable_is_allowed, name_layer_action};
use crate::messages::tool::common_functionality::utility_functions::make_path_editable_is_allowed;
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position;
@@ -131,9 +131,9 @@ pub struct NodeGraphMessageHandler {
reordering_export: Option<usize>,
/// The end index of the moved connector
end_index: Option<usize>,
/// 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
/// 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
frontend_wires: HashSet<(NodeId, usize)>,
evaluation_errors: Vec<NodeEvaluationError>,
}
@@ -450,18 +450,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
return;
};
responses.add(DocumentMessage::AddTransaction);
let node_ids: Vec<NodeId> = selected_nodes.selected_nodes().cloned().collect();
let layers = node_ids.iter().filter(|node_id| network_interface.is_layer(node_id, selection_network_path)).count();
if !node_ids.is_empty() {
responses.add(match (layers == node_ids.len(), node_ids.len()) {
(true, _) => name_layer_action("Deleted", layers),
(false, 1) => DocumentMessage::NameInteraction { action: "Deleted a node".into() },
(false, count) => DocumentMessage::NameInteraction {
action: format!("Deleted {count} nodes"),
},
});
}
responses.add(NodeGraphMessage::DeleteNodes { node_ids, delete_children });
responses.add(NodeGraphMessage::DeleteNodes {
node_ids: selected_nodes.selected_nodes().cloned().collect::<Vec<_>>(),
delete_children,
});
responses.add(NodeGraphMessage::RunDocumentGraph);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::SendGraph);
@@ -658,7 +650,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
insert_node_input_index,
} => {
network_interface.insert_node_between(&node_id, &input_connector, insert_node_input_index, selection_network_path);
network_interface.connect_read_node_to_map(&node_id, selection_network_path);
}
NodeGraphMessage::InsertDotOnWire { node_id, input_connector, x, y } => {
network_interface.insert_dot_on_wire(node_id, &input_connector, IVec2::new(x, y), selection_network_path);
@@ -2026,7 +2017,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.iter().map(|node| &node.id) {
for node_id in &self.frontend_nodes {
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;
@@ -2061,8 +2052,9 @@ 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 {
self.frontend_nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
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 });
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
@@ -2079,36 +2071,6 @@ 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::*;
@@ -2172,15 +2134,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
if graph_view_overlay_open {
if !rubber_band {
responses.add(NodeGraphMessage::SendGraph);
}
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 => {
@@ -2224,9 +2183,6 @@ 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 {
@@ -3454,8 +3410,7 @@ impl NodeGraphMessageHandler {
.exports
.iter()
.any(|export| matches!(export, NodeInput::Node { node_id: export_node_id, .. } if *export_node_id == node_id));
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 {
if selection_is_not_already_the_output && no_other_selections {
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, operator_only: bool) -> Vec<WidgetInstance> {
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: 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, operator_only);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, operator_only);
let error = math_expression_error(expression, accepts_reducers);
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
let input = MathExpressionInput::new(expression.clone())
.tokens(tokens)
.tooltips(tooltips)
.operator_only(operator_only)
.accepts_reducers(accepts_reducers)
.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(if operator_only { "Invalid Operator" } else { "Invalid Math Expression" })
.tooltip_label("Invalid Math Expression")
.tooltip_description(math_expression_error_description(error)),
None => IconLabel::new("Empty12px"),
};
@@ -3942,13 +3942,12 @@ mod tests {
#[test]
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
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}`");
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}`");
}
assert!(math_expression_error("2 +", false).is_some());
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!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
}
@@ -664,39 +664,6 @@ 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,7 +4,6 @@ use super::{
};
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::test_utils::test_prelude::*;
@@ -3533,121 +3532,3 @@ 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,9 +1,4 @@
use super::resolved_types::TypeSource;
use super::*;
use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::vector::style::Gradient;
use graphene_std::{Color, Graphic};
impl NodeNetworkInterface {
/// The top left corner of a node in node graph grid coordinates.
@@ -1160,41 +1155,6 @@ impl NodeNetworkInterface {
self.create_wire(&upstream_output, &InputConnector::node_at_index(*node_id, insert_node_input_index), network_path);
}
/// Feeds an unconnected Map node's mapped input with the Read node matching the element type of its content.
pub fn connect_read_node_to_map(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
if self.reference(node_id, network_path) != Some(DefinitionIdentifier::ProtoNode(graphene_std::graphic::map::IDENTIFIER)) {
return;
}
let mapped_input = InputConnector::node_at_index(*node_id, 1);
if !matches!(self.input_from_connector(&mapped_input, network_path), Some(NodeInput::Value { .. })) {
return;
}
let Some(content_source) = self.upstream_output_connector(&InputConnector::primary_input(*node_id), network_path) else {
return;
};
let Some(mut read_node_template) = read_node_for_content(&self.output_type(&content_source, network_path))
.and_then(resolve_proto_node_type)
.map(|definition| definition.default_node_template())
else {
return;
};
let Some(map_position) = self.position(node_id, network_path) else {
return;
};
let below_content_source = content_source
.node_id()
.and_then(|source| Some(self.position(&source, network_path)?.y + self.node_height(&source, network_path) as i32 + 1));
let read_node_position = IVec2::new(map_position.x - NODE_CHAIN_WIDTH, below_content_source.unwrap_or(map_position.y + 2));
read_node_template.node_type_metadata = NodeTypePersistentMetadata::node(read_node_position);
let read_node_id = NodeId::new();
self.insert_node(read_node_id, read_node_template, network_path);
self.create_wire(&OutputConnector::primary_output(read_node_id), &mapped_input, network_path);
}
/// Inserts the freshly-created `node_id` onto the wire feeding `input_connector`: the previous upstream becomes the
/// new node's primary (index 0) input, and the new node feeds `input_connector`.
///
@@ -1615,30 +1575,3 @@ impl NodeNetworkInterface {
self.layer_chain(layer, network_path) == intended_chain
}
}
/// The Read node yielding each element of a Map node's content, unbundling a whole-list `Item<Bundle<T>>` wire to its `T`.
pub(super) fn read_node_for_content(content_type: &TypeSource) -> Option<ProtoNodeIdentifier> {
use graphene_std::context::{read_color, read_gradient, read_graphic, read_number, read_raster, read_vector};
use graphene_std::text_nodes::read_string;
let bundle_element = content_type.compiled_nested_type().and_then(Type::bundle_element_name);
let element_type = content_type.compiled_element_type()?;
[
(concrete!(Vector), read_vector::IDENTIFIER),
(concrete!(Graphic), read_graphic::IDENTIFIER),
(concrete!(Raster<CPU>), read_raster::IDENTIFIER),
(concrete!(Color), read_color::IDENTIFIER),
(concrete!(Gradient), read_gradient::IDENTIFIER),
(concrete!(f64), read_number::IDENTIFIER),
(concrete!(String), read_string::IDENTIFIER),
]
.into_iter()
.find_map(|(candidate, read_node)| {
let matches = match (bundle_element, &candidate) {
(Some(bundle_element), Type::Concrete(descriptor)) => descriptor.name == bundle_element,
_ => candidate == *element_type,
};
matches.then_some(read_node)
})
}
@@ -1408,10 +1408,8 @@ 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 if self.number_of_outputs(&toggle_id, network_path) > 0 {
Previewing::Yes { previewed: primary_output }
} else {
return;
Previewing::Yes { previewed: primary_output }
};
self.set_previewing(previewing, network_path);
}
@@ -376,10 +376,6 @@ 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"],
@@ -1270,10 +1266,6 @@ 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)");
}
}
}
}
@@ -1392,8 +1384,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 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`.
// 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`.
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
.network_interface
.document_network()
@@ -1424,7 +1416,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
})
.is_some();
// The rewritten "Math Function" expression, or `None` when only the Extend + "Math Formula" form can preserve the node's meaning
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
let inline_b_constant = match operand_b.as_value() {
Some(TaggedValue::Number(constant)) => Some(*constant),
_ => None,
@@ -1444,8 +1436,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
};
if let Some(fx_expression) = fx_expression {
// "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 {
// "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 {
continue;
};
let mut node_template = definition.default_node_template();
@@ -1459,7 +1451,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 Formula" reads; an unwired constant operand becomes a one-item list value
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
let as_list_input = |input: &NodeInput| match input.as_value() {
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
_ => input.clone(),
@@ -1469,7 +1461,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_formula::IDENTIFIER)) else {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_f::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
@@ -1862,7 +1854,6 @@ 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);
@@ -1985,9 +1976,10 @@ 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. 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 {
// 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 {
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);
@@ -3848,46 +3840,6 @@ 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
@@ -4604,7 +4556,7 @@ mod tests {
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
@@ -4639,7 +4591,7 @@ mod tests {
document.network_interface.insert_node(
node_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
..Default::default()
},
@@ -4662,44 +4614,8 @@ mod tests {
assert_eq!(outward_wires.as_deref(), Some([InputConnector::node_at_index(node_id, 0)].as_slice()));
}
// 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"
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
#[test]
fn old_math_nodes_split_into_the_expression_node_pair() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
@@ -4750,7 +4666,7 @@ mod tests {
.expect("an Extend node should be spliced in")
};
// A static expression that never reads `B` becomes "Math Function" with `A` renamed to `x` and the `B` input dropped
// A static expression that never reads `B` becomes "Math f(x)" with `A` renamed to `x` and the `B` input dropped
{
let inputs = vec![
NodeInput::node(source_a_id, 0),
@@ -4760,7 +4676,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_function::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.len(),
@@ -4782,7 +4698,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_function::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
let node = &document.network_interface.document_network().nodes[&math_id];
assert_eq!(
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
@@ -4801,7 +4717,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_formula::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::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)));
@@ -4823,7 +4739,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_formula::IDENTIFIER);
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::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,10 +143,6 @@ 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,184 +0,0 @@
//! Tints what a step changed onto a close-up of the document, colored by how the layer under each changed pixel changed.
use super::utility_types::Pixels;
use glam::{DVec2, UVec2};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Change {
Added,
Removed,
Changed,
}
/// Where a layer's change shows, in document coordinates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChangedArea {
pub change: Change,
pub bounds: [DVec2; 2],
}
/// How far apart two premultiplied channels must be for a pixel to count as changed, out of 255.
const THRESHOLD: u8 = 16;
/// How much of a tint's color covers a changed pixel.
const TINT_STRENGTH: f32 = 0.6;
/// How opaque unchanged pixels stay, so the tints stand out.
const UNCHANGED_OPACITY: f32 = 0.35;
fn tint_color(change: Change) -> [u8; 3] {
match change {
Change::Added => [64, 200, 96],
Change::Removed => [232, 64, 64],
Change::Changed => [240, 176, 32],
}
}
/// The close-up `after` of `frame` with each pixel that differs from `before`, the whole document before the step
/// showing `before_frame`, tinted by the change of the area it falls in. A pixel that lost coverage shows as it was.
pub fn tint_changes(after: &Pixels, frame: [DVec2; 2], before: &Pixels, before_frame: [DVec2; 2], areas: &[ChangedArea]) -> Pixels {
let size = after.size;
let mut rgba = Vec::with_capacity(after.rgba.len());
for y in 0..size.y {
for x in 0..size.x {
let point = frame[0] + (DVec2::new(x as f64, y as f64) + 0.5) / size.as_dvec2() * (frame[1] - frame[0]);
let now = pixel(after, UVec2::new(x, y));
let then = sample(before, before_frame, point);
let shown = if differs(now, then) {
let lost = now[3] < then[3];
tint(if lost { then } else { now }, change_at(areas, point, lost))
} else {
[now[0], now[1], now[2], (now[3] as f32 * UNCHANGED_OPACITY) as u8]
};
rgba.extend_from_slice(&shown);
}
}
Pixels { size, rgba }
}
/// The area around every change, with a margin, at the thumbnails' aspect ratio. None when nothing changed.
pub fn close_up(areas: &[ChangedArea]) -> Option<[DVec2; 2]> {
/// The thumbnails' width over their height.
const ASPECT_RATIO: f64 = 1.5;
let [min, max] = areas.iter().map(|area| area.bounds).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])])?;
let margin = ((max - min) * 0.15).max(DVec2::splat(4.));
let (min, max) = (min - margin, max + margin);
let size = max - min;
let size = if size.x >= size.y * ASPECT_RATIO {
DVec2::new(size.x, size.x / ASPECT_RATIO)
} else {
DVec2::new(size.y * ASPECT_RATIO, size.y)
};
let center = (min + max) / 2.;
Some([center - size / 2., center + size / 2.])
}
/// The change of the areas holding `point`, preferring a removal where the pixel lost coverage and an addition elsewhere.
fn change_at(areas: &[ChangedArea], point: DVec2, lost: bool) -> Change {
let holding = |change: Change| areas.iter().any(|area| area.change == change && contains(area.bounds, point));
let order = match lost {
true => [Change::Removed, Change::Changed, Change::Added],
false => [Change::Added, Change::Changed, Change::Removed],
};
order.into_iter().find(|&change| holding(change)).unwrap_or(Change::Changed)
}
fn contains(bounds: [DVec2; 2], point: DVec2) -> bool {
point.cmpge(bounds[0]).all() && point.cmple(bounds[1]).all()
}
fn pixel(pixels: &Pixels, at: UVec2) -> [u8; 4] {
let index = (at.y * pixels.size.x + at.x) as usize * 4;
pixels.rgba.get(index..index + 4).and_then(|pixel| pixel.try_into().ok()).unwrap_or([0; 4])
}
/// The pixel of `pixels`, which shows `frame`, at a document point, transparent outside it.
fn sample(pixels: &Pixels, frame: [DVec2; 2], point: DVec2) -> [u8; 4] {
let at = (point - frame[0]) / (frame[1] - frame[0]) * pixels.size.as_dvec2();
if at.cmplt(DVec2::ZERO).any() || at.cmpge(pixels.size.as_dvec2()).any() {
return [0; 4];
}
pixel(pixels, at.as_uvec2())
}
fn differs(a: [u8; 4], b: [u8; 4]) -> bool {
let premultiplied = |pixel: [u8; 4]| pixel.map(|channel| (channel as u16 * pixel[3] as u16 / 255) as u8);
let (a, b) = (premultiplied(a), premultiplied(b));
a.iter().zip(&b).any(|(a, b)| a.abs_diff(*b) > THRESHOLD) || a[3].abs_diff(b[3]) > THRESHOLD
}
fn tint(pixel: [u8; 4], change: Change) -> [u8; 4] {
let color = tint_color(change);
let mix = |channel: u8, tint: u8| (channel as f32 + (tint as f32 - channel as f32) * TINT_STRENGTH) as u8;
[mix(pixel[0], color[0]), mix(pixel[1], color[1]), mix(pixel[2], color[2]), pixel[3]]
}
#[cfg(test)]
mod tests {
use super::*;
const FRAME: [DVec2; 2] = [DVec2::ZERO, DVec2::new(4., 2.)];
const CLEAR: [u8; 4] = [0; 4];
const WHITE: [u8; 4] = [255; 4];
/// A 4×2 image of the given pixels, row by row.
fn image(pixels: [[u8; 4]; 8]) -> Pixels {
Pixels {
size: UVec2::new(4, 2),
rgba: pixels.concat(),
}
}
fn left_half(change: Change) -> ChangedArea {
ChangedArea {
change,
bounds: [DVec2::ZERO, DVec2::new(2., 2.)],
}
}
#[test]
fn what_stayed_fades_and_what_came_is_tinted_as_added() {
let before = image([CLEAR; 8]);
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Added)]);
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Added));
assert_eq!(pixel(&tinted, UVec2::new(3, 1))[3], 0, "transparent pixels that stayed stay transparent");
let unchanged = tint_changes(&after, FRAME, &after, FRAME, &[]);
assert_eq!(pixel(&unchanged, UVec2::new(0, 0))[3], (255. * UNCHANGED_OPACITY) as u8);
}
#[test]
fn what_went_shows_as_it_was_tinted_as_removed() {
let before = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
let after = image([CLEAR; 8]);
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Removed)]);
let removed = pixel(&tinted, UVec2::new(1, 1));
assert_eq!(removed, tint(WHITE, Change::Removed));
assert_eq!(removed[3], 255, "a removed pixel keeps the coverage it had");
}
#[test]
fn a_moved_layer_is_tinted_as_changed_where_it_was_and_where_it_is() {
let before = image([WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
let after = image([CLEAR, WHITE, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR, CLEAR]);
let tinted = tint_changes(&after, FRAME, &before, FRAME, &[left_half(Change::Changed)]);
assert_eq!(pixel(&tinted, UVec2::new(0, 0)), tint(WHITE, Change::Changed), "where it was");
assert_eq!(pixel(&tinted, UVec2::new(1, 0)), tint(WHITE, Change::Changed), "where it is");
}
#[test]
fn the_close_up_samples_the_whole_document_before_at_its_own_scale() {
// The before image shows twice the area, so its left pixel column covers the close-up's left two
let before = image([WHITE, CLEAR, CLEAR, CLEAR, WHITE, CLEAR, CLEAR, CLEAR]);
let before_frame = [DVec2::ZERO, DVec2::new(8., 4.)];
let after = image([WHITE, WHITE, CLEAR, CLEAR, WHITE, WHITE, CLEAR, CLEAR]);
let tinted = tint_changes(&after, FRAME, &before, before_frame, &[]);
assert_eq!(pixel(&tinted, UVec2::new(1, 0))[3], (255. * UNCHANGED_OPACITY) as u8, "still covered, so unchanged");
assert_eq!(pixel(&tinted, UVec2::new(2, 0))[3], 0);
}
}
@@ -5,39 +5,12 @@ use crate::messages::prelude::*;
pub enum HistoryMessage {
Refresh,
Tick,
Expand {
id: String,
expanded: bool,
},
Expand { id: String, expanded: bool },
LoadMore,
GoBack {
id: String,
},
RemoveStep {
id: String,
},
BringBack {
id: String,
},
Follow {
id: Option<String>,
},
Rename {
id: String,
label: String,
},
Tag {
id: String,
tag: String,
on: bool,
},
GraphOverlay {
open: bool,
},
GraphOverlayToggle,
Captured {
document_id: DocumentId,
step: document_graph_storage::TimeStamp,
capture: Option<Box<super::utility_types::DocumentCapture>>,
},
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 },
}
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,3 @@
mod changes;
mod history_message;
mod history_message_handler;
pub mod utility_types;
@@ -1,45 +1,4 @@
//! What the History panel shows, as the frontend receives it, and the changes it asks of the head's line.
use glam::DVec2;
use graph_craft::document::NodeId;
use std::collections::HashMap;
/// The document as rendered once a step is done, for the History panel to show and compare.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct DocumentCapture {
/// The whole document.
pub image: CaptureImage,
/// The document area `image` shows.
pub frame: [DVec2; 2],
/// The area asked for in detail, and its image.
pub detail: Option<([DVec2; 2], CaptureImage)>,
/// The proto node giving each layer's own content, whose ID changes with that content.
pub layer_sources: HashMap<NodeId, NodeId>,
}
/// A capture rendered like the layer thumbnails: pixels from Vello, or an SVG for the frontend to draw when the GPU is unavailable.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum CaptureImage {
Pixels(Pixels),
Svg(String),
}
/// Straight RGBA pixels, row by row.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct Pixels {
pub size: glam::UVec2,
pub rgba: Vec<u8>,
}
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum LineChange {
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
MoveHead,
/// Drops a retired interaction and mints the later ones again on its parent.
Remove,
/// Does a step off the line again on top of it.
Restore,
}
//! 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))]
@@ -50,8 +9,8 @@ pub struct HistoryPanelState {
pub progress: Vec<HistoryProgressRow>,
pub more: bool,
pub following: Option<String>,
/// Others are connected, so authors, whether work is in history yet and head moves concern them too.
pub collaborating: bool,
/// In a session, a head move affects everyone.
pub session: bool,
}
/// One interaction, a run of deltas that undo takes back together.
@@ -79,17 +38,6 @@ pub struct HistoryRow {
pub head: bool,
pub expanded: bool,
pub details: Vec<HistoryDeltaRow>,
/// How the document looked once this step was done, if the panel was open to capture it.
pub thumbnail: Option<HistoryThumbnail>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryThumbnail {
/// The ID the frontend received the whole document's image under.
pub whole: String,
/// The ID of a close-up of what the step changed, tinted by how, when the step before was captured too.
pub detail: Option<String>,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
@@ -105,42 +53,10 @@ pub struct HistoryDeltaRow {
pub id: String,
pub label: String,
pub author: String,
pub mine: bool,
pub color: String,
pub time: Option<f64>,
}
/// Every step in history as a tree on first parents, for the history graph drawn over the viewport.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryGraphState {
pub nodes: Vec<HistoryGraphNode>,
/// The widest column plus one.
pub width: f64,
/// The deepest step's depth plus one.
pub depth: usize,
}
/// One interaction, placed in the tree.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct HistoryGraphNode {
/// The rev closing the interaction, in decimal.
pub id: String,
pub label: String,
/// The column, in step widths from the left. A parent sits centred over its children.
pub x: f64,
/// Steps from the root.
pub depth: usize,
pub parent: Option<String>,
/// Steps joined into this one by a merge.
pub merged: Vec<String>,
pub head: bool,
pub undone: bool,
/// Off the head's line and not undone.
pub abandoned: bool,
pub thumbnail: Option<HistoryThumbnail>,
}
/// A person with unretired work in the room's hot log.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
@@ -153,5 +69,4 @@ pub struct HistoryProgressRow {
pub ops: usize,
/// Still being made, not closed and waiting.
pub open: bool,
pub thumbnail: Option<HistoryThumbnail>,
}
@@ -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))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
pub enum IngestAction {
Open,
/// Open a distributed file such as a demo artwork as a copy with its own session room.
@@ -144,7 +144,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
documents: &mut self.documents,
active_document_id: self.active_document_id,
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
executor: &self.executor,
};
self.history.process_message(message, responses, context);
}
@@ -432,6 +431,14 @@ 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
@@ -1142,7 +1149,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
PortfolioMessage::UpdateDocumentWidgets => {
if let Some(document) = self.active_document() {
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time, self.history.graph_open());
document.update_document_widgets(responses, animation.is_playing(), timing_information.animation_time);
}
}
PortfolioMessage::UpdateOpenDocumentsList => {
@@ -1177,7 +1184,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
PrevDocument,
));
common.extend(actions!(IngestMessageDiscriminant; Import));
common.extend(self.history.actions());
}
common
@@ -37,8 +37,6 @@ 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,
@@ -80,12 +78,6 @@ 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);
@@ -123,7 +115,6 @@ 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() {
@@ -139,7 +130,6 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
};
gdd.leave();
self.detach(document_id);
self.joined.remove(&document_id);
refresh_session_views(responses);
}
SyncMessage::Fork => {
@@ -149,7 +139,6 @@ 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}");
@@ -179,14 +168,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, None, responses);
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, 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, Some(document_id), responses);
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
// The poll drained the inbox, so the next arrival wakes the next poll
self.arm(document_id, responses);
}
@@ -230,7 +219,7 @@ impl SyncMessageHandler {
}
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
let token = self.joined.get(&document_id).copied().unwrap_or_else(|| SessionToken::for_document(gdd.manifest().document_id));
let token = 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)) {
@@ -260,7 +249,6 @@ 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 {
@@ -289,8 +277,6 @@ 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>,
@@ -298,10 +284,9 @@ 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().filter(|(id, _)| only.is_none_or(|only| only == **id)) {
for (&document_id, document) in documents.iter_mut() {
let cursor = (Some(document_id) == active_document_id).then(|| active_cursor.clone()).flatten();
self.poll_document(document_id, document, &resources, preferences, cursor, responses);
}
@@ -352,9 +337,7 @@ impl SyncMessageHandler {
None => return,
Some(Role::Undecided) => {
let since = *self.undecided_since.entry(document_id).or_insert_with(now_ms);
// 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() {
if now_ms() - since >= ROLE_GRACE_MS && gdd.decide_role().is_some() {
self.undecided_since.remove(&document_id);
refresh_session_views(responses);
}
@@ -387,7 +370,6 @@ 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);
@@ -415,7 +397,10 @@ impl SyncMessageHandler {
refresh_session_views(responses);
}
Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses),
Event::MetadataChanged => refresh_session_views(responses),
Event::MetadataChanged => {
refresh_session_views(responses);
responses.add(HistoryMessage::Refresh);
}
Event::CursorMoved { .. } => {}
}
}
@@ -429,11 +414,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:?}"));
@@ -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))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum PanelType {
Welcome,
@@ -44,7 +44,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))]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum DockingSplitDirection {
Left,
@@ -256,6 +256,10 @@ 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();
@@ -39,9 +39,6 @@ pub enum PreferencesMessage {
SaveAsGdd {
enabled: bool,
},
SaveWithHistory {
enabled: bool,
},
ToggleShowStoragePreferences,
UserName {
name: String,
@@ -23,7 +23,6 @@ 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")]
@@ -60,7 +59,6 @@ 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(),
@@ -101,10 +99,8 @@ 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 });
@@ -151,9 +147,6 @@ 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);
@@ -17,16 +17,6 @@ use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
use graphene_std::vector::{HandleExt, PointId, SegmentId, VectorGeometry, VectorModificationType};
use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape};
/// Names the open interaction after what a tool did to `count` layers, such as "Moved 2 layers".
pub fn name_layer_action(verb: &str, count: usize) -> DocumentMessage {
let action = match count {
0 => verb.to_string(),
1 => format!("{verb} a layer"),
count => format!("{verb} {count} layers"),
};
DocumentMessage::NameInteraction { action }
}
/// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable.
pub fn should_extend(document: &DocumentMessageHandler, goal: DVec2, tolerance: f64, layers: impl Iterator<Item = LayerNodeIdentifier>) -> Option<(LayerNodeIdentifier, PointId, DVec2)> {
closest_point(document, goal, tolerance, layers, |_| false)
@@ -1976,7 +1976,6 @@ impl Fsm for PenToolFsmState {
}
(PenToolFsmState::Ready, PenToolMessage::DragStart { append_to_selected }) => {
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Drew a path segment".into() });
tool_data.handle_mode = HandleMode::Free;
// Get the closest point and the segment it is on
@@ -2016,7 +2015,6 @@ impl Fsm for PenToolFsmState {
// Each segment placement is its own history step, spanning from this click through the release that finalizes it
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Drew a path segment".into() });
// Merge two layers if the point is connected to the end point of another path
@@ -2500,28 +2498,12 @@ impl Fsm for PenToolFsmState {
mod test_pen_tool {
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::tool::common_functionality::snap_session::WAKE_DWELL_ON_APPROACH;
use crate::test_utils::EditorTestUtils;
use crate::test_utils::test_prelude::*;
use glam::{DAffine2, DVec2};
use graphene_std::vector::misc::{BooleanOperation, HandleId, ManipulatorPointId};
use glam::DAffine2;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId};
use graphene_std::vector::{SegmentId, VectorGeometry};
fn assert_expected_anchors(editor: &EditorTestUtils, expected_anchors: &[DVec2]) {
let (layer, vector) = drawn_path(editor).expect("Expected a drawn path");
let layer_to_viewport = editor.active_document().metadata().transform_to_viewport(layer);
let mut viewport_points: Vec<DVec2> = vector.anchor_positions().into_iter().map(|pos| layer_to_viewport.transform_point2(pos)).collect();
for (expected_index, &expected_position) in expected_anchors.iter().enumerate() {
let Some(viewport_index) = viewport_points.iter().position(|viewport| viewport.distance_squared(expected_position) < 1e-10) else {
panic!("The expected anchor index {expected_index} and position {expected_position} was not found in the actual anchors {viewport_points:?}");
};
viewport_points.remove(viewport_index);
}
assert!(viewport_points.is_empty(), "Viewport point(s) were not matched: {viewport_points:?}");
}
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> {
let document = editor.active_document();
@@ -2583,267 +2565,6 @@ mod test_pen_tool {
const C: DVec2 = DVec2::new(200., 200.);
const D: DVec2 = DVec2::new(100., 200.);
async fn create_a_rectangle() -> EditorTestUtils {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
// Draw a rectangle not at the origin (so will end up with a non-identity transform)
editor.draw_rect(A.x, A.y, C.x, C.y).await;
editor
}
/// Using the path tool to merge layers (by setting the endpoint to an anchor of another layer) should produce only expected anchor positions.
#[tokio::test]
async fn merging_layers_simple() {
let mut editor = create_a_rectangle().await;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle
click_pen(&mut editor, B).await;
// Validate that these anchors are the only ones that exist
let expected_anchors = [A, B, C, D, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_two_pen_paths() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Create First Pen path
click_pen(&mut editor, A).await;
click_pen(&mut editor, C).await;
// Abort the first pen process
editor.handle_message(ToolMessage::Pen(PenToolMessage::Abort)).await;
// Create a second pen stroke
click_pen(&mut editor, B).await;
click_pen(&mut editor, C).await;
// Validate that these anchors are the only ones that exist
let expected_anchors = [A, B, C];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_group_with_offset() {
let mut editor = create_a_rectangle().await;
// Group rectangle
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group = editor.active_document().metadata().all_layers().next().unwrap();
let offset = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group,
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle (offset by the group transform)
click_pen(&mut editor, B + offset).await;
let expected_anchors = [A + offset, B + offset, C + offset, D + offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_different_groups_with_offsets() {
let mut editor = create_a_rectangle().await;
// Group rectangle into Group 1
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group1 = editor.active_document().metadata().all_layers().next().unwrap();
let offset1 = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group1,
transform: DAffine2::from_translation(offset1),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Nest Group 1 inside Group 2 with a different offset
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::Layer,
})
.await;
let group2 = editor.active_document().metadata().all_layers().next().unwrap();
let offset2 = DVec2::new(30., -20.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: group2,
transform: DAffine2::from_translation(offset2),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
let total_offset = offset1 + offset2;
// Start the pen somewhere random
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
// Connect to the top right of the rectangle (offset by the nested group transforms)
click_pen(&mut editor, B + total_offset).await;
let expected_anchors = [A + total_offset, B + total_offset, C + total_offset, D + total_offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_artboard_with_offset() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let offset = DVec2::new(60., 70.);
editor.drag_tool(ToolType::Artboard, 0., 0., 500., 500., ModifierKeys::empty()).await;
let artboard = editor.active_document().metadata().all_layers().next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard,
transform: DAffine2::from_translation(offset),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x + offset.x, A.y + offset.y, C.x + offset.x, C.y + offset.y).await;
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
click_pen(&mut editor, B + offset).await;
let expected_anchors = [A + offset, B + offset, C + offset, D + offset, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_in_artboards_with_different_offsets() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Create first artboard with offset
editor.drag_tool(ToolType::Artboard, 0., 0., 400., 400., ModifierKeys::empty()).await;
let artboard1 = editor.active_document().metadata().all_layers().next().unwrap();
let offset1 = DVec2::new(50., 60.);
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard1,
transform: DAffine2::from_translation(offset1),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Draw rectangle in first artboard
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x + offset1.x, A.y + offset1.y, C.x + offset1.x, C.y + offset1.y).await;
// Create second artboard with different offset
let offset2 = DVec2::new(-30., 40.);
let artboard2_origin = DVec2::new(600., 600.);
editor
.drag_tool(
ToolType::Artboard,
artboard2_origin.x,
artboard2_origin.y,
artboard2_origin.x + 400.,
artboard2_origin.y + 400.,
ModifierKeys::empty(),
)
.await;
let artboard2 = editor.active_document().metadata().all_layers().next().unwrap();
editor
.handle_message(GraphOperationMessage::TransformSet {
layer: artboard2,
transform: DAffine2::from_translation(offset2),
transform_in: TransformIn::Local,
skip_rerender: false,
})
.await;
// Start pen in second artboard
let pen_start = artboard2_origin + offset2 + DVec2::new(50., 50.);
click_pen(&mut editor, pen_start).await;
// Connect to anchor B of the rectangle in the first artboard
click_pen(&mut editor, B + offset1).await;
let expected_anchors = [A + offset1, B + offset1, C + offset1, D + offset1, pen_start];
assert_expected_anchors(&editor, &expected_anchors);
}
async fn test_boolean_operation(operation: BooleanOperation) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_primary_color(Color::RED).await;
editor.draw_rect(A.x, A.y, C.x, C.y).await;
editor.draw_rect(150., 150., 250., 250.).await;
// Select both rectangles and create boolean operation layer
let layers: Vec<_> = editor.active_document().metadata().all_layers().collect();
editor
.handle_message(NodeGraphMessage::SelectedNodesSet {
nodes: layers.iter().map(|l| l.to_node()).collect(),
})
.await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: GroupFolderType::BooleanOperation(operation),
})
.await;
let bool_layer = editor.active_document().metadata().all_layers().next().unwrap();
let bool_vector = editor.active_document().network_interface.compute_modified_vector(bool_layer).expect("Boolean layer vector");
let bool_to_viewport = editor.active_document().metadata().transform_to_viewport(bool_layer);
let mut expected_anchors: Vec<DVec2> = bool_vector.anchor_positions().into_iter().map(|pos| bool_to_viewport.transform_point2(pos)).collect();
// Connect pen to one of the anchors of the boolean operation
let connect_anchor = expected_anchors[0];
let pen_start = DVec2::new(999., 999.);
click_pen(&mut editor, pen_start).await;
click_pen(&mut editor, connect_anchor).await;
expected_anchors.push(pen_start);
assert_expected_anchors(&editor, &expected_anchors);
}
#[tokio::test]
async fn merging_layers_with_different_boolean_outputs() {
for operation in [BooleanOperation::Union, BooleanOperation::SubtractFront, BooleanOperation::Intersect, BooleanOperation::Difference] {
test_boolean_operation(operation).await;
}
}
#[tokio::test]
async fn enter_or_esc_after_a_single_click_leaves_no_layer() {
for key in [Key::Enter, Key::Escape] {
@@ -22,9 +22,7 @@ use crate::messages::tool::common_functionality::shape_editor::SelectionShapeTyp
use crate::messages::tool::common_functionality::snap_session::{BoxFeatures, FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView, snapping_hints};
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
use crate::messages::tool::common_functionality::transformation_cage::*;
use crate::messages::tool::common_functionality::utility_functions::{
name_layer_action, push_nearest_anchors, resize_bounds, rotate_bounds, skew_bounds, text_bounding_box, transforming_transform_cage,
};
use crate::messages::tool::common_functionality::utility_functions::{push_nearest_anchors, resize_bounds, rotate_bounds, skew_bounds, text_bounding_box, transforming_transform_cage};
use glam::DMat2;
use graph_craft::document::NodeId;
use graphene_std::Color;
@@ -1748,10 +1746,6 @@ impl Fsm for SelectToolFsmState {
// Deselect layer if not snap dragging
responses.add(DocumentMessage::EndTransaction);
tool_data.axis_align = false;
if has_dragged {
let verb = if tool_data.non_duplicated_layers.is_some() { "Duplicated" } else { "Moved" };
responses.add(name_layer_action(verb, tool_data.layers_dragging.len()));
}
if !has_dragged && input.keyboard.key(remove_from_selection) && tool_data.layer_selected_on_start.is_none() {
// When you click on the layer with remove from selection key (shift) pressed, we deselect all nodes that are children.
@@ -1838,14 +1832,6 @@ impl Fsm for SelectToolFsmState {
) => {
let drag_too_small = input.mouse.position.distance(tool_data.drag_start) < 10. * f64::EPSILON;
let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction };
if !drag_too_small {
responses.add(match self {
SelectToolFsmState::DraggingPivot => DocumentMessage::NameInteraction { action: "Moved the pivot".into() },
SelectToolFsmState::RotatingBounds => name_layer_action("Rotated", tool_data.layers_dragging.len()),
SelectToolFsmState::SkewingBounds { .. } => name_layer_action("Skewed", tool_data.layers_dragging.len()),
_ => name_layer_action("Resized", tool_data.layers_dragging.len()),
});
}
tool_data.pivot_before_drag = None;
let pivot_gizmo = tool_data.pivot_gizmo();
@@ -1100,7 +1100,6 @@ impl Fsm for ShapeToolFsmState {
) && clicked_on_shape_endpoints(layer, document, input, tool_data)
{
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Moved a line end".into() });
let moving = Moving {
layers: vec![layer],
@@ -1167,11 +1166,6 @@ impl Fsm for ShapeToolFsmState {
tool_data.data.start(snap_session, SnapView::new(document, *document_id, input), drawn);
responses.add(DocumentMessage::StartTransaction);
let shape = format!("{:?}", tool_data.current_shape).to_lowercase();
let article = if shape.starts_with(['a', 'e', 'i', 'o', 'u']) { "an" } else { "a" };
responses.add(DocumentMessage::NameInteraction {
action: format!("Drew {article} {shape}"),
});
let node = match tool_data.current_shape {
ShapeType::Polygon => Polygon::create_node(tool_options.vertices),
@@ -548,7 +548,6 @@ impl TextToolData {
self.layer = layer;
if self.load_layer_text_node(document, fonts).is_some() {
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Edited text".into() });
self.set_editing(true, fonts, responses);
@@ -568,7 +567,6 @@ impl TextToolData {
fn new_text(&mut self, document: &DocumentMessageHandler, editing_text: EditingText, fonts: &FontsMessageHandler, responses: &mut VecDeque<Message>) {
self.new_text = String::new();
responses.add(DocumentMessage::AddTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Added text".into() });
self.layer = LayerNodeIdentifier::new_unchecked(NodeId::new());
@@ -767,7 +765,6 @@ impl Fsm for TextToolFsmState {
if dragging_bounds.is_some() {
responses.add(DocumentMessage::StartTransaction);
responses.add(DocumentMessage::NameInteraction { action: "Resized a text box".into() });
// Set the original transform
if let Some(id) = selected {
@@ -1199,32 +1196,6 @@ mod test_text_tool {
(metadata.transform_to_viewport(layer) * frame * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()
}
#[tokio::test]
async fn a_word_longer_than_the_max_width_breaks_to_stay_within_it() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
provide_fonts(&mut editor).await;
let layer = LayerNodeIdentifier::new_unchecked(NodeId::new());
let typesetting = TypesettingConfig {
max_width: Some(100.),
..Default::default()
};
editor
.handle_message(GraphOperationMessage::NewTextLayer {
id: layer.to_node(),
text: "Supercalifragilisticexpialidocious".into(),
font: Font::default(),
typesetting,
parent: LayerNodeIdentifier::ROOT_PARENT,
insert_index: 0,
})
.await;
let [min, max] = editor.active_document().metadata().bounding_box_document(layer).expect("the text should have bounds");
assert!(max.x - min.x <= 100. + 1e-6, "the text is {} wide, wider than its max width of 100", max.x - min.x);
}
#[tokio::test]
async fn a_text_box_stretched_by_its_right_edge_to_near_the_edge_of_a_rectangle_lands_on_it() {
let mut editor = EditorTestUtils::create();
@@ -11,7 +11,7 @@ use crate::messages::tool::common_functionality::shape_editor::ShapeState;
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
use crate::messages::tool::common_functionality::snap_session::{BoxFeatures, FeatureMap, Locus, Moving, PointOptions, SnapSession, SnapView};
use crate::messages::tool::common_functionality::transformation_cage::MIN_FEATURE_TRAVEL;
use crate::messages::tool::common_functionality::utility_functions::{is_almost_colinear, name_layer_action, push_nearest_anchors};
use crate::messages::tool::common_functionality::utility_functions::{is_almost_colinear, push_nearest_anchors};
use crate::messages::tool::tool_messages::path_tool::MAX_SNAPPING_POINTS;
use crate::messages::tool::tool_messages::select_tool;
use crate::messages::tool::tool_messages::tool_prelude::Key;
@@ -321,12 +321,6 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
// Messages
TransformLayerMessage::ApplyTransformOperation { final_transform } => {
let verb = match self.transform_operation {
TransformOperation::Grabbing(_) => Some("Moved"),
TransformOperation::Rotating(_) => Some("Rotated"),
TransformOperation::Scaling(_) => Some("Scaled"),
TransformOperation::None => None,
};
selected.original_transforms.clear();
self.typing.clear();
if final_transform {
@@ -343,12 +337,6 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
} else {
update_colinear_handles(&selected_layers, document, responses);
responses.add(DocumentMessage::EndTransaction);
if let Some(verb) = verb {
responses.add(match using_path_tool {
true => DocumentMessage::NameInteraction { action: format!("{verb} points") },
false => name_layer_action(verb, selected_layers.len()),
});
}
responses.add(ToolMessage::UpdateHints);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
+2 -25
View File
@@ -81,16 +81,7 @@ pub enum NodeGraphUpdate {
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
Thumbnails {
responses: VecDeque<FrontendMessage>,
document_id: DocumentId,
},
DocumentCapture {
document_id: DocumentId,
step: document_graph_storage::TimeStamp,
/// `None` when a newer graph replaced the one the request was for, so it can be asked again.
capture: Option<Box<crate::messages::portfolio::history::utility_types::DocumentCapture>>,
},
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
InspectResult(Box<InspectResult>),
}
@@ -212,18 +203,6 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view");
}
/// Asks for the document as rendered once what was submitted before has run, for the History panel's `step`, with the area `detail` close up.
/// Returns false when the runtime doesn't hold the document's graph as it is now, so nothing was asked.
pub fn submit_document_capture(&self, document: &DocumentMessageHandler, document_id: DocumentId, step: document_graph_storage::TimeStamp, detail: Option<[DVec2; 2]>) -> bool {
if self.node_graph_document != Some(document_id) || self.node_graph_hash != document.network_interface.network_hash() {
return false;
}
self.sender
.send(GraphRuntimeRequest::CaptureDocument { document_id, step, detail })
.expect("Failed to send the capture request");
true
}
/// Updates the network to monitor all inputs. Useful for the testing.
#[cfg(test)]
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
@@ -469,7 +448,7 @@ impl NodeGraphExecutor {
let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
for response in results.by_ref() {
while let Some(response) = results.next() {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse {
@@ -685,7 +664,6 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses);
}
}
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
}
}
@@ -704,7 +682,6 @@ impl NodeGraphExecutor {
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::DocumentCapture { document_id, step, capture } => responses.add(HistoryMessage::Captured { document_id, step, capture }),
_ => {}
}
}
+1 -27
View File
@@ -46,8 +46,6 @@ pub struct NodeRuntime {
pending_export: Option<ExecutionRequest>,
pending_eyedropper: Option<ExecutionRequest>,
pending_thumbnails: Option<DocumentId>,
/// The step the History panel wants the document captured for, once what is pending has run.
pending_capture: Option<(DocumentId, document_graph_storage::TimeStamp, Option<[DVec2; 2]>)>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
@@ -84,12 +82,6 @@ pub enum GraphRuntimeRequest {
layers: HashSet<NodeId>,
document_id: DocumentId,
},
CaptureDocument {
document_id: DocumentId,
step: document_graph_storage::TimeStamp,
/// The area to render close up as well.
detail: Option<[DVec2; 2]>,
},
/// The full path from the root network to the node the Data panel inspects, or empty for none.
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
@@ -139,7 +131,6 @@ impl NodeRuntime {
pending_export: None,
pending_eyedropper: None,
pending_thumbnails: None,
pending_capture: None,
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
@@ -178,15 +169,7 @@ impl NodeRuntime {
let mut graph = None;
for request in self.receiver.try_iter() {
match request {
GraphRuntimeRequest::GraphUpdate(update) => {
graph = Some(update);
// The graph may be another document's, or show a later step than the one asked for
if let Some((document_id, step, _)) = self.pending_capture.take() {
self.sender
.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture: None })
.expect("Failed to send response");
}
}
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
self.pending_export = Some(request);
@@ -201,7 +184,6 @@ impl NodeRuntime {
self.thumbnails.set_in_view(layers);
self.pending_thumbnails = Some(document_id);
}
GraphRuntimeRequest::CaptureDocument { document_id, step, detail } => self.pending_capture = Some((document_id, step, detail)),
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
Some(update) => update.node_to_inspect = node_to_inspect,
@@ -291,14 +273,6 @@ impl NodeRuntime {
if let Some(viewport) = viewport {
texture = self.run_viewport(viewport).await;
}
if let Some((document_id, step, detail)) = self.pending_capture.take()
&& let Some(network) = &self.old_graph
&& let Some(capture) = self.thumbnails.capture_document(network, &self.executor, &self.editor_api, detail).await
{
let capture = Some(Box::new(capture));
self.sender.send(NodeGraphUpdate::DocumentCapture { document_id, step, capture }).expect("Failed to send response");
}
}
(self.editor_wake)();
@@ -1,6 +1,5 @@
use super::evaluated_output;
use crate::messages::frontend::FrontendMessage;
use crate::messages::portfolio::history::utility_types::{CaptureImage, DocumentCapture, Pixels};
#[cfg(feature = "gpu")]
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
@@ -225,58 +224,22 @@ impl Thumbnails {
}
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
self.show_svg(layer, content.svg(), responses).await;
}
/// Renders the whole document as the network's export gives it, and the area `detail` close up, the way layer
/// thumbnails are rendered, along with what each layer currently shows.
pub async fn capture_document(&self, network: &NodeNetwork, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, detail: Option<[DVec2; 2]>) -> Option<DocumentCapture> {
let content = match network.exports.first().and_then(|export| network.input_source(&[], export)) {
Some(source) => {
let &(content_node, _) = executor.tree().source_map().get(source.as_slice())?;
ThumbnailContent::evaluate(executor, content_node)?
}
// Nothing reaches the export, so the document shows nothing
None => ThumbnailContent::Graphics(List::default()),
let bounds = content.bounds();
let footprint = Footprint {
transform: DAffine2::from_translation(bounds[0]),
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
quality: RenderQuality::Full,
};
let frame = content.bounds();
let frames: Vec<[DVec2; 2]> = std::iter::once(frame).chain(detail).collect();
let mut images: Vec<CaptureImage> = match self.render_frames_with_vello(&content, &frames, editor_api).await {
Some(pixels) => pixels.into_iter().map(CaptureImage::Pixels).collect(),
None => frames.iter().map(|&frame| CaptureImage::Svg(content.svg_of(frame))).collect(),
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let detail_image = (images.len() > 1).then(|| images.pop()).flatten();
Some(DocumentCapture {
image: images.pop()?,
frame,
detail: detail.zip(detail_image),
layer_sources: self.sources.clone(),
})
}
let mut render = SvgRender::new();
content.graphic().render_svg(&mut render, &render_params);
render.format_svg(bounds[0], bounds[1]);
/// Renders each frame of the content into a cell the size of a layer thumbnail, giving none if Vello is unavailable.
#[cfg(feature = "gpu")]
async fn render_frames_with_vello(&self, content: &ThumbnailContent, frames: &[[DVec2; 2]], editor_api: &PlatformEditorApi) -> Option<Vec<Pixels>> {
let executor = editor_api.application_io.as_ref()?.gpu_executor()?;
let cell_size = cell_size(self.scale);
let size = UVec2::new(cell_size.x * frames.len() as u32, cell_size.y);
let texture = executor.render_vello(size, DAffine2::IDENTITY, &mut |scene| atlas::draw_frames(scene, cell_size, content, frames));
let texture = texture.inspect_err(|error| log::error!("Failed to render the document capture: {error}")).ok()?;
let raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8();
let cell = |index: usize| Pixels {
size: cell_size,
rgba: atlas::cell_pixels(&pixels, size.x, cell_size, UVec2::new(index as u32 * cell_size.x, 0)),
};
Some((0..frames.len()).map(cell).collect())
}
#[cfg(not(feature = "gpu"))]
async fn render_frames_with_vello(&self, _content: &ThumbnailContent, _frames: &[[DVec2; 2]], _editor_api: &PlatformEditorApi) -> Option<Vec<Pixels>> {
None
self.show_svg(layer, render.svg.to_svg_string(), responses).await;
}
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
@@ -381,28 +344,6 @@ impl ThumbnailContent {
}
}
fn svg(&self) -> String {
self.svg_of(self.bounds())
}
/// The SVG of the area `bounds`.
fn svg_of(&self, bounds: [DVec2; 2]) -> String {
let footprint = Footprint {
transform: DAffine2::from_translation(bounds[0]),
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
quality: RenderQuality::Full,
};
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
self.graphic().render_svg(&mut render, &render_params);
render.format_svg(bounds[0], bounds[1]);
render.svg.to_svg_string()
}
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] {
let bounds = match self {
@@ -504,7 +445,6 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
#[cfg(test)]
mod tests {
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
use crate::messages::portfolio::history::utility_types::CaptureImage;
use crate::test_utils::test_prelude::*;
use glam::UVec2;
use graph_craft::document::NodeId;
@@ -527,27 +467,6 @@ mod tests {
editor.runtime.executor.tree().source_map().get(path).map(|(id, _)| *id)
}
#[tokio::test]
async fn a_document_capture_shows_the_document_and_what_each_layer_shows() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
compile_and_run(&mut editor).await;
let runtime = &editor.runtime;
let network = runtime.old_graph.as_ref().expect("The document should have compiled");
let capture = runtime.thumbnails.capture_document(network, &runtime.executor, &runtime.editor_api, None).await;
let capture = capture.expect("The document should render");
match &capture.image {
CaptureImage::Pixels(pixels) => assert!(pixels.rgba.chunks(4).any(|pixel| pixel[3] > 0), "The rectangle should be drawn"),
CaptureImage::Svg(svg) => assert!(svg.contains("<path"), "The rectangle should be drawn: {svg}"),
}
assert!(capture.layer_sources.contains_key(&layer), "The rectangle's layer should have its content");
let [min, max] = capture.frame;
assert!(min.cmple(DVec2::ZERO).all() && max.cmpge(DVec2::splat(10.)).all(), "The frame {min} to {max} should hold the rectangle");
}
#[tokio::test]
async fn a_merge_layer_shows_its_content_and_another_layer_its_output() {
let mut editor = EditorTestUtils::create();
@@ -1,5 +1,5 @@
use super::{ThumbnailContent, cell_size};
use glam::{DAffine2, DVec2, UVec2};
use glam::{DAffine2, UVec2};
use graph_craft::document::NodeId;
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
use graphene_std::renderer::{RenderOutputType, RenderParams};
@@ -43,57 +43,44 @@ impl ThumbnailAtlasLayout {
}
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
cell_pixels(atlas_pixels, self.size().x, self.cell_size, self.cell_origin(index))
let atlas_row_length = self.size().x as usize * 4;
let row_length = self.cell_size.x as usize * 4;
let origin = self.cell_origin(index).as_usizevec2();
(origin.y..origin.y + self.cell_size.y as usize)
.filter_map(|row| {
let start = row * atlas_row_length + origin.x * 4;
atlas_pixels.get(start..start + row_length)
})
.flatten()
.copied()
.collect()
}
}
/// The pixels of the cell at `origin` in an atlas `atlas_width` pixels wide, row by row.
pub fn cell_pixels(atlas_pixels: &[u8], atlas_width: u32, cell_size: UVec2, origin: UVec2) -> Vec<u8> {
let atlas_row_length = atlas_width as usize * 4;
let row_length = cell_size.x as usize * 4;
let origin = origin.as_usizevec2();
(origin.y..origin.y + cell_size.y as usize)
.filter_map(|row| {
let start = row * atlas_row_length + origin.x * 4;
atlas_pixels.get(start..start + row_length)
})
.flatten()
.copied()
.collect()
}
/// Draws the content of each layer in the layout centered within its cell.
pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout, contents: &HashMap<NodeId, ThumbnailContent>) {
for (index, layer) in layout.layers.iter().enumerate() {
let Some(content) = contents.get(layer) else { continue };
draw_cell(scene, layout.cell_origin(index), layout.cell_size, content, content.bounds());
}
}
/// Draws the area `frame` of the content into each cell of a row of them, one per frame.
pub fn draw_frames(scene: &mut VelloSceneBuilder, cell_size: UVec2, content: &ThumbnailContent, frames: &[[DVec2; 2]]) {
for (index, &frame) in frames.iter().enumerate() {
draw_cell(scene, UVec2::new(index as u32 * cell_size.x, 0), cell_size, content, frame);
}
}
fn draw_cell(scene: &mut VelloSceneBuilder, origin: UVec2, cell_size: UVec2, content: &ThumbnailContent, frame: [DVec2; 2]) {
let render_params = RenderParams {
footprint: Footprint::BOUNDLESS,
render_output_type: RenderOutputType::Vello,
thumbnail: true,
..Default::default()
};
let (origin, cell_size) = (origin.as_dvec2(), cell_size.as_dvec2());
let [min, max] = frame;
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
let cell_size = layout.cell_size.as_dvec2();
// The clip also limits content filling the whole scene, like a background, to the cell
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
content.graphic().render_to_vello(scene, transform, &render_params);
scene.pop_layer();
for (index, layer) in layout.layers.iter().enumerate() {
let Some(content) = contents.get(layer) else { continue };
let origin = layout.cell_origin(index).as_dvec2();
let [min, max] = content.bounds();
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
// The clip also limits content filling the whole scene, like a background, to the cell
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
content.graphic().render_to_vello(scene, transform, &render_params);
scene.pop_layer();
}
}
/// The RGBA pixels with runs of fully transparent ones left out, which most of a thumbnail's margins are.
+1 -1
View File
@@ -114,7 +114,7 @@ impl EditorTestUtils {
return Ok(result);
}
}
Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")))
return 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> {
@@ -5,7 +5,6 @@
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import Graph from "/src/components/views/Graph.svelte";
import HistoryGraph from "/src/components/views/HistoryGraph.svelte";
import RemoteCursor from "/src/components/views/RemoteCursor.svelte";
import RulerInput from "/src/components/widgets/inputs/RulerInput.svelte";
import ScrollbarInput from "/src/components/widgets/inputs/ScrollbarInput.svelte";
@@ -13,7 +12,6 @@
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import type { AppWindowStore } from "/src/stores/app-window";
import type { DocumentStore } from "/src/stores/document";
import type { HistoryStore } from "/src/stores/history";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { MessageBody } from "/src/subscriptions-router";
import { fillChoiceColor, createSRgba8, sRgba8FromCSS } from "/src/utility-functions/colors";
@@ -33,7 +31,6 @@
const editor = getContext<EditorWrapper>("editor");
const appWindow = getContext<AppWindowStore>("appWindow");
const document = getContext<DocumentStore>("document");
const historyGraphOpen = getContext<HistoryStore>("history").graphOpen;
const remoteCursors = document.remoteCursorsStore;
// Interactive text editing
@@ -771,9 +768,6 @@
<div class="graph-view" class:open={$document.graphViewOverlayOpen} style:--fade-artwork={`${$document.fadeArtwork}%`} data-graph>
<Graph />
</div>
{#if $historyGraphOpen}
<HistoryGraph />
{/if}
</LayoutCol>
<LayoutCol class="ruler-or-scrollbar right-scrollbar">
<ScrollbarInput
+69 -101
View File
@@ -2,7 +2,6 @@
import { getContext, onDestroy } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import HistoryShot from "/src/components/views/HistoryShot.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
@@ -12,7 +11,6 @@
const editor = getContext<EditorWrapper>("editor");
const history = getContext<HistoryStore>("history");
const thumbnails = history.thumbnails;
// Relative times age while the panel stays open
let now = Date.now();
@@ -33,9 +31,6 @@
return new Date(ms).toLocaleDateString();
}
// Alone, the newest step not yet in history is where the document is
$: pendingHead = !$history.collaborating && $history.progress.length > 0;
function count(n: number, one: string, many: string): string {
return `${n} ${n === 1 ? one : many}`;
}
@@ -56,12 +51,6 @@
if (tag.trim()) editor.tagHistoryInteraction(id, tag, true);
taggingId = undefined;
}
// The inputs open focused and close once focus leaves them, committed or not
function focusInput(node: HTMLElement) {
const input = node.querySelector("[data-input-element]");
if (input instanceof HTMLElement) input.focus();
}
</script>
<LayoutCol class="history-panel">
@@ -72,53 +61,38 @@
</LayoutRow>
{/if}
<LayoutCol class="body" scrollableY={true}>
{#each $history.progress as row, index}
<!-- Alone, work not yet in history is shown as an ordinary step -->
<div class="row" class:head={pendingHead && index === 0}>
<span class="gutter"></span>
{#if $history.collaborating}
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
{:else}
<span class="rail"><span class="dot"></span></span>
{/if}
{#if row.thumbnail}<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />{/if}
{#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">
{#if $history.collaborating}<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span> ·{/if}
{count(row.ops, "change", "changes")}
{#if $history.collaborating}· {row.open ? "in progress" : "not yet in history"}{/if}
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
· {count(row.ops, "change", "changes")}
· {row.open ? "in progress" : "not yet in history"}
</span>
</div>
{#if pendingHead && index === 0}<span class="marker">Now</span>{/if}
</div>
{/each}
{#each $history.rows as row (row.id)}
<div class="row" class:head={row.head && !pendingHead} class:undone={row.undone} class:abandoned={row.abandoned}>
{#if row.deltas > 1 || row.thumbnail?.detail}
<button
class="expand"
class:expanded={row.expanded}
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
></button>
{:else}
<span class="gutter"></span>
{/if}
<span class="rail"><span class="dot" style:background={$history.collaborating || !row.mine ? row.color : undefined}></span></span>
{#if row.thumbnail}<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} />{/if}
<div class="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}
<span class="editing" use:focusInput on:focusout={() => (renamingId = undefined)}>
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
</span>
<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">
{#if $history.collaborating || !row.mine}<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span> ·{/if}
{#if row.time}{when(row.time, now)} ·{/if}
{count(row.deltas, "change", "changes")}
<span 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">
@@ -126,23 +100,21 @@
<span class="tag">{tag}<button class="remove" data-tooltip-label="Remove the tag" on:click={() => editor.tagHistoryInteraction(row.id, tag, false)}>×</button></span>
{/each}
{#if taggingId === row.id}
<span class="editing" use:focusInput on:focusout={() => (taggingId = undefined)}>
<TextInput value="" placeholder="Tag name" narrow={true} on:commitText={({ detail }) => commitTag(row.id, detail)} />
</span>
<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="chip branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button>
<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="chip" data-tooltip-label="Name this step" on:click={() => (renamingId = row.id)}>Name</button>
<button class="chip" data-tooltip-label="Tag this step" on:click={() => (taggingId = row.id)}>Tag</button>
<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"
@@ -157,9 +129,7 @@
icon="HistoryUndo"
size={16}
tooltipLabel="Go back to here"
tooltipDescription={$history.collaborating
? "Move everyone's document back to this step. The steps since stay as a branch."
: "Move the document back to this step. The steps since stay as a branch."}
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}
@@ -172,27 +142,19 @@
/>
{/if}
</span>
{#if row.head && !pendingHead}<span class="marker">Now</span>{/if}
{#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}
{#if row.thumbnail?.detail}
<div class="row comparison" class:undone={row.undone}>
<span class="gutter"></span>
<span class="rail"></span>
<HistoryShot thumbnail={row.thumbnail} images={$thumbnails} large={true} />
</div>
{/if}
{#each row.details as delta (delta.id)}
<div class="row delta" class:undone={row.undone}>
<span class="gutter"></span>
<span class="rail"><span class="tick"></span></span>
<div class="text">
<span class="label">{delta.label}</span>
<span class="meta">
{#if $history.collaborating || !delta.mine}<span class="author">{delta.author}</span>{/if}
{#if delta.time}{$history.collaborating || !delta.mine ? "· " : ""}{when(delta.time, now)}{/if}
<span class="author">{delta.author}</span>
{#if delta.time}· {when(delta.time, now)}{/if}
</span>
</div>
</div>
@@ -243,45 +205,36 @@
&.delta {
min-height: 24px;
padding-left: 28px;
font-size: 11px;
}
&.comparison {
padding-top: 4px;
padding-bottom: 4px;
}
.actions {
flex: 0 0 auto;
display: flex;
align-items: center;
gap: 2px;
visibility: hidden;
}
&:hover .actions,
&:focus-within .actions {
visibility: visible;
}
.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;
.chip {
font-size: 11px;
line-height: 14px;
padding: 0 4px;
border: none;
border-radius: 2px;
background: var(--color-4-dimgray);
color: var(--color-c-brightgray);
cursor: pointer;
&:hover {
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
&:hover {
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
}
.gutter {
flex: 0 0 16px;
&:hover .actions {
visibility: visible;
}
.expand {
@@ -293,11 +246,6 @@
background: none;
position: relative;
cursor: pointer;
color: var(--color-8-uppergray);
&:hover {
color: var(--color-e-nearwhite);
}
&::after {
content: "";
@@ -305,11 +253,23 @@
left: 5px;
top: 4px;
border: 4px solid transparent;
border-left: 5px solid currentColor;
border-left: 5px solid var(--color-8-uppergray);
}
&.expanded::after {
transform: rotate(90deg);
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);
}
}
@@ -322,7 +282,6 @@
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--color-8-uppergray);
&.hollow {
background: none;
@@ -405,10 +364,23 @@
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);
}
}
}
}
@@ -424,10 +396,6 @@
}
}
.editing {
display: contents;
}
.more {
display: flex;
justify-content: center;
@@ -1,240 +0,0 @@
<script lang="ts">
import { getContext, tick } from "svelte";
import HistoryShot from "/src/components/views/HistoryShot.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import type { HistoryStore } from "/src/stores/history";
import type { EditorWrapper, HistoryGraphNode } from "/wrapper/pkg/graphite_wasm_wrapper";
const editor = getContext<EditorWrapper>("editor");
const history = getContext<HistoryStore>("history");
const graph = history.graph;
const thumbnails = history.thumbnails;
// Each step's card and the room around it
const NODE_WIDTH = 168;
const NODE_HEIGHT = 44;
const COLUMN = 184;
const ROW = 72;
const PADDING = 24;
let body: HTMLDivElement | undefined;
let scrolledToHead = false;
$: byId = new Map($graph.nodes.map((node) => [node.id, node]));
$: head = $graph.nodes.find((node) => node.head);
$: if (head && !scrolledToHead) scrollToHead();
function left(node: HistoryGraphNode): number {
return PADDING + node.x * COLUMN;
}
function top(node: HistoryGraphNode): number {
return PADDING + node.depth * ROW;
}
// From the bottom of the parent's card to the top of the child's
function edge(parent: HistoryGraphNode, child: HistoryGraphNode): string {
const [x1, y1] = [left(parent) + NODE_WIDTH / 2, top(parent) + NODE_HEIGHT];
const [x2, y2] = [left(child) + NODE_WIDTH / 2, top(child)];
const middle = (y1 + y2) / 2;
return `M ${x1} ${y1} C ${x1} ${middle}, ${x2} ${middle}, ${x2} ${y2}`;
}
function onHeadLine(node: HistoryGraphNode): boolean {
return !node.undone && !node.abandoned;
}
function tooltip(node: HistoryGraphNode): string {
if (node.head) return "Where the document is now";
if (node.undone) return "Redo up to here";
if (node.abandoned) return "Show this branch in the History panel";
return "Go back to here";
}
function choose(node: HistoryGraphNode) {
if (node.abandoned) editor.followHistoryBranch(node.id);
else if (!node.head) editor.goBackToHistoryInteraction(node.id);
}
async function scrollToHead() {
scrolledToHead = true;
await tick();
body?.querySelector("[data-head]")?.scrollIntoView({ block: "center", inline: "center" });
}
</script>
<!-- Pointer presses and wheel scrolls stay here rather than reaching the viewport's tools beneath -->
<div class="history-graph" on:pointerdown|stopPropagation on:wheel|stopPropagation>
<div class="header">
<TextLabel>History</TextLabel>
<IconButton icon="CloseX" size={16} tooltipLabel="Hide the history graph" action={() => editor.setHistoryGraphOpen(false)} />
</div>
<div class="body" bind:this={body}>
{#if $graph.nodes.length === 0}
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
{/if}
<div class="canvas" style:width={`${PADDING * 2 + Math.max(0, $graph.width - 1) * COLUMN + NODE_WIDTH}px`} style:height={`${PADDING * 2 + $graph.depth * ROW}px`}>
<svg class="edges">
{#each $graph.nodes as node (node.id)}
{@const parent = node.parent ? byId.get(node.parent) : undefined}
{#if parent}
<path d={edge(parent, node)} class:head-line={onHeadLine(node)} class:undone={node.undone} />
{/if}
{#each node.merged as merged}
{@const other = byId.get(merged)}
{#if other}<path d={edge(other, node)} class="merge" />{/if}
{/each}
{/each}
</svg>
{#each $graph.nodes as node (node.id)}
<div
class="node"
class:head={node.head}
class:head-line={onHeadLine(node)}
class:undone={node.undone}
class:abandoned={node.abandoned}
style:left={`${left(node)}px`}
style:top={`${top(node)}px`}
style:width={`${NODE_WIDTH}px`}
style:height={`${NODE_HEIGHT}px`}
data-head={node.head || undefined}
>
<button class="step" data-tooltip-label={tooltip(node)} on:click={() => choose(node)}>
{#if node.thumbnail}<HistoryShot thumbnail={node.thumbnail} images={$thumbnails} />{/if}
<span class="label">{node.label}</span>
</button>
{#if node.abandoned}
<IconButton
icon="HistoryRedo"
size={16}
tooltipLabel="Bring back"
tooltipDescription="Do this step again on top of the current line."
action={() => editor.bringBackHistoryInteraction(node.id)}
/>
{/if}
{#if node.head}<span class="marker">Now</span>{/if}
</div>
{/each}
</div>
</div>
</div>
<style lang="scss">
.history-graph {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
background: var(--color-2-mildblack);
.header {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
padding: 4px 8px;
border-bottom: 1px solid var(--color-4-dimgray);
}
.body {
flex: 1 1 0;
overflow: auto;
position: relative;
> .text-label {
position: absolute;
padding: 16px;
}
}
.canvas {
position: relative;
}
.edges {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
path {
fill: none;
stroke: var(--color-5-dullgray);
stroke-width: 2;
&.head-line {
stroke: var(--color-e-nearwhite);
}
&.undone {
stroke-dasharray: 4 3;
}
&.merge {
stroke-dasharray: 2 4;
}
}
}
.node {
position: absolute;
box-sizing: border-box;
display: flex;
align-items: center;
gap: 2px;
padding: 0 4px 0 0;
border-radius: 4px;
border: 1px solid var(--color-4-dimgray);
background: var(--color-3-darkgray);
&.head-line {
border-color: var(--color-8-uppergray);
}
&.head {
border-color: var(--color-e-nearwhite);
background: var(--color-4-dimgray);
}
&.undone,
&.abandoned {
.step {
opacity: 0.6;
}
}
.step {
flex: 1 1 0;
min-width: 0;
height: 100%;
display: flex;
align-items: center;
gap: 6px;
padding: 0 0 0 6px;
border: none;
background: none;
color: var(--color-e-nearwhite);
text-align: left;
cursor: pointer;
.label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.marker {
flex: 0 0 auto;
font-size: 10px;
line-height: 14px;
padding: 0 4px;
border-radius: 2px;
background: var(--color-5-dullgray);
color: var(--color-e-nearwhite);
}
}
}
</style>
@@ -1,56 +0,0 @@
<script lang="ts">
import type { HistoryThumbnail } from "/wrapper/pkg/graphite_wasm_wrapper";
export let thumbnail: HistoryThumbnail;
// The images the frontend received, by ID
export let images: Record<string, string>;
export let large = false;
</script>
<span class="history-shot" class:large>
<span class="image" data-tooltip-label="The document once this step was done">
{#if images[thumbnail.whole]}<img src={images[thumbnail.whole]} alt="" />{/if}
</span>
{#if thumbnail.detail}
<span class="image" data-tooltip-label="What this step changed, close up" data-tooltip-description="Green was added, red removed, and yellow changed.">
{#if images[thumbnail.detail]}<img src={images[thumbnail.detail]} alt="" />{/if}
</span>
{/if}
</span>
<style lang="scss">
.history-shot {
flex: 0 0 auto;
display: flex;
gap: 2px;
.image {
width: 36px;
height: 24px;
border-radius: 2px;
overflow: hidden;
background-image: var(--color-transparent-checkered-background);
background-size: var(--color-transparent-checkered-background-size-mini);
background-position: var(--color-transparent-checkered-background-position-mini);
background-repeat: var(--color-transparent-checkered-background-repeat);
}
&.large {
gap: 4px;
.image {
// The size captures are rendered at, like layer thumbnails
width: 72px;
height: 48px;
background-size: var(--color-transparent-checkered-background-size);
background-position: var(--color-transparent-checkered-background-position);
}
}
img {
display: block;
width: 100%;
height: 100%;
}
}
</style>
+4 -12
View File
@@ -228,7 +228,6 @@ 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";
@@ -248,10 +247,8 @@ 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 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 NodeMathF from "/../branding/assets/16x16-nodes/node-math-f.svg";
import NodeMathFx from "/../branding/assets/16x16-nodes/node-math-fx.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";
@@ -273,7 +270,6 @@ 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";
@@ -510,7 +506,6 @@ 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 },
@@ -530,10 +525,8 @@ export const ICON_16X16_NODES = {
NodeMap: { svg: NodeMap, size: 16 },
NodeMapPoints: { svg: NodeMapPoints, size: 16 },
NodeMask: { svg: NodeMask, size: 16 },
NodeMathAggregate: { svg: NodeMathAggregate, size: 16 },
NodeMathFormula: { svg: NodeMathFormula, size: 16 },
NodeMathFunction: { svg: NodeMathFunction, size: 16 },
NodeMathRunning: { svg: NodeMathRunning, size: 16 },
NodeMathF: { svg: NodeMathF, size: 16 },
NodeMathFx: { svg: NodeMathFx, size: 16 },
NodeMax: { svg: NodeMax, size: 16 },
NodeMaximum: { svg: NodeMaximum, size: 16 },
NodeMedianFilter: { svg: NodeMedianFilter, size: 16 },
@@ -555,7 +548,6 @@ 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 },
+4 -77
View File
@@ -1,70 +1,18 @@
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
import type { HistoryGraphState, HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
export type HistoryStore = ReturnType<typeof createHistoryStore>;
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, collaborating: false };
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);
// The captured images by the ID rows name them with, sent once each
const thumbnails: Writable<Record<string, string>> = import.meta.hot?.data?.thumbnails || writable<Record<string, string>>({});
// The history graph drawn over the viewport, sent only while it is open
const graph: Writable<HistoryGraphState> = import.meta.hot?.data?.graph || writable<HistoryGraphState>({ nodes: [], width: 0, depth: 0 });
const graphOpen: Writable<boolean> = import.meta.hot?.data?.graphOpen || writable<boolean>(false);
if (import.meta.hot) {
import.meta.hot.data.store = store;
import.meta.hot.data.thumbnails = thumbnails;
import.meta.hot.data.graph = graph;
import.meta.hot.data.graphOpen = graphOpen;
}
if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, set } = store;
// The most recent images kept, oldest dropped first. Each step has a whole image and maybe a close-up, so twice as many as the editor keeps captures
const MAX_THUMBNAILS = 600;
// The size an SVG capture is drawn at, twice the largest a capture is shown
const RASTER_WIDTH = 144;
const RASTER_HEIGHT = 96;
// Kept as a small PNG rather than the pixels themselves
function encodePixels(pixels: Uint8Array, width: number, height: number): string {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
canvas.getContext("2d")?.putImageData(new ImageData(new Uint8ClampedArray(pixels), width, height), 0, 0);
return canvas.toDataURL("image/png");
}
// Without the GPU a capture comes as an SVG, which can embed whole images, so it is kept as a small PNG, or as the SVG when the browser can't draw it
async function rasterize(svg: string): Promise<string> {
// An SVG drawn as an image needs an intrinsic size, which the capture's only gives as a view box
const sized = svg.replace("<svg ", `<svg width="${RASTER_WIDTH}" height="${RASTER_HEIGHT}" `);
const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(sized)}`;
try {
const image = new Image();
image.src = url;
await image.decode();
const canvas = document.createElement("canvas");
canvas.width = RASTER_WIDTH;
canvas.height = RASTER_HEIGHT;
canvas.getContext("2d")?.drawImage(image, 0, 0, RASTER_WIDTH, RASTER_HEIGHT);
return canvas.toDataURL("image/png");
} catch {
return url;
}
}
function keepThumbnail(id: string, url: string) {
thumbnails.update((images) => {
const ids = Object.keys(images);
const kept = ids.length < MAX_THUMBNAILS ? images : Object.fromEntries(ids.slice(ids.length - MAX_THUMBNAILS + 1).map((id) => [id, images[id]]));
return { ...kept, [id]: url };
});
}
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
@@ -75,24 +23,7 @@ export function createHistoryStore(subscriptions: SubscriptionsRouter) {
set(data.state);
});
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnail", async (data) => {
const url = await rasterize(data.svg);
keepThumbnail(data.id, url);
});
subscriptions.subscribeFrontendMessage("UpdateHistoryThumbnailPixels", (data) => {
keepThumbnail(data.id, encodePixels(data.pixels, data.width, data.height));
});
subscriptions.subscribeFrontendMessage("UpdateHistoryGraph", (data) => {
graph.set(data.graph);
});
subscriptions.subscribeFrontendMessage("UpdateHistoryGraphOverlay", (data) => {
graphOpen.set(data.open);
});
return { subscribe, thumbnails: { subscribe: thumbnails.subscribe }, graph: { subscribe: graph.subscribe }, graphOpen: { subscribe: graphOpen.subscribe } };
return { subscribe };
}
export function destroyHistoryStore() {
@@ -100,9 +31,5 @@ export function destroyHistoryStore() {
if (!subscriptions) return;
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnail");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryThumbnailPixels");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryGraph");
subscriptions.unsubscribeFrontendMessage("UpdateHistoryGraphOverlay");
subscriptionsRouter = undefined;
}
+17 -21
View File
@@ -7,8 +7,6 @@
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::*;
@@ -96,7 +94,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: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>, resend_widget: bool) -> Message {
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let update = LayoutMessage::WidgetValueUpdate {
layout_target,
@@ -113,7 +111,7 @@ mod editor_commands {
}
/// Commit the value of a given UI widget to the history
fn widget_value_commit(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>) -> Message {
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
LayoutMessage::WidgetValueCommit {
layout_target,
widget_id: WidgetId(widget_id),
@@ -123,7 +121,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: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>, resend_widget: bool) -> Message {
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
let widget_id = WidgetId(widget_id);
let mut messages: Vec<Message> = vec![
LayoutMessage::WidgetValueCommit {
@@ -149,13 +147,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: Ts<LayoutTarget>, widget_id: u64) -> Message {
fn widget_value_drag_drop(layout_target: 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: Ts<LayoutTarget>, widget_id: u64, name: String, mime_type: String, data: Vec<u8>) -> Message {
fn widget_value_file_drop(layout_target: 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()
@@ -163,7 +161,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: Ts<LayoutTarget>, widget_id: u64, source: String, caret: Option<u32>, asked: bool) -> Message {
fn analyze_math_expression(layout_target: LayoutTarget, widget_id: u64, source: String, caret: Option<u32>, asked: bool) -> Message {
LayoutMessage::AnalyzeMathExpression {
layout_target,
widget_id: WidgetId(widget_id),
@@ -259,7 +257,7 @@ mod editor_commands {
}
/// Bring a panel to the front, reopening it if closed
fn focus_panel(panel_type: Ts<PanelType>) -> Message {
fn focus_panel(panel_type: PanelType) -> Message {
WorkspaceMessage::FocusPanel { panel_type }.into()
}
@@ -300,12 +298,7 @@ mod editor_commands {
HistoryMessage::Tag { id, tag, on }.into()
}
/// Show or hide the history graph over the viewport
fn set_history_graph_open(open: bool) -> Message {
HistoryMessage::GraphOverlay { open }.into()
}
fn split_panel_group(target_group: u64, direction: Ts<DockingSplitDirection>, tabs: Vec<Ts<PanelType>>, active_tab_index: usize) -> Message {
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
WorkspaceMessage::SplitPanelGroup {
target_group: PanelGroupId(target_group),
direction,
@@ -485,7 +478,7 @@ mod editor_commands {
}
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
fn update_primary_color(color: Ts<SRGBA8>) -> Message {
fn update_primary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: true,
@@ -494,7 +487,7 @@ mod editor_commands {
}
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
fn update_secondary_color(color: Ts<SRGBA8>) -> Message {
fn update_secondary_color(color: SRGBA8) -> Message {
ToolMessage::SelectWorkingColor {
color: Color::from(color),
primary: false,
@@ -503,7 +496,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: Ts<FillChoiceSRGBA8>, allow_none: bool, disabled: bool) -> Message {
fn open_color_picker(initial_value: FillChoiceSRGBA8, allow_none: bool, disabled: bool) -> Message {
ColorPickerMessage::Open {
initial_value: FillChoice::from(&initial_value.0),
allow_none,
@@ -518,7 +511,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: Ts<SRGBA8>) -> Message {
fn update_gradient_stop_color(color: SRGBA8) -> Message {
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
}
@@ -710,12 +703,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: Ts<FileType>, width: u32, height: u32, data: Vec<u8>) -> Message {
fn save_rasterized_export(name: String, file_type: 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: Ts<IngestAction>) -> Message {
fn ingest_picked(name: String, mime_type: String, data: Vec<u8>, action: IngestAction) -> Message {
IngestMessage::Ingest {
data,
action,
@@ -933,6 +926,7 @@ 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>")]
@@ -942,6 +936,7 @@ 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")]
@@ -967,5 +962,6 @@ 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;
}
+1 -8
View File
@@ -250,14 +250,7 @@ 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: 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;
}
};
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
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.34", optional = true, default-features = false, features = ["all-types"] }
glam = { version = "0.33", optional = true, default-features = false, features = ["all-types"] }
reqwest = { version = "0.13", optional = true, default-features = false }
[package.metadata.docs.rs]
+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 DynAny<'_> + '_ {
unsafe impl StaticType for dyn for<'i> DynAny<'_> + '_ {
type Static = dyn DynAny<'static>;
}
unsafe impl StaticType for dyn DynAny<'_> + Send + Sync + '_ {
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + Sync + '_ {
type Static = dyn DynAny<'static> + Send + Sync;
}
unsafe impl StaticType for dyn DynAny<'_> + Send + '_ {
unsafe impl StaticType for dyn for<'i> 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,7 +18,6 @@ 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,12 +17,6 @@ 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 {
+10 -162
View File
@@ -1,11 +1,10 @@
use crate::ast::BinaryOp;
use crate::constants::{Builtin, BuiltinFunction, builtin_function};
use crate::context::{NothingMap, ValueProvider};
use crate::context::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;
@@ -81,17 +80,6 @@ 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.
@@ -99,69 +87,8 @@ impl Reducer {
if items.iter().any(|Value::Number(number)| number.is_nan()) {
return None;
}
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
let Value::Number(result) = self.evaluate_unsettled(items)?;
(!result.is_nan()).then(|| Value::Number(result.canonical()))
}
fn evaluate_unsettled(&self, items: &[Value]) -> Option<Value> {
@@ -211,7 +138,13 @@ impl Reducer {
match self {
Reducer::FoldLeft(op) => {
let combine = matrix_fold_step(*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 mut iter = items.iter().copied();
let Some(first) = iter.next() else {
@@ -228,60 +161,6 @@ 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
@@ -551,35 +430,4 @@ 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}");
}
}
}
}
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more