mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a43c661f14 | ||
|
|
96d5a442b0 | ||
|
|
de11d29d8e | ||
|
|
194c5b2222 | ||
|
|
e8f9413e03 | ||
|
|
7bc0f042ce | ||
|
|
674b3a213f | ||
|
|
3bf32443ed | ||
|
|
5f100946f2 | ||
|
|
13abf9fa8c | ||
|
|
236ab7a11c | ||
|
|
5b008936d2 | ||
|
|
9a9436c5b9 |
No files matched your search
@@ -137,6 +137,7 @@ jobs:
|
||||
const sectionTitles = ['Compilation', 'Update', 'Run Once', 'Cached Execution'];
|
||||
|
||||
let hasSignificantChanges = false;
|
||||
let hasRegressions = false;
|
||||
let regressionDetails = [];
|
||||
|
||||
for (let i = 0; i < allOutputs.length; i++) {
|
||||
@@ -153,19 +154,25 @@ jobs:
|
||||
|
||||
if (isSignificantChange(diffPct, absoluteChange, outputName)) {
|
||||
hasSignificantChanges = true;
|
||||
regressionDetails.push({
|
||||
module_path: benchmark.module_path,
|
||||
id: benchmark.id,
|
||||
diffPct,
|
||||
absoluteChange,
|
||||
sectionTitle
|
||||
});
|
||||
|
||||
// Only an increase in instruction count is a regression; improvements must not fail CI.
|
||||
if (diffPct > 0) {
|
||||
hasRegressions = true;
|
||||
regressionDetails.push({
|
||||
module_path: benchmark.module_path,
|
||||
id: benchmark.id,
|
||||
diffPct,
|
||||
absoluteChange,
|
||||
sectionTitle
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
core.setOutput('has-significant-changes', hasSignificantChanges);
|
||||
core.setOutput('has-regressions', hasRegressions);
|
||||
core.setOutput('regression-details', JSON.stringify(regressionDetails));
|
||||
|
||||
- name: Comment PR
|
||||
@@ -319,7 +326,7 @@ jobs:
|
||||
}
|
||||
|
||||
- name: Fail on significant regressions
|
||||
if: steps.analyze.outputs.has-significant-changes == 'true'
|
||||
if: steps.analyze.outputs.has-regressions == 'true'
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
|
||||
Generated
+26
@@ -1269,6 +1269,24 @@ dependencies = [
|
||||
"litrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "document-format"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"document-container",
|
||||
"futures",
|
||||
"graph-craft",
|
||||
"graph-storage",
|
||||
"graphene-resource",
|
||||
"log",
|
||||
"rmp-serde",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "downcast-rs"
|
||||
version = "1.2.1"
|
||||
@@ -2210,11 +2228,14 @@ dependencies = [
|
||||
"bitflags 2.11.0",
|
||||
"color",
|
||||
"derivative",
|
||||
"document-container",
|
||||
"document-format",
|
||||
"dyn-any",
|
||||
"env_logger",
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-storage",
|
||||
"graphene-hash",
|
||||
"graphene-std",
|
||||
"graphite-proc-macros",
|
||||
@@ -3863,6 +3884,7 @@ dependencies = [
|
||||
"log",
|
||||
"node-macro",
|
||||
"smallvec",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -4594,11 +4616,15 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
"vello",
|
||||
|
||||
+4
-1
@@ -9,6 +9,7 @@ members = [
|
||||
"desktop/platform/win",
|
||||
"document/container",
|
||||
"document/graph-storage",
|
||||
"document/document-format",
|
||||
"editor",
|
||||
"frontend/wrapper",
|
||||
"libraries/dyn-any",
|
||||
@@ -88,7 +89,9 @@ repeat-nodes = { path = "node-graph/nodes/repeat" }
|
||||
math-nodes = { path = "node-graph/nodes/math" }
|
||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
graph-storage = { path = "document/graph-storage" }
|
||||
graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-format = { path = "document/document-format" }
|
||||
document-container = { path = "document/container" }
|
||||
raster-nodes = { path = "node-graph/nodes/raster" }
|
||||
graphene-std = { path = "node-graph/nodes/gstd" }
|
||||
interpreted-executor = { path = "node-graph/interpreted-executor" }
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ impl App {
|
||||
let wake = Arc::new(move || {
|
||||
wake_scheduler.schedule(AppEvent::DesktopWrapperMessage(DesktopWrapperMessage::Wake));
|
||||
});
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), wgpu_context.clone(), wake);
|
||||
let desktop_wrapper = DesktopWrapper::new(rand::rng().random(), Arc::new(resource_storage), dirs::app_autosave_documents_dir(), wgpu_context.clone(), wake);
|
||||
|
||||
Self {
|
||||
render_state: None,
|
||||
|
||||
@@ -42,8 +42,8 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
default_filename: name,
|
||||
default_folder: folder,
|
||||
filters: vec![FileFilter {
|
||||
name: "Graphite".to_string(),
|
||||
extensions: vec!["graphite".to_string()],
|
||||
name: "Graphite Document".to_string(),
|
||||
extensions: vec!["gdd".to_string()],
|
||||
}],
|
||||
context: SaveFileDialogContext::Document { document_id, content },
|
||||
});
|
||||
|
||||
@@ -25,7 +25,7 @@ pub struct DesktopWrapper {
|
||||
}
|
||||
|
||||
impl DesktopWrapper {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
pub fn new(uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, working_copy_root: std::path::PathBuf, wgpu_context: WgpuContext, schedule_wake: Wake) -> Self {
|
||||
#[cfg(target_os = "windows")]
|
||||
let host = Host::Windows;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -36,7 +36,7 @@ impl DesktopWrapper {
|
||||
let application_io = PlatformApplicationIo::new_with_context(wgpu_context);
|
||||
|
||||
Self {
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, application_io, schedule_wake),
|
||||
editor: Editor::new(env, uuid_random_seed, resource_storage, Some(working_copy_root), application_io, schedule_wake),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
//! Each codec streams entries in both directions: writers wrap an `io::Write` sink, and
|
||||
//! `deserialize` reads from any `io::Read + Seek` source and streams entries into any [`Container`].
|
||||
|
||||
#[cfg(any(feature = "xz", feature = "zip"))]
|
||||
use crate::AsyncContainer;
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
use crate::ContainerError;
|
||||
use crate::{Container, Result};
|
||||
use crate::Result;
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
/// Hard cap on the total decompressed size a codec will materialize from one archive.
|
||||
@@ -55,12 +57,23 @@ pub trait Archive {
|
||||
|
||||
/// Read entries from `source` and write each into `dest`, streaming so neither the full
|
||||
/// archive nor the full container ever sits in memory at once.
|
||||
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()>;
|
||||
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()>;
|
||||
}
|
||||
|
||||
pub trait ArchiveWriter {
|
||||
pub trait ArchiveWriter: Sized {
|
||||
type Sink;
|
||||
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
fn finish(self) -> Result<()>;
|
||||
|
||||
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
|
||||
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
|
||||
fn finish_into(self) -> Result<Self::Sink>;
|
||||
|
||||
/// Finish the archive, discarding the sink. For file-backed archives the bytes are already on disk.
|
||||
fn finish(self) -> Result<()> {
|
||||
self.finish_into()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Archive container formats distinguishable by their leading magic bytes.
|
||||
@@ -86,12 +99,16 @@ impl ArchiveFormat {
|
||||
|
||||
/// Deserialize an archive into `dest`, auto-detecting the format from `bytes`' magic header.
|
||||
/// Errors if the bytes are neither a recognized xz nor zip archive.
|
||||
#[cfg(all(feature = "xz", feature = "zip"))]
|
||||
pub fn open_auto<C: Container>(bytes: &[u8], dest: &mut C) -> Result<()> {
|
||||
#[cfg(any(feature = "xz", feature = "zip"))]
|
||||
pub fn open_auto<C: AsyncContainer>(bytes: &[u8], dest: &mut C) -> Result<()> {
|
||||
let source = std::io::Cursor::new(bytes);
|
||||
match ArchiveFormat::detect(bytes) {
|
||||
#[cfg(feature = "xz")]
|
||||
Some(ArchiveFormat::Xz) => Xz::open(source, dest),
|
||||
#[cfg(feature = "zip")]
|
||||
Some(ArchiveFormat::Zip) => Zip::open(source, dest),
|
||||
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip)".into())),
|
||||
#[allow(unreachable_patterns)]
|
||||
Some(format) => Err(ContainerError::Codec(format!("tried to open {format:?}, but the binary was compiled without the feature enabled "))),
|
||||
None => Err(ContainerError::Codec("unrecognized archive format (not xz or zip) ".into())),
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Xz-compressed tarball archive codec.
|
||||
|
||||
use crate::archive::{Archive, ArchiveWriter, MAX_DECOMPRESSED_SIZE, checked_entry_size};
|
||||
use crate::{Container, ContainerError, Result, validate_path};
|
||||
use crate::{AsyncContainer, ContainerError, Result, validate_path};
|
||||
use lzma_rust2::{XzOptions, XzReader, XzWriter as InnerXzWriter};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Archive for Xz {
|
||||
})
|
||||
}
|
||||
|
||||
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()> {
|
||||
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
|
||||
// `take` bounds how many bytes we decompress from the xz stream, but each tar entry's declared
|
||||
// size is fed to `write_sized`, which pre-allocates from it before reading. Cap the cumulative
|
||||
// declared size too so a header claiming a huge size can't trigger a giant allocation up front.
|
||||
@@ -46,7 +46,7 @@ impl Archive for Xz {
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
dest.write_sized(&path, size, &mut |buffer| {
|
||||
dest.write_sized_non_blocking(&path, size, &mut |buffer| {
|
||||
entry.read_exact(buffer).map_err(ContainerError::Io)?;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -57,6 +57,8 @@ impl Archive for Xz {
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ArchiveWriter for XzWriter<W> {
|
||||
type Sink = W;
|
||||
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
let tar = self.tar.as_mut().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
|
||||
@@ -69,21 +71,14 @@ impl<W: Write + Seek> ArchiveWriter for XzWriter<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(mut self) -> Result<()> {
|
||||
self.finish_inner()?;
|
||||
Ok(())
|
||||
fn finish_into(mut self) -> Result<W> {
|
||||
self.finish_inner()
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> XzWriter<W> {
|
||||
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
|
||||
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
|
||||
pub fn finish_into(mut self) -> Result<W> {
|
||||
self.finish_inner()
|
||||
}
|
||||
|
||||
/// Unwind the layered writers in order (flush the tar trailer, then finish xz) and hand back the
|
||||
/// innermost sink. Shared by `finish` and `finish_into`.
|
||||
/// innermost sink.
|
||||
fn finish_inner(&mut self) -> Result<W> {
|
||||
let mut tar = self.tar.take().ok_or_else(|| ContainerError::Codec("XzWriter already finished".into()))?;
|
||||
tar.finish()?;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Zip archive codec.
|
||||
|
||||
use crate::archive::{Archive, ArchiveWriter, checked_entry_size};
|
||||
use crate::{Container, ContainerError, Result, validate_path};
|
||||
use crate::{AsyncContainer, ContainerError, Result, validate_path};
|
||||
use std::io::{Read, Seek, Write};
|
||||
|
||||
use zip::ZipArchive;
|
||||
@@ -24,7 +24,7 @@ impl Archive for Zip {
|
||||
})
|
||||
}
|
||||
|
||||
fn open<R: Read + Seek, C: Container>(source: R, dest: &mut C) -> Result<()> {
|
||||
fn open<R: Read + Seek, C: AsyncContainer>(source: R, dest: &mut C) -> Result<()> {
|
||||
let mut archive = ZipArchive::new(source).map_err(zip_err)?;
|
||||
|
||||
// Zip headers declare each entry's uncompressed size up front; `checked_entry_size` caps the running
|
||||
@@ -41,7 +41,7 @@ impl Archive for Zip {
|
||||
|
||||
let size = checked_entry_size(&mut total_size, entry.size())?;
|
||||
|
||||
dest.write_sized(&name, size, &mut |buffer| {
|
||||
dest.write_sized_non_blocking(&name, size, &mut |buffer| {
|
||||
entry.read_exact(buffer).map_err(ContainerError::Io)?;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -52,6 +52,8 @@ impl Archive for Zip {
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ArchiveWriter for ZipWriter<W> {
|
||||
type Sink = W;
|
||||
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
validate_path(path)?;
|
||||
self.inner.start_file(path, self.options).map_err(zip_err)?;
|
||||
@@ -59,16 +61,7 @@ impl<W: Write + Seek> ArchiveWriter for ZipWriter<W> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish(self) -> Result<()> {
|
||||
self.inner.finish().map_err(zip_err)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> ZipWriter<W> {
|
||||
/// Finish the archive and return the underlying sink, for in-memory archives where the caller
|
||||
/// wants the written bytes (e.g. `Cursor<Vec<u8>>`) back.
|
||||
pub fn finish_into(self) -> Result<W> {
|
||||
fn finish_into(self) -> Result<W> {
|
||||
self.inner.finish().map_err(zip_err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,6 +271,14 @@ pub trait AsyncContainer {
|
||||
/// and `Ok` is returned eagerly; a later failure is logged.
|
||||
fn write_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
|
||||
/// Synchronous write. Same eager-enqueue semantics on OPFS as [`write_non_blocking`](Self::write_non_blocking);
|
||||
/// queued appends preserve order relative to earlier queued writes/appends.
|
||||
fn write_sized_non_blocking(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
let mut buf = vec![0u8; size];
|
||||
fill(&mut buf)?;
|
||||
self.write_non_blocking(path, &buf)
|
||||
}
|
||||
|
||||
/// Synchronous append. Same eager-enqueue semantics on OPFS as [`write_non_blocking`](Self::write_non_blocking);
|
||||
/// queued appends preserve order relative to earlier queued writes/appends.
|
||||
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()>;
|
||||
@@ -320,6 +328,10 @@ impl<C: Container + ?Sized> AsyncContainer for C {
|
||||
Container::write(self, path, bytes)
|
||||
}
|
||||
|
||||
fn write_sized_non_blocking(&self, path: &str, size: usize, fill: &mut dyn FnMut(&mut [u8]) -> Result<()>) -> Result<()> {
|
||||
Container::write_sized(self, path, size, fill)
|
||||
}
|
||||
|
||||
fn append_non_blocking(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
Container::append(self, path, bytes)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
[package]
|
||||
name = "document-format"
|
||||
description = "Typed handle for the .gdd document format, sitting over graph-storage and document-container"
|
||||
edition.workspace = true
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[features]
|
||||
# Runtime bridge: the editor↔storage conversion methods (stage/commit from a `NodeNetwork`,
|
||||
# `network_ids`, `declarations`). Off lets a standalone migration tool build without `graph-craft`
|
||||
# or `core-types`. Forwards to `graph-storage/conversion`.
|
||||
conversion = ["graph-storage/conversion", "dep:graph-craft", "dep:core-types"]
|
||||
# Compressed-archive export/open. Each forwards to the matching `document-container` feature and
|
||||
# gates that format's `ExportFormat` arm and sink. The folder/memory codec-free core needs neither.
|
||||
zip = ["document-container/zip"]
|
||||
xz = ["document-container/xz"]
|
||||
default = ["conversion", "zip", "xz"]
|
||||
|
||||
[dependencies]
|
||||
document-container = { workspace = true }
|
||||
graph-storage = { workspace = true, default-features = false }
|
||||
graph-craft = { workspace = true, optional = true }
|
||||
graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rmp-serde = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
thiserror = "2.0"
|
||||
log = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
futures = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Codec for a stream of values. Single-value writes are just streams of length one.
|
||||
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Codec {
|
||||
/// A single JSON document. `append` to a non-empty buffer errors.
|
||||
Json,
|
||||
/// Newline-delimited compact JSON, one value per line.
|
||||
JsonLines,
|
||||
/// A single MessagePack blob. `append` to a non-empty buffer errors.
|
||||
MessagePack,
|
||||
/// Length-prefixed MessagePack frames: `[u32 big-endian length][MessagePack bytes]` per value.
|
||||
MessagePackFrames,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CodecError {
|
||||
#[error("MessagePack encode error: {0}")]
|
||||
MessagePackEncode(#[from] rmp_serde::encode::Error),
|
||||
#[error("MessagePack decode error: {0}")]
|
||||
MessagePackDecode(#[from] rmp_serde::decode::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("frame length {0} exceeds u32")]
|
||||
FrameTooLarge(usize),
|
||||
#[error("frame length prefix truncated: need 4 bytes, have {0}")]
|
||||
TruncatedLengthPrefix(usize),
|
||||
#[error("declared frame length {declared} exceeds remaining buffer ({remaining} bytes)")]
|
||||
TruncatedFrame { declared: usize, remaining: usize },
|
||||
#[error("single-value codec cannot append to a non-empty buffer")]
|
||||
SingleValueAlreadyWritten,
|
||||
#[error("expected at least one value, got none")]
|
||||
Empty,
|
||||
#[error("expected exactly one value, got more")]
|
||||
ExpectedSingle,
|
||||
}
|
||||
|
||||
impl Codec {
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self {
|
||||
Codec::Json => "json",
|
||||
Codec::JsonLines => "jsonl",
|
||||
Codec::MessagePack => "bin",
|
||||
Codec::MessagePackFrames => "frames",
|
||||
}
|
||||
}
|
||||
|
||||
/// Append one value to `output` in this codec's framing.
|
||||
/// Single-value codecs error if `output` is non-empty.
|
||||
pub fn append<T: Serialize>(self, output: &mut Vec<u8>, value: &T) -> Result<(), CodecError> {
|
||||
match self {
|
||||
Codec::Json => {
|
||||
if !output.is_empty() {
|
||||
return Err(CodecError::SingleValueAlreadyWritten);
|
||||
}
|
||||
serde_json::to_writer_pretty(output, value)?;
|
||||
Ok(())
|
||||
}
|
||||
Codec::JsonLines => {
|
||||
serde_json::to_writer(&mut *output, value)?;
|
||||
output.push(b'\n');
|
||||
Ok(())
|
||||
}
|
||||
Codec::MessagePack => {
|
||||
if !output.is_empty() {
|
||||
return Err(CodecError::SingleValueAlreadyWritten);
|
||||
}
|
||||
rmp_serde::encode::write(output, value)?;
|
||||
Ok(())
|
||||
}
|
||||
Codec::MessagePackFrames => {
|
||||
let payload = rmp_serde::to_vec(value)?;
|
||||
let length = u32::try_from(payload.len()).map_err(|_| CodecError::FrameTooLarge(payload.len()))?;
|
||||
output.extend_from_slice(&length.to_be_bytes());
|
||||
output.extend_from_slice(&payload);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate values from `bytes`. Single-value codecs yield exactly one item;
|
||||
/// stream codecs yield however many were written.
|
||||
pub fn iter<'a, T: DeserializeOwned + 'a>(self, bytes: &'a [u8]) -> Box<dyn Iterator<Item = Result<T, CodecError>> + 'a> {
|
||||
match self {
|
||||
Codec::Json => {
|
||||
let single = serde_json::from_slice::<T>(bytes).map_err(CodecError::from);
|
||||
Box::new(std::iter::once(single))
|
||||
}
|
||||
Codec::JsonLines => Box::new(JsonLineIter {
|
||||
remaining: bytes,
|
||||
_marker: std::marker::PhantomData,
|
||||
}),
|
||||
Codec::MessagePack => {
|
||||
let single = rmp_serde::from_slice::<T>(bytes).map_err(CodecError::from);
|
||||
Box::new(std::iter::once(single))
|
||||
}
|
||||
Codec::MessagePackFrames => Box::new(MessagePackFrameIter {
|
||||
remaining: bytes,
|
||||
_marker: std::marker::PhantomData,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serialize a single value into a fresh buffer.
|
||||
pub fn write_single<T: Serialize>(self, value: &T) -> Result<Vec<u8>, CodecError> {
|
||||
let mut output = Vec::new();
|
||||
self.append(&mut output, value)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Deserialize the single value in `bytes`. Errors if zero or more than one value is present.
|
||||
pub fn read_single<T: DeserializeOwned>(self, bytes: &[u8]) -> Result<T, CodecError> {
|
||||
let mut iter = self.iter::<T>(bytes);
|
||||
let first = iter.next().ok_or(CodecError::Empty)??;
|
||||
match iter.next() {
|
||||
// A trailing decode error is more informative than `ExpectedSingle`, so surface it.
|
||||
Some(Err(error)) => return Err(error),
|
||||
Some(Ok(_)) => return Err(CodecError::ExpectedSingle),
|
||||
None => {}
|
||||
}
|
||||
Ok(first)
|
||||
}
|
||||
}
|
||||
|
||||
struct JsonLineIter<'a, T> {
|
||||
remaining: &'a [u8],
|
||||
_marker: std::marker::PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned> Iterator for JsonLineIter<'_, T> {
|
||||
type Item = Result<T, CodecError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
loop {
|
||||
if self.remaining.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (line, tail) = match self.remaining.iter().position(|&byte| byte == b'\n') {
|
||||
Some(index) => (&self.remaining[..index], &self.remaining[index + 1..]),
|
||||
None => (self.remaining, &[][..]),
|
||||
};
|
||||
self.remaining = tail;
|
||||
|
||||
let trimmed = trim_ascii(line);
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
return Some(serde_json::from_slice(trimmed).map_err(CodecError::from));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MessagePackFrameIter<'a, T> {
|
||||
remaining: &'a [u8],
|
||||
_marker: std::marker::PhantomData<fn() -> T>,
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned> Iterator for MessagePackFrameIter<'_, T> {
|
||||
type Item = Result<T, CodecError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.remaining.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let buffer = std::mem::take(&mut self.remaining);
|
||||
|
||||
let Some((length_bytes, tail)) = buffer.split_first_chunk::<4>() else {
|
||||
return Some(Err(CodecError::TruncatedLengthPrefix(buffer.len())));
|
||||
};
|
||||
let length = u32::from_be_bytes(*length_bytes) as usize;
|
||||
|
||||
if tail.len() < length {
|
||||
return Some(Err(CodecError::TruncatedFrame {
|
||||
declared: length,
|
||||
remaining: tail.len(),
|
||||
}));
|
||||
}
|
||||
|
||||
let (frame, after) = tail.split_at(length);
|
||||
self.remaining = after;
|
||||
|
||||
Some(rmp_serde::from_slice(frame).map_err(CodecError::from))
|
||||
}
|
||||
}
|
||||
|
||||
fn trim_ascii(bytes: &[u8]) -> &[u8] {
|
||||
let start = bytes.iter().position(|byte| !byte.is_ascii_whitespace()).unwrap_or(bytes.len());
|
||||
let end = bytes.iter().rposition(|byte| !byte.is_ascii_whitespace()).map(|index| index + 1).unwrap_or(start);
|
||||
&bytes[start..end]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
struct Frame {
|
||||
id: u32,
|
||||
label: String,
|
||||
}
|
||||
|
||||
fn frames() -> [Frame; 3] {
|
||||
[Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }, Frame { id: 3, label: "gamma".into() }]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trip_single() {
|
||||
let frame = Frame { id: 7, label: "solo".into() };
|
||||
let bytes = Codec::Json.write_single(&frame).unwrap();
|
||||
let decoded: Frame = Codec::Json.read_single(&bytes).unwrap();
|
||||
assert_eq!(decoded, frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_append_to_non_empty_errors() {
|
||||
let mut buffer = b"already here".to_vec();
|
||||
let result = Codec::Json.append(&mut buffer, &Frame { id: 1, label: "x".into() });
|
||||
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_pack_round_trip_single() {
|
||||
let frame = Frame { id: 99, label: "blob".into() };
|
||||
let bytes = Codec::MessagePack.write_single(&frame).unwrap();
|
||||
let decoded: Frame = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||
assert_eq!(decoded, frame);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_pack_append_to_non_empty_errors() {
|
||||
let mut buffer = vec![0xAB];
|
||||
let result = Codec::MessagePack.append(&mut buffer, &Frame { id: 1, label: "x".into() });
|
||||
assert!(matches!(result, Err(CodecError::SingleValueAlreadyWritten)), "got {result:?}");
|
||||
}
|
||||
|
||||
/// A type-erased `serde_json::Value` round-trips through the binary codec: the property postcard
|
||||
/// could not satisfy (it raises `WontImplement` on self-describing values), which is why the
|
||||
/// resource/attribute deltas that carry `serde_json::Value` bodies need a self-describing codec.
|
||||
#[test]
|
||||
fn message_pack_round_trips_serde_json_value() {
|
||||
let value = serde_json::json!({ "kind": "embedded", "priority": 1.5, "tags": ["a", "b"] });
|
||||
let bytes = Codec::MessagePack.write_single(&value).unwrap();
|
||||
let decoded: serde_json::Value = Codec::MessagePack.read_single(&bytes).unwrap();
|
||||
assert_eq!(decoded, value);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_lines_round_trip_and_skip_blanks() {
|
||||
let frames = [Frame { id: 1, label: "alpha".into() }, Frame { id: 2, label: "beta".into() }];
|
||||
|
||||
let mut buffer = Vec::new();
|
||||
Codec::JsonLines.append(&mut buffer, &frames[0]).unwrap();
|
||||
buffer.extend_from_slice(b" \n\n");
|
||||
Codec::JsonLines.append(&mut buffer, &frames[1]).unwrap();
|
||||
|
||||
let decoded: Vec<Frame> = Codec::JsonLines.iter(&buffer).collect::<Result<_, _>>().unwrap();
|
||||
assert_eq!(decoded, frames);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_pack_frames_round_trip() {
|
||||
let frames = frames();
|
||||
let mut buffer = Vec::new();
|
||||
for frame in &frames {
|
||||
Codec::MessagePackFrames.append(&mut buffer, frame).unwrap();
|
||||
}
|
||||
let decoded: Vec<Frame> = Codec::MessagePackFrames.iter(&buffer).collect::<Result<_, _>>().unwrap();
|
||||
assert_eq!(decoded, frames);
|
||||
}
|
||||
|
||||
/// A crash mid-append leaves a torn final frame. The length prefix lets us detect that
|
||||
/// deterministically (declared length exceeds the bytes that actually made it to disk) rather
|
||||
/// than decoding a partial value into a plausible-but-wrong one.
|
||||
#[test]
|
||||
fn message_pack_frames_detect_truncation() {
|
||||
let mut buffer = Vec::new();
|
||||
Codec::MessagePackFrames.append(&mut buffer, &Frame { id: 7, label: "ok".into() }).unwrap();
|
||||
buffer.truncate(buffer.len() - 1);
|
||||
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
|
||||
assert!(matches!(last, Err(CodecError::TruncatedFrame { .. })), "got {last:?}");
|
||||
}
|
||||
|
||||
/// A buffer whose first record's length prefix itself is incomplete (fewer than 4 bytes) is
|
||||
/// reported as a truncated prefix rather than mis-read as a zero-length frame.
|
||||
#[test]
|
||||
fn message_pack_frames_detect_truncated_length_prefix() {
|
||||
let buffer = vec![0x00, 0x00];
|
||||
let last = Codec::MessagePackFrames.iter::<Frame>(&buffer).last().unwrap();
|
||||
assert!(matches!(last, Err(CodecError::TruncatedLengthPrefix(2))), "got {last:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_single_then_read_with_iter_yields_one() {
|
||||
let frame = Frame { id: 5, label: "one".into() };
|
||||
for codec in [Codec::Json, Codec::JsonLines, Codec::MessagePack, Codec::MessagePackFrames] {
|
||||
let bytes = codec.write_single(&frame).unwrap();
|
||||
let collected: Vec<Frame> = codec.iter(&bytes).collect::<Result<_, _>>().unwrap();
|
||||
assert_eq!(collected, vec![Frame { id: 5, label: "one".into() }], "codec {codec:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_single_rejects_multi_value_stream() {
|
||||
let mut buffer = Vec::new();
|
||||
Codec::JsonLines.append(&mut buffer, &Frame { id: 1, label: "a".into() }).unwrap();
|
||||
Codec::JsonLines.append(&mut buffer, &Frame { id: 2, label: "b".into() }).unwrap();
|
||||
let result: Result<Frame, _> = Codec::JsonLines.read_single(&buffer);
|
||||
assert!(matches!(result, Err(CodecError::ExpectedSingle)), "got {result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_are_distinct() {
|
||||
let exts = [
|
||||
Codec::Json.extension(),
|
||||
Codec::JsonLines.extension(),
|
||||
Codec::MessagePack.extension(),
|
||||
Codec::MessagePackFrames.extension(),
|
||||
];
|
||||
let unique: std::collections::HashSet<_> = exts.iter().collect();
|
||||
assert_eq!(unique.len(), exts.len(), "extensions collide: {exts:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Unified error type for the `document-format` crate.
|
||||
//!
|
||||
//! Every fallible [`crate::Gdd`] method returns [`Result<T>`]. Variants are grouped by failure
|
||||
//! domain (container I/O, codec, CRDT, format validation, export)
|
||||
|
||||
use document_container::ContainerError;
|
||||
#[cfg(feature = "conversion")]
|
||||
use graph_storage::CommitError;
|
||||
use graph_storage::CrdtError;
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
use crate::codec::CodecError;
|
||||
use crate::io::ReadError;
|
||||
|
||||
/// Crate-wide result alias.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Anything that can go wrong reading, mutating, or exporting a `.gdd` document. Per the format's
|
||||
/// load-time policy, any unexpected condition is a hard error rather than a silent fallback.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// Working-copy container I/O failed (read, write, or path validation).
|
||||
#[error("container error: {0}")]
|
||||
Container(#[from] ContainerError),
|
||||
/// A typed payload could not be located or read from the container.
|
||||
#[error("read error: {0}")]
|
||||
Read(#[from] ReadError),
|
||||
/// A payload failed to encode or decode in its recorded codec.
|
||||
#[error("codec error: {0}")]
|
||||
Codec(#[from] CodecError),
|
||||
/// A CRDT operation was rejected while replaying a hot op or moving the undo/redo cursor.
|
||||
#[error("CRDT error: {0}")]
|
||||
Crdt(#[from] CrdtError),
|
||||
/// Staging a runtime snapshot into the session failed (conversion or CRDT apply).
|
||||
#[cfg(feature = "conversion")]
|
||||
#[error("commit error: {0}")]
|
||||
Commit(#[from] CommitError),
|
||||
/// The manifest's `format` field is not the `.gdd` magic, so this is not a `.gdd` document.
|
||||
#[error("not a .gdd document (manifest format = {found:?}, expected {expected:?})")]
|
||||
WrongFormat { found: String, expected: &'static str },
|
||||
/// The manifest declares a format version newer than this build can open.
|
||||
#[error("unsupported format version: found {found}, max supported {max_supported}")]
|
||||
UnsupportedVersion { found: u32, max_supported: u32 },
|
||||
/// The requested export options are incoherent (e.g. neither registry nor history included).
|
||||
#[error("invalid export options: {0}")]
|
||||
InvalidExportOptions(&'static str),
|
||||
/// An export marked a resource for embedding but its bytes were absent from the byte store.
|
||||
#[error("embedded resource {0} missing from the byte store")]
|
||||
MissingResource(ResourceHash),
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Export: walking the working copy through an archive codec, keeping payloads as-is.
|
||||
//!
|
||||
//! [`ExportFormat`] / [`ExportOptions`] are the public settings; the [`Gdd`] export methods drive a
|
||||
//! [`ExportSink`] (folder / zip / xz) through the manifest → registry → history → resources sequence.
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
|
||||
use graphene_resource::{LoadResource, Resource, ResourceHash};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
|
||||
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
|
||||
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum ExportFormat {
|
||||
/// Copy the working copy to a destination folder.
|
||||
Folder,
|
||||
/// Wrap as a `.gdd.zip` archive.
|
||||
#[cfg(feature = "zip")]
|
||||
Zip,
|
||||
/// Wrap as a `.gdd.tar.xz` archive (whole-archive xz via `lzma-rust2`).
|
||||
#[cfg(feature = "xz")]
|
||||
Xz,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub struct ExportOptions {
|
||||
/// Whether to include the registry snapshot. `false` produces a history-only export, useful
|
||||
/// for VCS workflows where the diffable `history.jsonl` is the interesting payload and the
|
||||
/// registry would rewrite whole-file on every retirement. Consumers replay history from an
|
||||
/// empty registry.
|
||||
pub include_registry: bool,
|
||||
/// Whether to include history + hot-log. `false` produces a flat snapshot (registry only),
|
||||
/// useful for sharing without revealing edit history and for cutting file size.
|
||||
pub include_history: bool,
|
||||
/// Materialize every non-`DataSource::Embedded` resource into `resources/<hash>` for portability.
|
||||
/// Does not mutate the in-memory `Gdd`.
|
||||
pub embed_all_resources: bool,
|
||||
}
|
||||
|
||||
impl ExportOptions {
|
||||
/// Returns an error description if the combination is incoherent.
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
if !self.include_registry && !self.include_history {
|
||||
return Err("export must include at least one of: registry, history");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ExportOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
include_registry: true,
|
||||
include_history: true,
|
||||
embed_all_resources: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Stream the working copy to `dest` as a folder/zip/xz archive, keeping payload codecs as-is.
|
||||
/// Does not mutate `self` and does not buffer the export. Native-only (writes a filesystem path).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidExportOptions`] for incoherent options, [`Error::MissingResource`] if an
|
||||
/// embedded resource's bytes are absent from `byte_store`.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub async fn export(&self, dest: &Path, format: ExportFormat, options: ExportOptions, byte_store: &dyn LoadResource, legacy_document: Option<&[u8]>) -> Result<(), Error> {
|
||||
options.validate().map_err(Error::InvalidExportOptions)?;
|
||||
|
||||
match format {
|
||||
ExportFormat::Folder => {
|
||||
let mut folder = document_container::backends::folder::FolderBackend::create(dest)?;
|
||||
let mut sink = FolderSink { folder: &mut folder };
|
||||
self.stream_entries(options, byte_store, &mut sink).await?;
|
||||
if let Some(legacy) = legacy_document {
|
||||
sink.write_entry(self.layout.legacy_path(), legacy)?;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "zip")]
|
||||
ExportFormat::Zip => {
|
||||
let file = std::fs::File::create(dest).map_err(document_container::ContainerError::Io)?;
|
||||
self.export_archive::<document_container::archive::Zip, _>(file, options, byte_store, legacy_document).await?;
|
||||
}
|
||||
#[cfg(feature = "xz")]
|
||||
ExportFormat::Xz => {
|
||||
let file = std::fs::File::create(dest).map_err(document_container::ContainerError::Io)?;
|
||||
self.export_archive::<document_container::archive::Xz, _>(file, options, byte_store, legacy_document).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// In-memory variant of [`export`](Self::export) returning the archive bytes. Available on every
|
||||
/// target (no `std::fs`) but buffers the whole archive. `legacy_document` is embedded verbatim at
|
||||
/// [`Layout::legacy_path`]. `ExportFormat::Folder` has no single-file form and is rejected.
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
pub async fn export_to_bytes(&self, format: ExportFormat, options: ExportOptions, byte_store: &dyn LoadResource, legacy_document: Option<&[u8]>) -> Result<Vec<u8>, Error> {
|
||||
options.validate().map_err(Error::InvalidExportOptions)?;
|
||||
|
||||
let cursor = std::io::Cursor::new(Vec::new());
|
||||
let buffer = match format {
|
||||
ExportFormat::Folder => return Err(Error::InvalidExportOptions("folder export has no single-file byte form")),
|
||||
#[cfg(feature = "zip")]
|
||||
ExportFormat::Zip => self.export_archive::<document_container::archive::Zip, _>(cursor, options, byte_store, legacy_document).await?,
|
||||
#[cfg(feature = "xz")]
|
||||
ExportFormat::Xz => self.export_archive::<document_container::archive::Xz, _>(cursor, options, byte_store, legacy_document).await?,
|
||||
};
|
||||
|
||||
Ok(buffer.into_inner())
|
||||
}
|
||||
|
||||
/// Stream entries into a fresh `A` archive over `output`, append the optional legacy blob, then
|
||||
/// finalize and hand back the inner sink. The shared body of both archive export paths.
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
async fn export_archive<A, W>(&self, output: W, options: ExportOptions, byte_store: &dyn LoadResource, legacy_document: Option<&[u8]>) -> Result<W, Error>
|
||||
where
|
||||
A: document_container::archive::Archive,
|
||||
W: std::io::Write + std::io::Seek + Send,
|
||||
A::Writer<W>: ExportSink + document_container::archive::ArchiveWriter<Sink = W>,
|
||||
{
|
||||
use document_container::archive::ArchiveWriter;
|
||||
|
||||
let mut writer = A::writer(output)?;
|
||||
self.stream_entries(options, byte_store, &mut writer).await?;
|
||||
if let Some(legacy) = legacy_document {
|
||||
ExportSink::write_entry(&mut writer, self.layout.legacy_path(), legacy)?;
|
||||
}
|
||||
Ok(writer.finish_into()?)
|
||||
}
|
||||
|
||||
/// Drive a sink through manifest → session → registry → history → resources, one entry at a time,
|
||||
/// keeping each payload's recorded codec.
|
||||
async fn stream_entries(&self, options: ExportOptions, byte_store: &dyn LoadResource, sink: &mut dyn ExportSink) -> Result<(), Error> {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let codecs = self.manifest.codecs;
|
||||
sink.write_entry(&io::path_for(self.layout.manifest_basename(), MANIFEST_CODEC), &MANIFEST_CODEC.write_single(&self.manifest)?)?;
|
||||
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let session_state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
|
||||
|
||||
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
|
||||
|
||||
// Resources to embed as bytes: every `Embedded` entry, plus link-only ones when
|
||||
// `embed_all_resources`. Bytes already in the working copy are written by the copy-through pass
|
||||
// below, so only the gap is loaded from the byte store here.
|
||||
let mut export_session = self.session.clone();
|
||||
let mut hashes_from_store: Vec<ResourceHash> = Vec::new();
|
||||
let mut links_to_promote: Vec<graph_storage::ResourceId> = Vec::new();
|
||||
for (id, entry) in &export_session.registry().resources {
|
||||
let Some(hash) = entry.hash else { continue };
|
||||
let embed = entry.has_embedded_source() || options.embed_all_resources;
|
||||
if !embed {
|
||||
continue;
|
||||
}
|
||||
if !entry.has_embedded_source() {
|
||||
links_to_promote.push(*id);
|
||||
}
|
||||
if !working_copy_hashes.contains(&hash) {
|
||||
hashes_from_store.push(hash);
|
||||
}
|
||||
}
|
||||
|
||||
hashes_from_store.sort_unstable();
|
||||
hashes_from_store.dedup();
|
||||
|
||||
// Fail fast if an embedded resource is missing, then promote link-only sources on the clone so
|
||||
// the exported registry and history stay consistent. The live `Gdd` is untouched.
|
||||
let mut embedded_bytes: Vec<(ResourceHash, Resource)> = Vec::new();
|
||||
for hash in hashes_from_store {
|
||||
let Some(resource) = byte_store.load(hash).await else {
|
||||
return Err(Error::MissingResource(hash));
|
||||
};
|
||||
embedded_bytes.push((hash, resource));
|
||||
}
|
||||
export_session.embed_resource_sources(links_to_promote)?;
|
||||
|
||||
if options.include_registry {
|
||||
// With history, the persisted snapshot is the retired registry and the hot log layers on top
|
||||
// (mirrors `Session::load`); without history it must be the full working registry, since
|
||||
// `bootstrap_from_registry` reconstructs the whole document from it alone.
|
||||
let snapshot = if options.include_history { export_session.retired_registry() } else { export_session.registry() };
|
||||
sink.write_entry(&io::path_for(self.layout.registry_basename(), codecs.registry), &codecs.registry.write_single(snapshot)?)?;
|
||||
}
|
||||
|
||||
if options.include_history {
|
||||
let mut buffer = Vec::new();
|
||||
for delta in export_session.history() {
|
||||
codecs.history.append(&mut buffer, delta)?;
|
||||
}
|
||||
if !buffer.is_empty() {
|
||||
sink.write_entry(&io::path_for(self.layout.history_basename(), codecs.history), &buffer)?;
|
||||
}
|
||||
|
||||
// Carry the un-retired hot ops alongside history so a document exported mid-interaction (e.g. a save
|
||||
// during a tool drag) isn't shipped with its pending edits dropped. `open` replays them on top of
|
||||
// the retired snapshot, same as the working copy does.
|
||||
let mut hot_buffer = Vec::new();
|
||||
for hot_op in export_session.hot_log() {
|
||||
codecs.hot_log.append(&mut hot_buffer, hot_op)?;
|
||||
}
|
||||
if !hot_buffer.is_empty() {
|
||||
sink.write_entry(&io::path_for(self.layout.hot_log_basename(), codecs.hot_log), &hot_buffer)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy bytes the working copy already holds, tracking covered hashes so the embed pass below
|
||||
// doesn't re-emit them.
|
||||
let mut emitted = std::collections::HashSet::new();
|
||||
let resources_dir = self.layout.resources_dir();
|
||||
if self.working.list_dirs("").await?.iter().any(|d| d == resources_dir) {
|
||||
let prefix = format!("{resources_dir}/");
|
||||
for path in self.working.list(resources_dir).await? {
|
||||
if let Some(hash) = path.strip_prefix(&prefix).and_then(|name| name.parse::<ResourceHash>().ok()) {
|
||||
emitted.insert(hash);
|
||||
}
|
||||
let holder = self.working.read(&path).await?;
|
||||
|
||||
// Native `External` (mmap'd) holders copy CoW via a source path; others write bytes.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
match holder.source_path() {
|
||||
Some(src_path) => sink.write_entry_from_path(&path, src_path)?,
|
||||
None => sink.write_entry(&path, holder.as_slice())?,
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
sink.write_entry(&path, holder.as_slice())?;
|
||||
}
|
||||
}
|
||||
|
||||
for (hash, resource) in &embedded_bytes {
|
||||
if emitted.insert(*hash) {
|
||||
sink.write_entry(&self.layout.resource_path(hash), resource.as_ref())?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Sink an export streams entries into, so one async loop drives folder/zip/xz writes. Archive sinks
|
||||
/// work on every target; the folder sink and `write_entry_from_path` are native-only. `Send` because
|
||||
/// `stream_entries` holds `&mut dyn ExportSink` across `.await`s.
|
||||
pub(crate) trait ExportSink: Send {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error>;
|
||||
|
||||
/// Copy a file from disk into the sink. Default reads it into memory; the folder sink overrides to
|
||||
/// `fs::copy` (CoW). Native-only: only reachable for an `External` (mmap'd) holder.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn write_entry_from_path(&mut self, path: &str, src: &std::path::Path) -> Result<(), Error> {
|
||||
let bytes = std::fs::read(src).map_err(document_container::ContainerError::Io)?;
|
||||
self.write_entry(path, &bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
struct FolderSink<'a> {
|
||||
folder: &'a mut document_container::backends::folder::FolderBackend,
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl ExportSink for FolderSink<'_> {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
|
||||
document_container::Container::write(self.folder, path, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_entry_from_path(&mut self, path: &str, src: &std::path::Path) -> Result<(), Error> {
|
||||
document_container::validate_path(path)?;
|
||||
let dest = self.folder.root().join(path);
|
||||
if let Some(parent) = dest.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(document_container::ContainerError::Io)?;
|
||||
}
|
||||
std::fs::copy(src, &dest).map_err(document_container::ContainerError::Io)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "zip")]
|
||||
impl<W: std::io::Write + std::io::Seek + Send> ExportSink for document_container::archive::ZipWriter<W> {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
|
||||
use document_container::archive::ArchiveWriter;
|
||||
ArchiveWriter::write_entry(self, path, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "xz")]
|
||||
impl<W: std::io::Write + std::io::Seek + Send> ExportSink for document_container::archive::XzWriter<W> {
|
||||
fn write_entry(&mut self, path: &str, bytes: &[u8]) -> Result<(), Error> {
|
||||
use document_container::archive::ArchiveWriter;
|
||||
ArchiveWriter::write_entry(self, path, bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Bridge between [`crate::Codec`] and [`document_container::AnyContainer`]. Each payload's codec
|
||||
//! is known up front (the manifest is always JSON; every other payload's codec is recorded in the
|
||||
//! manifest), so reads and writes address a fixed `{basename}.{ext}` path without probing.
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer};
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::{Codec, CodecError};
|
||||
|
||||
/// Compose a container path from `basename` and `codec.extension()`.
|
||||
pub fn path_for(basename: &str, codec: Codec) -> String {
|
||||
format!("{basename}.{}", codec.extension())
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ReadError {
|
||||
#[error("file not found for basename {basename:?} with codec {codec:?}")]
|
||||
NotFound { basename: String, codec: Codec },
|
||||
#[error("container error: {0}")]
|
||||
Container(#[from] document_container::ContainerError),
|
||||
#[error("codec error: {0}")]
|
||||
Codec(#[from] CodecError),
|
||||
}
|
||||
|
||||
/// Read `{basename}.{ext}` and decode the single value it contains.
|
||||
pub async fn read_single<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<T, ReadError> {
|
||||
let bytes = read_bytes(container, basename, codec).await?;
|
||||
Ok(codec.read_single::<T>(bytes.as_slice())?)
|
||||
}
|
||||
|
||||
/// Same as [`read_single`] but yields every value when `codec` is a stream codec.
|
||||
pub async fn iter<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<Vec<T>, ReadError> {
|
||||
let bytes = read_bytes(container, basename, codec).await?;
|
||||
Ok(codec.iter::<T>(bytes.as_slice()).collect::<Result<Vec<_>, _>>()?)
|
||||
}
|
||||
|
||||
/// Whether `{basename}.{ext}` exists for the given codec.
|
||||
pub async fn exists(container: &AnyContainer, basename: &str, codec: Codec) -> bool {
|
||||
container.exists(&path_for(basename, codec)).await
|
||||
}
|
||||
|
||||
/// Encode `value` with `codec` and write to `{basename}.{ext}`. Synchronous: the write goes through
|
||||
/// the container's sync write surface (durable on folder/memory, enqueued on OPFS).
|
||||
pub fn write_single<T: Serialize>(container: &AnyContainer, basename: &str, codec: Codec, value: &T) -> Result<(), crate::Error> {
|
||||
let bytes = codec.write_single(value)?;
|
||||
container.write_non_blocking(&path_for(basename, codec), &bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn read_bytes(container: &AnyContainer, basename: &str, codec: Codec) -> Result<document_container::ByteHolder, ReadError> {
|
||||
let path = path_for(basename, codec);
|
||||
if !container.exists(&path).await {
|
||||
return Err(ReadError::NotFound {
|
||||
basename: basename.to_string(),
|
||||
codec,
|
||||
});
|
||||
}
|
||||
Ok(container.read(&path).await?)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Path layout for a `.gdd` working copy.
|
||||
//!
|
||||
//! Layout owns basenames only — the codec choice for each payload is a runtime parameter at the
|
||||
//! read/write call site. Working-copy creation, exports, and migrations may all hit the same
|
||||
//! basename with different codecs.
|
||||
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
pub trait Layout {
|
||||
fn manifest_basename(&self) -> &str;
|
||||
fn session_basename(&self) -> &str;
|
||||
fn registry_basename(&self) -> &str;
|
||||
fn history_basename(&self) -> &str;
|
||||
fn hot_log_basename(&self) -> &str;
|
||||
fn resources_dir(&self) -> &str;
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String;
|
||||
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
|
||||
/// new format can be validated against (and recovered from) the old one. Dropped once `.gdd`
|
||||
/// becomes the sole source of truth.
|
||||
fn legacy_path(&self) -> &str;
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default)]
|
||||
pub struct GddV1Layout;
|
||||
|
||||
impl Layout for GddV1Layout {
|
||||
fn manifest_basename(&self) -> &str {
|
||||
"manifest"
|
||||
}
|
||||
fn session_basename(&self) -> &str {
|
||||
"session"
|
||||
}
|
||||
fn registry_basename(&self) -> &str {
|
||||
"registry"
|
||||
}
|
||||
fn history_basename(&self) -> &str {
|
||||
"history"
|
||||
}
|
||||
fn hot_log_basename(&self) -> &str {
|
||||
"hot-log"
|
||||
}
|
||||
fn resources_dir(&self) -> &str {
|
||||
"resources"
|
||||
}
|
||||
fn resource_path(&self, hash: &ResourceHash) -> String {
|
||||
format!("{}/{hash}", self.resources_dir())
|
||||
}
|
||||
fn legacy_path(&self) -> &str {
|
||||
"legacy.graphite"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Typed handle for `.gdd` documents.
|
||||
//!
|
||||
//! [`Gdd`] owns a [`graph_storage::Session`] plus a working-copy [`document_container::AnyContainer`].
|
||||
//! Mutations flow through `Gdd` to keep the session and the on-disk working copy mirrored.
|
||||
//! Export is a separate, explicit operation — see [`export::ExportFormat`].
|
||||
//!
|
||||
//! See the "On-disk container" section of `node-graph/rfcs/document-format.md` for the format spec.
|
||||
|
||||
use std::sync::Arc;
|
||||
// `Path` and `FolderBackend` are only used by the native-only path-based open/create, so they're
|
||||
// gated off wasm to avoid unused-import warnings.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graph_storage::{CommitError, NodeMetadataSource};
|
||||
use graph_storage::{Delta, HotOp, PeerId, Registry, Session};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::LoadResource;
|
||||
use graphene_resource::ResourceHash;
|
||||
|
||||
pub mod codec;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
pub mod io;
|
||||
pub mod layout;
|
||||
pub mod manifest;
|
||||
pub mod persist;
|
||||
pub mod resource;
|
||||
pub mod session_state;
|
||||
|
||||
pub use codec::{Codec, CodecError};
|
||||
pub use error::Error;
|
||||
pub use export::{ExportFormat, ExportOptions};
|
||||
pub use io::ReadError;
|
||||
pub use layout::{GddV1Layout, Layout};
|
||||
pub use manifest::{Manifest, PayloadCodecs};
|
||||
pub use resource::ResourceProxy;
|
||||
pub use session_state::SessionState;
|
||||
|
||||
/// The default [`Layout`], so callers write `GddV1` for the common `Gdd<GddV1Layout>` handle.
|
||||
pub type GddV1 = Gdd<GddV1Layout>;
|
||||
|
||||
/// The manifest is always JSON: it is the bootstrap file, read before any other payload's codec is
|
||||
/// known, so its own codec cannot itself be configurable.
|
||||
pub const MANIFEST_CODEC: Codec = Codec::Json;
|
||||
|
||||
/// Working-copy codecs. The working copy lives in appdata, not under VCS — these defaults
|
||||
/// optimize for size and write cost. MessagePack is self-describing, so it round-trips the
|
||||
/// type-erased `serde_json::Value` bodies that resource and attribute deltas carry (a non-self-
|
||||
/// describing format like postcard cannot). JSON/JSONL is opt-in via `ExportFormat::Folder` for
|
||||
/// users who want a diffable on-disk representation. Recorded in the manifest at create time and
|
||||
/// read back on open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
|
||||
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
|
||||
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::MessagePack;
|
||||
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::MessagePackFrames;
|
||||
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::MessagePackFrames;
|
||||
|
||||
/// Editor-facing handle. Owns the `Session` and the working-copy container; mutations are mirrored
|
||||
/// to disk continuously (every retirement appends to the history file and re-snapshots the registry).
|
||||
///
|
||||
/// The per-edit persist path (`commit_from_runtime`, `apply_hot_op`, `retire`) is synchronous and
|
||||
/// read-free: the manifest is cached in memory (so payload codecs need no disk read), and writes go
|
||||
/// through the container's sync write surface. Only `open` / `create` / `export` are async, since they
|
||||
/// read.
|
||||
/// `Clone` shares the working-copy container (`Arc<AnyContainer>`) so a cloned handle reads and writes
|
||||
/// the *same* on-disk/OPFS working copy — including any writes still queued on the OPFS backend. The
|
||||
/// `Session` is cloned (a snapshot copy); the container is shared.
|
||||
#[derive(Clone)]
|
||||
pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
pub(crate) session: Session,
|
||||
pub(crate) working: Arc<AnyContainer>,
|
||||
pub(crate) layout: L,
|
||||
/// In-memory copy of the manifest, kept authoritative since `Gdd` is its sole writer. Holds the
|
||||
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
|
||||
/// and synchronous.
|
||||
pub(crate) manifest: Manifest,
|
||||
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
|
||||
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
|
||||
pub(crate) view_settings: std::collections::BTreeMap<String, serde_json::Value>,
|
||||
/// Per-network view settings (node-graph nav + previewing), keyed by stable [`NetworkId`]. Same per-peer
|
||||
/// `session.json` treatment as [`view_settings`](Self::view_settings), but scoped per network.
|
||||
pub(crate) network_view_settings: std::collections::BTreeMap<graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
|
||||
}
|
||||
|
||||
/// Native folder-backed convenience constructors. On wasm the editor builds an OPFS-backed
|
||||
/// `AnyContainer` itself and uses [`Gdd::open_in`] / [`Gdd::create_in`] directly.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl<L: Layout + Default> Gdd<L> {
|
||||
/// Open an existing working copy at `path`. Validates the manifest, materializes the session
|
||||
/// from `registry.bin` (fast path) or by replaying `history.jsonl` (slow path), then applies
|
||||
/// the persisted hot log on top.
|
||||
pub async fn open(path: &Path) -> Result<Self, Error> {
|
||||
let working = AnyContainer::Folder(FolderBackend::open(path)?);
|
||||
let layout = L::default();
|
||||
Self::open_in(working, layout).await
|
||||
}
|
||||
|
||||
/// Create a fresh, empty working copy at `path` bound to `peer`. Writes a default manifest
|
||||
/// and session state; the caller fills in editor metadata via [`Gdd::update_manifest`].
|
||||
pub async fn create(path: &Path, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let working = AnyContainer::Folder(FolderBackend::create(path)?);
|
||||
let layout = L::default();
|
||||
Self::create_in(working, layout, peer, document_uuid, editor_version, stdlib_version).await
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Open a `.gdd` from archive bytes (xz or zip, auto-detected) by materializing it into `working`,
|
||||
/// then opening it as a working copy. The archive is deserialized into an in-memory staging backend
|
||||
/// (the archive reader is synchronous), then each entry is written into `working` via the sync
|
||||
/// `write_non_blocking` surface — durable on folder/memory, eagerly enqueued on OPFS. `working` is
|
||||
/// expected to be a fresh per-document container; entries with colliding paths are overwritten.
|
||||
#[cfg(any(feature = "zip", feature = "xz"))]
|
||||
pub async fn open_from_archive(bytes: &[u8], mut working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||
document_container::archive::open_auto(bytes, &mut working)?;
|
||||
|
||||
Self::open_in(working, layout).await
|
||||
}
|
||||
|
||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::WrongFormat`] / [`Error::UnsupportedVersion`] if the manifest fails validation, plus
|
||||
/// the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||
let manifest: Manifest = io::read_single(&working, layout.manifest_basename(), MANIFEST_CODEC).await?;
|
||||
validate_manifest(&manifest)?;
|
||||
let codecs = manifest.codecs;
|
||||
|
||||
let session_state: SessionState = match io::exists(&working, layout.session_basename(), codecs.session).await {
|
||||
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
|
||||
false => SessionState::default(),
|
||||
};
|
||||
|
||||
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
|
||||
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
|
||||
|
||||
let peer = session_state.peer_id;
|
||||
let mut session = match (has_registry, has_history) {
|
||||
(true, true) => {
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
let history = load_history(&working, &layout, codecs.history).await?;
|
||||
Session::load(peer, registry, history, session_state.head_rev, session_state.redo_stack, session_state.next_node_counter)
|
||||
}
|
||||
(true, false) => {
|
||||
// Registry-only export: synthesize a history that reproduces this state.
|
||||
let registry: Registry = io::read_single(&working, layout.registry_basename(), codecs.registry).await?;
|
||||
Session::bootstrap_from_registry(peer, registry)?
|
||||
}
|
||||
(false, _) => Session::replay_from_history(peer, load_history(&working, &layout, codecs.history).await?, session_state.next_node_counter)?,
|
||||
};
|
||||
|
||||
// Restore the published frontier (silent/published undo boundary) regardless of which load arm ran.
|
||||
if let Some(rev) = session_state.last_broadcast_rev {
|
||||
session.publish_up_to(rev);
|
||||
}
|
||||
|
||||
replay_hot_log(&working, &layout, codecs.hot_log, &mut session).await?;
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
working: Arc::new(working),
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: session_state.view_settings,
|
||||
network_view_settings: session_state.network_view_settings,
|
||||
})
|
||||
}
|
||||
|
||||
/// Backend-agnostic create. Records the working-copy default codecs (see `DEFAULT_*_CODEC`) in
|
||||
/// the manifest and writes each payload with its recorded codec.
|
||||
pub async fn create_in(working: AnyContainer, layout: L, peer: PeerId, document_uuid: u64, editor_version: String, stdlib_version: String) -> Result<Self, Error> {
|
||||
let manifest = Manifest::new(document_uuid, editor_version, stdlib_version);
|
||||
let codecs = manifest.codecs;
|
||||
io::write_single(&working, layout.manifest_basename(), MANIFEST_CODEC, &manifest)?;
|
||||
let session_state = SessionState { peer_id: peer, ..Default::default() };
|
||||
io::write_single(&working, layout.session_basename(), codecs.session, &session_state)?;
|
||||
|
||||
let session = Session::with_peer(peer);
|
||||
io::write_single(&working, layout.registry_basename(), codecs.registry, session.registry())?;
|
||||
|
||||
Ok(Self {
|
||||
session,
|
||||
working: Arc::new(working),
|
||||
layout,
|
||||
manifest,
|
||||
view_settings: std::collections::BTreeMap::new(),
|
||||
network_view_settings: std::collections::BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_manifest(manifest: &Manifest) -> Result<(), Error> {
|
||||
if manifest.format != manifest::FORMAT_MAGIC {
|
||||
return Err(Error::WrongFormat {
|
||||
found: manifest.format.clone(),
|
||||
expected: manifest::FORMAT_MAGIC,
|
||||
});
|
||||
}
|
||||
if manifest.format_version > manifest::SUPPORTED_FORMAT_VERSION {
|
||||
return Err(Error::UnsupportedVersion {
|
||||
found: manifest.format_version,
|
||||
max_supported: manifest::SUPPORTED_FORMAT_VERSION,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn load_history<L: Layout>(working: &AnyContainer, layout: &L, codec: Codec) -> Result<Vec<Delta>, Error> {
|
||||
if !io::exists(working, layout.history_basename(), codec).await {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
Ok(io::iter::<Delta>(working, layout.history_basename(), codec).await?)
|
||||
}
|
||||
|
||||
async fn replay_hot_log<L: Layout>(working: &AnyContainer, layout: &L, codec: Codec, session: &mut Session) -> Result<(), Error> {
|
||||
if !io::exists(working, layout.hot_log_basename(), codec).await {
|
||||
return Ok(());
|
||||
}
|
||||
for hot_op in io::iter::<HotOp>(working, layout.hot_log_basename(), codec).await? {
|
||||
session.replay_hot_op(hot_op)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub fn session(&self) -> &Session {
|
||||
&self.session
|
||||
}
|
||||
|
||||
pub fn can_undo(&self) -> bool {
|
||||
self.session.can_undo()
|
||||
}
|
||||
|
||||
pub fn can_redo(&self) -> bool {
|
||||
self.session.can_redo()
|
||||
}
|
||||
|
||||
pub fn registry(&self) -> &Registry {
|
||||
self.session.registry()
|
||||
}
|
||||
|
||||
/// The in-memory manifest. `Gdd` is its sole writer, so this is authoritative without re-reading
|
||||
/// disk.
|
||||
pub fn manifest(&self) -> &Manifest {
|
||||
&self.manifest
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &L {
|
||||
&self.layout
|
||||
}
|
||||
|
||||
/// The per-peer view settings read from `session.json` (PTZ, rulers, overlays, snapping, collapse).
|
||||
/// Opaque `ui::doc::*` blobs; the editor decodes them. Empty for a fresh document.
|
||||
pub fn view_settings(&self) -> &std::collections::BTreeMap<String, serde_json::Value> {
|
||||
&self.view_settings
|
||||
}
|
||||
|
||||
/// The per-network view settings read from `session.json` (node-graph nav + previewing), keyed by
|
||||
/// [`NetworkId`](graph_storage::NetworkId). Opaque `ui::nav::*` / `ui::previewing` blobs the editor decodes.
|
||||
pub fn network_view_settings(&self) -> &std::collections::BTreeMap<graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>> {
|
||||
&self.network_view_settings
|
||||
}
|
||||
|
||||
/// Resolve each runtime `network_path` to its stable [`NetworkId`](graph_storage::NetworkId), so the
|
||||
/// editor can key per-network, per-peer view state by a stable id. See [`Session::network_ids`].
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn network_ids<M: NodeMetadataSource>(
|
||||
&self,
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
) -> Result<std::collections::HashMap<Vec<core_types::uuid::NodeId>, graph_storage::NetworkId>, CommitError> {
|
||||
self.session.network_ids(network, metadata)
|
||||
}
|
||||
|
||||
/// Every resource hash referenced by the current registry or anywhere in history, so resource GC keeps
|
||||
/// redoable/re-undoable interactions' resources (notably proto-node declaration bytes) alive even when an
|
||||
/// undo has dropped them from the current registry.
|
||||
pub fn all_referenced_resource_hashes(&self) -> std::collections::HashSet<ResourceHash> {
|
||||
self.session.all_referenced_resource_hashes()
|
||||
}
|
||||
|
||||
/// Drop the session and return the working-copy container + layout.
|
||||
/// Intended for test code that needs to reopen against the same container; panics if the container
|
||||
/// is still shared by a `Gdd` clone (tests don't clone before calling this).
|
||||
pub fn into_storage(self) -> (AnyContainer, L) {
|
||||
let working = Arc::try_unwrap(self.working).unwrap_or_else(|_| panic!("into_storage called while the working-copy container is still shared by a Gdd clone"));
|
||||
(working, self.layout)
|
||||
}
|
||||
|
||||
/// Resolve the proto-node declarations referenced by the registry into a [`graph_storage::Declarations`]
|
||||
/// map, loading each `ProtoNode`'s bytes from `byte_store` (the global cache in the editor, the
|
||||
/// working-copy container for standalone). Only resources referenced by `Implementation::ProtoNode`
|
||||
/// are visited, so image/font resources are skipped. Cold-path (open / `to_runtime`); async
|
||||
/// because resource loads are.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub async fn declarations(&self, byte_store: &dyn LoadResource) -> graph_storage::Declarations {
|
||||
use graph_storage::Implementation;
|
||||
|
||||
let registry = self.session.registry();
|
||||
let mut declarations = graph_storage::Declarations::new();
|
||||
|
||||
for node in registry.node_instances.values() {
|
||||
let Implementation::ProtoNode(id) = node.implementation() else { continue };
|
||||
if declarations.contains_key(id) {
|
||||
continue;
|
||||
}
|
||||
let Some(hash) = registry.resources.get(id).and_then(|entry| entry.hash) else {
|
||||
log::error!("Declaration resource {id} has no resolved hash; cannot load ProtoNode");
|
||||
continue;
|
||||
};
|
||||
let Some(resource) = byte_store.load(hash).await else {
|
||||
log::error!("Declaration bytes for {id} (hash {hash}) missing from byte store");
|
||||
continue;
|
||||
};
|
||||
match graph_storage::decode_declaration(resource.as_ref()) {
|
||||
Ok(proto) => {
|
||||
declarations.insert(*id, proto);
|
||||
}
|
||||
Err(error) => log::error!("Failed to deserialize ProtoNode for {id}: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
declarations
|
||||
}
|
||||
|
||||
/// Store the legacy `.graphite` document bytes verbatim inside the working copy (dual-write soak).
|
||||
/// Synchronous (hot-path safe via `write_non_blocking`): called at the autosave boundary alongside
|
||||
/// the registry snapshot. The bytes are opaque to `Gdd` — it never deserializes them.
|
||||
// TODO: Add feature gate for legacy embedding
|
||||
pub fn store_legacy_document(&self, bytes: &[u8]) -> Result<(), ContainerError> {
|
||||
self.working.write_non_blocking(self.layout.legacy_path(), bytes)
|
||||
}
|
||||
|
||||
/// Read back the embedded legacy `.graphite` document, if present. The compare-on-open oracle and
|
||||
/// the recovery fallback both go through here. `None` when no legacy blob was ever written.
|
||||
pub async fn read_legacy_document(&self) -> Option<ByteHolder> {
|
||||
self.working.read(self.layout.legacy_path()).await.ok()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
//! Bootstrap file for a `.gdd` document. Always JSON regardless of payload codec choice.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Codec;
|
||||
use crate::{DEFAULT_HISTORY_CODEC, DEFAULT_HOT_LOG_CODEC, DEFAULT_REGISTRY_CODEC, DEFAULT_SESSION_CODEC};
|
||||
|
||||
/// Magic string carried in [`Manifest::format`] to identify a `.gdd` document.
|
||||
pub const FORMAT_MAGIC: &str = "gdd";
|
||||
|
||||
/// Maximum manifest version this build can open. Bumped when manifest layout changes
|
||||
/// in a way that older builds can't safely read.
|
||||
pub const SUPPORTED_FORMAT_VERSION: u32 = 1;
|
||||
|
||||
/// The on-disk codec for each working-copy payload, recorded so reads/writes never have to probe
|
||||
/// the filesystem to discover it. The manifest itself is excluded: it is always JSON, since it must
|
||||
/// be parsed before any other codec is known.
|
||||
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
|
||||
pub struct PayloadCodecs {
|
||||
pub registry: Codec,
|
||||
pub history: Codec,
|
||||
pub hot_log: Codec,
|
||||
pub session: Codec,
|
||||
}
|
||||
|
||||
impl Default for PayloadCodecs {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
registry: DEFAULT_REGISTRY_CODEC,
|
||||
history: DEFAULT_HISTORY_CODEC,
|
||||
hot_log: DEFAULT_HOT_LOG_CODEC,
|
||||
session: DEFAULT_SESSION_CODEC,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct Manifest {
|
||||
pub format: String,
|
||||
|
||||
pub format_version: u32,
|
||||
pub editor_version: String,
|
||||
pub stdlib_version: String,
|
||||
|
||||
pub document_id: u64,
|
||||
/// Codec used for each non-manifest payload on disk. Authoritative — never inferred from which
|
||||
/// file extension is present.
|
||||
#[serde(default)]
|
||||
pub codecs: PayloadCodecs,
|
||||
}
|
||||
|
||||
impl Manifest {
|
||||
pub fn new(document_id: u64, editor_version: String, stdlib_version: String) -> Self {
|
||||
Self {
|
||||
format: FORMAT_MAGIC.to_string(),
|
||||
format_version: SUPPORTED_FORMAT_VERSION,
|
||||
document_id,
|
||||
editor_version,
|
||||
stdlib_version,
|
||||
codecs: PayloadCodecs::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! The per-edit persist path on the [`Gdd`] handle: stage/retire/commit, hot-log and history
|
||||
//! append, registry snapshots, session-state and manifest writes, plus view-settings setters.
|
||||
//! Synchronous and read-free (the manifest is cached on the handle); the container's `*_non_blocking`
|
||||
//! surface absorbs durability.
|
||||
|
||||
use document_container::AsyncContainer;
|
||||
#[cfg(feature = "conversion")]
|
||||
use graph_storage::NodeMetadataSource;
|
||||
use graph_storage::{HotOp, Rev, TimeStamp};
|
||||
#[cfg(feature = "conversion")]
|
||||
use graphene_resource::ResourceStorage;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
use crate::manifest::Manifest;
|
||||
use crate::session_state::SessionState;
|
||||
use crate::{Gdd, MANIFEST_CODEC, io};
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
|
||||
/// the undone `Rev`. The working registry is rewound in place by the reverse delta, so re-snapshot it
|
||||
/// (alongside `head`) or a reopen would read a `registry.bin` inconsistent with the persisted cursor.
|
||||
pub fn undo(&mut self) -> Result<Rev, Error> {
|
||||
let rev = self.session.undo()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry.
|
||||
pub fn redo(&mut self) -> Result<Rev, Error> {
|
||||
let rev = self.session.redo()?;
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
Ok(rev)
|
||||
}
|
||||
|
||||
/// Edit the cached manifest and persist it. Always JSON, synchronous.
|
||||
pub fn update_manifest(&mut self, edit: impl FnOnce(&mut Manifest)) -> Result<(), Error> {
|
||||
edit(&mut self.manifest);
|
||||
io::write_single(&self.working, self.layout.manifest_basename(), MANIFEST_CODEC, &self.manifest)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stage a runtime snapshot as hot ops without retiring: diff the runtime against the working
|
||||
/// registry, append the hot frames (so a crash recovers the work), and persist proto-node
|
||||
/// declaration bytes. The working registry reflects the edit immediately, but nothing enters durable
|
||||
/// retired history until [`retire_pending_interaction`](Self::retire_pending_interaction). Staging on
|
||||
/// every edit while retiring only at interaction boundaries lets several edits coalesce into one retired
|
||||
/// interaction.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::Commit`] if the runtime diff is rejected by the session. On an [`Error::Container`] /
|
||||
/// [`Error::Codec`] from persisting the hot frames, the session has already advanced past what the
|
||||
/// working copy reflects, so the caller should treat the document as needing re-persist.
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn stage_runtime_snapshot<M: NodeMetadataSource>(
|
||||
&mut self,
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<(), Error> {
|
||||
let (hot_ops, declaration_bytes) = self.session.stage_from_runtime(network, metadata, resources)?;
|
||||
|
||||
for hot_op in &hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
|
||||
// Persist proto-node declaration content to the byte store (the global cache in the editor,
|
||||
// the working-copy container for standalone export). Content-addressed, so re-storing
|
||||
// identical bytes on every commit is an idempotent no-op.
|
||||
for bytes in declaration_bytes.values() {
|
||||
byte_store.store(bytes);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retire every pending hot op into durable history as a single interaction (marking the batch's last
|
||||
/// delta as the interaction boundary), then re-snapshot the registry. One interaction is one undo unit,
|
||||
/// so the caller invokes this at each undo-step boundary and before any undo/redo. A no-op when there
|
||||
/// are no pending hot ops.
|
||||
pub fn retire_pending_interaction(&mut self) -> Result<Vec<Rev>, Error> {
|
||||
let Some(up_to) = self.session.hot_log().iter().map(|hot_op| hot_op.timestamp).max() else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
self.retire_inner(up_to, true)
|
||||
}
|
||||
|
||||
/// Commit a runtime snapshot as one complete interaction: stage it, then immediately retire it into
|
||||
/// durable history. Convenience for callers that produce a whole interaction atomically (tests, and any
|
||||
/// one-shot commit). Equivalent to [`stage_runtime_snapshot`](Self::stage_runtime_snapshot) followed
|
||||
/// by [`retire_pending_interaction`](Self::retire_pending_interaction).
|
||||
#[cfg(feature = "conversion")]
|
||||
pub fn commit_from_runtime<M: NodeMetadataSource>(
|
||||
&mut self,
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
metadata: &M,
|
||||
resources: &graphene_resource::ResourceRegistry,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
) -> Result<Vec<Rev>, Error> {
|
||||
self.stage_runtime_snapshot(network, metadata, resources, byte_store)?;
|
||||
self.retire_pending_interaction()
|
||||
}
|
||||
|
||||
/// Apply a hot op from the broadcast stream, appending one frame to the hot log.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns [`Error::Crdt`] if the op is rejected by the session, or an [`Error::Container`] /
|
||||
/// [`Error::Codec`] if persisting the hot frame fails. On a persist failure the session has already
|
||||
/// advanced past what the working copy reflects, so the caller should treat the document as needing
|
||||
/// re-persist (mirrors [`stage_runtime_snapshot`](Self::stage_runtime_snapshot)).
|
||||
pub fn apply_hot_op(&mut self, op: HotOp) -> Result<(), Error> {
|
||||
self.session.apply_hot_op(op.clone())?;
|
||||
self.append_hot_frame(&op)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Persist freshly-staged hot ops and immediately retire them into durable history. Appends each
|
||||
/// hot frame (so a crash before retirement still recovers the work), then retires up to the last
|
||||
/// staged timestamp, which drains exactly these ops and re-snapshots the registry. Returns the
|
||||
/// retired `Rev`s. A no-op when nothing was staged.
|
||||
pub(crate) fn append_and_retire(&mut self, hot_ops: &[HotOp], interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
let Some(last) = hot_ops.last() else { return Ok(Vec::new()) };
|
||||
|
||||
for hot_op in hot_ops {
|
||||
self.append_hot_frame(hot_op)?;
|
||||
}
|
||||
|
||||
self.retire_inner(last.timestamp, interaction_end)
|
||||
}
|
||||
|
||||
/// Encode the history deltas identified by `revs` and append them to the history file. `revs` comes
|
||||
/// from `Session::retire` in append order, which is a valid replay order, so a direct per-rev lookup
|
||||
/// preserves replay order without scanning the whole history.
|
||||
fn append_history_deltas(&mut self, revs: &[Rev]) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for &rev in revs {
|
||||
let Some(delta) = self.session.delta(rev) else {
|
||||
log::error!("Retired rev {rev:?} missing from history; skipping its history frame");
|
||||
continue;
|
||||
};
|
||||
self.manifest.codecs.history.append(&mut buffer, delta)?;
|
||||
}
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.history_basename(), self.manifest.codecs.history), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Set a local annotation (e.g. a commit message) on an existing retired delta and re-persist it.
|
||||
/// Unlike the per-interaction marker written inline at retire, this targets an already-written delta, so
|
||||
/// the whole history file is rewritten in topological order. O(history) — fine for occasional user
|
||||
/// labeling, not for per-interaction marking (which uses the inline path). No-op if `rev` is unknown.
|
||||
pub fn annotate_delta(&mut self, rev: Rev, key: &str, value: serde_json::Value) -> Result<(), Error> {
|
||||
if self.session.annotate_delta(rev, key, value) {
|
||||
self.rewrite_history()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
|
||||
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
|
||||
fn rewrite_history(&mut self) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
for delta in self.session.history() {
|
||||
self.manifest.codecs.history.append(&mut buffer, delta)?;
|
||||
}
|
||||
self.working.write_non_blocking(&io::path_for(self.layout.history_basename(), self.manifest.codecs.history), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_session_state(&mut self) -> Result<(), Error> {
|
||||
let state = SessionState {
|
||||
peer_id: self.session.peer(),
|
||||
head_rev: self.session.head_rev(),
|
||||
last_broadcast_rev: self.session.last_broadcast_rev(),
|
||||
redo_stack: self.session.redo_stack().to_vec(),
|
||||
next_node_counter: self.session.next_node_counter(),
|
||||
view_settings: self.view_settings.clone(),
|
||||
network_view_settings: self.network_view_settings.clone(),
|
||||
};
|
||||
io::write_single(&self.working, self.layout.session_basename(), self.manifest.codecs.session, &state)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Re-snapshot the materialized working registry to `registry.bin`. `Session::load` trusts the stored
|
||||
/// registry to match the persisted `head`, so any cursor move (undo/redo) that rewinds the working
|
||||
/// registry without retiring must re-persist it or a reopen would read a registry inconsistent with
|
||||
/// `head`. Synchronous and hot-path-safe (`write_non_blocking`).
|
||||
fn persist_registry_snapshot(&mut self) -> Result<(), Error> {
|
||||
io::write_single(&self.working, self.layout.registry_basename(), self.manifest.codecs.registry, self.session.registry())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace the per-peer view settings and persist them to `session.json`. Called by the editor when
|
||||
/// the viewport or a document-level toggle changes; never enters the registry, history, or CRDT.
|
||||
pub fn set_view_settings(&mut self, view_settings: std::collections::BTreeMap<String, serde_json::Value>) -> Result<(), Error> {
|
||||
self.view_settings = view_settings;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Advance the published frontier to `rev` and persist it to `session.json`, so the silent/published
|
||||
/// undo boundary survives a reopen. Called by the (future) broadcast transport as commits are shared.
|
||||
pub fn publish_up_to(&mut self, rev: graph_storage::Rev) -> Result<(), Error> {
|
||||
self.session.publish_up_to(rev);
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
/// Replace the per-network view settings and persist them to `session.json`. Per-peer, per-network; never
|
||||
/// enters the registry, history, or CRDT.
|
||||
pub fn set_network_view_settings(
|
||||
&mut self,
|
||||
network_view_settings: std::collections::BTreeMap<graph_storage::NetworkId, std::collections::BTreeMap<String, serde_json::Value>>,
|
||||
) -> Result<(), Error> {
|
||||
self.network_view_settings = network_view_settings;
|
||||
self.persist_session_state()
|
||||
}
|
||||
|
||||
fn append_hot_frame(&mut self, op: &HotOp) -> Result<(), Error> {
|
||||
let mut buffer = Vec::new();
|
||||
self.manifest.codecs.hot_log.append(&mut buffer, op)?;
|
||||
self.working.append_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &buffer)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Working-copy checkpoint: promote hot ops with timestamp `≤ up_to` into retired deltas,
|
||||
/// append them to the history file, rewrite the hot log with remaining (unretired) ops, and
|
||||
/// re-snapshot the registry. Synchronous.
|
||||
pub fn retire(&mut self, up_to: TimeStamp) -> Result<Vec<Rev>, Error> {
|
||||
self.retire_inner(up_to, false)
|
||||
}
|
||||
|
||||
/// `interaction_end`: mark the batch's last delta as an interaction boundary (one undo unit) before its
|
||||
/// history frame is written, so the marker persists on reopen without a later frame rewrite.
|
||||
fn retire_inner(&mut self, up_to: TimeStamp, interaction_end: bool) -> Result<Vec<Rev>, Error> {
|
||||
let new_revs = self.session.retire(up_to)?;
|
||||
|
||||
// Mark before `append_history_deltas` so the on-disk frame carries the boundary.
|
||||
if interaction_end && let Some(&last) = new_revs.last() {
|
||||
self.session.mark_interaction_end(last);
|
||||
}
|
||||
|
||||
if !new_revs.is_empty() {
|
||||
self.append_history_deltas(&new_revs)?;
|
||||
}
|
||||
|
||||
// Rewrite hot log with whatever survived retirement.
|
||||
let mut hot_buffer = Vec::new();
|
||||
for hot_op in self.session.hot_log() {
|
||||
self.manifest.codecs.hot_log.append(&mut hot_buffer, hot_op)?;
|
||||
}
|
||||
self.working
|
||||
.write_non_blocking(&io::path_for(self.layout.hot_log_basename(), self.manifest.codecs.hot_log), &hot_buffer)?;
|
||||
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
|
||||
Ok(new_revs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Resource I/O on the [`Gdd`] handle: the content-addressed byte store that backs raster images,
|
||||
//! fonts, embedded WASM, and proto-node declarations. Registration goes through the session as an
|
||||
//! `AddResource` delta; the bytes live in the working copy's `resources/<hash>` directory.
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use document_container::{AnyContainer, AsyncContainer, ByteHolder, ContainerError};
|
||||
use graphene_resource::ResourceFuture;
|
||||
use graphene_resource::{LoadResource, Resource, ResourceHash, ResourceStorage};
|
||||
|
||||
use crate::Gdd;
|
||||
use crate::error::Error;
|
||||
use crate::layout::Layout;
|
||||
|
||||
impl<L: Layout> Gdd<L> {
|
||||
pub async fn read_resource(&self, hash: &ResourceHash) -> Result<ByteHolder, ContainerError> {
|
||||
self.working.read(&self.layout.resource_path(hash)).await
|
||||
}
|
||||
|
||||
/// Register a resource under `id` and store its bytes. Commits an `AddResource` delta (a single
|
||||
/// `DataSource::Embedded` source resolved to the content hash) through the session so the registry
|
||||
/// records the resource and the entry replicates, then writes the bytes into the working copy's
|
||||
/// content-addressed store. The caller owns `id` allocation.
|
||||
pub fn add_resource(&mut self, id: graph_storage::ResourceId, bytes: &[u8]) -> Result<(), Error> {
|
||||
let hash = ResourceHash::from(bytes);
|
||||
|
||||
self.working.write_non_blocking(&self.layout.resource_path(&hash), bytes)?;
|
||||
|
||||
let hot_ops = self.session.stage_embedded_resource(id, hash)?;
|
||||
self.append_and_retire(&hot_ops, false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Like [`add_resource`](Self::add_resource) but copies the bytes from a filesystem `src` rather
|
||||
/// than buffering them. Folder backends use `fs::copy` (CoW on supported filesystems); other
|
||||
/// backends fall back to read-then-write. Native-only: there is no filesystem source path on wasm.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub fn add_resource_from_path(&mut self, id: graph_storage::ResourceId, hash: ResourceHash, src: &Path) -> Result<(), Error> {
|
||||
let dest_path = self.layout.resource_path(&hash);
|
||||
if let AnyContainer::Folder(folder) = self.working.as_ref() {
|
||||
let full = folder.root().join(&dest_path);
|
||||
if let Some(parent) = full.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(ContainerError::Io)?;
|
||||
}
|
||||
std::fs::copy(src, &full).map_err(ContainerError::Io)?;
|
||||
} else {
|
||||
let bytes = std::fs::read(src).map_err(ContainerError::Io)?;
|
||||
// The folder fast path trusts the caller's hash to avoid reading the file; here we've read
|
||||
// the bytes anyway, so verify the hash matches and flag a content-addressing bug in debug.
|
||||
debug_assert_eq!(hash, ResourceHash::from(bytes.as_slice()), "add_resource_from_path hash does not match the file at {src:?}");
|
||||
self.working.write_non_blocking(&dest_path, &bytes)?;
|
||||
}
|
||||
|
||||
let hot_ops = self.session.stage_embedded_resource(id, hash)?;
|
||||
self.append_and_retire(&hot_ops, false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn has_resource(&self, hash: &ResourceHash) -> bool {
|
||||
self.working.exists(&self.layout.resource_path(hash)).await
|
||||
}
|
||||
|
||||
pub fn remove_resource(&self, hash: &ResourceHash) -> Result<(), ContainerError> {
|
||||
self.working.remove_non_blocking(&self.layout.resource_path(hash))
|
||||
}
|
||||
|
||||
/// Enumerate every resource currently in the working copy. Paths that don't parse as a
|
||||
/// `ResourceHash` (foreign files dropped into the resources directory) are silently skipped.
|
||||
pub async fn resource_hashes(&self) -> Result<Vec<ResourceHash>, ContainerError> {
|
||||
let dir = self.layout.resources_dir();
|
||||
if !self.working.list_dirs("").await?.iter().any(|d| d == dir) {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let entries = self.working.list(dir).await?;
|
||||
let prefix = format!("{dir}/");
|
||||
let mut hashes = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
let Some(name) = entry.strip_prefix(&prefix) else { continue };
|
||||
if let Ok(hash) = name.parse::<ResourceHash>() {
|
||||
hashes.push(hash);
|
||||
}
|
||||
}
|
||||
Ok(hashes)
|
||||
}
|
||||
|
||||
pub fn resource_proxy(&self) -> ResourceProxy<L>
|
||||
where
|
||||
L: Clone,
|
||||
{
|
||||
ResourceProxy(self.working.clone(), self.layout.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let bytes = self.working.read(&self.layout.resource_path(&hash)).await.ok()?;
|
||||
Some(Resource::new(bytes))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(Arc<AnyContainer>, T);
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
let bytes = self.0.read(&self.1.resource_path(&hash)).await.ok()?;
|
||||
Some(Resource::new(bytes))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> ResourceStorage for Gdd<L> {
|
||||
fn store(&self, data: &[u8]) -> ResourceHash {
|
||||
let hash = ResourceHash::from(data);
|
||||
if let Err(error) = self.working.write_non_blocking(&self.layout.resource_path(&hash), data) {
|
||||
log::error!("ResourceStorage::store failed for {hash}: {error}");
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
fn contains(&self, hash: &ResourceHash) -> bool {
|
||||
self.working.exists_non_blocking(&self.layout.resource_path(hash))
|
||||
}
|
||||
|
||||
fn garbage_collect(&self, used: &[ResourceHash]) {
|
||||
// `garbage_collect` is synchronous but listing resources is async, so the native path blocks on
|
||||
// it. That's unavailable on wasm (single-threaded; `block_on` would deadlock). The editor never
|
||||
// uses `Gdd` as the runtime `ResourceStorage` on wasm (it GCs the app-global cache instead), so
|
||||
// this is an unreachable configuration there rather than a missing feature.
|
||||
#[cfg(target_family = "wasm")]
|
||||
{
|
||||
let _ = used;
|
||||
log::error!("ResourceStorage::garbage_collect is not supported for Gdd on wasm");
|
||||
}
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
{
|
||||
let kept: std::collections::HashSet<&ResourceHash> = used.iter().collect();
|
||||
let hashes = match futures::executor::block_on(self.resource_hashes()) {
|
||||
Ok(hashes) => hashes,
|
||||
Err(error) => {
|
||||
log::error!("Failed to list resources during garbage_collect: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
for hash in hashes {
|
||||
if kept.contains(&hash) {
|
||||
continue;
|
||||
}
|
||||
if let Err(error) = self.working.remove_non_blocking(&self.layout.resource_path(&hash)) {
|
||||
log::error!("ResourceStorage::garbage_collect failed to remove {hash}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Persistent cursor state for the local peer. Separate from [`crate::Manifest`] because the
|
||||
//! manifest describes document identity (what this document *is*), while [`SessionState`]
|
||||
//! describes where the local peer's cursor sits inside it.
|
||||
//!
|
||||
//! Lives in `session.json`. Rewritten on retirement.
|
||||
|
||||
use graph_storage::{NetworkId, PeerId, Rev};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
|
||||
pub struct SessionState {
|
||||
/// This peer's identity for the document, stable per (device, document). Per-peer rather than
|
||||
/// document identity, so it lives with the cursor here, not in the manifest. Used for CRDT
|
||||
/// tiebreaking and minting peer-scoped IDs.
|
||||
#[serde(default)]
|
||||
pub peer_id: PeerId,
|
||||
/// Local-chain cursor. Points at the most recently applied retired delta, or `None` on an empty
|
||||
/// document (no commits yet).
|
||||
#[serde(default)]
|
||||
pub head_rev: Option<Rev>,
|
||||
/// Published frontier: the latest retired commit broadcast to a peer. Commits after it are silently
|
||||
/// rewritable on undo; commits at or before it are published. `None` until broadcast transport lands.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_broadcast_rev: Option<Rev>,
|
||||
/// Revs the user has undone past, so redo survives a reopen. (The legacy `VecDeque` redo history
|
||||
/// is not persisted, so within the shadow phase this is strictly more capable than the live editor.)
|
||||
#[serde(default)]
|
||||
pub redo_stack: Vec<Rev>,
|
||||
/// Shared-monotonic counter feeding `Document::next_node_id`. Persisted so reopens don't
|
||||
/// collide on minted IDs.
|
||||
#[serde(default)]
|
||||
pub next_node_counter: u64,
|
||||
/// Per-peer view settings (PTZ, rulers, overlays, snapping, panel collapse). Local to the viewer,
|
||||
/// so kept out of the CRDT/history. Editor owns the keys/values (opaque `ui::doc::*` blobs).
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub view_settings: BTreeMap<String, serde_json::Value>,
|
||||
/// Per-network view settings (node-graph nav + previewing), keyed by the stable storage [`NetworkId`].
|
||||
/// Per-peer like [`view_settings`](Self::view_settings); opaque `ui::nav::*` / `ui::previewing` blobs.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub network_view_settings: BTreeMap<NetworkId, BTreeMap<String, serde_json::Value>>,
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
// Exercises the runtime-conversion bridge and the zip archive round-trip, so it only compiles with
|
||||
// both features. A minimal-dependency build (e.g. `--no-default-features`) skips it entirely.
|
||||
#![cfg(all(feature = "conversion", feature = "zip"))]
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{Codec, Error, GddV1, GddV1Layout, Layout, Manifest, io, manifest};
|
||||
use graph_storage::{HotOp, Network, NetworkId, PeerId, ROOT_NETWORK, RegistryDelta, TimeStamp};
|
||||
|
||||
fn empty_container() -> AnyContainer {
|
||||
AnyContainer::Memory(MemoryBackend::new())
|
||||
}
|
||||
|
||||
/// A resource byte store for export calls. Empty unless a test pre-populates it; only consulted when
|
||||
/// `embed_all_resources` is set.
|
||||
fn empty_byte_store() -> graph_craft::application_io::resource::HashMapResourceStorage {
|
||||
graph_craft::application_io::resource::HashMapResourceStorage::new()
|
||||
}
|
||||
|
||||
/// A one-node network referencing `id` via a `TaggedValue::Resource` input. Conversion only snapshots
|
||||
/// resources the network references, so a resource needs a referencing node to survive into storage.
|
||||
fn network_referencing_resource(id: graphene_resource::ResourceId) -> graph_craft::document::NodeNetwork {
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
|
||||
NodeNetwork {
|
||||
nodes: [(
|
||||
NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Resource(id), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_in_round_trips_empty_document() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
|
||||
let created = match GddV1::create_in(container, GddV1Layout, PeerId(7), 0xFEED, "editor-x".into(), "stdlib-x".into()).await {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("create_in failed: {error:?}"),
|
||||
};
|
||||
|
||||
let (working, layout) = created.into_storage();
|
||||
let reopened = match GddV1::open_in(working, layout).await {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => panic!("open_in failed: {error:?}"),
|
||||
};
|
||||
|
||||
assert_eq!(reopened.session().peer(), PeerId(7));
|
||||
assert!(reopened.registry().node_instances.is_empty());
|
||||
assert!(reopened.registry().networks.is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_in_rejects_wrong_format_magic() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
let layout = GddV1Layout;
|
||||
|
||||
let mut bogus = Manifest::new(0xC0DE, "ed".into(), "std".into());
|
||||
bogus.format = "not-gdd".into();
|
||||
io::write_single(&container, layout.manifest_basename(), Codec::Json, &bogus).unwrap();
|
||||
|
||||
match GddV1::open_in(container, layout).await {
|
||||
Err(Error::WrongFormat { .. }) => {}
|
||||
Ok(_) => panic!("expected WrongFormat, got Ok"),
|
||||
Err(other) => panic!("expected WrongFormat, got {other:?}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifest_returns_what_create_in_wrote() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(13), 0xC0FFEE, "ed-1.2".into(), "std-0.7".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().peer(), PeerId(13));
|
||||
|
||||
let manifest = gdd.manifest();
|
||||
assert_eq!(manifest.document_id, 0xC0FFEE);
|
||||
assert_eq!(manifest.editor_version, "ed-1.2");
|
||||
assert_eq!(manifest.stdlib_version, "std-0.7");
|
||||
assert_eq!(manifest.format, manifest::FORMAT_MAGIC);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_manifest_changes_visible_after_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
gdd.update_manifest(|m| m.editor_version = "ed-NEW".into())
|
||||
.unwrap_or_else(|error| panic!("update_manifest failed: {error:?}"));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
let manifest = reopened.manifest();
|
||||
assert_eq!(manifest.editor_version, "ed-NEW");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_hot_op_persists_to_hot_log_and_survives_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// AddNetwork on the root network. Idempotent at apply, so two hot ops applied in sequence
|
||||
// produces one network in the registry.
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
assert!(gdd.registry().networks.contains_key(&ROOT_NETWORK), "hot op should have created the root network in memory");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
|
||||
assert!(reopened.registry().networks.contains_key(&ROOT_NETWORK), "hot op should have been replayed from the hot log on reopen");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retire_moves_eligible_hot_ops_to_history_and_keeps_rest() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Two hot ops: one with low timestamp (will retire), one with high (will stay).
|
||||
let early = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
};
|
||||
let late = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
id: NetworkId(42),
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 10, peer: PeerId(5) },
|
||||
};
|
||||
gdd.apply_hot_op(early).unwrap();
|
||||
gdd.apply_hot_op(late).unwrap();
|
||||
assert_eq!(gdd.session().hot_log().len(), 2);
|
||||
|
||||
// Retire only up to timestamp 5 → drains the early op, leaves the late one.
|
||||
let cutoff = TimeStamp { counter: 5, peer: PeerId(5) };
|
||||
gdd.retire(cutoff).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
|
||||
assert_eq!(gdd.session().hot_log().len(), 1, "late hot op should still be in hot log");
|
||||
assert_eq!(gdd.session().history().count(), 1, "early hot op should be in retired history");
|
||||
|
||||
// Reopen and confirm survival: hot log has the late op (replayed), history has the early op.
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
|
||||
assert!(reopened.registry().networks.contains_key(&ROOT_NETWORK), "retired op's effect should be in registry");
|
||||
assert!(reopened.registry().networks.contains_key(&NetworkId(42)), "hot op's effect should be replayed");
|
||||
assert_eq!(reopened.session().history().count(), 1);
|
||||
assert_eq!(reopened.session().hot_log().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
/// The published frontier (`last_broadcast_rev`, the silent/published undo boundary) persists in
|
||||
/// `session.json` and is restored on reopen.
|
||||
#[test]
|
||||
fn last_broadcast_rev_persists_across_reopen() {
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Retire one op so there is a real retired rev to mark as published.
|
||||
let op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
};
|
||||
gdd.apply_hot_op(op).unwrap();
|
||||
let retired = gdd.retire(TimeStamp { counter: 1, peer: PeerId(5) }).unwrap_or_else(|error| panic!("retire failed: {error:?}"));
|
||||
let published = *retired.last().expect("one retired rev");
|
||||
|
||||
assert_eq!(gdd.session().last_broadcast_rev(), None, "nothing is published before publish_up_to");
|
||||
gdd.publish_up_to(published).unwrap_or_else(|error| panic!("publish_up_to failed: {error:?}"));
|
||||
assert_eq!(gdd.session().last_broadcast_rev(), Some(published));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
assert_eq!(reopened.session().last_broadcast_rev(), Some(published), "published frontier should survive reopen");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_folder_round_trips_through_open() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xAB, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
|
||||
gdd.export(&dest, ExportFormat::Folder, ExportOptions::default(), &empty_byte_store(), None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
|
||||
// Payloads keep the working-copy codecs: registry is MessagePack (`.bin`), manifest is JSON.
|
||||
assert!(dest.join("registry.bin").exists());
|
||||
assert!(dest.join("manifest.json").exists());
|
||||
assert!(dest.join("session.json").exists());
|
||||
assert!(!dest.join("hot-log.bin").exists());
|
||||
assert!(!dest.join("hot-log.frames").exists());
|
||||
|
||||
// And the export is itself openable.
|
||||
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open failed: {error:?}"));
|
||||
assert_eq!(reopened.session().peer(), PeerId(3));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_zip_round_trips_via_deserialize() {
|
||||
use document_container::archive::{Archive, Zip};
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(4), 0xCD, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("doc.gdd.zip");
|
||||
|
||||
gdd.export(&dest, ExportFormat::Zip, ExportOptions::default(), &empty_byte_store(), None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
|
||||
let bytes = std::fs::read(&dest).unwrap();
|
||||
let mut restored = document_container::backends::memory::MemoryBackend::new();
|
||||
Zip::open(std::io::Cursor::new(&bytes), &mut restored).unwrap();
|
||||
use document_container::Container;
|
||||
assert!(restored.exists("manifest.json"));
|
||||
assert!(restored.exists("registry.bin"));
|
||||
assert!(restored.exists("session.json"));
|
||||
assert!(!restored.exists("hot-log.frames"));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_rejects_invalid_options() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xEF, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("nope");
|
||||
let options = ExportOptions {
|
||||
include_registry: false,
|
||||
include_history: false,
|
||||
embed_all_resources: false,
|
||||
};
|
||||
|
||||
match gdd.export(&dest, ExportFormat::Folder, options, &empty_byte_store(), None).await {
|
||||
Err(Error::InvalidExportOptions(_)) => {}
|
||||
Ok(_) => panic!("expected InvalidOptions, got Ok"),
|
||||
Err(other) => panic!("expected InvalidOptions, got {other:?}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_round_trip_add_read_remove() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(99), 0xCAFE, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"deadbeef cafe babe";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let id = ResourceId::new();
|
||||
|
||||
assert!(!gdd.has_resource(&hash).await);
|
||||
gdd.add_resource(id, payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
assert!(gdd.has_resource(&hash).await);
|
||||
|
||||
let read_back = gdd.read_resource(&hash).await.unwrap();
|
||||
assert_eq!(read_back.as_slice(), payload);
|
||||
|
||||
// The registry records the resource (entry keyed by id, resolved to the content hash).
|
||||
let entry = gdd.registry().resources.get(&id).expect("registry records the added resource");
|
||||
assert_eq!(entry.hash, Some(hash));
|
||||
|
||||
let hashes = gdd.resource_hashes().await.unwrap();
|
||||
assert_eq!(hashes, vec![hash]);
|
||||
|
||||
gdd.remove_resource(&hash).unwrap();
|
||||
assert!(!gdd.has_resource(&hash).await);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_survives_reopen() {
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(7), 0xC0DE, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"persistent bytes";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let id = ResourceId::new();
|
||||
gdd.add_resource(id, payload).unwrap();
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
|
||||
assert!(reopened.has_resource(&hash).await);
|
||||
assert_eq!(reopened.read_resource(&hash).await.unwrap().as_slice(), payload);
|
||||
|
||||
// The registry entry replicated through the history file and survives reopen.
|
||||
let entry = reopened.registry().resources.get(&id).expect("reopened registry records the resource");
|
||||
assert_eq!(entry.hash, Some(hash));
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_from_path_uses_fs_copy_on_folder_backend() {
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
// Need a folder-backed working copy to exercise the fs::copy path.
|
||||
let working_dir = tempfile::tempdir().unwrap();
|
||||
let working = AnyContainer::Folder(FolderBackend::create(working_dir.path()).unwrap());
|
||||
let mut gdd = GddV1::create_in(working, GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Source file outside the working copy.
|
||||
let payload = b"external resource bytes";
|
||||
let src_dir = tempfile::tempdir().unwrap();
|
||||
let src_path = src_dir.path().join("blob");
|
||||
std::fs::write(&src_path, payload).unwrap();
|
||||
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let id = ResourceId::new();
|
||||
gdd.add_resource_from_path(id, hash, &src_path)
|
||||
.unwrap_or_else(|error| panic!("add_resource_from_path failed: {error:?}"));
|
||||
|
||||
assert!(gdd.has_resource(&hash).await);
|
||||
assert_eq!(gdd.read_resource(&hash).await.unwrap().as_slice(), payload);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_carries_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(2), 0xBC, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"exported resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let id = ResourceId::new();
|
||||
gdd.add_resource(id, payload).unwrap();
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("export");
|
||||
gdd.export(&dest, ExportFormat::Folder, ExportOptions::default(), &empty_byte_store(), None).await.unwrap();
|
||||
|
||||
let resource_file = dest.join("resources").join(format!("{hash}"));
|
||||
assert!(resource_file.exists(), "exported resource file should exist at {resource_file:?}");
|
||||
assert_eq!(std::fs::read(&resource_file).unwrap(), payload);
|
||||
});
|
||||
}
|
||||
|
||||
/// `embed_all_resources` makes a link-only resource self-contained: the bytes (which live only in
|
||||
/// the byte store, not the working copy) are written into the export, the exported registry's chain
|
||||
/// gains a leading `Embedded` source ahead of the original `Url`, and the export reopens with both.
|
||||
#[test]
|
||||
fn embed_all_resources_materializes_link_only_resource() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graph_storage::NoMetadata;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(8), 0xF00D, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// A resource whose only source is a URL, resolved to a hash. The bytes live solely in the
|
||||
// byte store; the working copy never holds them.
|
||||
let payload = b"bytes behind a url";
|
||||
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::Url("https://example.com/r.bin".parse().unwrap()));
|
||||
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:?}"));
|
||||
|
||||
// The working copy holds no resource bytes (URL source, nothing embedded yet).
|
||||
assert!(!gdd.has_resource(&hash).await);
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("embedded");
|
||||
gdd.export(
|
||||
&dest,
|
||||
ExportFormat::Folder,
|
||||
ExportOptions {
|
||||
embed_all_resources: true,
|
||||
..Default::default()
|
||||
},
|
||||
&byte_store,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
|
||||
// Bytes materialized into the export.
|
||||
let resource_file = dest.join("resources").join(format!("{hash}"));
|
||||
assert!(resource_file.exists(), "embedded resource bytes should be written to {resource_file:?}");
|
||||
assert_eq!(std::fs::read(&resource_file).unwrap(), payload);
|
||||
|
||||
// Reopen the export: the registry chain now leads with Embedded, keeping the URL as fallback,
|
||||
// and the bytes are resolvable from the export itself with no byte store.
|
||||
let reopened = GddV1::open(&dest).await.unwrap_or_else(|error| panic!("open export failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&hash).await, "embedded bytes should be resolvable from the export");
|
||||
|
||||
let entry = reopened.registry().resources.get(&id).expect("resource entry survived export");
|
||||
assert_eq!(entry.hash, Some(hash));
|
||||
let embedded = serde_json::to_value(DataSource::Embedded).unwrap();
|
||||
let url = serde_json::to_value(DataSource::Url("https://example.com/r.bin".parse().unwrap())).unwrap();
|
||||
let chain: Vec<_> = entry.sources.iter().map(|(_, value)| value.source.clone()).collect();
|
||||
assert_eq!(chain, vec![embedded, url], "Embedded leads the chain, URL kept as fallback");
|
||||
});
|
||||
}
|
||||
|
||||
/// A plain export (no `embed_all_resources`) still materializes the bytes of an already-`Embedded`
|
||||
/// resource, pulling from the byte store when the working copy doesn't hold them (the editor case
|
||||
/// where bytes live in the app-global cache, not the per-document working copy).
|
||||
#[test]
|
||||
fn export_materializes_embedded_resource_from_byte_store() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graph_storage::NoMetadata;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), 0xBEEF, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// An Embedded resource whose bytes live only in the byte store, not the working copy.
|
||||
let payload = b"embedded bytes in the cache";
|
||||
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:?}"));
|
||||
|
||||
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
|
||||
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let dest = dir.path().join("plain");
|
||||
// Default options: embed_all_resources is false.
|
||||
gdd.export(&dest, ExportFormat::Folder, ExportOptions::default(), &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
|
||||
let resource_file = dest.join("resources").join(format!("{hash}"));
|
||||
assert!(resource_file.exists(), "embedded resource bytes should be pulled from the store into {resource_file:?}");
|
||||
assert_eq!(std::fs::read(&resource_file).unwrap(), payload);
|
||||
});
|
||||
}
|
||||
|
||||
/// 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"
|
||||
/// export, which previously failed at `embed_resource_sources` and fell back to the legacy blob.
|
||||
#[test]
|
||||
fn export_round_trips_unretired_hot_ops() {
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graph_storage::NoMetadata;
|
||||
use graphene_resource::{DataSource, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(3), 0xF15E, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"hot resource bytes";
|
||||
let hash = graphene_resource::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);
|
||||
|
||||
// Stage into the working copy without retiring, leaving the conversion in the hot log.
|
||||
gdd.stage_runtime_snapshot(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("stage_runtime_snapshot failed: {error:?}"));
|
||||
assert!(!gdd.session().hot_log().is_empty(), "staging without retiring should leave hot ops");
|
||||
assert!(gdd.registry().resources.contains_key(&id), "working registry should reflect the staged resource");
|
||||
|
||||
// Export to an archive and reopen it from scratch: the staged (hot) state must survive.
|
||||
let archive = gdd
|
||||
.export_to_bytes(document_format::ExportFormat::Zip, document_format::ExportOptions::default(), &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export_to_bytes failed: {error:?}"));
|
||||
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("open_from_archive failed: {error:?}"));
|
||||
|
||||
assert!(reopened.registry().resources.contains_key(&id), "the staged resource must survive export and reopen");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_in_rejects_future_format_version() {
|
||||
futures::executor::block_on(async {
|
||||
let container = empty_container();
|
||||
let layout = GddV1Layout;
|
||||
|
||||
let mut future_version = Manifest::new(0xC0DE, "ed".into(), "std".into());
|
||||
future_version.format_version = manifest::SUPPORTED_FORMAT_VERSION + 1;
|
||||
io::write_single(&container, layout.manifest_basename(), Codec::Json, &future_version).unwrap();
|
||||
|
||||
match GddV1::open_in(container, layout).await {
|
||||
Err(Error::UnsupportedVersion { .. }) => {}
|
||||
Ok(_) => panic!("expected UnsupportedVersion, got Ok"),
|
||||
Err(other) => panic!("expected UnsupportedVersion, got {other:?}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_in_records_default_codecs_in_manifest() {
|
||||
futures::executor::block_on(async {
|
||||
let gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let codecs = gdd.manifest().codecs;
|
||||
assert_eq!(codecs.registry, Codec::MessagePack);
|
||||
assert_eq!(codecs.history, Codec::MessagePackFrames);
|
||||
assert_eq!(codecs.hot_log, Codec::MessagePackFrames);
|
||||
assert_eq!(codecs.session, Codec::Json);
|
||||
});
|
||||
}
|
||||
|
||||
/// The `RegisterPeer` op auto-emitted on the first commit rides the hot-op pipeline through
|
||||
/// persistence and retirement, so the `peer_users` mapping survives a reopen.
|
||||
#[test]
|
||||
fn first_commit_registers_peer_and_survives_reopen() {
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graph_storage::{NoMetadata, UserId};
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(21), 0xAB, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
nodes: [(
|
||||
core_types::uuid::NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::identity::IdentityNode")),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &HashMapResourceStorage::new())
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
assert_eq!(gdd.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "first commit registers the peer");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
assert_eq!(reopened.registry().peer_users.get(&PeerId(21)), Some(&UserId(21)), "registration survives reopen");
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persist_path_writes_at_manifest_declared_codec_paths() {
|
||||
// The manifest declares the on-disk codec for each payload; the persist path must write at the
|
||||
// extension that codec implies, and reopen (which reads the codec from the manifest) must find them.
|
||||
futures::executor::block_on(async {
|
||||
use document_container::AsyncContainer;
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(5), 0xDEAD, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let hot_op = HotOp {
|
||||
op: RegistryDelta::AddNetwork {
|
||||
id: ROOT_NETWORK,
|
||||
network: Network::default(),
|
||||
},
|
||||
timestamp: TimeStamp { counter: 1, peer: PeerId(5) },
|
||||
};
|
||||
gdd.apply_hot_op(hot_op).unwrap_or_else(|error| panic!("apply_hot_op failed: {error:?}"));
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
// Defaults: hot log is MessagePackFrames (.frames), manifest is always JSON.
|
||||
assert!(working.exists(&io::path_for(layout.hot_log_basename(), Codec::MessagePackFrames)).await);
|
||||
assert!(working.exists(&io::path_for(layout.manifest_basename(), Codec::Json)).await);
|
||||
|
||||
let reopened = GddV1::open_in(working, layout).await.unwrap_or_else(|error| panic!("open_in failed: {error:?}"));
|
||||
assert!(reopened.registry().networks.contains_key(&ROOT_NETWORK));
|
||||
});
|
||||
}
|
||||
|
||||
/// Complete declaration round-trip through the byte store: committing a runtime network with a
|
||||
/// proto-node persists its `ProtoNode` content into a `ResourceStorage`, and resolving declarations
|
||||
/// back through that store reconstructs the proto-node identifier in `to_runtime`. This is the
|
||||
/// editor-shaped path (declaration bytes live in the resource store, not the Gdd container).
|
||||
#[test]
|
||||
fn declarations_round_trip_through_byte_store() {
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, concrete};
|
||||
use graph_storage::NoMetadata;
|
||||
use graphene_resource::ResourceRegistry;
|
||||
|
||||
const PROTO: &str = "graphene_core::ops::identity::IdentityNode";
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(core_types::uuid::NodeId(0), 0)],
|
||||
nodes: [(
|
||||
core_types::uuid::NodeId(0),
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(u32), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(PROTO)),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(1), 0xAB, "ed".into(), "std".into())
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
// Commit: declaration bytes flow into the byte store, not the Gdd container.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
gdd.commit_from_runtime(&network, &NoMetadata, &ResourceRegistry::new(), &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
// Resolve declarations back through the store and convert to a runtime network.
|
||||
let declarations = gdd.declarations(&byte_store).await;
|
||||
assert_eq!(declarations.len(), 1, "expected one proto-node declaration resolved from the byte store");
|
||||
|
||||
let (converted, _entries) = gdd.registry().to_runtime_with_metadata(&declarations).unwrap_or_else(|error| panic!("to_runtime failed: {error:?}"));
|
||||
|
||||
let node = converted.nodes.values().next().expect("converted network has the node");
|
||||
match &node.implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => assert_eq!(identifier.as_str(), PROTO, "proto-node identifier survived the byte-store round-trip"),
|
||||
other => panic!("expected a ProtoNode implementation, got {other:?}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -7,13 +7,13 @@ license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[features]
|
||||
conversion = ["dep:graph-craft"]
|
||||
conversion = ["dep:graph-craft", "dep:core-types"]
|
||||
default = ["conversion"]
|
||||
|
||||
[dependencies]
|
||||
graph-craft = { workspace = true, optional = true }
|
||||
core-types = { workspace = true, optional = true }
|
||||
graphene-resource = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
|
||||
thiserror = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
@@ -24,3 +24,4 @@ rmp-serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
core-types = { workspace = true }
|
||||
@@ -21,14 +21,18 @@ pub mod to_runtime;
|
||||
pub use attributes::*;
|
||||
pub use crdt::*;
|
||||
pub use document::*;
|
||||
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
|
||||
pub use history::History;
|
||||
pub use ids::*;
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
pub use model::*;
|
||||
pub use registry::*;
|
||||
pub use resources::*;
|
||||
pub use session::*;
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub use to_runtime::Declarations;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::NodeMetadataSource;
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
use crate::from_runtime;
|
||||
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, NodeMetadataSource, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use crate::{ApplyMode, Delta, Document, History, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId};
|
||||
use graphene_resource::{ResourceHash, ResourceId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -19,6 +22,7 @@ impl Session {
|
||||
/// Mints a fresh `PeerId` from the process-wide UUID generator and wraps an empty `Document`.
|
||||
/// Two peers in the same process will collide (the generator is seeded once); use `with_peer`
|
||||
/// in tests where determinism matters.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
pub fn new() -> Self {
|
||||
Self::with_peer(PeerId(core_types::uuid::generate_uuid()))
|
||||
}
|
||||
@@ -51,6 +55,12 @@ impl Session {
|
||||
&self.document.working_registry
|
||||
}
|
||||
|
||||
/// The registry after applying retired history only, without the unretired hot tail. Persisted as the
|
||||
/// snapshot alongside `history` + hot log so a reopen restores the same retired-then-hot layering.
|
||||
pub fn retired_registry(&self) -> &Registry {
|
||||
&self.document.retired_snapshot
|
||||
}
|
||||
|
||||
/// Diff the current registry against a fresh conversion of `network`, then commit each emitted
|
||||
/// op as its own `Delta` on the local chain. One `clock.tick()` per op (strictly causal within
|
||||
/// a commit). Returns the new `Rev`s in commit order (empty if nothing changed) plus the
|
||||
@@ -107,15 +117,15 @@ impl Session {
|
||||
ops.push(RegistryDelta::AddSource { id, key, source: embedded.clone() });
|
||||
}
|
||||
|
||||
// Caller contract: this runs on a throwaway export clone with no unretired hot ops, so the
|
||||
// working registry equals the snapshot. Overwriting working with the advanced snapshot below
|
||||
// would otherwise drop hot-zone edits, so reject the call rather than corrupt state.
|
||||
if !self.document.hot_log.is_empty() {
|
||||
return Err(CrdtError::HotLogNotEmpty);
|
||||
}
|
||||
|
||||
// These are retired deltas, so `commit_ops` advances the retired snapshot and history. The working
|
||||
// registry sits at `retired_snapshot + hot tail`, so mirror each committed delta onto it with its own
|
||||
// timestamp rather than cloning the snapshot over it, which would discard any unretired hot-zone edits.
|
||||
let revs = self.commit_ops(ops, false)?;
|
||||
self.document.working_registry = self.document.retired_snapshot.clone();
|
||||
for &rev in &revs {
|
||||
let Some(delta) = self.document.history.get(rev) else { continue };
|
||||
let (kind, timestamp) = (delta.kind.clone(), delta.timestamp);
|
||||
self.document.apply_op_idempotent(kind, timestamp)?;
|
||||
}
|
||||
Ok(revs)
|
||||
}
|
||||
|
||||
@@ -432,6 +442,12 @@ impl Session {
|
||||
self.document.history.iter()
|
||||
}
|
||||
|
||||
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
|
||||
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
|
||||
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
|
||||
self.document.history.get(rev)
|
||||
}
|
||||
|
||||
/// Verify the retired history loaded from an untrusted source: content-addressed ids match their
|
||||
/// recomputed hashes, and the deltas are topologically ordered. See [`History::verify`].
|
||||
pub fn verify_history(&self) -> Result<(), CrdtError> {
|
||||
@@ -465,6 +481,19 @@ impl Session {
|
||||
self.document.head
|
||||
}
|
||||
|
||||
/// The latest retired commit broadcast to at least one peer. Commits after it are silently
|
||||
/// rewritable; commits at or before it are published. `None` until broadcast transport lands.
|
||||
pub fn last_broadcast_rev(&self) -> Option<Rev> {
|
||||
self.document.last_broadcast_rev
|
||||
}
|
||||
|
||||
/// Advance the published frontier to `rev` as commits are broadcast. The frontier is monotonic, so
|
||||
/// this only moves it forward (never back to `None`). Set by the (future) broadcast transport;
|
||||
/// persisted in `session.json` so the silent/published boundary survives a reopen.
|
||||
pub fn publish_up_to(&mut self, rev: Rev) {
|
||||
self.document.last_broadcast_rev = Some(rev);
|
||||
}
|
||||
|
||||
/// Test-only: every retired delta, cloned, for feeding one session's branch into another's `merge`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cloned_deltas(&self) -> Vec<Delta> {
|
||||
@@ -488,6 +517,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Errors from `Session::commit_from_runtime`.
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum CommitError {
|
||||
#[error("Failed to convert runtime network: {0}")]
|
||||
@@ -496,6 +526,7 @@ pub enum CommitError {
|
||||
Crdt(#[from] CrdtError),
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "conversion", test))]
|
||||
impl Default for Session {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
@@ -537,8 +568,6 @@ pub enum CrdtError {
|
||||
/// PeerId is already registered to a different UserId.
|
||||
#[error("Peer {0:?} is already registered to a different user")]
|
||||
PeerRegistrationConflict(PeerId),
|
||||
#[error("Operation requires an empty hot log")]
|
||||
HotLogNotEmpty,
|
||||
#[error("Delta stored under {stored} hashes to {expected}")]
|
||||
RevMismatch { stored: Rev, expected: Rev },
|
||||
}
|
||||
@@ -777,20 +777,33 @@ fn no_op_commit_preserves_redo_stack() {
|
||||
assert!(session.can_redo(), "a no-op commit must not clear the redo stack");
|
||||
}
|
||||
|
||||
/// `embed_resource_sources` overwrites the working registry with the snapshot, valid only when no
|
||||
/// unretired hot ops are present. Called with a non-empty hot log it must error rather than silently
|
||||
/// drop the hot-zone edits.
|
||||
/// `embed_resource_sources` commits its `AddSource` deltas as retired, then mirrors them onto the
|
||||
/// working registry. With unretired hot ops present it must keep the hot-zone edits (export of a
|
||||
/// mid-interaction document is lossless) rather than clobbering the working registry with the snapshot.
|
||||
#[test]
|
||||
fn embed_resource_sources_rejects_unretired_hot_ops() {
|
||||
fn embed_resource_sources_preserves_unretired_hot_ops() {
|
||||
let mut session = Session::with_peer(PeerId(1));
|
||||
let resources = graphene_resource::ResourceRegistry::new();
|
||||
|
||||
// Stage without retiring, leaving hot ops in the log.
|
||||
session.stage_from_runtime(&tiny_network(), &NoMetadata, &resources).expect("stage");
|
||||
assert!(!session.hot_log().is_empty(), "staging should leave unretired hot ops");
|
||||
// Retire a base so the network's nodes live in the retired snapshot.
|
||||
session.stage_from_runtime(&tiny_network(), &NoMetadata, &resources).expect("stage base");
|
||||
let base_up_to = session.hot_log().last().expect("staged base").timestamp;
|
||||
session.retire(base_up_to).expect("retire base");
|
||||
|
||||
let result = session.embed_resource_sources(std::iter::empty::<ResourceId>());
|
||||
assert!(matches!(result, Err(crate::CrdtError::HotLogNotEmpty)), "expected HotLogNotEmpty, got {result:?}");
|
||||
// Stage an embedded resource without retiring, leaving it in the hot log (the working registry now
|
||||
// holds it, the retired snapshot does not).
|
||||
let hash = ResourceHash::from(&b"hot-resource"[..]);
|
||||
let id = ResourceId::new();
|
||||
session.stage_embedded_resource(id, hash).expect("stage resource");
|
||||
assert!(!session.hot_log().is_empty(), "staging should leave unretired hot ops");
|
||||
assert!(session.registry().resources.contains_key(&id), "working registry should hold the hot resource");
|
||||
|
||||
session.embed_resource_sources(std::iter::empty::<ResourceId>()).expect("embed tolerates a non-empty hot log");
|
||||
|
||||
// The hot-zone resource survives in the working registry (not reset to the snapshot), and the hot log
|
||||
// is untouched so a later retire still promotes it.
|
||||
assert!(session.registry().resources.contains_key(&id), "hot resource must survive the embed");
|
||||
assert!(!session.hot_log().is_empty(), "embed must not drain the hot log");
|
||||
}
|
||||
|
||||
/// A delta's `Rev` is content-addressed, so two byte-equal deltas must hash identically regardless
|
||||
|
||||
@@ -19,6 +19,9 @@ gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
|
||||
# Local dependencies
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graph-storage = { workspace = true, features = ["conversion"] }
|
||||
document-format = { workspace = true }
|
||||
document-container = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
interpreted-executor = { workspace = true }
|
||||
graphene-std = { workspace = true } # NOTE: `core-types` should not be added here because `graphene-std` re-exports its contents
|
||||
|
||||
@@ -10,11 +10,18 @@ pub struct Editor {
|
||||
}
|
||||
|
||||
impl Editor {
|
||||
pub fn new(environment: Environment, uuid_random_seed: u64, resource_storage: Arc<dyn ResourceStorage>, mut application_io: PlatformApplicationIo, wake: Wake) -> Self {
|
||||
pub fn new(
|
||||
environment: Environment,
|
||||
uuid_random_seed: u64,
|
||||
resource_storage: Arc<dyn ResourceStorage>,
|
||||
working_copy_root: Option<std::path::PathBuf>,
|
||||
mut application_io: PlatformApplicationIo,
|
||||
wake: Wake,
|
||||
) -> Self {
|
||||
ENVIRONMENT.set(environment).expect("Editor shoud only be initialized once");
|
||||
graphene_std::uuid::set_uuid_seed(uuid_random_seed);
|
||||
|
||||
let mut dispatcher = Dispatcher::new(resource_storage);
|
||||
let mut dispatcher = Dispatcher::new(resource_storage, working_copy_root);
|
||||
dispatcher.message_handlers.future_message_handler.set_wake(wake);
|
||||
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
|
||||
crate::node_graph_executor::replace_application_io(application_io);
|
||||
|
||||
@@ -176,6 +176,9 @@ pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
|
||||
|
||||
// DOCUMENT
|
||||
pub const FILE_EXTENSION: &str = "graphite";
|
||||
/// New document container format. Save now writes a `.gdd` (with the legacy `.graphite` embedded as a
|
||||
/// fallback during the dual-write soak); `.graphite` stays a supported open/import input.
|
||||
pub const GDD_FILE_EXTENSION: &str = "gdd";
|
||||
pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
|
||||
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
|
||||
pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
@@ -89,9 +89,10 @@ const DEBUG_MESSAGE_BLOCK_LIST: &[MessageDiscriminant] = &[
|
||||
const DEBUG_MESSAGE_ENDING_BLOCK_LIST: &[&str] = &["PointerMove", "PointerOutsideViewport", "Overlays", "Draw", "CurrentTime", "Time"];
|
||||
|
||||
impl Dispatcher {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>) -> Self {
|
||||
pub fn new(resource_storage: Arc<dyn ResourceStorage>, working_copy_root: Option<std::path::PathBuf>) -> Self {
|
||||
let mut s = Self::default();
|
||||
s.message_handlers.resource_storage_message_handler = ResourceStorageMessageHandler::new(resource_storage);
|
||||
s.message_handlers.portfolio_message_handler.set_working_copy_root(working_copy_root);
|
||||
s
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,11 @@ use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded};
|
||||
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
// Native spawns onto a multi-thread tokio runtime, so the boxed future must be `Send`. Wasm uses
|
||||
// `spawn_local` on the single JS thread, where `Send` is unavailable (OPFS/`JsFuture` are `!Send`)
|
||||
// and unnecessary. `WasmNotSend` (`Send` on native, no-op on wasm) expresses the input bound on
|
||||
// `MessageFuture::new`; the stored trait-object alias still needs a `cfg` split because `Send` is
|
||||
// an auto trait usable in a `dyn` bound while `WasmNotSend` is not.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type InnerMessageFuture = Pin<Box<dyn Future<Output = Message> + Send + 'static>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
@@ -132,7 +137,7 @@ impl MessageHandler<FutureMessage, FutureMessageContext> for FutureMessageHandle
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(TokioSpawner::default())
|
||||
Arc::new(TokioSpawner)
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
@@ -140,37 +145,27 @@ fn default_spawner() -> Arc<dyn MessageSpawner> {
|
||||
Arc::new(WasmSpawner)
|
||||
}
|
||||
|
||||
/// Process-global runtime for editor async work. Held in a `LazyLock` so it lives for the lifetime
|
||||
/// of the process and is never dropped: dropping a `tokio::runtime::Runtime` blocks to join its
|
||||
/// worker threads, which panics if it happens inside an async context (e.g. a `#[tokio::test]` body
|
||||
/// or the desktop event loop). A leaked-for-process runtime sidesteps that entirely.
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
struct TokioSpawner {
|
||||
/// Built lazily on first spawn. `multi_thread(1)` lets Tokio manage its own driver.
|
||||
runtime: std::sync::OnceLock<tokio::runtime::Runtime>,
|
||||
}
|
||||
static EDITOR_ASYNC_RUNTIME: std::sync::LazyLock<tokio::runtime::Runtime> = std::sync::LazyLock::new(|| {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct async-message tokio runtime")
|
||||
});
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl Default for TokioSpawner {
|
||||
fn default() -> Self {
|
||||
Self { runtime: std::sync::OnceLock::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl TokioSpawner {
|
||||
fn runtime(&self) -> &tokio::runtime::Runtime {
|
||||
self.runtime.get_or_init(|| {
|
||||
tokio::runtime::Builder::new_multi_thread()
|
||||
.worker_threads(1)
|
||||
.thread_name("graphite-async")
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("failed to construct async-message tokio runtime")
|
||||
})
|
||||
}
|
||||
}
|
||||
struct TokioSpawner;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
impl MessageSpawner for TokioSpawner {
|
||||
fn spawn(&self, future: InnerMessageFuture, results: UnboundedSender<Message>, wake: Wake) {
|
||||
self.runtime().spawn(async move {
|
||||
EDITOR_ASYNC_RUNTIME.spawn(async move {
|
||||
let message = future.await;
|
||||
let _ = results.unbounded_send(message);
|
||||
wake();
|
||||
|
||||
@@ -336,6 +336,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(list) => list.identifier(),
|
||||
Self::Color(list) => list.identifier(),
|
||||
Self::Gradient(list) => list.identifier(),
|
||||
Self::Text(list) => list.identifier(),
|
||||
}
|
||||
}
|
||||
// Don't put a breadcrumb for Graphic
|
||||
@@ -350,6 +351,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Color(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Gradient(list) => list.layout_with_breadcrumb(data),
|
||||
Self::Text(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -421,6 +423,10 @@ impl TableItemLayout for Vector {
|
||||
TextLabel::new("Fill Gradient End").narrow(true).widget_instance(),
|
||||
TextLabel::new(format_dvec2(gradient.end)).narrow(true).widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Fill Gradient Transform").narrow(true).widget_instance(),
|
||||
TextLabel::new(format_transform_matrix(gradient.transform)).narrow(true).widget_instance(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -225,6 +225,8 @@ pub enum DocumentMessage {
|
||||
UpdateClickTargets {
|
||||
click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
},
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
MigrateLegacyGradients,
|
||||
UpdateOutlines {
|
||||
outlines: HashMap<NodeId, Vec<Arc<ClickTarget>>>,
|
||||
},
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::utility_types::network_interface::{self, NodeNetworkInterface, Transa
|
||||
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
|
||||
use crate::application::{GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
|
||||
use crate::consts::{
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
|
||||
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION, LAYER_INDENT_OFFSET, NODE_CHAIN_WIDTH, SCALE_EFFECT, SCROLLBAR_SPACING,
|
||||
VIEWPORT_ROTATE_SNAP_INTERVAL,
|
||||
};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
@@ -64,7 +64,8 @@ pub struct DocumentMessageContext<'a> {
|
||||
pub fonts: &'a FontsMessageHandler,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize, ExtractField)]
|
||||
#[derivative(Clone, Debug)]
|
||||
#[serde(default)]
|
||||
pub struct DocumentMessageHandler {
|
||||
// ======================
|
||||
@@ -91,6 +92,13 @@ pub struct DocumentMessageHandler {
|
||||
/// Resources embedded in the document.
|
||||
#[serde(default, skip_serializing_if = "ResourceMessageHandler::is_empty")]
|
||||
pub resources: ResourceMessageHandler,
|
||||
/// Per-document `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None`
|
||||
/// until the mount future built by `load_document` resolves (the working-copy container is
|
||||
/// constructed asynchronously). Not serialized. A clone shares the same working-copy container
|
||||
/// (`Gdd` holds an `Arc<AnyContainer>`), so a cloned document still reads the live working copy.
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore")]
|
||||
pub storage: Option<document_format::GddV1>,
|
||||
/// Tracks which layer occurrences are collapsed in the Layers panel, keyed by tree path.
|
||||
#[serde(deserialize_with = "deserialize_collapsed_layers", default)]
|
||||
pub collapsed: CollapsedLayers,
|
||||
@@ -124,6 +132,11 @@ pub struct DocumentMessageHandler {
|
||||
/// The path of the to the document file.
|
||||
#[serde(skip)]
|
||||
pub(crate) path: Option<PathBuf>,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Set when a freshly-opened document still has legacy bounding-box-relative gradients; the deferred gradient
|
||||
/// migration converts them to absolute after the first graph run (when geometry bounds are available) and clears this.
|
||||
#[serde(skip)]
|
||||
pub(crate) pending_gradient_migration: bool,
|
||||
/// Path to network currently viewed in the node graph overlay. This will eventually be stored in each panel, so that multiple panels can refer to different networks
|
||||
#[serde(skip)]
|
||||
breadcrumb_network_path: Vec<NodeId>,
|
||||
@@ -167,6 +180,7 @@ impl Default for DocumentMessageHandler {
|
||||
// ============================================
|
||||
network_interface: default_document_network_interface(),
|
||||
resources: ResourceMessageHandler::default(),
|
||||
storage: None,
|
||||
collapsed: CollapsedLayers::default(),
|
||||
commit_hash: GRAPHITE_GIT_COMMIT_HASH.to_string(),
|
||||
document_ptz: PTZ::default(),
|
||||
@@ -181,6 +195,8 @@ impl Default for DocumentMessageHandler {
|
||||
// =============================================
|
||||
name: DEFAULT_DOCUMENT_NAME.to_string(),
|
||||
path: None,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
pending_gradient_migration: false,
|
||||
breadcrumb_network_path: Vec::new(),
|
||||
selection_network_path: Vec::new(),
|
||||
document_undo_history: VecDeque::new(),
|
||||
@@ -389,8 +405,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![] });
|
||||
self.layer_range_selection_reference = None;
|
||||
}
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(viewport, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(viewport, responses),
|
||||
DocumentMessage::DocumentHistoryBackward => self.undo_with_history(document_id, viewport, resource_storage, responses),
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, resource_storage, responses),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -777,7 +793,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let layer_node_id = NodeId::new();
|
||||
let layer_id = LayerNodeIdentifier::new_unchecked(layer_node_id);
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
// Emit the transaction as an explicit StartTransaction ... CommitTransaction pair bracketing the
|
||||
// mutations, rather than `AddTransaction`. `AddTransaction` prepends its Start/Commit as a tight
|
||||
// pair that the dispatcher drains before these sibling mutation messages, so the commit closes
|
||||
// before the layer is added and the storage staging sees an empty diff. Interleaving the pair
|
||||
// around the mutations makes them all siblings drained in order (Start, mutate, Commit), so the
|
||||
// commit observes the paste and stages it.
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
|
||||
let layer = graph_modification_utils::new_image_layer(image, layer_node_id, layer_parent, responses);
|
||||
|
||||
@@ -786,7 +808,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
// Fold the name into the paste's single transaction so the whole paste is one undo step.
|
||||
skip_adding_history_step: true,
|
||||
});
|
||||
}
|
||||
if let Some((parent, insert_index)) = parent_and_insert_index {
|
||||
@@ -807,6 +830,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::CommitTransaction);
|
||||
|
||||
// Force chosen tool to be Select Tool after importing image.
|
||||
responses.add(ToolMessage::ActivateTool { tool_type: ToolType::Select });
|
||||
}
|
||||
@@ -844,7 +869,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
// Fold the name into the paste's single transaction so the whole paste is one undo step.
|
||||
skip_adding_history_step: true,
|
||||
});
|
||||
}
|
||||
if let Some((parent, insert_index)) = parent_and_insert_index {
|
||||
@@ -978,28 +1004,52 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
|
||||
responses.add(PortfolioMessage::AutoSaveActiveDocument);
|
||||
|
||||
let name = format!("{}.{}", self.name.clone(), FILE_EXTENSION);
|
||||
let name = format!("{}.{}", self.name.clone(), GDD_FILE_EXTENSION);
|
||||
let path = if let DocumentMessage::SaveDocumentAs = message { None } else { self.path.clone() };
|
||||
if path.is_some() {
|
||||
responses.add(DocumentMessage::MarkAsSaved);
|
||||
}
|
||||
let folder = self.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
|
||||
|
||||
// The clone shares the live working-copy container (Arc), so its storage reads the state the
|
||||
// queued AutoSaveActiveDocument just committed.
|
||||
let mut document = self.clone();
|
||||
let resources_load_handle = resource_storage.resources();
|
||||
let export_load_handle = resource_storage.resources();
|
||||
|
||||
responses.add(async move {
|
||||
document.resources.collect_garbage(document.used_resources(false).as_ref());
|
||||
document.resources.embed_resources(resources_load_handle).await;
|
||||
|
||||
let content = document.serialize_document().into_bytes().into();
|
||||
// The legacy .graphite blob, resources embedded inline so it stays self-contained as the .gdd recovery fallback.
|
||||
let legacy_document = document.serialize_document().into_bytes();
|
||||
|
||||
// Export the working copy as a .gdd with the legacy blob embedded; fall back to the bare legacy blob if there is no working copy or the export fails.
|
||||
let content = match &document.storage {
|
||||
Some(storage) => storage
|
||||
.export_to_bytes(
|
||||
document_format::ExportFormat::Xz,
|
||||
document_format::ExportOptions::default(),
|
||||
export_load_handle.as_ref(),
|
||||
Some(&legacy_document),
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|error| {
|
||||
log::error!("Save: building .gdd export failed, falling back to legacy .graphite: {error}");
|
||||
legacy_document
|
||||
}),
|
||||
None => {
|
||||
log::warn!("Save: working copy not mounted yet, saving legacy .graphite only");
|
||||
legacy_document
|
||||
}
|
||||
};
|
||||
|
||||
Message::Frontend(FrontendMessage::TriggerSaveDocument {
|
||||
document_id,
|
||||
name,
|
||||
path,
|
||||
folder,
|
||||
content,
|
||||
content: content.into(),
|
||||
})
|
||||
});
|
||||
}
|
||||
@@ -1245,6 +1295,11 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
|
||||
DocumentMessage::StartTransaction => {
|
||||
// A new undo step is beginning, so the previous interaction's staged hot ops are complete:
|
||||
// retire them into one durable Gdd interaction. This aligns one Gdd interaction to one legacy
|
||||
// undo step (a tool drag fires several `CommitTransaction`s but one `StartTransaction`).
|
||||
self.retire_storage_interaction();
|
||||
|
||||
self.network_interface.start_transaction();
|
||||
let network_interface_clone = self.network_interface.clone();
|
||||
self.document_undo_history.push_back(network_interface_clone);
|
||||
@@ -1274,6 +1329,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
self.network_interface.finish_transaction();
|
||||
self.document_redo_history.clear();
|
||||
|
||||
// Stage this commit into the `Gdd` working copy. Retirement into a durable interaction happens
|
||||
// at the undo-step boundary (`StartTransaction`), so several commits in one user action
|
||||
// coalesce into one undo unit. Legacy snapshot undo stays authoritative.
|
||||
if let Some(byte_store) = resource_storage.storage() {
|
||||
self.commit_storage_snapshot(byte_store);
|
||||
}
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
DocumentMessage::AbortTransaction => match self.network_interface.transaction_status() {
|
||||
@@ -1365,6 +1428,38 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_click_targets(layer_click_targets);
|
||||
}
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
DocumentMessage::MigrateLegacyGradients => {
|
||||
if self.pending_gradient_migration {
|
||||
self.pending_gradient_migration = false;
|
||||
|
||||
// Read each layer's legacy gradient and compute its absolute form from the now-available local bounds
|
||||
let layers: Vec<_> = self.metadata().all_layers().collect();
|
||||
let conversions: Vec<(NodeId, Fill)> = layers
|
||||
.into_iter()
|
||||
.filter_map(|layer| {
|
||||
let gradient = graph_modification_utils::get_gradient(layer, &self.network_interface)?;
|
||||
if gradient.absolute {
|
||||
return None;
|
||||
}
|
||||
let fill_node_id = graph_modification_utils::get_fill_node_id(layer, &self.network_interface)?;
|
||||
let bounds = self.metadata().nonzero_bounding_box(layer);
|
||||
let bounding_box = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
let layer_transform = self.metadata().upstream_transform(layer.to_node());
|
||||
Some((fill_node_id, Fill::Gradient(gradient.to_absolute(bounding_box, layer_transform))))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let converted_any = !conversions.is_empty();
|
||||
for (fill_node_id, fill) in conversions {
|
||||
self.network_interface
|
||||
.set_input(&InputConnector::node(fill_node_id, 1), NodeInput::value(TaggedValue::Fill(fill), false), &[]);
|
||||
}
|
||||
if converted_any {
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
}
|
||||
}
|
||||
DocumentMessage::UpdateOutlines { outlines } => {
|
||||
let layer_outlines = outlines
|
||||
.into_iter()
|
||||
@@ -1700,6 +1795,40 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
}
|
||||
|
||||
impl DocumentMessageHandler {
|
||||
/// Build a document handler from a `.gdd` working copy: the runtime `interface` rebuilt from the
|
||||
/// stored registry plus the mounted `Gdd`. The caller converts the registry to `interface`; this
|
||||
/// restores the document-level `ui::doc::*` settings and resource registry and takes ownership of
|
||||
/// the working copy. Post-load fixups (`load_structure`, validation, graph run) are the loader's job.
|
||||
pub fn from_storage(interface: NodeNetworkInterface, storage: document_format::GddV1, name: String, path: Option<std::path::PathBuf>) -> Self {
|
||||
let mut document = Self {
|
||||
network_interface: interface,
|
||||
name,
|
||||
path,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
document.apply_stored_document_settings(&storage.view_settings().clone());
|
||||
match storage.registry().to_resource_registry() {
|
||||
Ok(resource_registry) => document.resources.registry = resource_registry,
|
||||
Err(error) => log::error!("Opening .gdd: failed to rebuild resource registry: {error}"),
|
||||
}
|
||||
document.storage = Some(storage);
|
||||
|
||||
document
|
||||
}
|
||||
|
||||
/// Post-load fixups for a document built from storage: per-node input/output metadata validation
|
||||
/// and the layer-structure rebuild. Mirrors the essential part of the legacy load path; the
|
||||
/// old-file layer-stacking realignment is skipped (a current-format `.gdd` doesn't need it).
|
||||
pub fn finalize_storage_load(&mut self) {
|
||||
for (node_id, node, path) in self.network_interface.document_network().clone().recursive_nodes() {
|
||||
self.network_interface.validate_input_metadata(node_id, node, &path);
|
||||
self.network_interface.validate_output_names(node_id, node, &path);
|
||||
}
|
||||
|
||||
self.network_interface.load_structure();
|
||||
}
|
||||
|
||||
/// Translates a viewport mouse position to a document-space transform, or uses the viewport center if no mouse position is given.
|
||||
fn document_transform_from_mouse(&self, mouse: Option<(f64, f64)>, viewport: &ViewportMessageHandler) -> DAffine2 {
|
||||
let viewport_pos: DVec2 = mouse.map_or_else(|| viewport.center_in_viewport_space().into_dvec2() + viewport.offset().into_dvec2(), |pos| pos.into());
|
||||
@@ -1875,6 +2004,274 @@ impl DocumentMessageHandler {
|
||||
&self.selection_network_path
|
||||
}
|
||||
|
||||
/// Retire the pending staged hot ops (the current interaction) into durable Gdd history as one undo
|
||||
/// unit. Called at each undo-step boundary (a new `StartTransaction`) and before undo/redo, so the
|
||||
/// per-`CommitTransaction` staging coalesces into one retired interaction aligned with the legacy step.
|
||||
pub(crate) fn retire_storage_interaction(&mut self) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.retire_pending_interaction() {
|
||||
log::error!("Storage interaction retirement failed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Stage the runtime network into the document's `Gdd` working copy at each `CommitTransaction`.
|
||||
/// No-op while the working copy is still unmounted (its container is built asynchronously on
|
||||
/// document open); the mount picks up the current runtime state once it attaches. The staged hot ops
|
||||
/// are retired into durable history by [`retire_storage_interaction`](Self::retire_storage_interaction) at
|
||||
/// undo-step boundaries. Proto-node declaration bytes are persisted into `byte_store` (the app-global
|
||||
/// resource cache).
|
||||
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView};
|
||||
|
||||
if self.storage.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::collect_network_view_settings;
|
||||
|
||||
let network = self.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&self.network_interface);
|
||||
|
||||
// Per-network view state (node-graph nav + previewing) is per-peer too, so collect it (keyed by the
|
||||
// stable `NetworkId` the storage layer resolves) for `session.json`. Computed before the mutable
|
||||
// `storage` borrow below.
|
||||
let network_view_settings = self
|
||||
.storage
|
||||
.as_ref()
|
||||
.and_then(|storage| storage.network_ids(&network, &view).ok())
|
||||
.map(|network_ids| collect_network_view_settings(&self.network_interface, &network_ids));
|
||||
|
||||
// Per-peer view settings (PTZ, rulers, ...) persist in `session.json`, not the registry, so they
|
||||
// stay out of the CRDT/history (not undoable, not synced, may differ per viewer).
|
||||
let view_settings = DocumentSettings {
|
||||
document_ptz: &self.document_ptz,
|
||||
render_mode: &self.render_mode,
|
||||
overlays_visibility: &self.overlays_visibility_settings,
|
||||
rulers_visible: self.rulers_visible,
|
||||
snapping_state: &self.snapping_state,
|
||||
collapsed: &self.collapsed,
|
||||
}
|
||||
.to_view_map();
|
||||
|
||||
// Serialize the legacy document from the same `self` state captured above, so the embedded
|
||||
// blob and the registry snapshot describe one consistent document (no interleaved edit).
|
||||
let legacy_document = self.serialize_document();
|
||||
|
||||
// `view` borrows disjoint `self` fields, so the mutable `storage` borrow is independent.
|
||||
let storage = self.storage.as_mut().expect("checked present above");
|
||||
// Stage into the working copy without retiring: a tool drag fires several `CommitTransaction`s
|
||||
// but is one legacy undo step, so the deltas accumulate as hot ops and coalesce into one retired
|
||||
// interaction at the next undo-step boundary (`retire_pending_interaction`).
|
||||
if let Err(error) = storage.stage_runtime_snapshot(&network, &view, &self.resources.registry, byte_store) {
|
||||
log::error!("Storage snapshot staging failed: {error}");
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(error) = storage.set_view_settings(view_settings) {
|
||||
log::error!("Persisting view settings failed: {error}");
|
||||
}
|
||||
|
||||
if let Some(network_view_settings) = network_view_settings
|
||||
&& let Err(error) = storage.set_network_view_settings(network_view_settings)
|
||||
{
|
||||
log::error!("Persisting per-network view settings failed: {error}");
|
||||
}
|
||||
|
||||
// Dual-write soak: embed the legacy `.graphite` bytes inside the `.gdd` working copy so the new
|
||||
// format can be validated against (and recovered from) the old one on open.
|
||||
if let Err(error) = storage.store_legacy_document(legacy_document.as_bytes()) {
|
||||
log::error!("Embedding legacy document into working copy failed: {error}");
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
self.verify_storage_round_trip(&network, &view);
|
||||
}
|
||||
|
||||
/// Restore the per-peer view settings persisted in `session.json` (the `ui::doc::*`-keyed
|
||||
/// `view_settings` map) into the runtime handler fields. Each setting is applied only if present and
|
||||
/// decodable; missing or undecodable keys leave the current field untouched. Inverse of the view-
|
||||
/// settings half of `commit_storage_snapshot`; used when the `.gdd` is the load source.
|
||||
pub fn apply_stored_document_settings(&mut self, view_settings: &std::collections::BTreeMap<String, serde_json::Value>) {
|
||||
use graph_storage::attr::session::doc;
|
||||
|
||||
fn decode<T: serde::de::DeserializeOwned>(view_settings: &std::collections::BTreeMap<String, serde_json::Value>, key: &str) -> Option<T> {
|
||||
view_settings.get(key).and_then(|value| serde_json::from_value(value.clone()).ok())
|
||||
}
|
||||
|
||||
if let Some(value) = decode(view_settings, doc::PTZ) {
|
||||
self.document_ptz = value;
|
||||
}
|
||||
if let Some(value) = decode(view_settings, doc::RENDER_MODE) {
|
||||
self.render_mode = value;
|
||||
}
|
||||
if let Some(value) = decode(view_settings, doc::OVERLAYS) {
|
||||
self.overlays_visibility_settings = value;
|
||||
}
|
||||
if let Some(value) = decode(view_settings, doc::RULERS_VISIBLE) {
|
||||
self.rulers_visible = value;
|
||||
}
|
||||
if let Some(value) = decode(view_settings, doc::SNAPPING) {
|
||||
self.snapping_state = value;
|
||||
}
|
||||
if let Some(value) = decode(view_settings, doc::COLLAPSED) {
|
||||
self.collapsed = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// Debug-only: stored registry should equal a fresh `from_runtime`, and a `to_runtime` of the
|
||||
/// stored registry should equal the original network. Panics on drift so the dual-write soak
|
||||
/// fails loud in dev (and in tests); release builds skip this entirely and autosave never crashes.
|
||||
#[cfg(debug_assertions)]
|
||||
fn verify_storage_round_trip(
|
||||
&self,
|
||||
network: &graph_craft::document::NodeNetwork,
|
||||
view: &crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::StorageMetadataView,
|
||||
) {
|
||||
let Some(storage) = &self.storage else { return };
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let conversion = graph_storage::Registry::convert_from_runtime(network, view, &self.resources.registry, peer).expect("storage round-trip: from_runtime failed");
|
||||
let target = &conversion.registry;
|
||||
let declarations = conversion.declarations().expect("storage round-trip: declaration rebuild failed");
|
||||
|
||||
let stored = storage.registry();
|
||||
assert!(stored.value_equal(target), "storage round-trip: registry value drift after commit\n{}", diff_registries(stored, target));
|
||||
assert!(stored.order_consistent(target), "storage round-trip: timestamp order inconsistent between stored and target");
|
||||
|
||||
let (round_tripped, _entries) = stored.to_runtime_with_metadata(&declarations).expect("storage round-trip: to_runtime failed");
|
||||
assert!(
|
||||
&round_tripped == network,
|
||||
"storage round-trip: network drift after to_runtime\n{}",
|
||||
diff_networks(network, &round_tripped)
|
||||
);
|
||||
}
|
||||
|
||||
/// Move the `Gdd` undo/redo cursor (the authoritative path) and spawn the async future that rebuilds the
|
||||
/// interface from the cursor and swaps it in. Synchronous: flushes the open interaction, moves the cursor
|
||||
/// (persisting `session.json`), then clones the post-move `Gdd` and queues the rebuild. `had_oracle`
|
||||
/// records whether the legacy snapshot already applied, so the completion can compare; it travels with
|
||||
/// the spawned message. Returns whether the cursor moved (so callers know a rebuild is pending).
|
||||
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, had_oracle: bool, undo: bool, responses: &mut VecDeque<Message>) -> bool {
|
||||
// Flush any open interaction into retired history first: undo/redo operate on the retired chain, so
|
||||
// the most recent edit must be a committed interaction before the cursor moves.
|
||||
self.retire_storage_interaction();
|
||||
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
|
||||
let moved = if undo {
|
||||
if !storage.can_undo() {
|
||||
return false;
|
||||
}
|
||||
storage.undo().map(|_| ())
|
||||
} else {
|
||||
if !storage.can_redo() {
|
||||
return false;
|
||||
}
|
||||
storage.redo().map(|_| ())
|
||||
};
|
||||
if let Err(error) = moved {
|
||||
log::error!("Storage undo/redo cursor move failed: {error}");
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(store_handle) = resource_storage.store_handle() else {
|
||||
log::error!("Storage undo/redo: resource storage not initialized; cannot rebuild interface");
|
||||
return false;
|
||||
};
|
||||
|
||||
// Clone the post-move `Gdd` (a `Session` snapshot at the new cursor; the container is `Arc`-shared)
|
||||
// so the `'static` rebuild future reads the rewound state while the live document keeps its cursor.
|
||||
let gdd = storage.clone();
|
||||
responses.add(crate::messages::portfolio::portfolio_message_handler::rebuild_gdd_cursor_future(
|
||||
gdd,
|
||||
store_handle,
|
||||
document_id,
|
||||
had_oracle,
|
||||
));
|
||||
true
|
||||
}
|
||||
|
||||
/// Swap in the interface rebuilt from the `Gdd` cursor (authoritative), preserving transient state the
|
||||
/// registry doesn't model (navigation metadata, resolved types) by copying it from the current live
|
||||
/// interface. When `had_oracle` is set (the legacy snapshot applied synchronously), debug builds compare
|
||||
/// the rebuilt network against the legacy-restored one and log drift before overwriting. Always
|
||||
/// overwrites: the `Gdd` cursor is the source of truth, including the across-reopen case where no legacy
|
||||
/// snapshot exists.
|
||||
pub(crate) fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, responses: &mut VecDeque<Message>) {
|
||||
// The registry models document content only, so the rebuilt interface has default view and selection
|
||||
// state. Carry the user's current view, selection, and resolved types from the live interface so undo
|
||||
// changes the document without moving the camera, clearing the selection, or jumping the node graph.
|
||||
rebuilt.copy_all_transient_view_state(&self.network_interface);
|
||||
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
|
||||
rebuilt.load_structure();
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
if had_oracle {
|
||||
self.compare_rebuild_against_legacy(&rebuilt);
|
||||
}
|
||||
|
||||
self.network_interface = rebuilt;
|
||||
|
||||
// The live `Gdd` cursor's registry should match a fresh `from_runtime` of the now-swapped interface.
|
||||
#[cfg(debug_assertions)]
|
||||
self.verify_storage_cursor_matches_runtime();
|
||||
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
responses.add(NodeGraphMessage::SelectedNodesUpdated);
|
||||
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::UnloadWires);
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
}
|
||||
|
||||
/// Debug-only: the rebuilt network should equal the legacy-restored one. Logs drift (does not panic) so
|
||||
/// cursor/conversion bugs surface in dev without crashing the live editor while the path hardens.
|
||||
#[cfg(debug_assertions)]
|
||||
fn compare_rebuild_against_legacy(&self, rebuilt: &NodeNetworkInterface) {
|
||||
let legacy = self.network_interface.document_network();
|
||||
let candidate = rebuilt.document_network();
|
||||
if candidate != legacy {
|
||||
log::error!("undo/redo rebuild diverged from the legacy snapshot\n{}", diff_networks(legacy, candidate));
|
||||
#[cfg(test)]
|
||||
panic!()
|
||||
}
|
||||
}
|
||||
|
||||
/// Debug-only: after a `Gdd` cursor move, the cursor's registry should equal a fresh `from_runtime`
|
||||
/// of the current (legacy-restored) interface. Logs drift (see the call site for why it does not
|
||||
/// panic) so cursor bugs surface in dev without crashing the editor.
|
||||
#[cfg(debug_assertions)]
|
||||
fn verify_storage_cursor_matches_runtime(&self) {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::StorageMetadataView;
|
||||
|
||||
let Some(storage) = &self.storage else { return };
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let network = self.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&self.network_interface);
|
||||
let Ok(mut conversion) = graph_storage::Registry::convert_from_runtime(&network, &view, &self.resources.registry, peer) else {
|
||||
log::error!("undo/redo shadow: from_runtime failed");
|
||||
return;
|
||||
};
|
||||
|
||||
let stored = storage.registry();
|
||||
|
||||
// The runtime keeps resources alive while they're referenced by undo/redo history (so legacy redo
|
||||
// can restore them), but the `Gdd` cursor reverts the interaction's `AddResource`. So a resource the
|
||||
// runtime carries which the cursor dropped is expected, not drift, as long as it's history-only
|
||||
// (not referenced by the current network). Drop those from the conversion before comparing.
|
||||
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
|
||||
conversion.registry.resources.retain(|id, _| stored.resources.contains_key(id) || current_resources.contains(id));
|
||||
|
||||
if !stored.value_equal(&conversion.registry) {
|
||||
// Logged, not panicked: any remaining drift is a real cursor or conversion bug to triage, but
|
||||
// the shadow must not crash the live editor while we harden it toward a hard panic.
|
||||
log::error!(
|
||||
"undo/redo shadow: cursor registry diverged from the restored interface\n{}",
|
||||
diff_registries(stored, &conversion.registry)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialize_document(&self) -> String {
|
||||
let val = serde_json::to_string(self);
|
||||
// We fully expect the serialization to succeed
|
||||
@@ -2152,13 +2549,23 @@ impl DocumentMessageHandler {
|
||||
paths
|
||||
}
|
||||
|
||||
pub fn undo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let Some(previous_network) = self.undo(viewport, responses) else { return };
|
||||
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
// Apply the legacy snapshot synchronously so its `VecDeque` stays consistent and can serve as the
|
||||
// rebuild's oracle. The `Gdd` cursor then moves + persists and spawns the async rebuild that becomes
|
||||
// authoritative, overwriting the live interface when it lands. When no legacy snapshot applied (e.g.
|
||||
// an across-reopen undo where the legacy stack is empty but the persisted `Gdd` cursor can still
|
||||
// move), the rebuild overwrites with no comparison.
|
||||
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
|
||||
self.document_redo_history.push_back(previous_network);
|
||||
if self.document_redo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
self.document_redo_history.pop_front();
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
self.document_redo_history.push_back(previous_network);
|
||||
if self.document_redo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
self.document_redo_history.pop_front();
|
||||
}
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, true, responses);
|
||||
}
|
||||
|
||||
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
@@ -2188,14 +2595,20 @@ impl DocumentMessageHandler {
|
||||
|
||||
Some(previous_network)
|
||||
}
|
||||
pub fn redo_with_history(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
// Push the UpdateOpenDocumentsList message to the queue in order to update the save status of the open documents
|
||||
let Some(previous_network) = self.redo(viewport, responses) else { return };
|
||||
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
// Mirror `undo_with_history`: apply the legacy snapshot synchronously (oracle), then move the `Gdd`
|
||||
// cursor and spawn the authoritative async rebuild.
|
||||
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
|
||||
self.document_undo_history.push_back(previous_network);
|
||||
if self.document_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
self.document_undo_history.pop_front();
|
||||
}
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
self.document_undo_history.push_back(previous_network);
|
||||
if self.document_undo_history.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
|
||||
self.document_undo_history.pop_front();
|
||||
}
|
||||
self.drive_storage_undo_redo(document_id, resource_storage, legacy_applied, false, responses);
|
||||
}
|
||||
|
||||
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
|
||||
@@ -3542,6 +3955,240 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
pub(crate) fn diff_registries(stored: &graph_storage::Registry, target: &graph_storage::Registry) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut out = String::new();
|
||||
|
||||
let stored_node_ids: std::collections::BTreeSet<_> = stored.node_instances.keys().copied().collect();
|
||||
let target_node_ids: std::collections::BTreeSet<_> = target.node_instances.keys().copied().collect();
|
||||
let missing_nodes: Vec<_> = target_node_ids.difference(&stored_node_ids).collect();
|
||||
let extra_nodes: Vec<_> = stored_node_ids.difference(&target_node_ids).collect();
|
||||
let shared_node_diffs: Vec<_> = stored_node_ids
|
||||
.intersection(&target_node_ids)
|
||||
.filter(|id| !stored.node_instances[id].value_equal(&target.node_instances[id]))
|
||||
.collect();
|
||||
|
||||
let stored_network_ids: std::collections::BTreeSet<_> = stored.networks.keys().copied().collect();
|
||||
let target_network_ids: std::collections::BTreeSet<_> = target.networks.keys().copied().collect();
|
||||
let missing_networks: Vec<_> = target_network_ids.difference(&stored_network_ids).collect();
|
||||
let extra_networks: Vec<_> = stored_network_ids.difference(&target_network_ids).collect();
|
||||
let shared_network_diffs: Vec<_> = stored_network_ids
|
||||
.intersection(&target_network_ids)
|
||||
.filter(|id| !stored.networks[id].value_equal(&target.networks[id]))
|
||||
.collect();
|
||||
|
||||
let _ = writeln!(out, " nodes: stored={} target={}", stored_node_ids.len(), target_node_ids.len());
|
||||
if !missing_nodes.is_empty() {
|
||||
let _ = writeln!(out, " missing from stored: {missing_nodes:?}");
|
||||
}
|
||||
if !extra_nodes.is_empty() {
|
||||
let _ = writeln!(out, " extra in stored: {extra_nodes:?}");
|
||||
}
|
||||
if !shared_node_diffs.is_empty() {
|
||||
let _ = writeln!(out, " differing payloads: {shared_node_diffs:?}");
|
||||
for id in &shared_node_diffs {
|
||||
let stored_node = &stored.node_instances[id];
|
||||
let target_node = &target.node_instances[id];
|
||||
let _ = writeln!(out, " node {id}:");
|
||||
diff_node(&mut out, stored_node, target_node);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = writeln!(out, " networks: stored={} target={}", stored_network_ids.len(), target_network_ids.len());
|
||||
if !missing_networks.is_empty() {
|
||||
let _ = writeln!(out, " missing from stored: {missing_networks:?}");
|
||||
}
|
||||
if !extra_networks.is_empty() {
|
||||
let _ = writeln!(out, " extra in stored: {extra_networks:?}");
|
||||
}
|
||||
if !shared_network_diffs.is_empty() {
|
||||
let _ = writeln!(out, " differing payloads: {shared_network_diffs:?}");
|
||||
for id in &shared_network_diffs {
|
||||
let stored_network = &stored.networks[id];
|
||||
let target_network = &target.networks[id];
|
||||
let _ = writeln!(out, " network {id}:");
|
||||
diff_network(&mut out, stored_network, target_network);
|
||||
}
|
||||
}
|
||||
|
||||
let stored_resources: std::collections::BTreeSet<_> = stored.resources.keys().copied().collect();
|
||||
let target_resources: std::collections::BTreeSet<_> = target.resources.keys().copied().collect();
|
||||
let missing_resources: Vec<_> = target_resources.difference(&stored_resources).collect();
|
||||
let extra_resources: Vec<_> = stored_resources.difference(&target_resources).collect();
|
||||
if !missing_resources.is_empty() || !extra_resources.is_empty() {
|
||||
let _ = writeln!(out, " resources: stored={} target={}", stored_resources.len(), target_resources.len());
|
||||
if !missing_resources.is_empty() {
|
||||
let _ = writeln!(out, " missing from stored: {missing_resources:?}");
|
||||
}
|
||||
if !extra_resources.is_empty() {
|
||||
let _ = writeln!(out, " extra in stored: {extra_resources:?}");
|
||||
}
|
||||
}
|
||||
|
||||
if stored.attributes != target.attributes {
|
||||
let stored_keys: std::collections::BTreeSet<_> = stored.attributes.keys().collect();
|
||||
let target_keys: std::collections::BTreeSet<_> = target.attributes.keys().collect();
|
||||
let _ = writeln!(out, " document attributes differ: stored_keys={stored_keys:?} target_keys={target_keys:?}");
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn diff_node(out: &mut String, stored: &graph_storage::Node, target: &graph_storage::Node) {
|
||||
use std::fmt::Write;
|
||||
|
||||
if stored.implementation() != target.implementation() {
|
||||
let _ = writeln!(out, " implementation: stored={:?} target={:?}", stored.implementation(), target.implementation());
|
||||
}
|
||||
if stored.network() != target.network() {
|
||||
let _ = writeln!(out, " network back-pointer: stored={} target={}", stored.network(), target.network());
|
||||
}
|
||||
|
||||
let stored_inputs = stored.inputs();
|
||||
let target_inputs = target.inputs();
|
||||
if stored_inputs.len() != target_inputs.len() {
|
||||
let _ = writeln!(out, " inputs.len: stored={} target={}", stored_inputs.len(), target_inputs.len());
|
||||
}
|
||||
for (i, (s, t)) in stored_inputs.iter().zip(target_inputs.iter()).enumerate() {
|
||||
if s != t {
|
||||
let value_differs = s.input != t.input;
|
||||
let timestamp_differs = s.timestamp != t.timestamp;
|
||||
let _ = writeln!(out, " input[{i}]: value_differs={value_differs} timestamp_differs={timestamp_differs}");
|
||||
if value_differs {
|
||||
let _ = writeln!(out, " stored.value={:?}\n target.value={:?}", s.input, t.input);
|
||||
}
|
||||
if s.attributes != t.attributes {
|
||||
diff_attributes(out, &format!(" input[{i}].attributes"), &s.attributes, &t.attributes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if stored.attributes() != target.attributes() {
|
||||
diff_attributes(out, " attributes", stored.attributes(), target.attributes());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn diff_network(out: &mut String, stored: &graph_storage::Network, target: &graph_storage::Network) {
|
||||
use std::fmt::Write;
|
||||
|
||||
if stored.exports.len() != target.exports.len() {
|
||||
let _ = writeln!(out, " exports.len: stored={} target={}", stored.exports.len(), target.exports.len());
|
||||
}
|
||||
for (i, (s, t)) in stored.exports.iter().zip(target.exports.iter()).enumerate() {
|
||||
if s != t {
|
||||
let target_differs = s.target != t.target;
|
||||
let timestamp_differs = s.timestamp != t.timestamp;
|
||||
let _ = writeln!(out, " export[{i}]: target_differs={target_differs} timestamp_differs={timestamp_differs}");
|
||||
if target_differs {
|
||||
let _ = writeln!(out, " stored.target={:?}\n target.target={:?}", s.target, t.target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if stored.attributes != target.attributes {
|
||||
diff_attributes(out, " attributes", &stored.attributes, &target.attributes);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
fn diff_attributes(out: &mut String, label: &str, stored: &graph_storage::Attributes, target: &graph_storage::Attributes) {
|
||||
use std::fmt::Write;
|
||||
|
||||
let stored_keys: std::collections::BTreeSet<_> = stored.keys().collect();
|
||||
let target_keys: std::collections::BTreeSet<_> = target.keys().collect();
|
||||
let missing: Vec<_> = target_keys.difference(&stored_keys).collect();
|
||||
let extra: Vec<_> = stored_keys.difference(&target_keys).collect();
|
||||
let differing: Vec<_> = stored_keys.intersection(&target_keys).filter(|k| stored.get(**k) != target.get(**k)).collect();
|
||||
|
||||
let _ = writeln!(out, "{label}: missing_from_stored={missing:?} extra_in_stored={extra:?} differing_values={differing:?}");
|
||||
}
|
||||
|
||||
/// Human-readable summary of how two networks differ (exports, node set, per-node payloads, scope
|
||||
/// injections). Used by the debug-only `verify_storage_round_trip` and by compare-on-open, which runs
|
||||
/// in release too, so this is not debug-gated.
|
||||
pub(crate) fn diff_networks(expected: &graph_craft::document::NodeNetwork, actual: &graph_craft::document::NodeNetwork) -> String {
|
||||
use std::fmt::Write;
|
||||
let mut out = String::new();
|
||||
|
||||
if expected.exports != actual.exports {
|
||||
let _ = writeln!(out, " exports differ: expected={} actual={}", expected.exports.len(), actual.exports.len());
|
||||
for (i, (exp, act)) in expected.exports.iter().zip(actual.exports.iter()).enumerate() {
|
||||
if exp != act {
|
||||
let _ = writeln!(out, " [{i}] expected={exp:?}\n actual= {act:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let expected_ids: std::collections::BTreeSet<_> = expected.nodes.keys().copied().collect();
|
||||
let actual_ids: std::collections::BTreeSet<_> = actual.nodes.keys().copied().collect();
|
||||
let missing: Vec<_> = expected_ids.difference(&actual_ids).collect();
|
||||
let extra: Vec<_> = actual_ids.difference(&expected_ids).collect();
|
||||
let differing: Vec<_> = expected_ids.intersection(&actual_ids).filter(|id| expected.nodes.get(id) != actual.nodes.get(id)).collect();
|
||||
|
||||
if !missing.is_empty() || !extra.is_empty() || !differing.is_empty() {
|
||||
let _ = writeln!(out, " nodes: expected={} actual={}", expected_ids.len(), actual_ids.len());
|
||||
if !missing.is_empty() {
|
||||
let _ = writeln!(out, " missing from actual: {missing:?}");
|
||||
}
|
||||
if !extra.is_empty() {
|
||||
let _ = writeln!(out, " extra in actual: {extra:?}");
|
||||
}
|
||||
if !differing.is_empty() {
|
||||
let _ = writeln!(out, " differing payloads: {differing:?}");
|
||||
for id in &differing {
|
||||
if let (Some(exp), Some(act)) = (expected.nodes.get(id), actual.nodes.get(id)) {
|
||||
let _ = writeln!(out, " node {id}:");
|
||||
diff_document_node(&mut out, exp, act);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if expected.scope_injections != actual.scope_injections {
|
||||
let _ = writeln!(out, " scope_injections differ");
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Field-level diff between two runtime `DocumentNode`s with the same ID, so the compare-on-open log
|
||||
/// names *which* field diverged rather than just the node ID. `original_location` is `#[serde(skip)]`
|
||||
/// and recomputed at load, so it's a likely culprit for a payload mismatch that doesn't affect behavior.
|
||||
fn diff_document_node(out: &mut String, expected: &graph_craft::document::DocumentNode, actual: &graph_craft::document::DocumentNode) {
|
||||
use std::fmt::Write;
|
||||
|
||||
if expected.inputs != actual.inputs {
|
||||
let _ = writeln!(out, " inputs differ (len expected={} actual={})", expected.inputs.len(), actual.inputs.len());
|
||||
for (i, (e, a)) in expected.inputs.iter().zip(actual.inputs.iter()).enumerate() {
|
||||
if e != a {
|
||||
let _ = writeln!(out, " input[{i}]: expected={e:?}\n actual= {a:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if expected.call_argument != actual.call_argument {
|
||||
let _ = writeln!(out, " call_argument: expected={:?} actual={:?}", expected.call_argument, actual.call_argument);
|
||||
}
|
||||
if expected.implementation != actual.implementation {
|
||||
let _ = writeln!(out, " implementation: expected={:?} actual={:?}", expected.implementation, actual.implementation);
|
||||
}
|
||||
if expected.visible != actual.visible {
|
||||
let _ = writeln!(out, " visible: expected={} actual={}", expected.visible, actual.visible);
|
||||
}
|
||||
if expected.skip_deduplication != actual.skip_deduplication {
|
||||
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
|
||||
}
|
||||
if expected.context_features != actual.context_features {
|
||||
let _ = writeln!(out, " context_features: expected={:?} actual={:?}", expected.context_features, actual.context_features);
|
||||
}
|
||||
if expected.original_location != actual.original_location {
|
||||
let _ = writeln!(out, " original_location differs (recomputed at load, not stored):");
|
||||
let _ = writeln!(out, " expected={:?}\n actual= {:?}", expected.original_location, actual.original_location);
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a network interface with a single export
|
||||
fn default_document_network_interface() -> NodeNetworkInterface {
|
||||
let mut network_interface = NodeNetworkInterface::default();
|
||||
@@ -3908,6 +4555,37 @@ mod document_message_handler_tests {
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
assert!(true, "Application didn't crash after folder move operation");
|
||||
}
|
||||
|
||||
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
|
||||
// Inspecting it via the Data panel (which splices in a monitor node) must not leave a dangling reference that crashes compilation.
|
||||
#[tokio::test]
|
||||
async fn merge_selected_nodes_while_inspecting_does_not_crash() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let node_a = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let node_b = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_a, node_b] }).await;
|
||||
editor.handle_message(NodeGraphMessage::MergeSelectedNodes).await;
|
||||
|
||||
let merged = editor.active_document().network_interface.selected_nodes_in_nested_network(&[]).unwrap().0.clone();
|
||||
assert_eq!(merged.len(), 1, "merge should leave one encapsulating node selected");
|
||||
|
||||
// Simulate the Data panel inspecting the merged node, which compiles the graph with a monitor node spliced in
|
||||
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
portfolio
|
||||
.executor
|
||||
.submit_node_graph_evaluation(document, document_id, glam::UVec2::ONE, 1., Default::default(), merged, true, DVec2::ZERO)
|
||||
.unwrap();
|
||||
editor.runtime.run().await;
|
||||
|
||||
let mut messages = VecDeque::new();
|
||||
editor.editor.poll_node_graph_evaluation(&mut messages).unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_moving_folder_with_children() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
+8
-7
@@ -11,7 +11,6 @@ use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::descriptor;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::convert_usvg_path::convert_usvg_path;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::style::{Fill, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientType, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
@@ -684,7 +683,6 @@ fn import_usvg_node_inner(
|
||||
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
|
||||
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
let subpaths = convert_usvg_path(path);
|
||||
let bounds = subpaths.iter().filter_map(|subpath| subpath.bounding_box()).reduce(Quad::combine_bounds).unwrap_or_default();
|
||||
|
||||
// Skip creating a Transform node entirely when the SVG-native transform is identity.
|
||||
let node_transform = usvg_transform(node.abs_transform());
|
||||
@@ -697,8 +695,7 @@ fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
}
|
||||
|
||||
if let Some(fill) = path.fill() {
|
||||
let bounds_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
apply_usvg_fill(fill, modify_inputs, bounds_transform, graphite_gradient_stops);
|
||||
apply_usvg_fill(fill, modify_inputs, graphite_gradient_stops);
|
||||
}
|
||||
if let Some(stroke) = path.stroke() {
|
||||
apply_usvg_stroke(stroke, modify_inputs, node_transform);
|
||||
@@ -797,14 +794,13 @@ fn convert_spread_method(spread_method: usvg::SpreadMethod) -> GradientSpreadMet
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, bounds_transform: DAffine2, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, graphite_gradient_stops: &HashMap<String, GradientStops>) {
|
||||
modify_inputs.fill_set(match &fill.paint() {
|
||||
usvg::Paint::Color(color) => Fill::solid(usvg_color(*color, fill.opacity().get())),
|
||||
usvg::Paint::LinearGradient(linear) => {
|
||||
let gradient_transform = usvg_transform(linear.transform());
|
||||
let (start, end) = (DVec2::new(linear.x1() as f64, linear.y1() as f64), DVec2::new(linear.x2() as f64, linear.y2() as f64));
|
||||
let (start, end) = (gradient_transform.transform_point2(start), gradient_transform.transform_point2(end));
|
||||
let (start, end) = (bounds_transform.inverse().transform_point2(start), bounds_transform.inverse().transform_point2(end));
|
||||
|
||||
let gradient_type = GradientType::Linear;
|
||||
|
||||
@@ -827,6 +823,9 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
|
||||
gradient_type,
|
||||
stops,
|
||||
spread_method,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
})
|
||||
}
|
||||
usvg::Paint::RadialGradient(radial) => {
|
||||
@@ -834,7 +833,6 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
|
||||
let center = DVec2::new(radial.cx() as f64, radial.cy() as f64);
|
||||
let edge = center + DVec2::X * radial.r().get() as f64;
|
||||
let (start, end) = (gradient_transform.transform_point2(center), gradient_transform.transform_point2(edge));
|
||||
let (start, end) = (bounds_transform.inverse().transform_point2(start), bounds_transform.inverse().transform_point2(end));
|
||||
|
||||
let gradient_type = GradientType::Radial;
|
||||
|
||||
@@ -857,6 +855,9 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, b
|
||||
gradient_type,
|
||||
stops,
|
||||
spread_method,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
})
|
||||
}
|
||||
usvg::Paint::Pattern(_) => {
|
||||
|
||||
@@ -259,15 +259,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
Some(NodeInput::value(TaggedValue::Resource(font_resource_id), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.font_size), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.line_height_ratio), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.character_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_spacing), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.letter_tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_width.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_width.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(typesetting.max_height.is_some()), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.max_height.unwrap_or(100.)), false)),
|
||||
Some(NodeInput::value(TaggedValue::F64(typesetting.tilt), false)),
|
||||
Some(NodeInput::value(TaggedValue::TextAlign(typesetting.align), false)),
|
||||
Some(NodeInput::value(TaggedValue::Bool(false), false)),
|
||||
]);
|
||||
let text_to_vector = resolve_proto_node_type(graphene_std::text::text_to_vector::IDENTIFIER)
|
||||
.expect("Text to Vector node does not exist")
|
||||
.default_node_template();
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
@@ -275,12 +277,17 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
|
||||
// Build the chain `Text -> Text to Vector -> Transform -> Fill -> layer`
|
||||
let text_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_id, text, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_id, layer, &[], self.import);
|
||||
|
||||
self.responses.add(DocumentMessage::Resource(ResourceMessage::AddFont { resource_id: font_resource_id, font }));
|
||||
|
||||
let text_to_vector_id = NodeId::new();
|
||||
self.network_interface.insert_node(text_to_vector_id, text_to_vector, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&text_to_vector_id, layer, &[], self.import);
|
||||
|
||||
let transform_id = NodeId::new();
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
mod document_message;
|
||||
mod document_message_handler;
|
||||
#[cfg(test)]
|
||||
mod storage_round_trip_tests;
|
||||
|
||||
pub mod data_panel;
|
||||
pub mod graph_operation;
|
||||
@@ -12,5 +14,6 @@ pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
|
||||
pub(crate) use document_message_handler::diff_networks;
|
||||
#[doc(inline)]
|
||||
pub use document_message_handler::{DocumentMessageContext, DocumentMessageHandler};
|
||||
@@ -8,7 +8,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
DocumentNodeMetadata, DocumentNodePersistentMetadata, InputMetadata, NodeNetworkInterface, NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodeTemplate, NodeTypePersistentMetadata,
|
||||
Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::prelude::{FontsMessageHandler, Message, ResourceMessageHandler};
|
||||
use crate::messages::prelude::{FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
@@ -922,7 +922,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::scope("editor-api"), NodeInput::import(concrete!(String), 1)],
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(concrete!(String), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -1249,22 +1249,17 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::scope("editor-api")],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::IntoNode<&WgpuExecutor>")),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
inputs: vec![NodeInput::import(concrete!(List<Raster<CPU>>), 0), NodeInput::node(NodeId(0), 0)],
|
||||
inputs: vec![NodeInput::import(concrete!(List<Raster<CPU>>), 0), NodeInput::scope(platform_application_io::wgpu_executor::IDENTIFIER)],
|
||||
call_argument: generic!(T),
|
||||
implementation: DocumentNodeImplementation::ProtoNode(wgpu_executor::texture_conversion::upload_texture::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(memo::memoize::IDENTIFIER),
|
||||
..Default::default()
|
||||
},
|
||||
@@ -2047,6 +2042,10 @@ fn static_input_properties() -> InputProperties {
|
||||
map.insert(
|
||||
"text_font".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
// Lazily load the font catalog (like the Text tool) so the dropdown has entries
|
||||
if context.fonts.font_catalog.is_empty() {
|
||||
context.responses.add(FontsMessage::LoadCatalog);
|
||||
}
|
||||
let (font, style) = node_properties::font_inputs(ParameterWidgetsInfo::new(node_id, index, true, context));
|
||||
let mut result = vec![LayoutGroup::row(font)];
|
||||
if let Some(style) = style {
|
||||
|
||||
@@ -292,9 +292,21 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
return;
|
||||
};
|
||||
|
||||
let node_template = document_node_type.default_node_template();
|
||||
let mut node_template = document_node_type.default_node_template();
|
||||
self.context_menu = None;
|
||||
|
||||
// A freshly added Text node carries no font, so give it the default font (registered like the Text tool does)
|
||||
if node_type == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) {
|
||||
let font_resource_id = graph_craft::application_io::resource::ResourceId::new();
|
||||
if let Some(font_input) = node_template.document_node.inputs.get_mut(graphene_std::text::text::FontInput::INDEX) {
|
||||
*font_input = NodeInput::value(TaggedValue::Resource(font_resource_id), false);
|
||||
}
|
||||
responses.add(DocumentMessage::Resource(ResourceMessage::AddFont {
|
||||
resource_id: font_resource_id,
|
||||
font: graphene_std::text::Font::default(),
|
||||
}));
|
||||
}
|
||||
|
||||
if add_transaction {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
@@ -838,11 +850,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let currently_is_node = !network_interface.is_layer(&node_id, breadcrumb_network_path);
|
||||
let can_be_layer = network_interface.is_eligible_to_be_layer(&node_id, breadcrumb_network_path);
|
||||
|
||||
let selected_nodes = network_interface.selected_nodes_in_nested_network(selection_network_path);
|
||||
let is_clicked_selected = selected_nodes.as_ref().is_some_and(|selected| selected.selected_nodes().any(|id| *id == node_id));
|
||||
|
||||
// Right-clicking an unselected node selects just it, so selection-based actions like Merge Selected Nodes target it
|
||||
if !is_clicked_selected {
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
}
|
||||
|
||||
// Determine which layers the Lock/Unlock action would affect:
|
||||
// - If the right-clicked node is in the selection, it affects all selected layers
|
||||
// - If the right-clicked node is not in the selection, it affects just the right-clicked node
|
||||
let selected_nodes = network_interface.selected_nodes_in_nested_network(selection_network_path);
|
||||
let is_clicked_selected = selected_nodes.as_ref().is_some_and(|selected| selected.selected_nodes().any(|id| *id == node_id));
|
||||
let affected_layer_ids = if is_clicked_selected {
|
||||
selected_nodes.map(|selected| selected.selected_nodes().copied().filter(|id| network_interface.is_layer(id, selection_network_path)).collect())
|
||||
} else {
|
||||
|
||||
@@ -856,8 +856,13 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
return (vec![], None);
|
||||
};
|
||||
|
||||
if let Some(TaggedValue::Resource(resource_id)) = input.as_non_exposed_value() {
|
||||
let font = fonts.id_font(resources, *resource_id).unwrap_or_default();
|
||||
// A freshly added node carries the empty-resource `TypeDefault` placeholder until a font is chosen
|
||||
let font = match input.as_non_exposed_value() {
|
||||
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
|
||||
Some(TaggedValue::TypeDefault(_)) => Font::default(),
|
||||
_ => return (first_widgets, second_widgets),
|
||||
};
|
||||
{
|
||||
first_widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(vec![
|
||||
|
||||
@@ -228,10 +228,10 @@ pub fn text_width(text: &str, font_size: f64) -> f64 {
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size,
|
||||
line_height_ratio: 1.2,
|
||||
character_spacing: 0.,
|
||||
letter_spacing: 0.,
|
||||
letter_tilt: 0.,
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
tilt: 0.,
|
||||
align: TextAlign::AlignLeft,
|
||||
};
|
||||
|
||||
|
||||
@@ -1109,10 +1109,10 @@ impl OverlayContextInternal {
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size: FONT_SIZE,
|
||||
line_height_ratio: 1.2,
|
||||
character_spacing: 0.,
|
||||
letter_spacing: 0.,
|
||||
letter_tilt: 0.,
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
tilt: 0.,
|
||||
align: TextAlign::AlignLeft,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,783 @@
|
||||
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
|
||||
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
|
||||
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
|
||||
//! MessagePack codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
|
||||
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
use graph_storage::{NodeMetadataSource, PeerId};
|
||||
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{DocumentSettings, StorageMetadataView, build_interface_from_storage};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
/// Result of round-tripping a document through a `Gdd`: the runtime interface rebuilt from the
|
||||
/// reopened storage, the reopened registry, and the reopened per-peer view settings (`ui::doc::*`).
|
||||
struct RoundTrip {
|
||||
rebuilt: NodeNetworkInterface,
|
||||
registry: graph_storage::Registry,
|
||||
view_settings: std::collections::BTreeMap<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
/// Push `document`'s current runtime state through a fresh in-memory `Gdd` and reopen it. The commit
|
||||
/// goes through `commit_from_runtime` (the real autosave path: stage hot ops → retire → persist);
|
||||
/// the reopen reads the working copy back from the same container bytes, so the whole codec / file
|
||||
/// / replay pipeline is exercised, not just the in-memory conversion.
|
||||
async fn round_trip_through_gdd(document: &DocumentMessageHandler) -> RoundTrip {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
gdd.commit_from_runtime(&network, &view, &document.resources.registry, &byte_store).expect("commit_from_runtime");
|
||||
|
||||
// Per-peer view settings persist in session.json, separate from the registry commit.
|
||||
let view_settings = DocumentSettings {
|
||||
document_ptz: &document.document_ptz,
|
||||
render_mode: &document.render_mode,
|
||||
overlays_visibility: &document.overlays_visibility_settings,
|
||||
rulers_visible: document.rulers_visible,
|
||||
snapping_state: &document.snapping_state,
|
||||
collapsed: &document.collapsed,
|
||||
}
|
||||
.to_view_map();
|
||||
gdd.set_view_settings(view_settings).expect("set_view_settings");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
|
||||
let declarations = reopened.declarations(&byte_store).await;
|
||||
let registry = reopened.registry().clone();
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata");
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
|
||||
let view_settings = reopened.view_settings().clone();
|
||||
|
||||
RoundTrip { rebuilt, registry, view_settings }
|
||||
}
|
||||
|
||||
/// Every node addressable in `original` resolves identically through the round-tripped interface:
|
||||
/// the compute graph itself, then per-node positions, layer flags, names, locked/pinned.
|
||||
fn assert_documents_match(original: &NodeNetworkInterface, round_trip: &RoundTrip) {
|
||||
let original_view = StorageMetadataView::new(original);
|
||||
let rebuilt_view = StorageMetadataView::new(&round_trip.rebuilt);
|
||||
|
||||
assert_eq!(
|
||||
round_trip.rebuilt.document_network(),
|
||||
original.document_network(),
|
||||
"compute graph drifted through the storage round-trip"
|
||||
);
|
||||
|
||||
for (network_path, local_id) in node_paths(original) {
|
||||
let at = format!("node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(rebuilt_view.position(&network_path, local_id), original_view.position(&network_path, local_id), "position: {at}");
|
||||
assert_eq!(rebuilt_view.is_layer(&network_path, local_id), original_view.is_layer(&network_path, local_id), "is_layer: {at}");
|
||||
assert_eq!(
|
||||
rebuilt_view.display_name(&network_path, local_id),
|
||||
original_view.display_name(&network_path, local_id),
|
||||
"display_name: {at}"
|
||||
);
|
||||
assert_eq!(rebuilt_view.locked(&network_path, local_id), original_view.locked(&network_path, local_id), "locked: {at}");
|
||||
assert_eq!(rebuilt_view.pinned(&network_path, local_id), original_view.pinned(&network_path, local_id), "pinned: {at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk every node in every nested network, collecting `(network_path, local_id)` pairs.
|
||||
fn node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
||||
fn walk(interface: &NodeNetworkInterface, path: Vec<NodeId>, out: &mut Vec<(Vec<NodeId>, NodeId)>) {
|
||||
let Some(network) = interface.nested_network(&path) else { return };
|
||||
for (&local_id, node) in &network.nodes {
|
||||
out.push((path.clone(), local_id));
|
||||
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
|
||||
let mut child = path.clone();
|
||||
child.push(local_id);
|
||||
walk(interface, child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(interface, Vec::new(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn round_trip_drawn_shapes() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 200., 300., 400.).await;
|
||||
editor.draw_ellipse(120., 220., 280., 380.).await;
|
||||
editor.draw_polygon(50., 60., 250., 360.).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let round_trip = round_trip_through_gdd(document).await;
|
||||
assert_documents_match(&document.network_interface, &round_trip);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn round_trip_after_reorder() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_rect(50., 50., 150., 150.).await;
|
||||
editor.draw_rect(100., 100., 200., 200.).await;
|
||||
|
||||
// Reorder: raise the bottom layer so the layer stack differs from creation order.
|
||||
let bottom = editor.active_document().metadata().all_layers().next_back().expect("at least one layer");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![bottom.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::SelectedLayersRaise).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let round_trip = round_trip_through_gdd(document).await;
|
||||
assert_documents_match(&document.network_interface, &round_trip);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn round_trip_grouped_into_nested_network() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
|
||||
// Group both layers into a folder (a nested network), exercising flat-Registry addressing across
|
||||
// depth and `NetworkId` round-tripping.
|
||||
let layers: Vec<_> = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let round_trip = round_trip_through_gdd(document).await;
|
||||
assert_documents_match(&document.network_interface, &round_trip);
|
||||
}
|
||||
|
||||
/// Reproduces the first-commit-after-open failure: after reopening a `.gdd` and rebuilding the
|
||||
/// runtime, re-converting that runtime with `from_runtime` must reproduce the reopened registry.
|
||||
/// This is exactly what `verify_storage_round_trip` does on the first autosave after opening a `.gdd`.
|
||||
/// Uses a grouped document (nested network) because the bug is `from_runtime` assigning `NetworkId`s
|
||||
/// by traversal order rather than reproducing the stored ones, which cascades into node-path hashes.
|
||||
#[tokio::test]
|
||||
async fn recommit_after_open_is_stable() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
|
||||
let layers: Vec<_> = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let round_trip = round_trip_through_gdd(document).await;
|
||||
|
||||
// Re-convert the rebuilt runtime and assert it reproduces the reopened registry. `round_trip_through_gdd`
|
||||
// builds the `Gdd` with `PeerId(1)`, which the reopened registry inherits, so the re-conversion must
|
||||
// use that same peer for deterministic node-ID derivation. (`ui::doc::*` settings live in session.json,
|
||||
// not the registry, so they don't participate in this comparison.)
|
||||
let rebuilt_network = round_trip.rebuilt.document_network().clone();
|
||||
let view = StorageMetadataView::new(&round_trip.rebuilt);
|
||||
let reconverted = graph_storage::Registry::convert_from_runtime(&rebuilt_network, &view, &Default::default(), PeerId(1)).expect("re-convert from_runtime");
|
||||
|
||||
assert!(
|
||||
round_trip.registry.value_equal(&reconverted.registry),
|
||||
"re-converting the reopened runtime drifted from the reopened registry (network/node IDs not stable across to_runtime -> from_runtime)\n{}",
|
||||
crate::messages::portfolio::document::document_message_handler::diff_registries(&round_trip.registry, &reconverted.registry)
|
||||
);
|
||||
}
|
||||
|
||||
/// Reproduces the live "edit after opening a .gdd fails to commit" bug: build a grouped document,
|
||||
/// persist + reopen it as the editor does (registry -> runtime), then edit and commit through the
|
||||
/// reopened document. The commit must not fail with "Target node does not exist".
|
||||
#[tokio::test]
|
||||
async fn edit_after_open_commits_cleanly() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
|
||||
let layers: Vec<_> = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
|
||||
editor
|
||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType::Layer,
|
||||
})
|
||||
.await;
|
||||
|
||||
// Persist the document into a fresh Gdd and reopen it, then build a runtime document from the
|
||||
// reopened registry — the editor's .gdd-open path.
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let source = editor.active_document();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let source_network = source.network_interface.document_network().clone();
|
||||
let source_view = StorageMetadataView::new(&source.network_interface);
|
||||
gdd.commit_from_runtime(&source_network, &source_view, &source.resources.registry, &byte_store)
|
||||
.expect("commit_from_runtime");
|
||||
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
|
||||
let declarations = reopened.declarations(&byte_store).await;
|
||||
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).expect("to_runtime");
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage");
|
||||
|
||||
// Install the rebuilt interface + reopened storage and finalize like the editor's open path does.
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.network_interface = rebuilt;
|
||||
document.storage = Some(reopened);
|
||||
document.finalize_storage_load();
|
||||
}
|
||||
|
||||
// Mirror the live sequence via the real `commit_storage_snapshot` (which uses the full document-
|
||||
// settings view + the document's own resource registry, and runs `verify_storage_round_trip` in
|
||||
// debug — panicking on any drift). Initial commit after open, then a deletion, then commit again.
|
||||
// Deletion (not addition) is the trigger: it emits a `RemoveNode` whose retire/reverse is where
|
||||
// "Target node does not exist" surfaced live.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("at least one layer");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::DeleteSelectedLayers).await;
|
||||
|
||||
// `commit_storage_snapshot` only logs commit failures, so assert on the underlying `commit_from_runtime`
|
||||
// result directly to make the deletion commit a hard test failure rather than a silent log line.
|
||||
let document = editor.active_document_mut();
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
document
|
||||
.storage
|
||||
.as_mut()
|
||||
.expect("storage mounted")
|
||||
.commit_from_runtime(&network, &view, &Default::default(), &byte_store)
|
||||
.expect("commit after deleting a layer post-open must not fail");
|
||||
}
|
||||
|
||||
/// Drives the per-interaction undo/redo cursor: commit two interactions into a `Gdd`, then undo back to the
|
||||
/// one-interaction state and redo forward, asserting the registry's node set matches at each cursor
|
||||
/// position. Exercises `Gdd::commit_from_runtime` (inline interaction-end mark) + `Session::undo/redo`.
|
||||
#[tokio::test]
|
||||
async fn gdd_undo_redo_walks_interactions() {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
|
||||
// Commit the active document's current runtime state as one interaction.
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
gdd.commit_from_runtime(&network, &view, &document.resources.registry, byte_store).expect("commit_from_runtime");
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
|
||||
let nodes_after_one: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
|
||||
let nodes_after_two: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
|
||||
assert!(nodes_after_two.len() > nodes_after_one.len(), "second interaction should add nodes");
|
||||
assert!(gdd.can_undo(), "two committed interactions should be undoable");
|
||||
assert!(!gdd.can_redo());
|
||||
|
||||
// Undo the second interaction: registry returns to the one-interaction node set.
|
||||
gdd.undo().expect("undo");
|
||||
let undone: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
assert_eq!(undone, nodes_after_one, "undo should restore the post-first-interaction node set");
|
||||
assert!(gdd.can_redo(), "after undo, redo must be available");
|
||||
|
||||
// Redo: back to the two-interaction state.
|
||||
gdd.redo().expect("redo");
|
||||
let redone: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
assert_eq!(redone, nodes_after_two, "redo should restore the post-second-interaction node set");
|
||||
|
||||
// A new edit after undo clears the redo stack.
|
||||
gdd.undo().expect("undo");
|
||||
editor.draw_rect(200., 200., 300., 300.).await;
|
||||
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
|
||||
assert!(!gdd.can_redo(), "a new edit after undo must abandon the redo branch");
|
||||
}
|
||||
|
||||
/// Reopen must restore the cursor *and* a working registry consistent with it. `Session::load` trusts
|
||||
/// the persisted `registry.bin` to match the persisted `head`, so an undo that rewinds the working
|
||||
/// registry has to re-snapshot it. Repro of the live "undo acts like redo after reload" bug: commit
|
||||
/// three interactions, undo one (registry at two), reopen, and assert the reopened registry is the
|
||||
/// two-interaction state (not the three-interaction state the last retirement wrote) and that undo from there
|
||||
/// still walks back to the one-interaction node set.
|
||||
#[tokio::test]
|
||||
async fn reopen_after_undo_restores_consistent_registry() {
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
|
||||
async fn commit_interaction(gdd: &mut GddV1, document: &DocumentMessageHandler, byte_store: &HashMapResourceStorage) {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
gdd.commit_from_runtime(&network, &view, &document.resources.registry, byte_store).expect("commit_from_runtime");
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
|
||||
let nodes_one: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
|
||||
let nodes_two: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
|
||||
editor.draw_rect(200., 200., 300., 300.).await;
|
||||
commit_interaction(&mut gdd, editor.active_document(), &byte_store).await;
|
||||
let nodes_three: std::collections::BTreeSet<_> = gdd.registry().node_instances.keys().copied().collect();
|
||||
|
||||
// Undo the third interaction: in-memory registry is now the two-interaction state and head moved back, but the
|
||||
// last retirement wrote the three-interaction registry to disk. The undo must re-snapshot it.
|
||||
gdd.undo().expect("undo");
|
||||
assert_eq!(gdd.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(), nodes_two);
|
||||
|
||||
// Reopen from the same container: the cursor and the working registry are read back from disk.
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let mut reopened = GddV1::open_in(working, layout).await.expect("open_in");
|
||||
|
||||
assert_eq!(
|
||||
reopened.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(),
|
||||
nodes_two,
|
||||
"reopened registry must match the undone (two-interaction) state, not the three-interaction state on disk"
|
||||
);
|
||||
assert!(reopened.can_undo(), "head is still above the first interaction, so undo is available after reopen");
|
||||
assert!(reopened.can_redo(), "the undone third interaction is still redoable after reopen");
|
||||
|
||||
// Redo after reopen: the persisted redo stack must still reach the three-interaction state (redo across
|
||||
// reopen must not be capped at the open point).
|
||||
reopened.redo().expect("redo after reopen");
|
||||
assert_eq!(
|
||||
reopened.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(),
|
||||
nodes_three,
|
||||
"redo after reopen must restore the third interaction, not stop at the reopened (two-interaction) state"
|
||||
);
|
||||
|
||||
// Undo twice from there: back through the third interaction to the one-interaction state, not a redo.
|
||||
reopened.undo().expect("first undo after reopen redo");
|
||||
reopened.undo().expect("second undo after reopen redo");
|
||||
assert_eq!(
|
||||
reopened.registry().node_instances.keys().copied().collect::<std::collections::BTreeSet<_>>(),
|
||||
nodes_one,
|
||||
"undo after reopen must rewind toward the one-interaction state, not act like a redo"
|
||||
);
|
||||
}
|
||||
|
||||
/// Drives the *live* shadow path: a real edit through the message pipeline (which fires
|
||||
/// `CommitTransaction`, committing one interaction into the `Gdd`), then a real `DocumentMessage::Undo`
|
||||
/// (which runs `shadow_storage_undo_redo` + the debug cursor-vs-runtime check). A clean run asserts
|
||||
/// the `Gdd` undo cursor reproduces the legacy-restored interface.
|
||||
#[tokio::test]
|
||||
async fn live_undo_shadows_storage_cursor() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_ellipse(50., 50., 150., 150.).await;
|
||||
assert_ne!(&before_edit, editor.active_document().network_interface.document_network(), "edit should change the network");
|
||||
|
||||
// Real undo: the shadow drives gdd.undo() and (debug) asserts the cursor matches the restored interface.
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &before_edit, "undo should restore the pre-edit network");
|
||||
|
||||
// Real redo: shadow drives gdd.redo() + checks again.
|
||||
editor.handle_message(DocumentMessage::Redo).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn round_trip_document_settings() {
|
||||
use graph_storage::attr::session::doc;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
// Set distinctive, non-default document-level settings so the round-trip proves real values move.
|
||||
{
|
||||
let document = editor.active_document_mut();
|
||||
document.render_mode = RenderMode::Outline;
|
||||
document.rulers_visible = false;
|
||||
document.snapping_state.snapping_enabled = !document.snapping_state.snapping_enabled;
|
||||
}
|
||||
|
||||
let document = editor.active_document();
|
||||
let round_trip = round_trip_through_gdd(document).await;
|
||||
assert_documents_match(&document.network_interface, &round_trip);
|
||||
|
||||
// The `ui::doc::*` view settings survived the persist/reopen cycle (in session.json, not the registry).
|
||||
let settings = &round_trip.view_settings;
|
||||
assert_eq!(settings.get(doc::RENDER_MODE), Some(&serde_json::to_value(RenderMode::Outline).unwrap()), "render_mode");
|
||||
assert_eq!(settings.get(doc::RULERS_VISIBLE), Some(&serde_json::to_value(false).unwrap()), "rulers_visible");
|
||||
assert_eq!(settings.get(doc::SNAPPING), Some(&serde_json::to_value(&document.snapping_state).unwrap()), "snapping_state");
|
||||
}
|
||||
|
||||
/// The exported `.gdd` archive must carry `session.json` so view settings (notably the document PTZ)
|
||||
/// survive a save/open on another machine. `session.json` is working-copy-only otherwise, so without it
|
||||
/// the archive opens with empty `view_settings` and the viewport resets to default. Exports to an archive
|
||||
/// and reopens via `open_from_archive`, asserting the PTZ round-trips.
|
||||
#[tokio::test]
|
||||
async fn gdd_archive_round_trips_view_settings() {
|
||||
use graph_storage::attr::session::doc;
|
||||
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
|
||||
// Stage a distinctive PTZ into the working copy's `view_settings`, as `commit_storage_snapshot` does.
|
||||
let mut ptz = crate::messages::portfolio::document::utility_types::misc::PTZ::default();
|
||||
ptz.pan = glam::DVec2::new(-960., -540.);
|
||||
ptz.set_zoom(0.459);
|
||||
let view_settings = std::collections::BTreeMap::from([(doc::PTZ.to_string(), serde_json::to_value(&ptz).unwrap())]);
|
||||
gdd.set_view_settings(view_settings).expect("set_view_settings");
|
||||
|
||||
// Export to an in-memory archive, then reopen it from bytes into a fresh container.
|
||||
let archive = gdd
|
||||
.export_to_bytes(document_format::ExportFormat::Zip, document_format::ExportOptions::default(), &byte_store, None)
|
||||
.await
|
||||
.expect("export_to_bytes");
|
||||
|
||||
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout)
|
||||
.await
|
||||
.expect("open_from_archive");
|
||||
|
||||
assert_eq!(
|
||||
reopened.view_settings().get(doc::PTZ),
|
||||
Some(&serde_json::to_value(&ptz).unwrap()),
|
||||
"the document PTZ must survive a .gdd archive export/open (session.json travels in the archive)"
|
||||
);
|
||||
}
|
||||
|
||||
/// Per-network node-graph navigation is per-peer view state: it must round-trip through `session.json`
|
||||
/// (keyed by stable `NetworkId`), not the registry/history. Sets a distinctive node-graph PTZ on the root
|
||||
/// network, persists + reopens through a `Gdd`, and asserts the nav is restored on the rebuilt interface
|
||||
/// while being absent from the stored registry's attributes.
|
||||
#[tokio::test]
|
||||
async fn per_network_navigation_round_trips_via_session_not_registry() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, collect_network_view_settings, network_ids_from_entries};
|
||||
use graph_storage::attr::session::network;
|
||||
|
||||
let byte_store = HashMapResourceStorage::new();
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
|
||||
// Set a distinctive node-graph PTZ on the root network (path `[]`).
|
||||
let ptz = editor.active_document_mut().network_interface.node_graph_ptz_mut(&[]).expect("root network ptz");
|
||||
ptz.pan = glam::DVec2::new(-321., 654.);
|
||||
ptz.set_zoom(0.75);
|
||||
let expected_pan = editor.active_document().network_interface.node_graph_ptz(&[]).unwrap().pan;
|
||||
|
||||
// Commit the document into a fresh `Gdd`, collecting the per-network view state the editor persists.
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0xABCD, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
let document = editor.active_document();
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
gdd.commit_from_runtime(&network, &view, &document.resources.registry, &byte_store).expect("commit_from_runtime");
|
||||
|
||||
let network_ids = gdd.network_ids(&network, &view).expect("network_ids");
|
||||
let network_view_settings = collect_network_view_settings(&document.network_interface, &network_ids);
|
||||
assert!(!network_view_settings.is_empty(), "the root network's non-default nav should be collected");
|
||||
gdd.set_network_view_settings(network_view_settings).expect("set_network_view_settings");
|
||||
|
||||
// The registry must NOT carry the node-graph nav (it's per-peer, not document content).
|
||||
let root_network = gdd.registry().networks.get(&graph_storage::ROOT_NETWORK).expect("root network in registry");
|
||||
assert!(root_network.attributes.get(network::NAV_PTZ).is_none(), "node-graph nav must not be stored in the registry attributes");
|
||||
|
||||
// Reopen, rebuild the interface, and apply the persisted per-network view state.
|
||||
let (working, layout) = gdd.into_storage();
|
||||
let reopened = GddV1::open_in(working, layout).await.expect("open_in");
|
||||
let declarations = reopened.declarations(&byte_store).await;
|
||||
let (rebuilt_network, node_entries, network_entries) = reopened.registry().to_runtime_with_full_metadata(&declarations).expect("to_runtime");
|
||||
let mut rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries.clone()).expect("build_interface_from_storage");
|
||||
|
||||
let reopened_ids = network_ids_from_entries(&network_entries);
|
||||
apply_network_view_settings(&mut rebuilt, &reopened_ids, reopened.network_view_settings());
|
||||
|
||||
assert_eq!(
|
||||
rebuilt.node_graph_ptz(&[]).map(|ptz| ptz.pan),
|
||||
Some(expected_pan),
|
||||
"the node-graph PTZ must be restored from session.json on reopen"
|
||||
);
|
||||
}
|
||||
|
||||
/// Mirror the real "new document, draw a rect, press undo" flow: mount storage and capture the
|
||||
/// new-document base as the mount-time snapshot (as `DocumentStorageMounted` does), then draw a rect
|
||||
/// (one `CommitTransaction` interaction) and undo. The shadow must reproduce the legacy-restored interface.
|
||||
#[tokio::test]
|
||||
async fn live_undo_new_document_draw_rect() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
// Mount-time snapshot: capture the new-document graph as the base interaction.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let before_rect = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
assert_ne!(&before_rect, editor.active_document().network_interface.document_network(), "drawing a rect should change the network");
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(editor.active_document().network_interface.document_network(), &before_rect, "undo should restore the pre-rect network");
|
||||
}
|
||||
|
||||
/// Pasting an image is one user action and must be one undo step. The paste handler emits a single
|
||||
/// `AddTransaction` bracketing the layer add, name set, reparent, and transform, so a single undo has
|
||||
/// to remove the whole layer. When the name set opens its own nested transaction (the historical
|
||||
/// wart), the first undo only reverts the name and leaves the layer behind, so this asserts the layer
|
||||
/// count returns to its pre-paste value after exactly one undo. Matches the `Gdd`'s one-interaction
|
||||
/// coalescing, which is the behavior the undo shadow validates against.
|
||||
#[tokio::test]
|
||||
async fn paste_image_with_name_is_one_undo_step() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let layers_before = editor.active_document().metadata().all_layers().count();
|
||||
|
||||
// Paste with a name so the handler emits the `SetDisplayName` sub-step that historically opened its
|
||||
// own transaction. `create_raster_image` passes `name: None` and so wouldn't exercise this path.
|
||||
let image = Image::new(2, 2, Color::WHITE);
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteImage {
|
||||
name: Some("pasted".into()),
|
||||
image,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
editor.active_document().metadata().all_layers().count(),
|
||||
layers_before + 1,
|
||||
"pasting an image should add exactly one layer"
|
||||
);
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(
|
||||
editor.active_document().metadata().all_layers().count(),
|
||||
layers_before,
|
||||
"one undo should remove the whole pasted layer, not just its name"
|
||||
);
|
||||
}
|
||||
|
||||
/// Pasting an image registers a resource; undoing the paste reverts the interaction's `AddResource` in the
|
||||
/// `Gdd` cursor while the runtime keeps the resource alive for legacy redo. So the cursor legitimately
|
||||
/// holds fewer resources than a fresh `from_runtime`, and the shadow must tolerate that. This drives
|
||||
/// the relaxed comparison: every resource the current network references must be present in the cursor,
|
||||
/// and any extra the runtime carries must be history-only (not referenced by the restored network).
|
||||
#[tokio::test]
|
||||
async fn undo_image_paste_resources_subset_of_runtime() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
let image = Image::new(2, 2, Color::WHITE);
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteImage {
|
||||
name: Some("pasted".into()),
|
||||
image,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let storage = document.storage.as_ref().expect("storage mounted");
|
||||
let stored: std::collections::BTreeSet<_> = storage.registry().resources.keys().copied().collect();
|
||||
|
||||
// Every resource the restored network still references must be in the cursor.
|
||||
let current: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
assert!(
|
||||
current.is_subset(&stored),
|
||||
"cursor is missing a resource the restored network references: current={current:?} stored={stored:?}"
|
||||
);
|
||||
|
||||
// The runtime, which retains the undone paste's resource for redo, may carry strictly more.
|
||||
let runtime: std::collections::BTreeSet<_> = document.resources.registry.ids().collect();
|
||||
assert!(stored.is_subset(&runtime), "cursor holds a resource the runtime dropped: stored={stored:?} runtime={runtime:?}");
|
||||
}
|
||||
|
||||
/// Two distinct edits (draw an ellipse, then paste an image) on an *opened* document are two undo
|
||||
/// steps. Undoing twice must step the `Gdd` cursor back two interactions in lockstep with the legacy
|
||||
/// snapshot path. The document is opened with existing content (a real demo artwork), so its non-empty
|
||||
/// base is the loaded state, which is *not* a legacy undo step. The mount-time base must therefore not
|
||||
/// become an undoable `Gdd` interaction, or the cursor gains one more interaction than the legacy path has undo
|
||||
/// steps and lags by a interaction once undo reaches back toward the base. Reproduces the live "open, draw,
|
||||
/// paste image, undo twice" divergence.
|
||||
#[tokio::test]
|
||||
async fn undo_twice_steps_cursor_two_interactions() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let base = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
editor.draw_rect(0., 0., 100., 100.).await;
|
||||
let after_rect = editor.active_document().network_interface.document_network().clone();
|
||||
|
||||
let image = Image::new(2, 2, Color::WHITE);
|
||||
editor
|
||||
.handle_message(PortfolioMessage::PasteImage {
|
||||
name: Some("pasted".into()),
|
||||
image,
|
||||
mouse: None,
|
||||
parent_and_insert_index: None,
|
||||
})
|
||||
.await;
|
||||
|
||||
// First undo: removes the paste, back to the post-rectangle network. Cursor and legacy must agree.
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(
|
||||
editor.active_document().network_interface.document_network(),
|
||||
&after_rect,
|
||||
"first undo should restore the post-rectangle network (paste removed)"
|
||||
);
|
||||
assert_cursor_matches_runtime(editor.active_document(), "after first undo");
|
||||
|
||||
// Re-stage after the undo, reproducing the live editor's post-undo graph re-evaluation. The pasted
|
||||
// image's resource is still in the runtime cache (kept alive for redo) though its node is gone, so a
|
||||
// naive snapshot would re-detect it as a new `AddResource` and retire it as a phantom interaction, which
|
||||
// would knock the cursor out of lockstep on the next undo. Scoping the snapshot to network-referenced
|
||||
// resources must keep this a no-op.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
|
||||
// Second undo: removes the rectangle, back to the loaded base. The cursor must step a second interaction
|
||||
// and land on the base, not one interaction short (paste resource resurfaced as a phantom interaction).
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
assert_eq!(
|
||||
editor.active_document().network_interface.document_network(),
|
||||
&base,
|
||||
"second undo should restore the loaded base network"
|
||||
);
|
||||
assert_cursor_matches_runtime(editor.active_document(), "after second undo");
|
||||
|
||||
// Back at the loaded base, neither path should be able to undo further: the load is not an undo step.
|
||||
// If the `Gdd` retired the mount base as its own interaction, the cursor can still undo here while legacy
|
||||
// cannot, which is the off-by-one that makes the cursor lag the legacy path by a interaction.
|
||||
let storage = editor.active_document().storage.as_ref().expect("storage mounted");
|
||||
assert!(!storage.can_undo(), "cursor must not undo past the loaded base (the load is not an undo step)");
|
||||
}
|
||||
|
||||
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface,
|
||||
/// mirroring the live shadow check (`verify_storage_cursor_matches_runtime`): node set, network set,
|
||||
/// and per-network export wiring must agree. The runtime keeps resources alive across undo (for legacy
|
||||
/// redo) while the cursor reverts the interaction's `AddResource`, so the runtime's resource set is allowed
|
||||
/// to be a superset of the cursor's, but a resource the current network references must be present.
|
||||
fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
let storage = document.storage.as_ref().expect("storage mounted");
|
||||
let peer = storage.session().peer();
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let view = StorageMetadataView::new(&document.network_interface);
|
||||
let target = graph_storage::Registry::convert_from_runtime(&network, &view, &document.resources.registry, peer).expect("from_runtime");
|
||||
|
||||
let stored = storage.registry();
|
||||
|
||||
let stored_nodes: std::collections::BTreeSet<_> = stored.node_instances.keys().copied().collect();
|
||||
let target_nodes: std::collections::BTreeSet<_> = target.registry.node_instances.keys().copied().collect();
|
||||
assert_eq!(stored_nodes, target_nodes, "cursor node set diverged from the restored interface {at}");
|
||||
|
||||
let stored_networks: std::collections::BTreeSet<_> = stored.networks.keys().copied().collect();
|
||||
let target_networks: std::collections::BTreeSet<_> = target.registry.networks.keys().copied().collect();
|
||||
assert_eq!(stored_networks, target_networks, "cursor network set diverged from the restored interface {at}");
|
||||
|
||||
// Compare export wiring per network: the paste rewires the document export, and undo must revert it.
|
||||
for (id, stored_network) in &stored.networks {
|
||||
let target_network = target.registry.networks.get(id).expect("network present in both (checked above)");
|
||||
let stored_targets: Vec<_> = stored_network.exports.iter().map(|export| export.target.clone()).collect();
|
||||
let target_targets: Vec<_> = target_network.exports.iter().map(|export| export.target.clone()).collect();
|
||||
assert_eq!(stored_targets, target_targets, "cursor export wiring diverged for network {id} {at}");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
async fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> HashMapResourceStorage {
|
||||
let gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 0x5EED, "test".into(), "test".into())
|
||||
.await
|
||||
.expect("create_in");
|
||||
editor.active_document_mut().storage = Some(gdd);
|
||||
HashMapResourceStorage::new()
|
||||
}
|
||||
|
||||
/// Open a real demo artwork, mount storage, edit it, and trigger autosave. The autosave runs
|
||||
/// `verify_storage_round_trip`, which panics (in debug, which tests are) on any conversion or
|
||||
/// round-trip drift — so a clean run is itself the assertion that the whole pipeline holds on real,
|
||||
/// non-synthetic document data. Also checks that committing edits grows the retired-delta history
|
||||
/// and that the editor's undo reverts the modification.
|
||||
#[tokio::test]
|
||||
async fn demo_artwork_edit_autosaves_and_round_trips() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
// Open a real demo artwork through the normal open path and let it render.
|
||||
let content = std::fs::read_to_string("../demo-artwork/changing-seasons.graphite").expect("read demo artwork");
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenFile {
|
||||
path: "changing-seasons.graphite".into(),
|
||||
content: content.bytes().collect(),
|
||||
})
|
||||
.await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor).await;
|
||||
|
||||
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let history_after_open = editor.active_document().storage.as_ref().unwrap().session().history().count();
|
||||
|
||||
// Snapshot the network, then make a real modification.
|
||||
let before_edit = editor.active_document().network_interface.document_network().clone();
|
||||
editor.draw_rect(64., 64., 192., 192.).await;
|
||||
let after_edit = editor.active_document().network_interface.document_network().clone();
|
||||
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
|
||||
|
||||
// Second autosave: again verifies the round-trip, and the edit must produce new retired history.
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
let history_after_edit = editor.active_document().storage.as_ref().unwrap().session().history().count();
|
||||
assert!(
|
||||
history_after_edit > history_after_open,
|
||||
"committing an edit should append retired deltas: {history_after_open} -> {history_after_edit}"
|
||||
);
|
||||
|
||||
// The editor's undo stack reverts the modification on a real document.
|
||||
editor.handle_message(DocumentMessage::Undo).await;
|
||||
let after_undo = editor.active_document().network_interface.document_network().clone();
|
||||
assert_eq!(after_undo, before_edit, "undo should restore the pre-edit network");
|
||||
|
||||
// Autosaving the undone state still round-trips cleanly (no drift panic).
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
mod deserialization;
|
||||
mod memo_network;
|
||||
mod resolved_types;
|
||||
pub mod storage_metadata;
|
||||
|
||||
use super::document_metadata::{DocumentMetadata, LayerNodeIdentifier, NodeRelations};
|
||||
use super::misc::PTZ;
|
||||
@@ -3435,6 +3436,37 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy every piece of transient view and selection state from `other_interface` onto `self`, for each
|
||||
/// network at every nesting level: navigation metadata (pan/zoom), selection undo/redo history, and the
|
||||
/// document-to-viewport canvas camera. Used when an interface is rebuilt from storage (the `Gdd` undo/redo
|
||||
/// cursor) and must keep the user's current view and selection rather than reset them, since the registry
|
||||
/// models document content only. `resolved_types` is a separate runtime cache the caller handles.
|
||||
pub fn copy_all_transient_view_state(&mut self, other_interface: &NodeNetworkInterface) {
|
||||
let mut stack = vec![vec![]];
|
||||
while let Some(path) = stack.pop() {
|
||||
let Some(self_network_metadata) = self.network_metadata_mut(&path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Some(other_network_metadata) = other_interface.network_metadata(&path) {
|
||||
let self_persistent = &mut self_network_metadata.persistent_metadata;
|
||||
let other_persistent = &other_network_metadata.persistent_metadata;
|
||||
self_persistent.navigation_metadata = other_persistent.navigation_metadata.clone();
|
||||
self_persistent.previewing = other_persistent.previewing;
|
||||
self_persistent.selection_undo_history = other_persistent.selection_undo_history.clone();
|
||||
self_persistent.selection_redo_history = other_persistent.selection_redo_history.clone();
|
||||
}
|
||||
|
||||
stack.extend(self_network_metadata.persistent_metadata.node_metadata.keys().map(|node_id| {
|
||||
let mut current_path: Vec<NodeId> = path.clone();
|
||||
current_path.push(*node_id);
|
||||
current_path
|
||||
}));
|
||||
}
|
||||
|
||||
self.document_metadata.document_to_viewport = other_interface.document_metadata.document_to_viewport;
|
||||
}
|
||||
|
||||
pub fn set_transform(&mut self, transform: DAffine2, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata_mut(network_path) else {
|
||||
log::error!("Could not get nested network in set_transform");
|
||||
@@ -6708,6 +6740,9 @@ impl NodePersistentMetadata {
|
||||
pub fn new(position: NodePosition) -> Self {
|
||||
Self { position }
|
||||
}
|
||||
pub fn position(&self) -> &NodePosition {
|
||||
&self.position
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer can either be position as Absolute or in a Stack
|
||||
|
||||
+721
@@ -0,0 +1,721 @@
|
||||
//! Bridge between `NodeNetworkInterface` and `graph-storage`'s `NodeMetadataSource` trait, plus
|
||||
//! an integration round-trip test against a demo `.graphite` document.
|
||||
//!
|
||||
//! The trait impl lives on the [`StorageMetadataView`] wrapper (not on `NodeNetworkInterface`
|
||||
//! directly) because several trait method names collide with inherent methods, and Rust silently
|
||||
//! resolves bare calls to the inherent ones.
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_storage::attr::session;
|
||||
use graph_storage::{InputMetadataEntry, NetworkMetadataEntry, NodeMetadataEntry, NodeMetadataSource, Position};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
use super::memo_network::MemoNetwork;
|
||||
use super::{
|
||||
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NodeNetworkInterface, NodeNetworkMetadata, NodePersistentMetadata,
|
||||
NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
|
||||
};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
|
||||
use crate::messages::portfolio::document::utility_types::misc::SnappingState;
|
||||
use crate::messages::portfolio::document::utility_types::nodes::CollapsedLayers;
|
||||
|
||||
/// Fired when the storage entry list disagrees with the converted `NodeNetwork`.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum InterfaceRebuildError {
|
||||
#[error("input_metadata length {got} does not match inputs length {expected} for node {node:?} in network {network_path:?}")]
|
||||
InputMetadataLengthMismatch { node: NodeId, network_path: Vec<NodeId>, expected: usize, got: usize },
|
||||
}
|
||||
|
||||
/// Per-peer view settings persisted in `session.json` under `ui::doc::*` (viewport view, render mode,
|
||||
/// overlay/ruler visibility, snapping, collapsed layers). Not part of the registry/CRDT/history; see
|
||||
/// [`DocumentSettings::to_view_map`].
|
||||
pub struct DocumentSettings<'a> {
|
||||
pub document_ptz: &'a PTZ,
|
||||
pub render_mode: &'a RenderMode,
|
||||
pub overlays_visibility: &'a OverlaysVisibilitySettings,
|
||||
pub rulers_visible: bool,
|
||||
pub snapping_state: &'a SnappingState,
|
||||
pub collapsed: &'a CollapsedLayers,
|
||||
}
|
||||
|
||||
/// Adapts a `&NodeNetworkInterface` to `graph-storage`'s `NodeMetadataSource` (node/network metadata
|
||||
/// only; document-level view settings live in `session.json`, not the registry).
|
||||
pub struct StorageMetadataView<'a> {
|
||||
interface: &'a NodeNetworkInterface,
|
||||
}
|
||||
|
||||
impl<'a> StorageMetadataView<'a> {
|
||||
pub fn new(interface: &'a NodeNetworkInterface) -> Self {
|
||||
Self { interface }
|
||||
}
|
||||
}
|
||||
|
||||
impl StorageMetadataView<'_> {
|
||||
fn persistent(&self, network_path: &[NodeId], local_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
|
||||
Some(&self.interface.node_metadata(&local_id, network_path)?.persistent_metadata)
|
||||
}
|
||||
|
||||
fn input_persistent(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&InputPersistentMetadata> {
|
||||
Some(&self.persistent(network_path, local_id)?.input_metadata.get(input_index)?.persistent_metadata)
|
||||
}
|
||||
}
|
||||
|
||||
impl NodeMetadataSource for StorageMetadataView<'_> {
|
||||
fn position(&self, network_path: &[NodeId], local_id: NodeId) -> Option<Position> {
|
||||
match &self.persistent(network_path, local_id)?.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||
LayerPosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
|
||||
LayerPosition::Stack(offset) => Some(Position::Stack(offset)),
|
||||
},
|
||||
NodeTypePersistentMetadata::Node(node) => match *node.position() {
|
||||
NodePosition::Absolute(v) => Some(Position::Absolute([v.x, v.y])),
|
||||
NodePosition::Chain => Some(Position::Chain),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn is_layer(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
|
||||
self.persistent(network_path, local_id)
|
||||
.is_some_and(|p| matches!(p.node_type_metadata, NodeTypePersistentMetadata::Layer(_)))
|
||||
}
|
||||
|
||||
fn display_name(&self, network_path: &[NodeId], local_id: NodeId) -> Option<&str> {
|
||||
Some(self.persistent(network_path, local_id)?.display_name.as_str())
|
||||
}
|
||||
|
||||
fn locked(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
|
||||
self.persistent(network_path, local_id).is_some_and(|p| p.locked)
|
||||
}
|
||||
|
||||
fn pinned(&self, network_path: &[NodeId], local_id: NodeId) -> bool {
|
||||
self.persistent(network_path, local_id).is_some_and(|p| p.pinned)
|
||||
}
|
||||
|
||||
fn input_name(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&str> {
|
||||
Some(self.input_persistent(network_path, local_id, input_index)?.input_name.as_str())
|
||||
}
|
||||
|
||||
fn input_description(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&str> {
|
||||
Some(self.input_persistent(network_path, local_id, input_index)?.input_description.as_str())
|
||||
}
|
||||
|
||||
fn widget_override(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> Option<&str> {
|
||||
self.input_persistent(network_path, local_id, input_index)?.widget_override.as_deref()
|
||||
}
|
||||
|
||||
fn input_data(&self, network_path: &[NodeId], local_id: NodeId, input_index: usize) -> HashMap<String, serde_json::Value> {
|
||||
self.input_persistent(network_path, local_id, input_index).map(|p| p.input_data.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn output_names(&self, network_path: &[NodeId], local_id: NodeId) -> Vec<String> {
|
||||
self.persistent(network_path, local_id).map(|p| p.output_names.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
|
||||
let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?;
|
||||
network_metadata.persistent_metadata.reference.as_deref()
|
||||
}
|
||||
}
|
||||
|
||||
impl DocumentSettings<'_> {
|
||||
/// Serialize the per-peer view settings into the `ui::doc::*`-keyed map persisted in `session.json`
|
||||
/// (via `Gdd::set_view_settings`). A field that fails to serialize is skipped, not fatal.
|
||||
pub fn to_view_map(&self) -> BTreeMap<String, serde_json::Value> {
|
||||
let entries = [
|
||||
(session::doc::PTZ, serde_json::to_value(self.document_ptz)),
|
||||
(session::doc::RENDER_MODE, serde_json::to_value(self.render_mode)),
|
||||
(session::doc::OVERLAYS, serde_json::to_value(self.overlays_visibility)),
|
||||
(session::doc::RULERS_VISIBLE, serde_json::to_value(self.rulers_visible)),
|
||||
(session::doc::SNAPPING, serde_json::to_value(self.snapping_state)),
|
||||
(session::doc::COLLAPSED, serde_json::to_value(self.collapsed)),
|
||||
];
|
||||
|
||||
entries
|
||||
.into_iter()
|
||||
.filter_map(|(key, value)| match value {
|
||||
Ok(value) => Some((key.to_string(), value)),
|
||||
Err(error) => {
|
||||
log::error!("Failed to serialize document setting {key}: {error}");
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of the position extraction in `NodeMetadataSource::position`.
|
||||
/// `(Stack, !is_layer)` and `(Chain, is_layer)` shouldn't arise from a faithful round-trip; they fall back to a default of the matching variant.
|
||||
pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersistentMetadata {
|
||||
match (position, is_layer) {
|
||||
(Position::Absolute([x, y]), true) => NodeTypePersistentMetadata::layer(IVec2::new(x, y)),
|
||||
(Position::Absolute([x, y]), false) => NodeTypePersistentMetadata::node(IVec2::new(x, y)),
|
||||
(Position::Stack(offset), _) => {
|
||||
let mut metadata = NodeTypePersistentMetadata::layer(IVec2::ZERO);
|
||||
if let NodeTypePersistentMetadata::Layer(layer) = &mut metadata {
|
||||
layer.position = LayerPosition::Stack(offset);
|
||||
}
|
||||
metadata
|
||||
}
|
||||
(Position::Chain, _) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `NodeNetworkInterface` from a `NodeNetwork` plus the metadata vecs `Registry::to_runtime_with_full_metadata` emits.
|
||||
///
|
||||
/// Sets private fields directly (rather than via public setters) because we're constructing a fresh self-consistent snapshot;
|
||||
/// the setters' transient-cache invalidation isn't needed.
|
||||
pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<NodeMetadataEntry>, network_entries: Vec<NetworkMetadataEntry>) -> Result<NodeNetworkInterface, InterfaceRebuildError> {
|
||||
let mut network_metadata = NodeNetworkMetadata::default();
|
||||
seed_metadata_tree(&network, &mut network_metadata);
|
||||
apply_entries_into_tree(&network, &mut network_metadata, node_entries)?;
|
||||
apply_network_entries_into_tree(&mut network_metadata, network_entries);
|
||||
|
||||
let mut interface = NodeNetworkInterface::default();
|
||||
interface.network = MemoNetwork::new(network);
|
||||
interface.network_metadata = network_metadata;
|
||||
Ok(interface)
|
||||
}
|
||||
|
||||
/// Build the runtime-`network_path` -> stable-`NetworkId` map from the `NetworkMetadataEntry`s that
|
||||
/// `to_runtime_with_full_metadata` emits, so the open path can apply per-network view settings.
|
||||
pub fn network_ids_from_entries(network_entries: &[NetworkMetadataEntry]) -> HashMap<Vec<NodeId>, graph_storage::NetworkId> {
|
||||
network_entries.iter().map(|entry| (entry.network_path.clone(), entry.network_id)).collect()
|
||||
}
|
||||
|
||||
/// Collect the per-network, per-peer view state (node-graph nav + previewing) from `interface` into a
|
||||
/// map keyed by the stable storage [`NetworkId`](graph_storage::NetworkId). `network_ids` maps each
|
||||
/// runtime `network_path` to its id (from the `from_runtime`/`to_runtime` conversion). This is what the
|
||||
/// editor persists into `session.json` so it stays out of the CRDT/history. Networks at their default
|
||||
/// nav with no preview produce no entry.
|
||||
pub fn collect_network_view_settings(
|
||||
interface: &NodeNetworkInterface,
|
||||
network_ids: &HashMap<Vec<NodeId>, graph_storage::NetworkId>,
|
||||
) -> BTreeMap<graph_storage::NetworkId, BTreeMap<String, serde_json::Value>> {
|
||||
let mut out = BTreeMap::new();
|
||||
|
||||
for (network_path, &network_id) in network_ids {
|
||||
let Some(network_metadata) = interface.network_metadata.nested_metadata(network_path) else {
|
||||
continue;
|
||||
};
|
||||
let navigation = &network_metadata.persistent_metadata.navigation_metadata;
|
||||
|
||||
let mut settings = BTreeMap::new();
|
||||
if let Ok(value) = serde_json::to_value(navigation.node_graph_ptz) {
|
||||
settings.insert(session::network::NAV_PTZ.to_string(), value);
|
||||
}
|
||||
if let Ok(value) = serde_json::to_value(navigation.node_graph_to_viewport) {
|
||||
settings.insert(session::network::NAV_TRANSFORM.to_string(), value);
|
||||
}
|
||||
if let Ok(value) = serde_json::to_value(navigation.node_graph_width) {
|
||||
settings.insert(session::network::NAV_WIDTH.to_string(), value);
|
||||
}
|
||||
|
||||
// Skip the inert `Previewing::No` default so a network that has never been previewed stays empty.
|
||||
if !matches!(network_metadata.persistent_metadata.previewing, Previewing::No)
|
||||
&& let Ok(value) = serde_json::to_value(&network_metadata.persistent_metadata.previewing)
|
||||
{
|
||||
settings.insert(session::network::PREVIEWING.to_string(), value);
|
||||
}
|
||||
|
||||
if !settings.is_empty() {
|
||||
out.insert(network_id, settings);
|
||||
}
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply persisted per-network view state (node-graph nav + previewing) from `session.json` onto
|
||||
/// `interface`. Inverse of [`collect_network_view_settings`]: `network_ids` resolves each runtime
|
||||
/// `network_path` to its [`NetworkId`](graph_storage::NetworkId), and the matching inner map is decoded
|
||||
/// back onto the network's navigation/previewing metadata.
|
||||
pub fn apply_network_view_settings(
|
||||
interface: &mut NodeNetworkInterface,
|
||||
network_ids: &HashMap<Vec<NodeId>, graph_storage::NetworkId>,
|
||||
network_view_settings: &BTreeMap<graph_storage::NetworkId, BTreeMap<String, serde_json::Value>>,
|
||||
) {
|
||||
for (network_path, network_id) in network_ids {
|
||||
let Some(settings) = network_view_settings.get(network_id) else { continue };
|
||||
let Some(network_metadata) = interface.network_metadata.nested_metadata_mut(network_path) else {
|
||||
continue;
|
||||
};
|
||||
let persistent = &mut network_metadata.persistent_metadata;
|
||||
|
||||
if let Some(value) = settings.get(session::network::NAV_PTZ)
|
||||
&& let Ok(ptz) = serde_json::from_value::<PTZ>(value.clone())
|
||||
{
|
||||
persistent.navigation_metadata.node_graph_ptz = ptz;
|
||||
}
|
||||
if let Some(value) = settings.get(session::network::NAV_TRANSFORM)
|
||||
&& let Ok(transform) = serde_json::from_value(value.clone())
|
||||
{
|
||||
persistent.navigation_metadata.node_graph_to_viewport = transform;
|
||||
}
|
||||
if let Some(value) = settings.get(session::network::NAV_WIDTH)
|
||||
&& let Ok(width) = serde_json::from_value(value.clone())
|
||||
{
|
||||
persistent.navigation_metadata.node_graph_width = width;
|
||||
}
|
||||
if let Some(value) = settings.get(session::network::PREVIEWING)
|
||||
&& let Ok(previewing) = serde_json::from_value::<Previewing>(value.clone())
|
||||
{
|
||||
persistent.previewing = previewing;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Entries whose `network_path` doesn't resolve are skipped with a warning (per-network drift is more often a stale path than corruption).
|
||||
fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries: Vec<NetworkMetadataEntry>) {
|
||||
for entry in entries {
|
||||
let Some(network_metadata) = metadata.nested_metadata_mut(&entry.network_path) else {
|
||||
log::warn!("apply_network_entries_into_tree: nested network at {:?} not found, skipping", entry.network_path);
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Some(reference) = entry.reference {
|
||||
network_metadata.persistent_metadata.reference = Some(reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Walks `network` recursively, ensuring `metadata` has a default `DocumentNodeMetadata` slot for every node at every nesting level.
|
||||
/// Mirrors the editor invariant that `NodeNetworkPersistentMetadata::node_metadata` contains every document-node key.
|
||||
fn seed_metadata_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMetadata) {
|
||||
for (&local_id, node) in &network.nodes {
|
||||
let node_metadata = metadata.persistent_metadata.node_metadata.entry(local_id).or_default();
|
||||
|
||||
if let DocumentNodeImplementation::Network(nested) = &node.implementation {
|
||||
let child = node_metadata.persistent_metadata.network_metadata.get_or_insert_with(NodeNetworkMetadata::default);
|
||||
seed_metadata_tree(nested, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Patches entries onto the metadata tree previously seeded by [`seed_metadata_tree`].
|
||||
/// Entries with stale `(network_path, local_id)` are skipped with a warning; `input_metadata` length mismatches escalate to `InterfaceRebuildError`.
|
||||
fn apply_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMetadata, entries: Vec<NodeMetadataEntry>) -> Result<(), InterfaceRebuildError> {
|
||||
// Group entries by network_path so we do one nested_metadata_mut lookup per network.
|
||||
let mut by_path: HashMap<Vec<NodeId>, Vec<NodeMetadataEntry>> = HashMap::new();
|
||||
for entry in entries {
|
||||
by_path.entry(entry.network_path.clone()).or_default().push(entry);
|
||||
}
|
||||
|
||||
for (path, entries) in by_path {
|
||||
let nested_network = nested_network_at(network, &path);
|
||||
|
||||
let Some(network_metadata) = metadata.nested_metadata_mut(&path) else {
|
||||
log::warn!("apply_entries_into_tree: nested network at {path:?} not found, skipping {} entries", entries.len());
|
||||
continue;
|
||||
};
|
||||
|
||||
for entry in entries {
|
||||
let Some(document_node_metadata) = network_metadata.persistent_metadata.node_metadata.get_mut(&entry.local_id) else {
|
||||
log::warn!("apply_entries_into_tree: node {:?} not seeded under network {path:?}, skipping", entry.local_id);
|
||||
continue;
|
||||
};
|
||||
|
||||
let persistent = &mut document_node_metadata.persistent_metadata;
|
||||
|
||||
if let Some(position) = entry.position {
|
||||
persistent.node_type_metadata = position_to_runtime(position, entry.is_layer);
|
||||
} else if entry.is_layer {
|
||||
persistent.node_type_metadata = NodeTypePersistentMetadata::layer(IVec2::ZERO);
|
||||
}
|
||||
|
||||
if let Some(name) = entry.display_name {
|
||||
persistent.display_name = name;
|
||||
}
|
||||
persistent.locked = entry.locked;
|
||||
persistent.pinned = entry.pinned;
|
||||
|
||||
// The converted runtime is the source of truth for input count; drift indicates a bug worth surfacing.
|
||||
let expected_inputs = nested_network.and_then(|net| net.nodes.get(&entry.local_id)).map(|doc_node| doc_node.inputs.len());
|
||||
if let Some(expected) = expected_inputs
|
||||
&& expected != entry.input_metadata.len()
|
||||
{
|
||||
return Err(InterfaceRebuildError::InputMetadataLengthMismatch {
|
||||
node: entry.local_id,
|
||||
network_path: path.clone(),
|
||||
expected,
|
||||
got: entry.input_metadata.len(),
|
||||
});
|
||||
}
|
||||
|
||||
persistent.input_metadata = entry.input_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
|
||||
|
||||
if !entry.output_names.is_empty() {
|
||||
persistent.output_names = entry.output_names;
|
||||
}
|
||||
|
||||
document_node_metadata.transient_metadata = DocumentNodeTransientMetadata::default();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `None` when the path is invalid; callers treat that as "skip silently" since the surrounding `nested_metadata_mut` already warns.
|
||||
fn nested_network_at<'a>(root: &'a NodeNetwork, path: &[NodeId]) -> Option<&'a NodeNetwork> {
|
||||
let mut current = root;
|
||||
for segment in path {
|
||||
let node = current.nodes.get(segment)?;
|
||||
let DocumentNodeImplementation::Network(nested) = &node.implementation else { return None };
|
||||
current = nested;
|
||||
}
|
||||
Some(current)
|
||||
}
|
||||
|
||||
/// Storage-side `None` restores as `""` (the runtime's "unset" sentinel for `input_name` / `input_description`).
|
||||
fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
|
||||
InputMetadata {
|
||||
persistent_metadata: InputPersistentMetadata {
|
||||
input_name: entry.input_name.unwrap_or_default(),
|
||||
input_description: entry.input_description.unwrap_or_default(),
|
||||
widget_override: entry.widget_override,
|
||||
input_data: entry.input_data,
|
||||
},
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::collections::HashMap;
|
||||
|
||||
use graph_storage::{NodeMetadataSource, PeerId, Registry};
|
||||
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::DocumentMessageHandler;
|
||||
|
||||
/// Load a demo `.graphite` straight into a `DocumentMessageHandler` for inspection.
|
||||
fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
let path = format!("../demo-artwork/{file_name}");
|
||||
let content = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("Failed to read {path}: {e}"));
|
||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Walk every node in every nested network and collect `(network_path, local_id)` pairs so the
|
||||
/// test can iterate every node addressable from the metadata side.
|
||||
fn collect_all_node_paths(interface: &NodeNetworkInterface) -> Vec<(Vec<NodeId>, NodeId)> {
|
||||
fn walk(interface: &NodeNetworkInterface, path: Vec<NodeId>, out: &mut Vec<(Vec<NodeId>, NodeId)>) {
|
||||
let Some(network) = interface.nested_network(&path) else { return };
|
||||
for (&local_id, node) in &network.nodes {
|
||||
out.push((path.clone(), local_id));
|
||||
|
||||
if matches!(&node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)) {
|
||||
let mut child = path.clone();
|
||||
child.push(local_id);
|
||||
walk(interface, child, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut out = Vec::new();
|
||||
walk(interface, Vec::new(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Loads a demo artwork, round-trips its `NodeNetwork + NodeNetworkInterface metadata` through
|
||||
/// `Registry`, and asserts every node's `ui::*` attributes survive unchanged.
|
||||
///
|
||||
/// Uses one demo (rather than the full set) because this is an exhaustive per-node check.
|
||||
#[test]
|
||||
fn editor_metadata_round_trip_against_demo() {
|
||||
let document = load_demo("changing-seasons.graphite");
|
||||
let interface = &document.network_interface;
|
||||
let source = StorageMetadataView::new(interface);
|
||||
|
||||
let network = interface.document_network().clone();
|
||||
|
||||
let conversion = Registry::convert_from_runtime(&network, &source, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
|
||||
let (_converted_network, entries) = registry.to_runtime_with_metadata(&declarations).expect("to_runtime_with_metadata failed");
|
||||
|
||||
// Index emitted entries by their (network_path, local_id) address.
|
||||
let entries_by_address: HashMap<(Vec<NodeId>, NodeId), &graph_storage::NodeMetadataEntry> = entries.iter().map(|e| ((e.network_path.clone(), e.local_id), e)).collect();
|
||||
|
||||
let mut checked_any_position = false;
|
||||
let mut checked_any_layer = false;
|
||||
let mut checked_any_input_metadata = false;
|
||||
|
||||
for (network_path, local_id) in collect_all_node_paths(interface) {
|
||||
let expected_position = source.position(&network_path, local_id);
|
||||
let expected_is_layer = source.is_layer(&network_path, local_id);
|
||||
let expected_display = source.display_name(&network_path, local_id).map(str::to_owned);
|
||||
let expected_locked = source.locked(&network_path, local_id);
|
||||
let expected_pinned = source.pinned(&network_path, local_id);
|
||||
let expected_output_names = source.output_names(&network_path, local_id);
|
||||
|
||||
// Pull per-input metadata directly off the runtime side. We use the runtime invariant
|
||||
// (`input_metadata.len() == inputs.len()`) as the iteration bound rather than calling the
|
||||
// trait per index, since the trait would return `None` past the end and we want a strict
|
||||
// slot-by-slot comparison.
|
||||
let input_count = interface.document_node(&local_id, &network_path).map(|node| node.inputs.len()).unwrap_or(0);
|
||||
let any_input_metadata_present = (0..input_count).any(|i| {
|
||||
source.input_name(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|
||||
|| source.input_description(&network_path, local_id, i).is_some_and(|s| !s.is_empty())
|
||||
|| source.widget_override(&network_path, local_id, i).is_some()
|
||||
|| !source.input_data(&network_path, local_id, i).is_empty()
|
||||
});
|
||||
|
||||
let any_metadata = expected_position.is_some()
|
||||
|| expected_is_layer
|
||||
|| expected_display.as_deref().is_some_and(|s| !s.is_empty())
|
||||
|| expected_locked
|
||||
|| expected_pinned
|
||||
|| any_input_metadata_present
|
||||
|| !expected_output_names.is_empty();
|
||||
|
||||
if !any_metadata {
|
||||
assert!(
|
||||
entries_by_address.get(&(network_path.clone(), local_id)).is_none(),
|
||||
"node {local_id:?} in network {network_path:?} has no editor metadata but produced an entry"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let entry = entries_by_address
|
||||
.get(&(network_path.clone(), local_id))
|
||||
.unwrap_or_else(|| panic!("missing entry for node {local_id:?} in network {network_path:?}"));
|
||||
|
||||
assert_eq!(entry.position, expected_position, "position mismatch for node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(entry.is_layer, expected_is_layer, "is_layer mismatch for node {local_id:?} in network {network_path:?}");
|
||||
// The trait round-trip drops empty display names (treats them as "unset") so the entry's
|
||||
// `display_name` is `None` when the runtime carries `""`. Normalize before comparing.
|
||||
let normalized_expected_display = expected_display.as_deref().filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
assert_eq!(
|
||||
entry.display_name, normalized_expected_display,
|
||||
"display_name mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(entry.locked, expected_locked, "locked mismatch for node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(entry.pinned, expected_pinned, "pinned mismatch for node {local_id:?} in network {network_path:?}");
|
||||
assert_eq!(entry.output_names, expected_output_names, "output_names mismatch for node {local_id:?} in network {network_path:?}");
|
||||
|
||||
// Per-input metadata: the entry's `input_metadata` vec has the same length as the node's
|
||||
// input slot count, and each slot matches the trait's per-field view (with the same
|
||||
// "empty string ↔ None" normalization as `display_name`).
|
||||
assert_eq!(
|
||||
entry.input_metadata.len(),
|
||||
input_count,
|
||||
"input_metadata length mismatch for node {local_id:?} in network {network_path:?}: entry has {}, node has {input_count}",
|
||||
entry.input_metadata.len(),
|
||||
);
|
||||
for (index, input_entry) in entry.input_metadata.iter().enumerate() {
|
||||
let expected_name = source.input_name(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let expected_description = source.input_description(&network_path, local_id, index).filter(|s| !s.is_empty()).map(str::to_owned);
|
||||
let expected_widget = source.widget_override(&network_path, local_id, index).map(str::to_owned);
|
||||
let expected_data = source.input_data(&network_path, local_id, index);
|
||||
|
||||
assert_eq!(
|
||||
input_entry.input_name, expected_name,
|
||||
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
input_entry.input_description, expected_description,
|
||||
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
input_entry.widget_override, expected_widget,
|
||||
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
input_entry.input_data, expected_data,
|
||||
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
}
|
||||
|
||||
if entry.position.is_some() {
|
||||
checked_any_position = true;
|
||||
}
|
||||
if entry.is_layer {
|
||||
checked_any_layer = true;
|
||||
}
|
||||
if any_input_metadata_present {
|
||||
checked_any_input_metadata = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: a real artwork should exercise at least these two shapes; otherwise the test is
|
||||
// just iterating empty metadata and proving nothing.
|
||||
assert!(checked_any_position, "demo artwork produced no positioned nodes — fixture is wrong or extraction is broken");
|
||||
assert!(checked_any_layer, "demo artwork produced no layer nodes — fixture is wrong or extraction is broken");
|
||||
// Demo artworks always have some custom widget overrides / input names; if not, the
|
||||
// per-input round-trip isn't actually being exercised here.
|
||||
assert!(checked_any_input_metadata, "demo artwork produced no per-input metadata — fixture is wrong or extraction is broken");
|
||||
}
|
||||
|
||||
/// Full editor-side round-trip: original interface → Registry → (NodeNetwork, Vec<entry>) →
|
||||
/// freshly-built interface. Asserts the rebuilt interface presents the same `ui::*` state as
|
||||
/// the original when read through `StorageMetadataView`.
|
||||
#[test]
|
||||
fn editor_interface_rebuild_round_trip() {
|
||||
let document = load_demo("changing-seasons.graphite");
|
||||
let original = &document.network_interface;
|
||||
let original_view = StorageMetadataView::new(original);
|
||||
|
||||
let network = original.document_network().clone();
|
||||
let conversion = Registry::convert_from_runtime(&network, &original_view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||
let declarations = conversion.declarations().expect("rebuild declarations");
|
||||
let registry = conversion.registry;
|
||||
let (rebuilt_network, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&declarations).expect("to_runtime_with_full_metadata failed");
|
||||
|
||||
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries).expect("build_interface_from_storage failed");
|
||||
let rebuilt_view = StorageMetadataView::new(&rebuilt);
|
||||
|
||||
// Every node the original carried must also resolve identically through the rebuilt view.
|
||||
// Iterating over the *rebuilt* interface verifies that the rebuild covered every node, not
|
||||
// just the ones the entries vec mentioned.
|
||||
for (network_path, local_id) in collect_all_node_paths(&rebuilt) {
|
||||
assert_eq!(
|
||||
rebuilt_view.position(&network_path, local_id),
|
||||
original_view.position(&network_path, local_id),
|
||||
"position mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
rebuilt_view.is_layer(&network_path, local_id),
|
||||
original_view.is_layer(&network_path, local_id),
|
||||
"is_layer mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
// Original display names are returned by the source as-is (including `""`). After
|
||||
// round-trip the rebuilt interface also stores `""` for nodes that had no name set,
|
||||
// so this comparison is exact.
|
||||
assert_eq!(
|
||||
rebuilt_view.display_name(&network_path, local_id),
|
||||
original_view.display_name(&network_path, local_id),
|
||||
"display_name mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
rebuilt_view.locked(&network_path, local_id),
|
||||
original_view.locked(&network_path, local_id),
|
||||
"locked mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
rebuilt_view.pinned(&network_path, local_id),
|
||||
original_view.pinned(&network_path, local_id),
|
||||
"pinned mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
|
||||
// Per-input metadata: walk both interfaces' input slots in lockstep.
|
||||
let original_inputs = original.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
|
||||
let rebuilt_inputs = rebuilt.document_node(&local_id, &network_path).map(|n| n.inputs.len()).unwrap_or(0);
|
||||
assert_eq!(
|
||||
rebuilt_inputs, original_inputs,
|
||||
"input count mismatch for node {local_id:?} in network {network_path:?}: rebuilt={rebuilt_inputs} original={original_inputs}"
|
||||
);
|
||||
|
||||
for index in 0..rebuilt_inputs {
|
||||
assert_eq!(
|
||||
rebuilt_view.input_name(&network_path, local_id, index),
|
||||
original_view.input_name(&network_path, local_id, index),
|
||||
"input_name mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
rebuilt_view.input_description(&network_path, local_id, index),
|
||||
original_view.input_description(&network_path, local_id, index),
|
||||
"input_description mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
rebuilt_view.widget_override(&network_path, local_id, index),
|
||||
original_view.widget_override(&network_path, local_id, index),
|
||||
"widget_override mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
rebuilt_view.input_data(&network_path, local_id, index),
|
||||
original_view.input_data(&network_path, local_id, index),
|
||||
"input_data mismatch at slot {index} for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
rebuilt_view.output_names(&network_path, local_id),
|
||||
original_view.output_names(&network_path, local_id),
|
||||
"output_names mismatch for node {local_id:?} in network {network_path:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// Symmetric: every node in the original must also exist in the rebuilt interface.
|
||||
for (network_path, local_id) in collect_all_node_paths(original) {
|
||||
assert!(
|
||||
rebuilt.nested_network(&network_path).and_then(|n| n.nodes.get(&local_id)).is_some(),
|
||||
"original node {local_id:?} in network {network_path:?} missing after rebuild"
|
||||
);
|
||||
}
|
||||
|
||||
// Per-network metadata: every nested network path (including the root) must resolve to the same
|
||||
// `reference` in the rebuilt interface. Node-graph nav + previewing are per-peer view state that
|
||||
// lives in `session.json`, not the registry, so they're not round-tripped here.
|
||||
let mut network_paths_to_check: Vec<Vec<NodeId>> = vec![Vec::new()];
|
||||
for (network_path, local_id) in collect_all_node_paths(original) {
|
||||
let mut child = network_path.clone();
|
||||
child.push(local_id);
|
||||
if original.nested_network(&child).is_some() {
|
||||
network_paths_to_check.push(child);
|
||||
}
|
||||
}
|
||||
|
||||
let mut checked_any_reference = false;
|
||||
for path in &network_paths_to_check {
|
||||
assert_eq!(rebuilt_view.reference(path), original_view.reference(path), "reference mismatch for network {path:?}");
|
||||
if original_view.reference(path).is_some() {
|
||||
checked_any_reference = true;
|
||||
}
|
||||
}
|
||||
|
||||
assert!(checked_any_reference, "demo artwork produced no reference metadata — fixture is wrong or extraction is broken");
|
||||
}
|
||||
|
||||
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
||||
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
||||
#[test]
|
||||
fn document_settings_round_trip() {
|
||||
let mut document = load_demo("changing-seasons.graphite");
|
||||
|
||||
// Set distinctive, non-default values so the round-trip proves real data moved, not defaults.
|
||||
document.render_mode = RenderMode::Outline;
|
||||
document.rulers_visible = false;
|
||||
document.collapsed = CollapsedLayers(vec![vec![NodeId(7)], vec![NodeId(7), NodeId(42)]]);
|
||||
|
||||
let view_settings = DocumentSettings {
|
||||
document_ptz: &document.document_ptz,
|
||||
render_mode: &document.render_mode,
|
||||
overlays_visibility: &document.overlays_visibility_settings,
|
||||
rulers_visible: document.rulers_visible,
|
||||
snapping_state: &document.snapping_state,
|
||||
collapsed: &document.collapsed,
|
||||
}
|
||||
.to_view_map();
|
||||
|
||||
// Apply the serialized view settings onto a fresh handler and compare each field's serialized
|
||||
// form (avoids requiring `PartialEq` on every setting type).
|
||||
let mut restored = DocumentMessageHandler::default();
|
||||
restored.apply_stored_document_settings(&view_settings);
|
||||
|
||||
assert_eq!(serde_json::to_value(restored.render_mode).unwrap(), serde_json::to_value(document.render_mode).unwrap(), "render_mode");
|
||||
assert_eq!(
|
||||
serde_json::to_value(restored.rulers_visible).unwrap(),
|
||||
serde_json::to_value(document.rulers_visible).unwrap(),
|
||||
"rulers_visible"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(restored.document_ptz).unwrap(),
|
||||
serde_json::to_value(document.document_ptz).unwrap(),
|
||||
"document_ptz"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(restored.overlays_visibility_settings).unwrap(),
|
||||
serde_json::to_value(document.overlays_visibility_settings).unwrap(),
|
||||
"overlays"
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(restored.snapping_state).unwrap(),
|
||||
serde_json::to_value(document.snapping_state).unwrap(),
|
||||
"snapping_state"
|
||||
);
|
||||
assert_eq!(serde_json::to_value(restored.collapsed).unwrap(), serde_json::to_value(document.collapsed).unwrap(), "collapsed");
|
||||
}
|
||||
}
|
||||
@@ -644,7 +644,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
// text
|
||||
// ================================
|
||||
NodeReplacement {
|
||||
node: graphene_std::text::text::IDENTIFIER,
|
||||
node: ProtoNodeIdentifier::new("graphene_std::text::TextNode"),
|
||||
aliases: &["graphene_core::text::text::TextNode", "graphene_core::text::TextGeneratorNode", "graphene_core::text::TextNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -978,6 +978,16 @@ pub fn document_migration_string_preprocessing(document_serialized_content: Stri
|
||||
.fold(document_serialized_content, |document_serialized_content, (old, new)| document_serialized_content.replace(old, new))
|
||||
}
|
||||
|
||||
/// Rebuilds the old 13-input "Text" node template from the current `text` template plus the trailing `separate_glyphs` input it dropped,
|
||||
/// so the staged input-count migrations can still upgrade old text nodes before the split.
|
||||
fn legacy_text_node_template() -> Option<NodeTemplate> {
|
||||
let mut template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER))?.default_node_template();
|
||||
template.document_node.implementation = DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode"));
|
||||
template.document_node.inputs.push(NodeInput::value(TaggedValue::Bool(false), false));
|
||||
template.persistent_node_metadata.input_metadata.push(Default::default());
|
||||
Some(template)
|
||||
}
|
||||
|
||||
fn replace_optional_f64_null(input: &str) -> String {
|
||||
let mut result = String::new();
|
||||
let mut last_end = 0;
|
||||
@@ -1111,6 +1121,9 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
|
||||
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
|
||||
document.network_interface.migrate_path_modify_node();
|
||||
|
||||
// Legacy `Fill::Gradient`s are converted to absolute by the deferred migration pass once the first graph run yields geometry bounds
|
||||
document.pending_gradient_migration = true;
|
||||
|
||||
let network = document.network_interface.document_network().clone();
|
||||
|
||||
// Apply string and node replacements to each node
|
||||
@@ -1250,6 +1263,19 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Record which old text nodes are chain-positioned now, before `migrate_node`'s staged input-count migrations run, since those set
|
||||
// the upstream chain to absolute; the split below re-chains exactly the nodes that were originally part of a layer chain.
|
||||
let text_nodes_in_chain: std::collections::HashSet<NodeId> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, _, path)| {
|
||||
(document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")))
|
||||
&& document.network_interface.is_chain(node_id, &path))
|
||||
.then_some(*node_id)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Apply upgrades to each unmodified node.
|
||||
let nodes = document
|
||||
.network_interface
|
||||
@@ -1260,6 +1286,91 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
for (node_id, node, network_path) in &nodes {
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
|
||||
// The old geometry-producing "Text" node was split into the current "Text" (`String[]`) -> "Text to Vector" pair, which reuses the same
|
||||
// proto identifier. Runs after `migrate_node` normalizes old text nodes to the legacy 13-input layout, distinguished from the current
|
||||
// 12-input node by the trailing `separate_glyphs` input (index 12): forward inputs 0..=11 onto the new node and move it onto `text_to_vector`.
|
||||
let old_text_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
// `separate_glyphs` is a `Bool` value or a wire feeding one; only a different value type there means a newer input, not the old node
|
||||
let has_legacy_separate_glyphs = node.inputs.len() == 13 && node.inputs.get(12).is_some_and(|input| matches!(input.as_value(), None | Some(TaggedValue::Bool(_))));
|
||||
(has_legacy_separate_glyphs && document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode"))))
|
||||
.then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &old_text_nodes {
|
||||
// Pre-load `outward_wires` so the splice below resolves the original downstream wiring from cache rather than a mutated state.
|
||||
let _ = document.network_interface.outward_wires(network_path);
|
||||
|
||||
// Convert the old node in place to the current `text` node (12 inputs), capturing its old inputs.
|
||||
let Some(text_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut text_template = text_definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut text_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut text_template) else {
|
||||
continue;
|
||||
};
|
||||
// The current `text` node reorders the legacy inputs (Letter Tilt moved up to sit right after Letter Spacing), so map each new
|
||||
// input index to the legacy 13-input index it sources from. Legacy order:
|
||||
// [primary, text, font, size, line_height, letter_spacing, has_max_width, max_width, has_max_height, max_height, letter_tilt, align, separate_glyphs].
|
||||
const LEGACY_INPUT_FOR_NEW: [usize; 12] = [0, 1, 2, 3, 4, 5, 10, 6, 7, 8, 9, 11];
|
||||
for (new_index, &legacy_index) in LEGACY_INPUT_FOR_NEW.iter().enumerate() {
|
||||
if let Some(input) = old_inputs.get(legacy_index) {
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, new_index), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
let separate_glyphs = old_inputs.get(12).cloned();
|
||||
|
||||
// Collect the inputs reading the old text node's output before any rewiring so the new node can be spliced onto those wires.
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let text_was_in_chain = text_nodes_in_chain.contains(node_id);
|
||||
|
||||
// Insert the `text_to_vector` node that converts the `text` `String[]` output back into vector geometry.
|
||||
let Some(text_to_vector_definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::text::text_to_vector::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let text_to_vector_id = NodeId::new();
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(text_to_vector_id, text_to_vector_definition.default_node_template(), network_path);
|
||||
|
||||
// Splice `text_to_vector` onto the wire(s) leaving `text` (`insert_node_between` is the pure wire-splice the editor uses for
|
||||
// dropping a node on a wire), then carry the old `separate_glyphs` value onto its second input.
|
||||
if let Some((first_consumer, remaining_consumers)) = downstream_consumers.split_first() {
|
||||
document.network_interface.insert_node_between(&text_to_vector_id, first_consumer, 0, network_path);
|
||||
for consumer in remaining_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(text_to_vector_id, 0), network_path);
|
||||
}
|
||||
} else {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(text_to_vector_id, 0), NodeInput::node(*node_id, 0), network_path);
|
||||
}
|
||||
if let Some(separate_glyphs) = separate_glyphs {
|
||||
document.network_interface.set_input(&InputConnector::node(text_to_vector_id, 1), separate_glyphs, network_path);
|
||||
}
|
||||
|
||||
// If `text` was in a layer chain, re-chain `text_to_vector` and its upstream so both lay out by distance from the layer (the splice
|
||||
// broke the chain, like `move_node_to_chain_start`). Otherwise `text` is absolute, so place `text_to_vector` beside it instead of
|
||||
// leaving it at the origin.
|
||||
if text_was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&text_to_vector_id, network_path);
|
||||
} else if let Some(text_position) = document.network_interface.position(node_id, network_path) {
|
||||
document
|
||||
.network_interface
|
||||
.shift_absolute_node_position(&text_to_vector_id, text_position + IVec2::new(7, 0), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) -> Option<()> {
|
||||
@@ -1484,8 +1595,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
|
||||
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut template: NodeTemplate = resolve_document_node_type(&reference)?.default_node_template();
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 8 {
|
||||
let mut template: NodeTemplate = legacy_text_node_template()?;
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
|
||||
@@ -1507,7 +1618,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
if inputs_count == 6 {
|
||||
old_inputs[5].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().character_spacing), false)
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_spacing), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
@@ -1534,7 +1645,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
if inputs_count >= 9 {
|
||||
old_inputs[8].clone()
|
||||
} else {
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().tilt), false)
|
||||
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)
|
||||
},
|
||||
network_path,
|
||||
);
|
||||
@@ -1561,8 +1672,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Insert bool parameters for `has_max_width` and `has_max_height`:
|
||||
// https://github.com/GraphiteEditor/Graphite/pull/3643
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) && inputs_count == 11 {
|
||||
let mut template: NodeTemplate = resolve_document_node_type(&reference)?.default_node_template();
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 11 {
|
||||
let mut template: NodeTemplate = legacy_text_node_template()?;
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
|
||||
|
||||
@@ -1714,7 +1825,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert text nodes from the old `editor-api` scope + `Font` input to a single font `Resource` input.
|
||||
// The chosen typeface is recorded as a `DataSource::Font` in the document's resource registry and loaded on open.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER) && inputs_count == 13 && matches!(node.inputs.first(), Some(NodeInput::Scope(_))) {
|
||||
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 13 && matches!(node.inputs.first(), Some(NodeInput::Scope(_))) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
@@ -2254,6 +2365,28 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
// `load_resource` no longer takes the `editor-api`
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::load_resource::IDENTIFIER) && inputs_count == 3 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
document.network_interface.set_input(&InputConnector::node(*node_id, 1), old_inputs[2].clone(), network_path);
|
||||
}
|
||||
|
||||
// `wgpu-executor` scope was removed, change to the auto injected scope node `graphene_std::platform_application_io::wgpu_executor`
|
||||
for (i, input) in node.inputs.iter().enumerate() {
|
||||
if let NodeInput::Scope(name) = input
|
||||
&& *name == "wgpu-executor"
|
||||
{
|
||||
document.network_interface.set_input(
|
||||
&InputConnector::node(*node_id, i),
|
||||
NodeInput::Scope("graphene_std::platform_application_io::WgpuExecutorNode".into()),
|
||||
network_path,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================================
|
||||
// PUT ALL MIGRATIONS ABOVE THIS LINE
|
||||
// ==================================
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const FALLBACK_FONT_BYTES: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
|
||||
pub static FALLBACK_FONT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| Resource::new(FALLBACK_FONT_BYTES));
|
||||
// Re-export the fallback font resource from text-nodes, which is the authoritative location.
|
||||
// This avoids duplicating the font bytes in the editor binary.
|
||||
// This file can be removed after deciding where to place the authority of fallback_resource.
|
||||
pub use graphene_std::text_nodes::FALLBACK_FONT_RESOURCE;
|
||||
@@ -9,7 +9,8 @@ use graphene_std::raster::Image;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[impl_message(Message, Portfolio)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(derivative::Derivative, serde::Serialize, serde::Deserialize)]
|
||||
#[derivative(Clone, Debug, PartialEq)]
|
||||
pub enum PortfolioMessage {
|
||||
// Sub-messages
|
||||
#[child]
|
||||
@@ -48,6 +49,20 @@ pub enum PortfolioMessage {
|
||||
DeleteDocument {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Delivers an asynchronously-built `Gdd` working copy into its document. Emitted by the mount
|
||||
/// future spawned in `load_document` once the working-copy container is ready. The payload is
|
||||
/// not serializable and a clone carries no `Gdd` (`clone_to_none`); it only ever travels once,
|
||||
/// from the mount future to the receiving handler. `reopened` is true when an existing working copy
|
||||
/// was opened (not freshly created): the persisted cursor is trusted as-is and the mount-time
|
||||
/// re-commit is skipped, since re-committing the legacy runtime would stack a spurious interaction on the
|
||||
/// restored cursor and make the first undo a no-op.
|
||||
DocumentStorageMounted {
|
||||
document_id: DocumentId,
|
||||
reopened: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
gdd: Option<document_format::GddV1>,
|
||||
},
|
||||
DestroyAllDocuments,
|
||||
EditorPreferences,
|
||||
GarbageCollectResources,
|
||||
@@ -97,6 +112,34 @@ pub enum PortfolioMessage {
|
||||
document_path: Option<PathBuf>,
|
||||
document_serialized_content: String,
|
||||
},
|
||||
/// Open a `.gdd` document container (archive bytes), building the runtime from its stored registry.
|
||||
OpenGddDocument {
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
/// Delivers a document built asynchronously from a `.gdd` archive (registry → runtime, working copy
|
||||
/// mounted) into the portfolio. Non-serializable payload that travels once, like `DocumentStorageMounted`.
|
||||
GddDocumentLoaded {
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
document_path: Option<PathBuf>,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
document: Option<Box<DocumentMessageHandler>>,
|
||||
},
|
||||
/// Delivers the interface rebuilt from the `Gdd` undo/redo cursor (which moved + persisted synchronously),
|
||||
/// so the async registry rebuild can swap into the live document. `interface` is `None` if the rebuild
|
||||
/// failed (logged at the source). `had_oracle` records whether the legacy snapshot applied synchronously,
|
||||
/// so the swap can debug-compare the rebuild against it. Non-serializable payload that travels once, like
|
||||
/// `GddDocumentLoaded`.
|
||||
GddUndoRedoRebuilt {
|
||||
document_id: DocumentId,
|
||||
had_oracle: bool,
|
||||
#[serde(skip, default)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
|
||||
interface: Option<Box<crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface>>,
|
||||
},
|
||||
LoadDocument {
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
@@ -199,3 +242,8 @@ pub enum PortfolioMessage {
|
||||
sizes: Vec<f64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Clone helper for the non-serializable `gdd` payload: a cloned mount message carries no `Gdd`.
|
||||
fn clone_to_none<T>(_: &Option<T>) -> Option<T> {
|
||||
None
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use super::document::utility_types::network_interface;
|
||||
use super::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageHandler};
|
||||
use super::utility_types::{PanelLayoutSubdivision, PanelType, WorkspacePanelLayout};
|
||||
use crate::application::{Editor, generate_uuid};
|
||||
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION};
|
||||
use crate::consts::{DEFAULT_DOCUMENT_NAME, DEFAULT_STROKE_WIDTH, FILE_EXTENSION, GDD_FILE_EXTENSION};
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::clipboard::utility_types::ClipboardContent;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
@@ -73,6 +73,16 @@ pub struct PortfolioMessageHandler {
|
||||
pub selection_mode: SelectionMode,
|
||||
pub reset_node_definitions_on_open: bool,
|
||||
pub workspace_panel_layout: WorkspacePanelLayout,
|
||||
/// Parent directory that holds every document's `Gdd` working copy; a given document mounts at
|
||||
/// `working_copy_root.join(format!("{id:x}"))`. A filesystem path on native; on web it is
|
||||
/// converted to an OPFS directory name at the container-construction seam. `None` means no
|
||||
/// persistent location is configured (tests, headless) — documents mount an in-memory working
|
||||
/// copy instead, so the mount path still runs but writes nowhere durable.
|
||||
working_copy_root: Option<PathBuf>,
|
||||
/// Number of `.gdd` opens whose async build is in flight. While non-zero, resource GC is skipped:
|
||||
/// the opening document's resources are being extracted into the cache but it isn't in `documents`
|
||||
/// yet, so GC would wrongly evict them (notably proto-node declaration bytes).
|
||||
pending_gdd_opens: usize,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -206,7 +216,9 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::GarbageCollectResources);
|
||||
}
|
||||
PortfolioMessage::AutoSaveDocument { document_id } => {
|
||||
let Some(document) = self.document(document_id) else { return };
|
||||
let Some(byte_store) = resource_storage.storage() else { return };
|
||||
let Some(document) = self.documents.get_mut(&document_id) else { return };
|
||||
document.commit_storage_snapshot(byte_store);
|
||||
responses.add(PersistentStateMessage::WriteDocument {
|
||||
document_id,
|
||||
document: document.serialize_document(),
|
||||
@@ -381,6 +393,25 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
}
|
||||
PortfolioMessage::DocumentStorageMounted { document_id, reopened, gdd } => {
|
||||
let Some(document) = self.documents.get_mut(&document_id) else {
|
||||
// Document was closed before its working copy finished mounting; drop the `Gdd`.
|
||||
return;
|
||||
};
|
||||
document.storage = gdd;
|
||||
// On a fresh mount, capture the current runtime state into the working copy: edits made
|
||||
// during the mount window were skipped by `commit_storage_snapshot` (no-op while unmounted),
|
||||
// so this initial commit brings the working copy up to date. On a reopen the working copy
|
||||
// already holds the persisted cursor; re-committing here would stack a spurious interaction on it
|
||||
// and make the first undo a no-op, so trust the restored cursor and skip the commit.
|
||||
if !reopened && let Some(byte_store) = resource_storage.storage() {
|
||||
document.commit_storage_snapshot(byte_store);
|
||||
// Seal the freshly-converted document as the base revision: the conversion is a completed
|
||||
// import, not an in-progress interaction, so retire it into history rather than leaving it in
|
||||
// the hot log (where it would never reach an interaction boundary on a save without edits).
|
||||
document.retire_storage_interaction();
|
||||
}
|
||||
}
|
||||
PortfolioMessage::DestroyAllDocuments => {
|
||||
// Empty the list of internal document data
|
||||
self.documents.clear();
|
||||
@@ -396,6 +427,11 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
// We don't know what can be safely garbage collected
|
||||
return;
|
||||
}
|
||||
if self.pending_gdd_opens > 0 {
|
||||
// A .gdd open is extracting its resources into the cache but isn't in `documents` yet,
|
||||
// so its hashes would look unused. Skip this cycle; GC resumes once the open lands.
|
||||
return;
|
||||
}
|
||||
|
||||
let mut used_resources = HashSet::new();
|
||||
for (id, info) in self.unloaded_documents.iter() {
|
||||
@@ -409,6 +445,13 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
for document in self.documents.values_mut() {
|
||||
document.garbage_collect_resources();
|
||||
used_resources.extend(document.resources.registry.resolved().filter_map(|info| info.hash.cloned()));
|
||||
// Also keep resources referenced by the `.gdd` storage anywhere in history (notably proto-node
|
||||
// declaration bytes), which the runtime resource registry doesn't track but the working copy
|
||||
// and `.gdd` export need in the global cache. History-wide, not just the current registry:
|
||||
// an undo drops an interaction's resources from the working registry, but redo still needs them.
|
||||
if let Some(storage) = &document.storage {
|
||||
used_resources.extend(storage.all_referenced_resource_hashes());
|
||||
}
|
||||
}
|
||||
used_resources.extend(self.fonts.used_resources());
|
||||
responses.add(ResourceStorageMessage::GarbageCollect {
|
||||
@@ -594,7 +637,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
responses.add(NavigationMessage::CanvasPan { delta: (0., 0.).into() });
|
||||
}
|
||||
|
||||
self.load_document(new_document, document_id, responses);
|
||||
self.load_document(new_document, document_id, resource_storage, responses);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::MoveAllPanelTabs {
|
||||
@@ -731,6 +774,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_serialized_content: content,
|
||||
});
|
||||
}
|
||||
FileContent::GddDocument(content) => {
|
||||
let document_path = if path.is_absolute() { Some(path) } else { None };
|
||||
responses.add(PortfolioMessage::OpenGddDocument {
|
||||
document_name: name,
|
||||
document_path,
|
||||
content,
|
||||
});
|
||||
}
|
||||
FileContent::Svg(svg) => {
|
||||
responses.add(PortfolioMessage::OpenSvg { name, svg });
|
||||
}
|
||||
@@ -758,6 +809,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document_serialized_content: content,
|
||||
});
|
||||
}
|
||||
FileContent::GddDocument(content) => {
|
||||
// Treat importing a `.gdd` document as opening it (same as the legacy path above).
|
||||
responses.add(PortfolioMessage::OpenGddDocument {
|
||||
document_name: name,
|
||||
document_path: Some(path),
|
||||
content,
|
||||
});
|
||||
}
|
||||
FileContent::Svg(svg) => {
|
||||
responses.add(PortfolioMessage::PasteSvg {
|
||||
name,
|
||||
@@ -799,6 +858,66 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::OpenGddDocument {
|
||||
document_name,
|
||||
document_path,
|
||||
content,
|
||||
} => {
|
||||
let document_id = DocumentId(generate_uuid());
|
||||
let Some(store_handle) = resource_storage.store_handle() else {
|
||||
log::error!("Cannot open .gdd: resource storage not initialized");
|
||||
return;
|
||||
};
|
||||
// Suppress resource GC until the open completes: the document's resources are extracted
|
||||
// into the cache before it joins `documents`, so GC would otherwise evict them mid-open.
|
||||
self.pending_gdd_opens += 1;
|
||||
responses.add(open_gdd_document_future(
|
||||
self.working_copy_root.clone(),
|
||||
document_id,
|
||||
document_name,
|
||||
document_path,
|
||||
content,
|
||||
store_handle,
|
||||
));
|
||||
}
|
||||
PortfolioMessage::GddDocumentLoaded {
|
||||
document_id,
|
||||
document_name,
|
||||
document_path,
|
||||
document,
|
||||
} => {
|
||||
self.pending_gdd_opens = self.pending_gdd_opens.saturating_sub(1);
|
||||
|
||||
let Some(mut document) = document.map(|boxed| *boxed) else {
|
||||
// The build failed and already logged; nothing to insert.
|
||||
return;
|
||||
};
|
||||
document.finalize_storage_load();
|
||||
document.set_save_state(true);
|
||||
|
||||
let name = document_name
|
||||
.filter(|name| !name.trim().is_empty())
|
||||
.or_else(|| document_path.as_ref().and_then(|path| path.file_stem()).map(|stem| stem.to_string_lossy().into_owned()))
|
||||
.unwrap_or_else(|| DEFAULT_DOCUMENT_NAME.to_string());
|
||||
document.name = self.resolve_document_name(name, None);
|
||||
document.path = document_path;
|
||||
|
||||
// The working copy is already mounted (we opened the .gdd), so skip the async re-mount.
|
||||
self.load_document(document, document_id, resource_storage, responses);
|
||||
responses.add(PortfolioMessage::SelectDocument { document_id });
|
||||
}
|
||||
PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface } => {
|
||||
let Some(document) = self.documents.get_mut(&document_id) else {
|
||||
// Document was closed before its undo/redo rebuild completed; drop the payload.
|
||||
return;
|
||||
};
|
||||
let Some(interface) = interface.map(|boxed| *boxed) else {
|
||||
// The rebuild failed and already logged; leave the live document untouched.
|
||||
return;
|
||||
};
|
||||
|
||||
document.apply_gdd_cursor_rebuild(interface, had_oracle, responses);
|
||||
}
|
||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
@@ -944,7 +1063,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
document.name = self.resolve_document_name(candidate_name, None);
|
||||
|
||||
// Load the document into the portfolio so it opens in the editor
|
||||
self.load_document(document, document_id, responses);
|
||||
self.load_document(document, document_id, resource_storage, responses);
|
||||
|
||||
responses.add(AppWindowMessage::Focus);
|
||||
|
||||
@@ -1837,6 +1956,12 @@ impl PortfolioMessageHandler {
|
||||
Self { executor, ..Default::default() }
|
||||
}
|
||||
|
||||
/// Set the parent directory under which each document's `Gdd` working copy is mounted. `None`
|
||||
/// mounts in-memory working copies (no durable location configured).
|
||||
pub fn set_working_copy_root(&mut self, root: Option<PathBuf>) {
|
||||
self.working_copy_root = root;
|
||||
}
|
||||
|
||||
pub fn document(&self, document_id: DocumentId) -> Option<&DocumentMessageHandler> {
|
||||
self.documents.get(&document_id)
|
||||
}
|
||||
@@ -1891,30 +2016,28 @@ impl PortfolioMessageHandler {
|
||||
if trimmed.is_empty() { self.generate_new_document_name(exclude) } else { trimmed.to_string() }
|
||||
}
|
||||
|
||||
/// `exclude` lets a renaming caller skip its own current name so a document can rename back to its
|
||||
/// existing slot rather than colliding with itself and getting bumped to the next number.
|
||||
/// `exclude` lets a renaming caller skip its own current name so a document can rename back to
|
||||
/// its existing slot rather than colliding with itself and getting bumped to the next number.
|
||||
pub fn generate_new_document_name(&self, exclude: Option<DocumentId>) -> String {
|
||||
let mut doc_title_numbers = self
|
||||
let untitled = DEFAULT_DOCUMENT_NAME;
|
||||
|
||||
// Collect the numbers already used by existing default-named documents, skipping the excluded one
|
||||
let taken_numbers = self
|
||||
.document_ids
|
||||
.iter()
|
||||
.filter(|id| exclude != Some(**id))
|
||||
.filter_map(|id| self.document_details(*id))
|
||||
.filter(|&&id| exclude != Some(id))
|
||||
.filter_map(|&id| self.document_details(id))
|
||||
.filter_map(|doc| {
|
||||
doc.name
|
||||
.rsplit_once(DEFAULT_DOCUMENT_NAME)
|
||||
.map(|(prefix, number)| (prefix.is_empty()).then(|| number.trim().parse::<isize>().ok()).flatten().unwrap_or(1))
|
||||
let rest = doc.name.strip_prefix(untitled)?.trim();
|
||||
if rest.is_empty() { Some(1) } else { rest.parse::<usize>().ok() }
|
||||
})
|
||||
.collect::<Vec<isize>>();
|
||||
.collect::<HashSet<usize>>();
|
||||
|
||||
doc_title_numbers.sort_unstable();
|
||||
doc_title_numbers.iter_mut().enumerate().for_each(|(i, number)| *number = *number - i as isize - 2);
|
||||
// Uses binary search to find the index of the element where number is bigger than i
|
||||
let new_doc_title_num = doc_title_numbers.binary_search(&0).unwrap_or_else(|e| e) + 1;
|
||||
// Pick the lowest number not already in use (a match always exists since the range is unbounded)
|
||||
let new_number = (1..).find(|number| !taken_numbers.contains(number)).unwrap_or(1);
|
||||
|
||||
match new_doc_title_num {
|
||||
1 => DEFAULT_DOCUMENT_NAME.to_string(),
|
||||
_ => format!("{DEFAULT_DOCUMENT_NAME} {new_doc_title_num}"),
|
||||
}
|
||||
// Return "Untitled Document" for the first, then "Untitled Document {N}" for subsequent ones
|
||||
if new_number == 1 { untitled.to_string() } else { format!("{untitled} {new_number}") }
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
@@ -1936,6 +2059,7 @@ impl PortfolioMessageHandler {
|
||||
Ok(content) => FileContent::Document(content),
|
||||
Err(_) => FileContent::Unsupported,
|
||||
},
|
||||
GDD_FILE_EXTENSION => FileContent::GddDocument(content),
|
||||
"svg" => match String::from_utf8(content) {
|
||||
Ok(content) => FileContent::Svg(content),
|
||||
Err(_) => FileContent::Unsupported,
|
||||
@@ -1955,7 +2079,7 @@ impl PortfolioMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
fn load_document(&mut self, mut new_document: DocumentMessageHandler, document_id: DocumentId, responses: &mut VecDeque<Message>) {
|
||||
fn load_document(&mut self, mut new_document: DocumentMessageHandler, document_id: DocumentId, resource_storage: &ResourceStorageMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let is_new_document = !self.document_ids.contains(&document_id);
|
||||
if is_new_document {
|
||||
self.document_ids.push_back(document_id);
|
||||
@@ -1982,6 +2106,59 @@ impl PortfolioMessageHandler {
|
||||
if is_new_document {
|
||||
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
|
||||
}
|
||||
|
||||
// Mount the per-document `Gdd` working copy asynchronously (its container is built off-thread).
|
||||
// The document is already usable; the working copy attaches once the future resolves. With no
|
||||
// configured root the working copy is in-memory, so the mount path still runs uniformly.
|
||||
// Pass the just-loaded runtime network + a resource handle so a reopen can compare the stored
|
||||
// `.gdd` against this legacy load (compare-on-open).
|
||||
let legacy_network = self
|
||||
.documents
|
||||
.get(&document_id)
|
||||
.map(|document| document.network_interface.document_network().clone())
|
||||
.unwrap_or_default();
|
||||
responses.add(Self::mount_document_storage(self.working_copy_root.clone(), document_id, legacy_network, resource_storage.resources()));
|
||||
}
|
||||
|
||||
/// Build the `FutureMessage` that constructs (or reopens) the document's `Gdd` working copy and
|
||||
/// delivers it back via [`PortfolioMessage::DocumentStorageMounted`]. With a configured root the
|
||||
/// working copy lives at `<root>/<id_hex>`; without one it is in-memory.
|
||||
///
|
||||
/// On a *reopen* (existing working copy), the freshly-read `.gdd` is converted back to a runtime
|
||||
/// network and compared against `legacy_network` (the document the user actually loaded) before
|
||||
/// the working copy attaches. This is the dual-write soak's compare-on-open: it validates the
|
||||
/// `.gdd` *read* path (deserialize + hot-log replay), which the in-process `verify_storage_round_trip`
|
||||
/// can't, since that never touches persisted bytes. Legacy stays authoritative; divergence is logged.
|
||||
fn mount_document_storage(
|
||||
working_copy_root: Option<std::path::PathBuf>,
|
||||
document_id: DocumentId,
|
||||
legacy_network: graph_craft::document::NodeNetwork,
|
||||
byte_store: Box<dyn graph_craft::application_io::resource::LoadResource>,
|
||||
) -> Message {
|
||||
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
|
||||
let editor_version = crate::application::GRAPHITE_GIT_COMMIT_HASH.to_string();
|
||||
let peer = graph_storage::PeerId(generate_uuid());
|
||||
|
||||
let future = async move {
|
||||
let (gdd, reopened) = match build_or_open_working_copy(path.as_deref(), peer, document_id.0, editor_version).await {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
log::error!("Failed to mount document storage for {document_id:?}: {error}");
|
||||
return Message::NoOp;
|
||||
}
|
||||
};
|
||||
|
||||
if reopened {
|
||||
compare_storage_against_runtime(&gdd, &legacy_network, byte_store.as_ref(), document_id).await;
|
||||
}
|
||||
|
||||
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
|
||||
document_id,
|
||||
reopened,
|
||||
gdd: Some(gdd),
|
||||
})
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
/// Returns an iterator over the open documents in order.
|
||||
@@ -2148,6 +2325,301 @@ fn display_name_with_fallback(info: &DocumentInfo) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a document's `Gdd` working copy. With `Some(path)` it opens an existing on-disk working
|
||||
/// copy (reopen / autosave recovery) or creates a fresh one bound to `peer`, choosing the backend
|
||||
/// per platform: a folder on native, an OPFS directory on web (where `path` is the OPFS directory
|
||||
/// name). With `None` it creates a fresh in-memory working copy (tests, headless) that persists
|
||||
/// nowhere durable.
|
||||
///
|
||||
/// Returns the working copy plus whether it was reopened from an existing on-disk working copy
|
||||
/// (`true`) versus freshly created (`false`). Only a reopen has independently-read stored state and
|
||||
/// an embedded legacy blob worth comparing against the legacy load (compare-on-open).
|
||||
async fn build_or_open_working_copy(
|
||||
path: Option<&std::path::Path>,
|
||||
peer: graph_storage::PeerId,
|
||||
document_uuid: u64,
|
||||
version: String,
|
||||
) -> Result<(document_format::GddV1, bool), document_format::Error> {
|
||||
use document_container::AnyContainer;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
|
||||
let Some(path) = path else {
|
||||
let container = AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new());
|
||||
let gdd = GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?;
|
||||
return Ok((gdd, false));
|
||||
};
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
let (container, exists) = {
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
let exists = path.join("manifest.json").is_file();
|
||||
let backend = if exists { FolderBackend::open(path)? } else { FolderBackend::create(path)? };
|
||||
(AnyContainer::Folder(backend), exists)
|
||||
};
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
let (container, exists) = {
|
||||
use document_container::AsyncContainer;
|
||||
use document_container::backends::opfs::OpfsBackend;
|
||||
let directory_name = path
|
||||
.to_str()
|
||||
.ok_or(document_format::Error::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
|
||||
let backend = OpfsBackend::open(directory_name).await?;
|
||||
let exists = backend.exists("manifest.json").await;
|
||||
(AnyContainer::Opfs(backend), exists)
|
||||
};
|
||||
|
||||
let gdd = if exists {
|
||||
GddV1::open_in(container, GddV1Layout).await?
|
||||
} else {
|
||||
GddV1::create_in(container, GddV1Layout, peer, document_uuid, version.clone(), version).await?
|
||||
};
|
||||
Ok((gdd, exists))
|
||||
}
|
||||
|
||||
/// Build the per-document container for a working copy at `path` (folder native, OPFS web), or an
|
||||
/// in-memory container when `path` is `None`. Does not open or create a `Gdd` — just the backend.
|
||||
async fn build_per_document_container(path: Option<&std::path::Path>) -> Result<document_container::AnyContainer, document_format::Error> {
|
||||
use document_container::AnyContainer;
|
||||
|
||||
let Some(path) = path else {
|
||||
return Ok(AnyContainer::Memory(document_container::backends::memory::MemoryBackend::new()));
|
||||
};
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
{
|
||||
use document_container::backends::folder::FolderBackend;
|
||||
let backend = if path.join("manifest.json").is_file() {
|
||||
FolderBackend::open(path)?
|
||||
} else {
|
||||
FolderBackend::create(path)?
|
||||
};
|
||||
Ok(AnyContainer::Folder(backend))
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
{
|
||||
use document_container::backends::opfs::OpfsBackend;
|
||||
let directory_name = path
|
||||
.to_str()
|
||||
.ok_or(document_format::Error::Container(document_container::ContainerError::InvalidPath(path.display().to_string())))?;
|
||||
let backend = OpfsBackend::open(directory_name).await?;
|
||||
Ok(AnyContainer::Opfs(backend))
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the `FutureMessage` that opens a `.gdd` archive: materialize it into the per-document working
|
||||
/// copy, build the runtime from the stored registry, validate it against the embedded legacy blob, and
|
||||
/// deliver the finished document via [`PortfolioMessage::GddDocumentLoaded`]. Resource bytes carried in
|
||||
/// the archive are extracted into `store_handle` (the app-global cache) so declarations and the runtime
|
||||
/// resolve. The registry build is authoritative; the embedded legacy blob is the always-checked oracle
|
||||
/// and the fallback if the build fails.
|
||||
fn open_gdd_document_future(
|
||||
working_copy_root: Option<std::path::PathBuf>,
|
||||
document_id: DocumentId,
|
||||
document_name: Option<String>,
|
||||
document_path: Option<std::path::PathBuf>,
|
||||
content: Vec<u8>,
|
||||
store_handle: crate::messages::resource_storage::ResourcesHandle,
|
||||
) -> Message {
|
||||
let path = working_copy_root.map(|root| root.join(format!("{:x}", document_id.0)));
|
||||
|
||||
let future = async move {
|
||||
let document = build_document_from_gdd(path.as_deref(), &content, &store_handle, document_id).await;
|
||||
Message::Portfolio(PortfolioMessage::GddDocumentLoaded {
|
||||
document_id,
|
||||
document_name,
|
||||
document_path,
|
||||
document: document.map(Box::new),
|
||||
})
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
/// Build the `FutureMessage` that rebuilds a document's interface from its `Gdd` undo/redo cursor. The
|
||||
/// cursor already moved and persisted synchronously in the handler; `gdd` is a snapshot clone at that
|
||||
/// post-move position. This loads the cursor's declarations, converts the registry back to a runtime
|
||||
/// network with full metadata, builds the interface, and delivers it via [`PortfolioMessage::GddUndoRedoRebuilt`]
|
||||
/// so the handler can swap it in (preserving transients) and compare against the legacy oracle. `interface`
|
||||
/// is `None` on failure (logged here), in which case the handler leaves the live document untouched.
|
||||
pub(crate) fn rebuild_gdd_cursor_future(gdd: document_format::GddV1, store_handle: crate::messages::resource_storage::ResourcesHandle, document_id: DocumentId, had_oracle: bool) -> Message {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::build_interface_from_storage;
|
||||
|
||||
let future = async move {
|
||||
let declarations = gdd.declarations(&store_handle).await;
|
||||
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
|
||||
Ok((network, node_entries, network_entries)) => match build_interface_from_storage(network, node_entries, network_entries) {
|
||||
Ok(interface) => Some(Box::new(interface)),
|
||||
Err(error) => {
|
||||
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to build interface: {error}");
|
||||
None
|
||||
}
|
||||
},
|
||||
Err(error) => {
|
||||
log::error!("Gdd undo/redo rebuild for {document_id:?}: failed to convert registry to runtime: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
Message::Portfolio(PortfolioMessage::GddUndoRedoRebuilt { document_id, had_oracle, interface })
|
||||
};
|
||||
future.into()
|
||||
}
|
||||
|
||||
/// Core of the `.gdd` open: archive -> working copy -> `Gdd` -> runtime interface, with the embedded
|
||||
/// legacy blob loaded for validation (always compared) and fallback (used if the registry build fails).
|
||||
/// Returns the built document, or `None` if neither the registry build nor the legacy fallback worked.
|
||||
async fn build_document_from_gdd(
|
||||
path: Option<&std::path::Path>,
|
||||
content: &[u8],
|
||||
store_handle: &impl graph_craft::application_io::resource::ResourceStorage,
|
||||
document_id: DocumentId,
|
||||
) -> Option<DocumentMessageHandler> {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::storage_metadata::{apply_network_view_settings, build_interface_from_storage, network_ids_from_entries};
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
|
||||
let container = match build_per_document_container(path).await {
|
||||
Ok(container) => container,
|
||||
Err(error) => {
|
||||
log::error!("Opening .gdd for {document_id:?}: failed to build working copy container: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let gdd = match GddV1::open_from_archive(content, container, GddV1Layout).await {
|
||||
Ok(gdd) => gdd,
|
||||
Err(error) => {
|
||||
log::error!("Opening .gdd for {document_id:?}: failed to open archive: {error}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
// Extract resource bytes carried in the archive into the global cache so declarations + runtime resolve.
|
||||
match gdd.resource_hashes().await {
|
||||
Ok(hashes) => {
|
||||
for hash in hashes {
|
||||
match gdd.read_resource(&hash).await {
|
||||
Ok(holder) => {
|
||||
store_handle.store(holder.as_slice());
|
||||
}
|
||||
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to read resource {hash}: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => log::error!("Opening .gdd for {document_id:?}: failed to list resources: {error}"),
|
||||
}
|
||||
|
||||
// Full legacy load of the embedded blob: serves as both the validation oracle and the fallback.
|
||||
let legacy_document = gdd
|
||||
.read_legacy_document()
|
||||
.await
|
||||
.and_then(|holder| String::from_utf8(holder.as_slice().to_vec()).ok())
|
||||
.and_then(|serialized| DocumentMessageHandler::deserialize_document(&document_migration_string_preprocessing(serialized)).ok());
|
||||
|
||||
// Build the runtime from the stored registry (authoritative).
|
||||
let declarations = gdd.declarations(store_handle).await;
|
||||
let interface = match gdd.registry().to_runtime_with_full_metadata(&declarations) {
|
||||
Ok((network, node_entries, network_entries)) => {
|
||||
let network_ids = network_ids_from_entries(&network_entries);
|
||||
match build_interface_from_storage(network, node_entries, network_entries) {
|
||||
Ok(mut interface) => {
|
||||
// Restore the per-network, per-peer view state (node-graph nav + previewing) from
|
||||
// `session.json`; it travels in the archive but isn't in the registry/history.
|
||||
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
|
||||
Some(interface)
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Opening .gdd for {document_id:?}: failed to build interface: {error}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
log::error!("Opening .gdd for {document_id:?}: failed to convert registry to runtime: {error}");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Compare the registry build against the legacy oracle (always, when both are available). Normalize the
|
||||
// benign generic-vs-resolved `call_argument` difference (see `normalize_call_arguments_for_compare`) so
|
||||
// it doesn't flag.
|
||||
if let Some(interface) = interface {
|
||||
if let Some(legacy) = &legacy_document {
|
||||
let mut built = interface.document_network().clone();
|
||||
let mut oracle = legacy.network_interface.document_network().clone();
|
||||
normalize_call_arguments_for_compare(&mut built);
|
||||
normalize_call_arguments_for_compare(&mut oracle);
|
||||
if built != oracle {
|
||||
log::error!(
|
||||
"Open-.gdd divergence for {document_id:?}: registry-built document differs from the embedded legacy blob\n{}",
|
||||
crate::messages::portfolio::document::diff_networks(&oracle, &built)
|
||||
);
|
||||
}
|
||||
}
|
||||
return Some(DocumentMessageHandler::from_storage(interface, gdd, String::new(), None));
|
||||
}
|
||||
|
||||
// Registry build failed: fall back to the embedded legacy document.
|
||||
log::warn!("Opening .gdd for {document_id:?}: registry build failed, falling back to embedded legacy document");
|
||||
if legacy_document.is_none() {
|
||||
log::error!("Opening .gdd for {document_id:?}: no embedded legacy document to fall back to");
|
||||
}
|
||||
legacy_document
|
||||
}
|
||||
|
||||
/// Compare-on-open: convert the reopened `.gdd`'s stored registry back to a runtime network and diff
|
||||
/// it against `legacy_network` (the document the user actually loaded). Validates the `.gdd` read path
|
||||
/// against the legacy load. Legacy is authoritative during the soak, so this only logs divergence; it
|
||||
/// never swaps the candidate in. Cold-path (runs once per open, off the edit hot path).
|
||||
async fn compare_storage_against_runtime(
|
||||
gdd: &document_format::GddV1,
|
||||
legacy_network: &graph_craft::document::NodeNetwork,
|
||||
byte_store: &dyn graph_craft::application_io::resource::LoadResource,
|
||||
document_id: DocumentId,
|
||||
) {
|
||||
let declarations = gdd.declarations(byte_store).await;
|
||||
let mut candidate = match gdd.registry().to_runtime_with_metadata(&declarations) {
|
||||
Ok((network, _entries)) => network,
|
||||
Err(error) => {
|
||||
log::error!("Compare-on-open for {document_id:?}: .gdd registry failed to convert to runtime: {error}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// One open/restore path resolves a node's generic `call_argument` (e.g. a layer's inner monitor node's
|
||||
// `T`) to a concrete `Context`, while storage faithfully keeps the authored `T`. That generic-vs-resolved
|
||||
// difference is benign (it's recomputed during compilation), so normalize it on both sides before
|
||||
// comparing to keep the soak signal focused on real drift.
|
||||
let mut legacy = legacy_network.clone();
|
||||
normalize_call_arguments_for_compare(&mut legacy);
|
||||
normalize_call_arguments_for_compare(&mut candidate);
|
||||
|
||||
if candidate != legacy {
|
||||
log::error!(
|
||||
"Compare-on-open divergence for {document_id:?}: the reopened .gdd does not match the legacy load\n{}",
|
||||
crate::messages::portfolio::document::diff_networks(&legacy, &candidate)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonicalize every node's `call_argument` (recursively, including nested networks) so a generic `T`
|
||||
/// and its compilation-resolved concrete `Context` compare equal. Storage keeps the authored generic
|
||||
/// form, but one load/restore path resolves it to `Context`; that difference is benign for the
|
||||
/// compare-on-open soak check. Concrete `call_arguments` other than `Context` are left untouched.
|
||||
fn normalize_call_arguments_for_compare(network: &mut graph_craft::document::NodeNetwork) {
|
||||
use graph_craft::Type;
|
||||
|
||||
let context = graph_craft::concrete!(graphene_std::Context);
|
||||
for node in network.nodes.values_mut() {
|
||||
if node.call_argument == context {
|
||||
node.call_argument = Type::Generic(std::borrow::Cow::Borrowed("T"));
|
||||
}
|
||||
if let graph_craft::document::DocumentNodeImplementation::Network(inner) = &mut node.implementation {
|
||||
normalize_call_arguments_for_compare(inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `None` if the name has no safe filename characters left or matches a Windows reserved device name, so callers fall back to an ID-based stem.
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
fn sanitize_filename_stem(name: &str) -> Option<String> {
|
||||
|
||||
@@ -789,8 +789,10 @@ impl PanelLayoutSubdivision {
|
||||
}
|
||||
|
||||
pub enum FileContent {
|
||||
/// A Graphite document.
|
||||
/// A legacy `.graphite` document (serialized runtime JSON).
|
||||
Document(String),
|
||||
/// A `.gdd` document container (archive bytes).
|
||||
GddDocument(Vec<u8>),
|
||||
/// A bitmap image.
|
||||
Image(Image<Color>),
|
||||
/// An SVG file string.
|
||||
|
||||
@@ -13,6 +13,20 @@ impl LoadResource for ResourcesHandle {
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceStorage for ResourcesHandle {
|
||||
fn store(&self, data: &[u8]) -> ResourceHash {
|
||||
self.inner.store(data)
|
||||
}
|
||||
|
||||
fn contains(&self, hash: &ResourceHash) -> bool {
|
||||
self.inner.contains(hash)
|
||||
}
|
||||
|
||||
fn garbage_collect(&self, used: &[ResourceHash]) {
|
||||
self.inner.garbage_collect(used)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct ResourceStorageMessageHandler {
|
||||
storage: Option<Arc<dyn ResourceStorage>>,
|
||||
@@ -28,6 +42,18 @@ impl ResourceStorageMessageHandler {
|
||||
inner: self.storage.clone().expect("Resource storage not initialized"),
|
||||
})
|
||||
}
|
||||
|
||||
/// The backing store as a `&dyn ResourceStorage`, for write paths (e.g. persisting declaration
|
||||
/// bytes on commit). `None` before initialization.
|
||||
pub fn storage(&self) -> Option<&dyn ResourceStorage> {
|
||||
self.storage.as_deref()
|
||||
}
|
||||
|
||||
/// An owned, cloneable handle that both loads and stores, for `'static` async tasks that need to
|
||||
/// read and write the cache off-thread. `None` before initialization.
|
||||
pub fn store_handle(&self) -> Option<ResourcesHandle> {
|
||||
self.storage.clone().map(|inner| ResourcesHandle { inner })
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for ResourceStorageMessageHandler {
|
||||
|
||||
@@ -292,6 +292,12 @@ pub fn get_upstream_gradient_value_node_id(layer: LayerNodeIdentifier, network_i
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_value::IDENTIFIER)))
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Get the layer's "Fill" node itself (whose `fill` input holds the paint value), not the node feeding that input.
|
||||
pub fn get_fill_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))
|
||||
}
|
||||
|
||||
/// Get the node connected to Fill's fill input, if any.
|
||||
pub fn get_fill_input_node_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
let fill_node_id = NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
@@ -337,10 +343,16 @@ pub fn gradient_space_transform(layer: LayerNodeIdentifier, network_interface: &
|
||||
.map(|footprint| footprint.transform)
|
||||
.unwrap_or(metadata.document_to_viewport);
|
||||
}
|
||||
let multiplied = metadata.transform_to_viewport(layer);
|
||||
let bounds = metadata.nonzero_bounding_box(layer);
|
||||
let bound_transform = glam::DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
multiplied * bound_transform
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// Only an existing legacy `Fill::Gradient` is in (0, 0)..(1, 1) bounding-box space; migrated and newly-created gradients are absolute (layer space).
|
||||
if get_gradient(layer, network_interface).is_some_and(|gradient| !gradient.absolute) {
|
||||
let bounds = metadata.nonzero_bounding_box(layer);
|
||||
let bound_transform = glam::DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
return metadata.transform_to_viewport(layer) * bound_transform;
|
||||
}
|
||||
|
||||
metadata.transform_to_viewport(layer)
|
||||
}
|
||||
|
||||
/// True when start→end (mapped through `transform` into viewport space) points predominantly rightward. For purely
|
||||
@@ -468,57 +480,54 @@ pub fn get_text<'a>(
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
fonts: &FontsMessageHandler,
|
||||
resources: &ResourceMessageHandler,
|
||||
) -> Option<(&'a String, Font, TypesettingConfig, bool)> {
|
||||
) -> Option<(&'a String, Font, TypesettingConfig)> {
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER))?;
|
||||
|
||||
let Some(TaggedValue::String(text)) = &inputs[graphene_std::text::text::TextInput::INDEX].as_value() else {
|
||||
let Some(TaggedValue::String(text)) = inputs.get(graphene_std::text::text::TextInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let font = match &inputs[graphene_std::text::text::FontInput::INDEX].as_value() {
|
||||
let font = match inputs.get(graphene_std::text::text::FontInput::INDEX)?.as_value() {
|
||||
Some(TaggedValue::Resource(resource_id)) => fonts.id_font(resources, *resource_id).unwrap_or_default(),
|
||||
_ => Font::default(),
|
||||
};
|
||||
let Some(&TaggedValue::F64(font_size)) = inputs[graphene_std::text::text::SizeInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::F64(font_size)) = inputs.get(graphene_std::text::text::SizeInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(line_height_ratio)) = inputs[graphene_std::text::text::LineHeightInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::F64(line_height_ratio)) = inputs.get(graphene_std::text::text::LineHeightInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(character_spacing)) = inputs[graphene_std::text::text::CharacterSpacingInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::F64(letter_spacing)) = inputs.get(graphene_std::text::text::LetterSpacingInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Bool(has_max_width)) = inputs[graphene_std::text::text::HasMaxWidthInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::Bool(has_max_width)) = inputs.get(graphene_std::text::text::HasMaxWidthInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(max_width)) = inputs[graphene_std::text::text::MaxWidthInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::F64(max_width)) = inputs.get(graphene_std::text::text::MaxWidthInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Bool(has_max_height)) = inputs[graphene_std::text::text::HasMaxHeightInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::Bool(has_max_height)) = inputs.get(graphene_std::text::text::HasMaxHeightInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(max_height)) = inputs[graphene_std::text::text::MaxHeightInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::F64(max_height)) = inputs.get(graphene_std::text::text::MaxHeightInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::F64(tilt)) = inputs[graphene_std::text::text::TiltInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::F64(letter_tilt)) = inputs.get(graphene_std::text::text::LetterTiltInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::TextAlign(align)) = inputs[graphene_std::text::text::AlignInput::INDEX].as_value() else {
|
||||
return None;
|
||||
};
|
||||
let Some(&TaggedValue::Bool(per_glyph_items)) = inputs[graphene_std::text::text::SeparateGlyphsInput::INDEX].as_value() else {
|
||||
let Some(&TaggedValue::TextAlign(align)) = inputs.get(graphene_std::text::text::AlignInput::INDEX)?.as_value() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size,
|
||||
line_height_ratio,
|
||||
letter_spacing,
|
||||
letter_tilt,
|
||||
max_width: has_max_width.then_some(max_width),
|
||||
max_height: has_max_height.then_some(max_height),
|
||||
character_spacing,
|
||||
tilt,
|
||||
align,
|
||||
};
|
||||
Some((text, font, typesetting, per_glyph_items))
|
||||
Some((text, font, typesetting))
|
||||
}
|
||||
|
||||
pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<f64> {
|
||||
|
||||
@@ -8,7 +8,6 @@ use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::transformation::OriginalTransforms;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::compass_rose::Axis;
|
||||
use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_std::renderer::Quad;
|
||||
@@ -302,9 +301,13 @@ impl SelectedEdges {
|
||||
}
|
||||
}
|
||||
|
||||
/// Aligns the mouse position to the closest axis
|
||||
pub fn axis_align_drag(axis_align: bool, axis: Axis, position: DVec2, start: DVec2) -> DVec2 {
|
||||
if axis_align {
|
||||
/// Aligns the mouse position to the closest axis. The `axis_constraint`, if nonzero, is a unit vector along which dragging is constrained (e.g. the compass rose's local axis direction).
|
||||
pub fn axis_align_drag(axis_align: bool, axis_constraint: DVec2, position: DVec2, start: DVec2) -> DVec2 {
|
||||
// An explicit axis constraint (the compass rose's local axis) takes priority over the screen-space angle snapping
|
||||
if axis_constraint != DVec2::ZERO {
|
||||
let mouse_position = position - start;
|
||||
start + axis_constraint * mouse_position.dot(axis_constraint)
|
||||
} else if axis_align {
|
||||
let mouse_position = position - start;
|
||||
let snap_resolution = SELECTION_DRAG_ANGLE.to_radians();
|
||||
let angle = -mouse_position.angle_to(DVec2::X);
|
||||
@@ -315,18 +318,14 @@ pub fn axis_align_drag(axis_align: bool, axis: Axis, position: DVec2, start: DVe
|
||||
} else {
|
||||
start
|
||||
}
|
||||
} else if axis.is_constraint() {
|
||||
let mouse_position = position - start;
|
||||
let axis_vector: DVec2 = axis.into();
|
||||
start + axis_vector * mouse_position.dot(axis_vector)
|
||||
} else {
|
||||
position
|
||||
}
|
||||
}
|
||||
|
||||
/// Snaps a dragging event from the artboard or select tool
|
||||
pub fn snap_drag(start: DVec2, current: DVec2, snap_to_axis: bool, axis: Axis, snap_data: SnapData, snap_manager: &mut SnapManager, candidates: &[SnapCandidatePoint]) -> DVec2 {
|
||||
let mouse_position = axis_align_drag(snap_to_axis, axis, snap_data.input.mouse.position, start);
|
||||
/// Snaps a dragging event from the artboard or select tool. A nonzero `axis_constraint` is a unit vector constraining the drag to that direction.
|
||||
pub fn snap_drag(start: DVec2, current: DVec2, snap_to_axis: bool, axis_constraint: DVec2, snap_data: SnapData, snap_manager: &mut SnapManager, candidates: &[SnapCandidatePoint]) -> DVec2 {
|
||||
let mouse_position = axis_align_drag(snap_to_axis, axis_constraint, snap_data.input.mouse.position, start);
|
||||
let document = snap_data.document;
|
||||
let total_mouse_delta_document = document.metadata().document_to_viewport.inverse().transform_vector2(mouse_position - start);
|
||||
let mouse_delta_document = document.metadata().document_to_viewport.inverse().transform_vector2(mouse_position - current);
|
||||
@@ -346,7 +345,7 @@ pub fn snap_drag(start: DVec2, current: DVec2, snap_to_axis: bool, axis: Axis, s
|
||||
let mut point = point.clone();
|
||||
point.document_point += total_mouse_delta_document;
|
||||
|
||||
let constrained_along_axis = snap_to_axis || axis.is_constraint();
|
||||
let constrained_along_axis = snap_to_axis || axis_constraint != DVec2::ZERO;
|
||||
let snapped = if constrained_along_axis {
|
||||
let constraint = SnapConstraint::Line {
|
||||
origin: point.document_point,
|
||||
|
||||
@@ -69,7 +69,7 @@ pub fn text_bounding_box(layer: LayerNodeIdentifier, document: &DocumentMessageH
|
||||
}
|
||||
|
||||
// Fallback: recompute from text content (e.g. layer hasn't rendered yet)
|
||||
let Some((text, font, typesetting, _)) = get_text(layer, &document.network_interface, fonts, &document.resources) else {
|
||||
let Some((text, font, typesetting)) = get_text(layer, &document.network_interface, fonts, &document.resources) else {
|
||||
return Quad::from_box([DVec2::ZERO, DVec2::ZERO]);
|
||||
};
|
||||
let font = fonts.get_resource_or_queue_load(&font, responses);
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::messages::portfolio::document::graph_operation::utility_types::Transf
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::compass_rose::Axis;
|
||||
use crate::messages::tool::common_functionality::measure;
|
||||
use crate::messages::tool::common_functionality::resize::Resize;
|
||||
use crate::messages::tool::common_functionality::snapping;
|
||||
@@ -336,7 +335,7 @@ impl Fsm for ArtboardToolFsmState {
|
||||
let snap_data = SnapData::ignore(document, input, viewport, &ignore);
|
||||
let document_to_viewport = document.metadata().document_to_viewport;
|
||||
let [start, current] = [tool_data.drag_start, tool_data.drag_current].map(|point| document_to_viewport.transform_point2(point));
|
||||
let mouse_delta = snap_drag(start, current, axis_align, Axis::None, snap_data, &mut tool_data.draw.snap_manager, &tool_data.snap_candidates);
|
||||
let mouse_delta = snap_drag(start, current, axis_align, DVec2::ZERO, snap_data, &mut tool_data.draw.snap_manager, &tool_data.snap_candidates);
|
||||
|
||||
let size = bounds.bounds[1] - bounds.bounds[0];
|
||||
let position = bounds.bounds[0] + bounds.transform.inverse().transform_vector2(mouse_delta);
|
||||
|
||||
@@ -363,6 +363,9 @@ fn get_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInter
|
||||
spread_method: chain_state.spread_method,
|
||||
start: chain_state.transform.transform_point2(DVec2::ZERO),
|
||||
end: chain_state.transform.transform_point2(DVec2::X),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
})
|
||||
} else {
|
||||
// Try to find a legacy Fill::Gradient that is selected in a Fill node
|
||||
@@ -799,6 +802,8 @@ struct GradientToolData {
|
||||
selected_gradient: Option<SelectedGradient>,
|
||||
snap_manager: SnapManager,
|
||||
drag_start: DVec2,
|
||||
/// The pointer-down position before snapping (document space), used to detect whether the mouse moved between the press and a double-click.
|
||||
drag_start_unsnapped: DVec2,
|
||||
auto_panning: AutoPanning,
|
||||
auto_pan_shift: DVec2,
|
||||
gradient_angle: f64,
|
||||
@@ -1058,8 +1063,9 @@ impl Fsm for GradientToolFsmState {
|
||||
}
|
||||
}
|
||||
(_, GradientToolMessage::DoubleClick) => {
|
||||
// Only reset if the mouse hasn't moved so we don't trigger from a click-then-click-and-drag being reported as a double-click
|
||||
let drag_start_viewport = document.metadata().document_to_viewport.transform_point2(tool_data.drag_start);
|
||||
// Only reset if the mouse hasn't moved so we don't trigger from a click-then-click-and-drag being reported as a double-click.
|
||||
// Compared against the unsnapped press position so a snap point near the stop doesn't make a stationary mouse look moved.
|
||||
let drag_start_viewport = document.metadata().document_to_viewport.transform_point2(tool_data.drag_start_unsnapped);
|
||||
if input.mouse.position.distance(drag_start_viewport) <= DRAG_THRESHOLD
|
||||
&& let Some(selected_gradient) = &mut tool_data.selected_gradient
|
||||
{
|
||||
@@ -1255,6 +1261,7 @@ impl Fsm for GradientToolFsmState {
|
||||
}
|
||||
|
||||
tool_data.drag_start = document_to_viewport.inverse().transform_point2(mouse);
|
||||
tool_data.drag_start_unsnapped = point.document_point;
|
||||
tool_data.auto_pan_shift = DVec2::ZERO;
|
||||
let tolerance = (MANIPULATOR_GROUP_MARKER_SIZE * 2.).powi(2);
|
||||
|
||||
|
||||
@@ -1282,13 +1282,23 @@ impl Fsm for SelectToolFsmState {
|
||||
.map(|bounding_box_manager| bounding_box_manager.transform * Quad::from_box(bounding_box_manager.bounds))
|
||||
.map_or(DVec2::X, |quad| (quad.top_left() - quad.top_right()).normalize_or(DVec2::X));
|
||||
|
||||
let mouse_delta = snap_drag(start, current, tool_data.axis_align, axis, snap_data, &mut tool_data.snap_manager, &tool_data.snap_candidates);
|
||||
let mouse_delta = match axis {
|
||||
Axis::X => mouse_delta.project_onto(e0),
|
||||
Axis::Y => mouse_delta.project_onto(e0.perp()),
|
||||
Axis::None => mouse_delta,
|
||||
// Constrain the drag to the selection's local axis (not the world axis) so a rotated object's arrows track the mouse one-to-one
|
||||
let axis_constraint = match axis {
|
||||
Axis::X => e0,
|
||||
Axis::Y => e0.perp(),
|
||||
Axis::None => DVec2::ZERO,
|
||||
};
|
||||
|
||||
let mouse_delta = snap_drag(
|
||||
start,
|
||||
current,
|
||||
tool_data.axis_align,
|
||||
axis_constraint,
|
||||
snap_data,
|
||||
&mut tool_data.snap_manager,
|
||||
&tool_data.snap_candidates,
|
||||
);
|
||||
|
||||
// TODO: Cache the result of `shallowest_unique_layers` to avoid this heavy computation every frame of movement, see https://github.com/GraphiteEditor/Graphite/pull/481
|
||||
for layer in document.network_interface.shallowest_unique_layers(&[]) {
|
||||
responses.add_front(GraphOperationMessage::TransformChange {
|
||||
|
||||
@@ -35,11 +35,11 @@ pub struct TextTool {
|
||||
}
|
||||
|
||||
pub struct TextOptions {
|
||||
font_size: f64,
|
||||
character_spacing: f64,
|
||||
font: Font,
|
||||
font_size: f64,
|
||||
letter_spacing: f64,
|
||||
letter_tilt: f64,
|
||||
fill: ToolColorOptions,
|
||||
tilt: f64,
|
||||
align: TextAlign,
|
||||
/// Set of layers we last synced from, used to detect real selection changes vs. internal node toggles.
|
||||
last_synced_selection: Vec<LayerNodeIdentifier>,
|
||||
@@ -48,11 +48,11 @@ pub struct TextOptions {
|
||||
impl Default for TextOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
font_size: 24.,
|
||||
character_spacing: 0.,
|
||||
font: Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into()),
|
||||
font_size: 24.,
|
||||
letter_spacing: 0.,
|
||||
letter_tilt: 0.,
|
||||
fill: ToolColorOptions::new_enabled(),
|
||||
tilt: 0.,
|
||||
align: TextAlign::default(),
|
||||
last_synced_selection: Vec::new(),
|
||||
}
|
||||
@@ -298,7 +298,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
ToolMessage::Text(TextToolMessage::UpdateOptions { options }) => options,
|
||||
ToolMessage::Text(TextToolMessage::SelectionChanged) => {
|
||||
if let Some(layer) = can_edit_selected(context.document)
|
||||
&& let Some((_, font, typesetting, _)) = graph_modification_utils::get_text(layer, &context.document.network_interface, context.fonts, &context.document.resources)
|
||||
&& let Some((_, font, typesetting)) = graph_modification_utils::get_text(layer, &context.document.network_interface, context.fonts, &context.document.resources)
|
||||
{
|
||||
self.options.align = typesetting.align;
|
||||
self.options.font_size = typesetting.font_size;
|
||||
@@ -516,7 +516,7 @@ impl TextToolData {
|
||||
fn load_layer_text_node(&mut self, document: &DocumentMessageHandler, fonts: &FontsMessageHandler) -> Option<()> {
|
||||
let transform = document.metadata().transform_to_viewport(self.layer);
|
||||
let color = graph_modification_utils::get_fill_color(self.layer, &document.network_interface).unwrap_or(Color::BLACK);
|
||||
let (text, font, typesetting, _) = graph_modification_utils::get_text(self.layer, &document.network_interface, fonts, &document.resources)?;
|
||||
let (text, font, typesetting) = graph_modification_utils::get_text(self.layer, &document.network_interface, fonts, &document.resources)?;
|
||||
self.editing_text = Some(EditingText {
|
||||
text: text.clone(),
|
||||
font,
|
||||
@@ -573,7 +573,7 @@ impl TextToolData {
|
||||
});
|
||||
responses.add(GraphOperationMessage::FillSet {
|
||||
layer: self.layer,
|
||||
fill: if let Some(color) = editing_text.color { Fill::Solid(color) } else { Fill::None },
|
||||
fill: editing_text.color.map_or(Fill::None, Fill::Solid),
|
||||
});
|
||||
let transform = editing_text.transform;
|
||||
self.editing_text = Some(editing_text);
|
||||
@@ -654,14 +654,21 @@ impl Fsm for TextToolFsmState {
|
||||
let ToolMessage::Text(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(TextToolFsmState::Editing, TextToolMessage::Overlays { context: mut overlay_context }) => {
|
||||
let transform = document.metadata().transform_to_viewport(tool_data.layer).to_cols_array();
|
||||
// While editing, the text is blanked, so the layer's rendered transform metadata is absent; read the Transform node so the overlay tracks placement
|
||||
let transform = document
|
||||
.metadata()
|
||||
.transform_to_viewport_with_first_transform_node_if_group(tool_data.layer, &document.network_interface)
|
||||
.to_cols_array();
|
||||
responses.add(FrontendMessage::DisplayEditableTextboxTransform { transform });
|
||||
if let Some(editing_text) = tool_data.editing_text.as_mut() {
|
||||
let font_resource = fonts.get_resource_or_queue_load(&editing_text.font, responses);
|
||||
let far = graphene_std::text::bounding_box(&tool_data.new_text, &font_resource, editing_text.typesetting, false);
|
||||
if far.x != 0. && far.y != 0. {
|
||||
let quad = Quad::from_box([DVec2::ZERO, far]);
|
||||
let transformed_quad = document.metadata().transform_to_viewport(tool_data.layer) * quad;
|
||||
let transformed_quad = document
|
||||
.metadata()
|
||||
.transform_to_viewport_with_first_transform_node_if_group(tool_data.layer, &document.network_interface)
|
||||
* quad;
|
||||
overlay_context.quad(transformed_quad, None, Some(fill_color));
|
||||
}
|
||||
}
|
||||
@@ -701,7 +708,7 @@ impl Fsm for TextToolFsmState {
|
||||
bounding_box_manager.render_quad(&mut overlay_context);
|
||||
// Draw red overlay if text is clipped
|
||||
let transformed_quad = layer_transform * bounds;
|
||||
if let Some((text, font, typesetting, _)) = graph_modification_utils::get_text(layer.unwrap(), &document.network_interface, fonts, &document.resources) {
|
||||
if let Some((text, font, typesetting)) = graph_modification_utils::get_text(layer.unwrap(), &document.network_interface, fonts, &document.resources) {
|
||||
let font_resource = fonts.get_resource_or_queue_load(&font, responses);
|
||||
if lines_clipping(text.as_str(), &font_resource, typesetting) {
|
||||
overlay_context.line(transformed_quad.0[2], transformed_quad.0[3], Some(COLOR_OVERLAY_RED), Some(3.));
|
||||
@@ -964,17 +971,23 @@ impl Fsm for TextToolFsmState {
|
||||
return TextToolFsmState::Editing;
|
||||
}
|
||||
|
||||
// Otherwise create some new text
|
||||
let constraint_size = has_dragged.then_some((start - end).abs());
|
||||
// Otherwise create some new text. The drag bounds are in viewport space; map them into document space for the text's
|
||||
// transform and wrapping size, then compose with document-to-viewport so the editing overlay (a screen-space CSS matrix) carries the zoom.
|
||||
let document_to_viewport = document.metadata().document_to_viewport;
|
||||
let viewport_to_document = document_to_viewport.inverse();
|
||||
let document_start = viewport_to_document.transform_point2(start);
|
||||
let document_end = viewport_to_document.transform_point2(end);
|
||||
|
||||
let constraint_size = has_dragged.then_some((document_start - document_end).abs());
|
||||
let editing_text = EditingText {
|
||||
text: String::new(),
|
||||
transform: DAffine2::from_translation(start),
|
||||
transform: document_to_viewport * DAffine2::from_translation(document_start),
|
||||
typesetting: TypesettingConfig {
|
||||
font_size: tool_options.font_size,
|
||||
letter_spacing: tool_options.letter_spacing,
|
||||
letter_tilt: tool_options.letter_tilt,
|
||||
max_width: constraint_size.map(|size| size.x),
|
||||
character_spacing: tool_options.character_spacing,
|
||||
max_height: constraint_size.map(|size| size.y),
|
||||
tilt: tool_options.tilt,
|
||||
align: tool_options.align,
|
||||
..TypesettingConfig::default()
|
||||
},
|
||||
|
||||
@@ -458,6 +458,11 @@ impl NodeGraphExecutor {
|
||||
first_element_source_id,
|
||||
});
|
||||
responses.add(DocumentMessage::UpdateClickTargets { click_targets });
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// Runs after click targets land (this graph run's geometry bounds) so the deferred gradient migration can use them.
|
||||
responses.add(DocumentMessage::MigrateLegacyGradients);
|
||||
|
||||
responses.add(DocumentMessage::UpdateOutlines { outlines });
|
||||
responses.add(DocumentMessage::UpdateTextFrames { text_frames });
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
|
||||
@@ -9,7 +9,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, ImageTexture, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig};
|
||||
use graphene_std::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::ops::Convert;
|
||||
@@ -414,10 +414,10 @@ impl NodeRuntime {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Graphic list: thumbnail
|
||||
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||
if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<Graphic>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = io.output.thumbnail_bounding_box(DAffine2::IDENTITY, true);
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
@@ -434,6 +434,13 @@ impl NodeRuntime {
|
||||
// Insert the vector modify
|
||||
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
|
||||
}
|
||||
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
||||
else if let Some(io) = introspected_data.downcast_ref::<IORecord<Context, List<String>>>() {
|
||||
if update_thumbnails {
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
|
||||
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
|
||||
}
|
||||
}
|
||||
// Other
|
||||
else {
|
||||
log::warn!("Failed to downcast monitor node output {parent_network_node_id:?}");
|
||||
@@ -609,11 +616,23 @@ impl PartialEq for InspectResult {
|
||||
|
||||
impl InspectState {
|
||||
/// Insert the monitor node alongside the inspect node identified by `inspect_path` (full path from root, last element is the target).
|
||||
/// Returns `None` if the path is empty or doesn't resolve to a node inside a reachable subnetwork.
|
||||
/// Returns `None` if the path is empty, doesn't resolve to a node inside a reachable subnetwork, or the target has no
|
||||
/// flatten-safe primary output to monitor (e.g. an empty merged subnetwork), which would otherwise leave the monitor's
|
||||
/// input dangling once the subnetwork is flattened away.
|
||||
pub fn monitor_inspect_node(network: &mut NodeNetwork, inspect_path: &[NodeId]) -> Option<Self> {
|
||||
let (inspect_node, parent_path) = inspect_path.split_last()?;
|
||||
let inspect_node = *inspect_node;
|
||||
let target_network = navigate_to_network_mut(network, parent_path)?;
|
||||
|
||||
// A subnetwork's primary output only survives flattening if its first export is a node
|
||||
let monitorable = match &target_network.nodes.get(&inspect_node)?.implementation {
|
||||
DocumentNodeImplementation::Network(inner) => matches!(inner.exports.first(), Some(NodeInput::Node { .. })),
|
||||
_ => true,
|
||||
};
|
||||
if !monitorable {
|
||||
return None;
|
||||
}
|
||||
|
||||
let monitor_id = NodeId::new();
|
||||
|
||||
// It is necessary to replace the inputs before inserting the monitor node to avoid changing the input of the new monitor node
|
||||
|
||||
@@ -94,7 +94,7 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("TriggerOpen", async () => {
|
||||
const files = await upload(`image/*,.${editor.fileExtension()}`, "data", true);
|
||||
const files = await upload(`image/*,.${editor.fileExtension()},.${editor.gddFileExtension()}`, "data", true);
|
||||
files.forEach((file) => editor.openFile(file.filename, file.content));
|
||||
});
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER};
|
||||
#[cfg(not(feature = "native"))]
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
use editor::application::{Editor, Environment, Host, Platform};
|
||||
use editor::consts::FILE_EXTENSION;
|
||||
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION};
|
||||
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
||||
@@ -95,7 +95,10 @@ impl EditorWrapper {
|
||||
|
||||
let application_io = PlatformApplicationIo::new().await;
|
||||
let wake = crate::helpers::async_wake_callback();
|
||||
let editor = Editor::new(Environment { platform: Platform::Web, host }, uuid_random_seed, storage, application_io, wake);
|
||||
// On web the working-copy root is an OPFS directory name (no real filesystem path); each
|
||||
// document mounts under `documents/<id_hex>`.
|
||||
let working_copy_root = Some(std::path::PathBuf::from("documents"));
|
||||
let editor = Editor::new(Environment { platform: Platform::Web, host }, uuid_random_seed, storage, working_copy_root, application_io, wake);
|
||||
|
||||
if EDITOR.with(|slot| slot.lock().ok().map(|mut guard| *guard = Some(editor))).is_none() {
|
||||
log::error!("Attempted to initialize the editor more than once");
|
||||
@@ -333,6 +336,12 @@ impl EditorWrapper {
|
||||
FILE_EXTENSION.into()
|
||||
}
|
||||
|
||||
/// Get the constant `GDD_FILE_EXTENSION`
|
||||
#[wasm_bindgen(js_name = gddFileExtension)]
|
||||
pub fn gdd_file_extension(&self) -> String {
|
||||
GDD_FILE_EXTENSION.into()
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
||||
#[wasm_bindgen(js_name = widgetValueUpdate)]
|
||||
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::DocumentNode;
|
||||
use crate::application_io::PlatformEditorApi;
|
||||
use crate::application_io::resource::Resource;
|
||||
use crate::proto::{Any as DAny, FutureAny};
|
||||
use brush_nodes::brush_stroke::BrushStroke;
|
||||
use core_types::color::SRGBA8;
|
||||
@@ -10,6 +11,7 @@ use core_types::{CacheHash, Color, ContextFeatures, MemoHash, Node, Type, TypeDe
|
||||
use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graphene_application_io::resource::ResourceHash;
|
||||
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||
use graphic_types::vector_types::vector::style::{Fill, Gradient, GradientStops};
|
||||
use graphic_types::vector_types::vector::{self, ReferencePoint};
|
||||
@@ -36,6 +38,7 @@ macro_rules! for_each_type_default {
|
||||
$action!(List<Vector>);
|
||||
$action!(List<String>);
|
||||
$action!(DocumentNode);
|
||||
$action!(Resource);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -90,6 +93,9 @@ macro_rules! tagged_value {
|
||||
ContextFeatures(ContextFeatures),
|
||||
#[serde(skip)]
|
||||
EditorApi(Arc<PlatformEditorApi>),
|
||||
/// Only used by the `resource` node, should never be serialized
|
||||
#[serde(skip)]
|
||||
ResourceHash(ResourceHash),
|
||||
}
|
||||
|
||||
impl CacheHash for TaggedValue {
|
||||
@@ -117,6 +123,7 @@ macro_rules! tagged_value {
|
||||
Self::ContextFeatures(features) => features.cache_hash(state),
|
||||
Self::RenderOutput(x) => x.cache_hash(state),
|
||||
Self::EditorApi(x) => x.cache_hash(state),
|
||||
Self::ResourceHash(x) => x.cache_hash(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -170,6 +177,7 @@ macro_rules! tagged_value {
|
||||
Self::DocumentNode(node) => Box::new(node),
|
||||
Self::ContextFeatures(features) => Box::new(features),
|
||||
Self::EditorApi(x) => Box::new(x),
|
||||
Self::ResourceHash(x) => Box::new(x),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -219,6 +227,7 @@ macro_rules! tagged_value {
|
||||
Self::DocumentNode(node) => Arc::new(node),
|
||||
Self::ContextFeatures(features) => Arc::new(features),
|
||||
Self::EditorApi(x) => Arc::new(x),
|
||||
Self::ResourceHash(x) => Arc::new(x),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,6 +255,7 @@ macro_rules! tagged_value {
|
||||
Self::DocumentNode(_) => concrete!(DocumentNode),
|
||||
Self::ContextFeatures(_) => concrete!(ContextFeatures),
|
||||
Self::EditorApi(_) => concrete!(&PlatformEditorApi),
|
||||
Self::ResourceHash(_) => concrete!(ResourceHash),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,6 +361,7 @@ macro_rules! tagged_value {
|
||||
Self::DocumentNode(node) => format!("DocumentNode({node:?})"),
|
||||
Self::ContextFeatures(features) => format!("ContextFeatures({features:?})"),
|
||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -397,7 +408,6 @@ tagged_value! {
|
||||
VectorModification(Box<VectorModification>),
|
||||
ImageData(Image<Color>),
|
||||
Resource(graphene_application_io::resource::ResourceId),
|
||||
ResourceHash(graphene_application_io::resource::ResourceHash),
|
||||
// ==========
|
||||
// ENUM TYPES
|
||||
// ==========
|
||||
|
||||
@@ -201,6 +201,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextFeatures]),
|
||||
#[cfg(target_family = "wasm")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &PlatformEditorApi, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &wgpu_executor::WgpuExecutor, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<&wgpu_executor::WgpuExecutor>, Context => graphene_std::ContextFeatures]),
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextFeatures]),
|
||||
|
||||
@@ -1,44 +1,13 @@
|
||||
use core_types::ProtoNodeIdentifier;
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::generic;
|
||||
use graphene_std::Context;
|
||||
use graphene_std::ContextDependencies;
|
||||
use graphene_std::registry::{NODE_METADATA, RegistryValueSource};
|
||||
use graphene_std::ContextFeatures;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn proto_node_template(identifier: ProtoNodeIdentifier, regular_inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
let metadata_lock = NODE_METADATA.lock().unwrap();
|
||||
let metadata = metadata_lock
|
||||
.get(&identifier)
|
||||
.unwrap_or_else(|| panic!("Node `{}` not registered in NODE_METADATA", identifier.as_str()));
|
||||
|
||||
let mut regular_iter = regular_inputs.into_iter();
|
||||
let inputs: Vec<NodeInput> = metadata
|
||||
.fields
|
||||
.iter()
|
||||
.map(|field| match &field.value_source {
|
||||
RegistryValueSource::Scope(name) => NodeInput::scope(*name),
|
||||
_ => regular_iter
|
||||
.next()
|
||||
.unwrap_or_else(|| panic!("Not enough non-scope inputs for `{}`", identifier.as_str())),
|
||||
})
|
||||
.collect();
|
||||
assert!(regular_iter.next().is_none(), "Too many non-scope inputs for `{}`", identifier.as_str());
|
||||
|
||||
let context_features = ContextDependencies::from(metadata.context_features.as_slice());
|
||||
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
context_features,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>) -> NodeNetwork {
|
||||
let inner_network = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(network),
|
||||
@@ -46,22 +15,84 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let output_node = DocumentNode {
|
||||
// TODO: Replace with "Output" definition?
|
||||
// let render_node = resolve_document_node_type("Output")
|
||||
// .expect("Output node type not found")
|
||||
// .node_template_input_override(vec![Some(NodeInput::node(NodeId(1), 0)), Some(NodeInput::node(NodeId(0), 1))])
|
||||
// .document_node;
|
||||
|
||||
let render_node = DocumentNode {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::Network(NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(5), 0)],
|
||||
nodes: [
|
||||
proto_node_template(
|
||||
graphene_std::render_node::render_intermediate::IDENTIFIER,
|
||||
vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
||||
),
|
||||
proto_node_template(graphene_std::render_node::render::IDENTIFIER, vec![NodeInput::node(NodeId(0), 0)]),
|
||||
proto_node_template(graphene_std::render_cache::render_output_cache::IDENTIFIER, vec![NodeInput::node(NodeId(1), 0)]),
|
||||
proto_node_template(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER, vec![NodeInput::node(NodeId(2), 0)]),
|
||||
proto_node_template(graphene_std::render_background::render_background::IDENTIFIER, vec![NodeInput::node(NodeId(3), 0)]),
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::INDEX,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![
|
||||
NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER),
|
||||
NodeInput::scope(graphene_std::platform_application_io::editor_api::IDENTIFIER),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
inputs: vec![
|
||||
NodeInput::scope(graphene_std::render_background::composite_background_pipeline::IDENTIFIER),
|
||||
NodeInput::node(NodeId(3), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
inject: ContextFeatures::empty(),
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
DocumentNode {
|
||||
call_argument: concrete!(graphene_std::application_io::RenderConfig),
|
||||
..proto_node_template(graphene_std::render_node::create_context::IDENTIFIER, vec![NodeInput::node(NodeId(4), 0)])
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
|
||||
context_features: graphene_std::ContextDependencies {
|
||||
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
|
||||
extract: ContextFeatures::INDEX,
|
||||
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
@@ -76,7 +107,7 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
|
||||
// wrap the inner network in a scope
|
||||
let nodes = vec![
|
||||
inner_network,
|
||||
output_node,
|
||||
render_node,
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)],
|
||||
|
||||
@@ -7,3 +7,5 @@ pub const LAYER_OUTLINE_STROKE_WEIGHT: f64 = 0.5;
|
||||
// Fonts
|
||||
pub const DEFAULT_FONT_FAMILY: &str = "Lato";
|
||||
pub const DEFAULT_FONT_STYLE: &str = "Regular (400)";
|
||||
pub const DEFAULT_FONT_SIZE: f64 = 24.;
|
||||
pub const DEFAULT_LINE_HEIGHT: f64 = 1.2;
|
||||
@@ -25,7 +25,8 @@ pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_GRADIENT_TYPE, ATTR_LOCATION, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_START, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_LEGACY, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use no_std_types::AsU32;
|
||||
|
||||
@@ -12,76 +12,76 @@ use std::fmt::Debug;
|
||||
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
pub const ATTR_TRANSFORM: &str = "transform";
|
||||
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
pub const ATTR_BLEND_MODE: &str = "blend_mode";
|
||||
|
||||
/// Item's opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Composed multiplicatively through nested groups. Affects content clipped to the item.
|
||||
pub const ATTR_OPACITY: &str = "opacity";
|
||||
|
||||
/// Item's fill opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Like opacity but does not affect content clipped to the item.
|
||||
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
|
||||
|
||||
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
|
||||
|
||||
/// `List<NodeId>` path from the root network to the layer node owning this item.
|
||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
|
||||
|
||||
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
|
||||
/// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for
|
||||
/// the original child layers after their content has been collapsed.
|
||||
pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers";
|
||||
|
||||
/// Optional `Vector` that overrides the item's own geometry for click-target generation.
|
||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
||||
/// by clicking anywhere within their bounds, not just the filled letterform.
|
||||
pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
|
||||
/// `DAffine2` mapping the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text'
|
||||
/// node's text frame in this item's local space. Each item carries the frame relative to its own
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
||||
|
||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_START: &str = "start";
|
||||
|
||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_END: &str = "end";
|
||||
|
||||
/// `String` for a regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
|
||||
pub const ATTR_NAME: &str = "name";
|
||||
|
||||
/// `String` for a JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||
pub const ATTR_TYPE: &str = "type";
|
||||
|
||||
/// Artboard's `DVec2` top-left corner in document coordinates.
|
||||
pub const ATTR_LOCATION: &str = "location";
|
||||
|
||||
/// Artboard's `DVec2` width and height.
|
||||
pub const ATTR_DIMENSIONS: &str = "dimensions";
|
||||
|
||||
/// Artboard's `Color` background fill.
|
||||
pub const ATTR_BACKGROUND: &str = "background";
|
||||
|
||||
/// `bool` for whether an artboard clips content to its bounds.
|
||||
pub const ATTR_CLIP: &str = "clip";
|
||||
|
||||
/// Gradient's `GradientSpreadMethod` (`Pad`, `Reflect`, or `Repeat`).
|
||||
pub const ATTR_SPREAD_METHOD: &str = "spread_method";
|
||||
|
||||
/// Gradient's `GradientType` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_TYPE: &str = "gradient_type";
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// `bool` runtime marker (never serialized) flagging a gradient that came from the legacy bounding-box-relative `Fill::Gradient`,
|
||||
/// so the renderer reproduces the pre-#4241 positioning instead of the new absolute path.
|
||||
pub const ATTR_GRADIENT_LEGACY: &str = "gradient_legacy";
|
||||
/// Vector graphics object's filled area paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_FILL: &str = "fill";
|
||||
|
||||
/// Vector graphics object's stroke paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_STROKE: &str = "stroke";
|
||||
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
|
||||
pub const ATTR_FONT_SIZE: &str = "font_size";
|
||||
/// Text item's font, as a `Resource` of the loaded font file.
|
||||
pub const ATTR_FONT: &str = "font";
|
||||
/// Text item's line height as a ratio of the font size (`f64`, implicit default `1.2`).
|
||||
pub const ATTR_LINE_HEIGHT: &str = "line_height";
|
||||
/// Text item's extra spacing between letters in document-space units (`f64`, implicit default `0.`).
|
||||
pub const ATTR_LETTER_SPACING: &str = "letter_spacing";
|
||||
/// Text item's maximum line-wrap width in document-space units (`Option<f64>`, implicit default `None`).
|
||||
pub const ATTR_MAX_WIDTH: &str = "max_width";
|
||||
/// Text item's maximum block height in document-space units, past which lines are not drawn (`Option<f64>`, implicit default `None`).
|
||||
pub const ATTR_MAX_HEIGHT: &str = "max_height";
|
||||
/// Text item's faux-italic letter tilt angle in degrees (`f64`, implicit default `0.`).
|
||||
pub const ATTR_LETTER_TILT: &str = "letter_tilt";
|
||||
/// Text item's `TextAlign` horizontal alignment of lines within the block.
|
||||
pub const ATTR_TEXT_ALIGN: &str = "text_align";
|
||||
|
||||
// ===========================
|
||||
// Implicit attribute defaults
|
||||
|
||||
@@ -19,3 +19,9 @@ impl RenderComplexity for Color {
|
||||
1
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for String {
|
||||
fn render_complexity(&self) -> usize {
|
||||
self.chars().count()
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List};
|
||||
use core_types::ops::{FromAnchorPosition, ListConvert};
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_LEGACY, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -22,6 +22,7 @@ pub enum Graphic {
|
||||
RasterGPU(List<Raster<GPU>>),
|
||||
Color(List<Color>),
|
||||
Gradient(List<GradientStops>),
|
||||
Text(List<String>),
|
||||
}
|
||||
|
||||
impl Default for Graphic {
|
||||
@@ -103,6 +104,18 @@ impl From<List<GradientStops>> for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// String
|
||||
impl From<String> for Graphic {
|
||||
fn from(text: String) -> Self {
|
||||
Graphic::Text(List::new_from_element(text))
|
||||
}
|
||||
}
|
||||
impl From<List<String>> for Graphic {
|
||||
fn from(text: List<String>) -> Self {
|
||||
Graphic::Text(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
|
||||
/// and discarding all other non-matching content. Recursion through `Graphic::Graphic` sub-`List`s composes transforms and opacity.
|
||||
fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
|
||||
@@ -180,15 +193,26 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
|
||||
/// Converts a `Fill` enum into the `List<Graphic>` representation used as paint storage.
|
||||
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
|
||||
pub fn fill_to_graphic_list(fill: &Fill) -> Option<List<Graphic>> {
|
||||
pub fn fill_to_graphic_list(fill: &Fill, bounding_box_transform: DAffine2) -> Option<List<Graphic>> {
|
||||
match fill {
|
||||
Fill::None => None,
|
||||
Fill::Solid(color) => Some(List::new_from_element((*color).into())),
|
||||
Fill::Gradient(gradient) => {
|
||||
let gradient_transform = gradient.transform * gradient.to_transform();
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// Absolute gradients carry their effective frame into the new pipeline; legacy bounding-box gradients bake the bbox
|
||||
// in and flag the legacy render path until the deferred migration converts them.
|
||||
let (transform, legacy) = if gradient.absolute {
|
||||
(gradient_transform, false)
|
||||
} else {
|
||||
(bounding_box_transform * gradient_transform, true)
|
||||
};
|
||||
let gradient_item = Item::new_from_element(gradient.stops.clone())
|
||||
.with_attribute(ATTR_TRANSFORM, gradient.to_transform())
|
||||
.with_attribute(ATTR_TRANSFORM, transform)
|
||||
.with_attribute(ATTR_GRADIENT_TYPE, gradient.gradient_type)
|
||||
.with_attribute(ATTR_SPREAD_METHOD, gradient.spread_method);
|
||||
.with_attribute(ATTR_SPREAD_METHOD, gradient.spread_method)
|
||||
.with_attribute(ATTR_GRADIENT_LEGACY, legacy);
|
||||
let gradient_list = List::new_from_item(gradient_item);
|
||||
|
||||
Some(List::new_from_element(Graphic::Gradient(gradient_list)))
|
||||
@@ -215,13 +239,27 @@ pub fn graphic_list_at<'a>(list: &'a List<Vector>, index: usize, attribute: &str
|
||||
.filter(|graphic_list| graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty()))
|
||||
}
|
||||
|
||||
/// Whether the item carries a non-blank paint attribute in any representation (`Graphic`, `Color`,
|
||||
/// `GradientStops`, `Vector`, or raster), checked by borrowing without cloning the renderable list.
|
||||
pub fn has_paint_at(list: &List<Vector>, index: usize, attribute: &str) -> bool {
|
||||
list.attribute::<List<Graphic>>(attribute, index)
|
||||
.is_some_and(|graphics| graphics.element(0).is_some_and(|graphic| !graphic.is_empty()))
|
||||
|| list.attribute::<List<Color>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|
||||
|| list.attribute::<List<GradientStops>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|
||||
|| list.attribute::<List<Vector>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|
||||
|| list.attribute::<List<Raster<CPU>>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|
||||
|| list.attribute::<List<Raster<GPU>>>(attribute, index).is_some_and(|paint_list| !paint_list.is_empty())
|
||||
}
|
||||
|
||||
/// Look up the fill paint graphics for a vector item, falling back to the legacy
|
||||
/// `style.fill` when the attribute is absent or empty.
|
||||
/// TODO: Remove once all fill paint sources flow through `List<Graphic>` directly without going through the `Fill` enum.
|
||||
pub fn fill_graphic_list_at(list: &List<Vector>, index: usize) -> Option<Cow<'_, List<Graphic>>> {
|
||||
graphic_list_at(list, index, ATTR_FILL).or_else(|| {
|
||||
let vector = list.element(index)?;
|
||||
fill_to_graphic_list(vector.style.fill()).map(Cow::Owned)
|
||||
let bounds = vector.nonzero_bounding_box();
|
||||
let bounding_box_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
fill_to_graphic_list(vector.style.fill(), bounding_box_transform).map(Cow::Owned)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -325,6 +363,12 @@ impl TryFromGraphic for GradientStops {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Text(t) = graphic { Some(t) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
// Local trait to convert types to List<Graphic> (avoids orphan rule issues)
|
||||
pub trait IntoGraphicList {
|
||||
fn into_graphic_list(self) -> List<Graphic>;
|
||||
@@ -381,6 +425,17 @@ impl IntoGraphicList for List<GradientStops> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<String> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
let mut graphic_list = List::new_from_element(Graphic::Text(self));
|
||||
if !layer_path.is_empty() {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for DAffine2 {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::default())
|
||||
@@ -457,6 +512,7 @@ impl Graphic {
|
||||
Graphic::RasterGPU(list) => all_clipped(list),
|
||||
Graphic::Color(list) => all_clipped(list),
|
||||
Graphic::Gradient(list) => all_clipped(list),
|
||||
Graphic::Text(list) => all_clipped(list),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -500,7 +556,7 @@ impl Graphic {
|
||||
}
|
||||
Graphic::Color(list) => list.element(0).is_some_and(|color| color.is_opaque()),
|
||||
Graphic::Gradient(list) => list.element(0).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque())),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) => false,
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,7 +576,7 @@ impl Graphic {
|
||||
}),
|
||||
Graphic::Color(list) => list.iter_element_values().all(|color| color.a() == 0.),
|
||||
Graphic::Gradient(list) => list.iter_element_values().all(|stops| stops.iter().all(|stop| stop.color.a() == 0.)),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) => false,
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,6 +595,7 @@ impl Graphic {
|
||||
Graphic::Gradient(list) => list.is_empty(),
|
||||
Graphic::RasterCPU(list) => list.is_empty(),
|
||||
Graphic::RasterGPU(list) => list.is_empty(),
|
||||
Graphic::Text(list) => list.is_empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -552,6 +609,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::Graphic(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(list) => list.bounding_box(transform, include_stroke),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -563,6 +621,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::Graphic(graphic) => graphic.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -592,6 +651,7 @@ impl RenderComplexity for Graphic {
|
||||
Self::RasterGPU(list) => list.render_complexity(),
|
||||
Self::Color(list) => list.render_complexity(),
|
||||
Self::Gradient(list) => list.render_complexity(),
|
||||
Self::Text(list) => list.render_complexity(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,8 @@ serde = ["dep:serde", "core-types/serde", "vector-types/serde", "graphic-types/s
|
||||
dyn-any = { workspace = true }
|
||||
core-types = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-resource = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
@@ -27,6 +29,8 @@ vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
vello_encoding = { workspace = true }
|
||||
parley = { workspace = true }
|
||||
skrifa = { workspace = true }
|
||||
|
||||
# Optional workspace dependencies
|
||||
serde = { workspace = true, optional = true }
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::renderer::{RenderParams, format_transform_matrix};
|
||||
use crate::renderer::{RenderParams, format_transform_matrix, gradient_placement, transform_is_invertible};
|
||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
@@ -45,7 +45,6 @@ pub trait RenderExt {
|
||||
element_transform: DAffine2,
|
||||
stroke_transform: DAffine2,
|
||||
bounds: DAffine2,
|
||||
transformed_bounds: DAffine2,
|
||||
render_params: &RenderParams,
|
||||
target: PaintTarget,
|
||||
) -> Self::Output;
|
||||
@@ -61,11 +60,12 @@ impl RenderExt for List<Color> {
|
||||
_element_transform: DAffine2,
|
||||
_stroke_transform: DAffine2,
|
||||
_bounds: DAffine2,
|
||||
_transformed_bounds: DAffine2,
|
||||
_render_params: &RenderParams,
|
||||
target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
let Some(color) = self.element(0) else { return r#" fill="none""#.to_string() };
|
||||
let Some(color) = self.element(0) else {
|
||||
return format!(r#" {}="none""#, target.paint_attr());
|
||||
};
|
||||
|
||||
let mut result = format!(r##" {}="#{}""##, target.paint_attr(), SRGBA8::from(*color).to_rgb_hex());
|
||||
if color.a() < 1. {
|
||||
@@ -83,11 +83,10 @@ impl RenderExt for List<GradientStops> {
|
||||
fn render(
|
||||
&self,
|
||||
svg_defs: &mut String,
|
||||
_item_transform: DAffine2,
|
||||
item_transform: DAffine2,
|
||||
element_transform: DAffine2,
|
||||
stroke_transform: DAffine2,
|
||||
bounds: DAffine2,
|
||||
transformed_bounds: DAffine2,
|
||||
_stroke_transform: DAffine2,
|
||||
_bounds: DAffine2,
|
||||
_render_params: &RenderParams,
|
||||
_target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
@@ -95,7 +94,7 @@ impl RenderExt for List<GradientStops> {
|
||||
|
||||
let Some(stops) = self.element(0) else { return 0 };
|
||||
let gradient_type: GradientType = self.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let gradient_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let local_gradient_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = self.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
|
||||
for (position, color, original_midpoint) in stops.interpolated_samples() {
|
||||
@@ -113,16 +112,17 @@ impl RenderExt for List<GradientStops> {
|
||||
stop.push_str(" />")
|
||||
}
|
||||
|
||||
let transform_points = element_transform * stroke_transform * bounds * gradient_transform;
|
||||
let start = transform_points.transform_point2(DVec2::ZERO);
|
||||
let end = transform_points.transform_point2(DVec2::X);
|
||||
|
||||
let gradient_transform = if transformed_bounds.matrix2.determinant() != 0. {
|
||||
transformed_bounds.inverse()
|
||||
// Need to cancel out the element's transform as it is already applied to the path itself.
|
||||
let element_transform_inverse = if transform_is_invertible(element_transform) {
|
||||
element_transform.inverse()
|
||||
} else {
|
||||
DAffine2::IDENTITY // Ignore if the transform cannot be inverted (the bounds are zero). See issue #1944.
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
let gradient_transform = format_transform_matrix(gradient_transform);
|
||||
|
||||
let document_transform = item_transform * local_gradient_transform;
|
||||
|
||||
let placement = gradient_placement(document_transform, gradient_type);
|
||||
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
|
||||
let gradient_transform = if gradient_transform.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
@@ -141,16 +141,15 @@ impl RenderExt for List<GradientStops> {
|
||||
GradientType::Linear => {
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<linearGradient id="{}" x1="{}" y1="{}" x2="{}" y2="{}"{spread_method}{gradient_transform}>{}</linearGradient>"#,
|
||||
gradient_id, start.x, start.y, end.x, end.y, stop
|
||||
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{spread_method}{gradient_transform}>{}</linearGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
GradientType::Radial => {
|
||||
let radius = (f64::powi(start.x - end.x, 2) + f64::powi(start.y - end.y, 2)).sqrt();
|
||||
let _ = write!(
|
||||
svg_defs,
|
||||
r#"<radialGradient id="{}" cx="{}" cy="{}" r="{}"{spread_method}{gradient_transform}>{}</radialGradient>"#,
|
||||
gradient_id, start.x, start.y, radius, stop
|
||||
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{spread_method}{gradient_transform}>{}</radialGradient>"#,
|
||||
gradient_id, stop
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -170,7 +169,6 @@ impl RenderExt for Stroke {
|
||||
_element_transform: DAffine2,
|
||||
_stroke_transform: DAffine2,
|
||||
_bounds: DAffine2,
|
||||
_transformed_bounds: DAffine2,
|
||||
render_params: &RenderParams,
|
||||
_target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
@@ -231,7 +229,6 @@ impl RenderExt for List<Graphic> {
|
||||
element_transform: DAffine2,
|
||||
stroke_transform: DAffine2,
|
||||
bounds: DAffine2,
|
||||
transformed_bounds: DAffine2,
|
||||
render_params: &RenderParams,
|
||||
target: PaintTarget,
|
||||
) -> Self::Output {
|
||||
@@ -239,12 +236,12 @@ impl RenderExt for List<Graphic> {
|
||||
let paint_attr = target.paint_attr();
|
||||
|
||||
match fill_graphic {
|
||||
Some(Graphic::Color(color_list)) => color_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, transformed_bounds, render_params, target),
|
||||
Some(Graphic::Color(color_list)) => color_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target),
|
||||
Some(Graphic::Gradient(gradient_list)) => {
|
||||
let gradient_id = gradient_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, transformed_bounds, render_params, target);
|
||||
let gradient_id = gradient_list.render(svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params, target);
|
||||
format!(r##" {paint_attr}="url(#{gradient_id})""##)
|
||||
}
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) => {
|
||||
Some(Graphic::Vector(_)) | Some(Graphic::RasterCPU(_)) | Some(Graphic::RasterGPU(_)) | Some(Graphic::Graphic(_)) | Some(Graphic::Text(_)) => {
|
||||
let bounds = if target == PaintTarget::Stroke {
|
||||
// To prevent a wraparound artefact occurring when the tile boundary and the stroke region are perfectly aligned, the local coordinate is expanded slightly.
|
||||
let inverse = |len: f64| if len > 0. { 1. / len } else { 0. };
|
||||
|
||||
@@ -6,29 +6,37 @@ use core_types::bounds::BoundingBox;
|
||||
use core_types::bounds::RenderBoundingBox;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::consts::DEFAULT_FONT_SIZE;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List};
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::{NodeId, generate_uuid};
|
||||
use core_types::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_GRADIENT_TYPE, ATTR_LOCATION, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_FONT,
|
||||
ATTR_FONT_SIZE, ATTR_GRADIENT_LEGACY, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_SPREAD_METHOD, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_hash::CacheHashWrapper;
|
||||
use graphic_types::graphic::{fill_graphic_list_at, graphic_list_at, is_stroke_fully_transparent_at, stroke_graphic_list_at};
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::graphic::{fill_graphic_list_at, graphic_list_at, has_paint_at, stroke_graphic_list_at};
|
||||
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster};
|
||||
use graphic_types::vector_types::gradient::{GradientStops, GradientType};
|
||||
use graphic_types::vector_types::subpath::Subpath;
|
||||
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
|
||||
use graphic_types::vector_types::vector::style::{Fill, PaintOrder, RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use kurbo::{Affine, Cap, Join, Shape, StrokeOpts};
|
||||
use kurbo::{Affine, BezPath, Cap, Join, Shape, StrokeOpts};
|
||||
use num_traits::Zero;
|
||||
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
|
||||
use skrifa::outline::{DrawSettings, OutlinePen};
|
||||
use skrifa::raw::FontRef as SkrifaFontRef;
|
||||
use skrifa::{GlyphId, MetadataProvider};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt::Write;
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use vector_types::gradient::GradientSpreadMethod;
|
||||
@@ -232,8 +240,10 @@ impl RenderParams {
|
||||
}
|
||||
|
||||
pub fn for_alignment(&self, transform: DAffine2) -> Self {
|
||||
let alignment_parent_transform = Some(transform);
|
||||
Self { alignment_parent_transform, ..*self }
|
||||
Self {
|
||||
alignment_parent_transform: Some(transform),
|
||||
..*self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_pattern(&self) -> Self {
|
||||
@@ -346,7 +356,6 @@ fn emit_svg_fill_path(
|
||||
element_transform: DAffine2,
|
||||
applied_stroke_transform: DAffine2,
|
||||
bounds_matrix: DAffine2,
|
||||
transformed_bounds_matrix: DAffine2,
|
||||
render_params: &RenderParams,
|
||||
) {
|
||||
render.leaf_tag("path", |attributes| {
|
||||
@@ -357,29 +366,44 @@ fn emit_svg_fill_path(
|
||||
}
|
||||
let defs = &mut attributes.0.svg_defs;
|
||||
let fill_attribute = fill_graphic_list
|
||||
.map(|list| {
|
||||
list.render(
|
||||
defs,
|
||||
item_transform,
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
bounds_matrix,
|
||||
transformed_bounds_matrix,
|
||||
render_params,
|
||||
PaintTarget::Fill,
|
||||
)
|
||||
})
|
||||
.map(|list| list.render(defs, item_transform, element_transform, applied_stroke_transform, bounds_matrix, render_params, PaintTarget::Fill))
|
||||
.unwrap_or_else(|| r#" fill="none""#.to_string());
|
||||
attributes.push_val(fill_attribute);
|
||||
});
|
||||
}
|
||||
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_vector: &Vector, parent_transform: &DAffine2, multiplied_transform: &DAffine2) -> Option<peniko::Brush> {
|
||||
/// Whether the affine transform inverts to a finite matrix (a zero, subnormal, or NaN determinant does not).
|
||||
pub(crate) fn transform_is_invertible(transform: DAffine2) -> bool {
|
||||
transform.matrix2.determinant().recip().is_finite()
|
||||
}
|
||||
|
||||
/// Maps a gradient's `transform` into the frame handed to the renderer: radial keeps the full matrix (so a
|
||||
/// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the
|
||||
/// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can
|
||||
/// represent since it stores only two endpoints.
|
||||
pub(crate) fn gradient_placement(transform: DAffine2, gradient_type: GradientType) -> DAffine2 {
|
||||
match gradient_type {
|
||||
GradientType::Radial => transform,
|
||||
GradientType::Linear => {
|
||||
let axis = transform.matrix2.x_axis;
|
||||
let band_normal = transform.matrix2.y_axis.perp();
|
||||
let line = if band_normal.length_squared() > 0. { axis.project_onto(band_normal) } else { axis };
|
||||
DAffine2 {
|
||||
matrix2: DMat2::from_cols(line, line.perp()),
|
||||
translation: transform.translation,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_transform: &DAffine2, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
let stops = gradient_list.element(0)?;
|
||||
|
||||
let gradient_type: GradientType = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let gradient_transform: DAffine2 = gradient_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = gradient_list.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
let legacy_bounding_box: bool = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_LEGACY, 0);
|
||||
|
||||
let mut peniko_stops = peniko::ColorStops::new();
|
||||
for (position, color, _) in stops.interpolated_samples() {
|
||||
@@ -389,18 +413,20 @@ fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_vect
|
||||
});
|
||||
}
|
||||
|
||||
let bounds = parent_vector.nonzero_bounding_box();
|
||||
let bound_transform = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
|
||||
let inverse_parent_transform = if parent_transform.matrix2.determinant() != 0. {
|
||||
parent_transform.inverse()
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
// Legacy bounding-box gradients reproduce the pre-#4241 renderer: literal endpoints in the layer's own space, with the
|
||||
// parent transform applied as the brush so its shear bends the bands. New gradients use the unit gradient placed by the desheared frame.
|
||||
let (start, end, gradient_to_device) = if legacy_bounding_box {
|
||||
let inverse_parent_transform = if transform_is_invertible(*parent_transform) {
|
||||
parent_transform.inverse()
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let mod_points = inverse_parent_transform * *multiplied_transform * gradient_transform;
|
||||
(mod_points.transform_point2(DVec2::ZERO), mod_points.transform_point2(DVec2::X), *parent_transform)
|
||||
} else {
|
||||
Default::default()
|
||||
(DVec2::ZERO, DVec2::X, gradient_placement(multiplied_transform * gradient_transform, gradient_type))
|
||||
};
|
||||
let mod_points = inverse_parent_transform * multiplied_transform * bound_transform * gradient_transform;
|
||||
|
||||
let start = mod_points.transform_point2(DVec2::ZERO);
|
||||
let end = mod_points.transform_point2(DVec2::X);
|
||||
|
||||
let brush = peniko::Brush::Gradient(peniko::Gradient {
|
||||
kind: match gradient_type {
|
||||
@@ -409,16 +435,13 @@ fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_vect
|
||||
end: to_point(end),
|
||||
}
|
||||
.into(),
|
||||
GradientType::Radial => {
|
||||
let radius = start.distance(end);
|
||||
peniko::RadialGradientPosition {
|
||||
start_center: to_point(start),
|
||||
start_radius: 0.,
|
||||
end_center: to_point(start),
|
||||
end_radius: radius as f32,
|
||||
}
|
||||
.into()
|
||||
GradientType::Radial => peniko::RadialGradientPosition {
|
||||
start_center: to_point(start),
|
||||
start_radius: 0.,
|
||||
end_center: to_point(start),
|
||||
end_radius: start.distance(end) as f32,
|
||||
}
|
||||
.into(),
|
||||
},
|
||||
extend: match spread_method {
|
||||
GradientSpreadMethod::Pad => peniko::Extend::Pad,
|
||||
@@ -430,7 +453,7 @@ fn create_peniko_gradient_brush(gradient_list: &List<GradientStops>, parent_vect
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
Some(brush)
|
||||
Some((brush, gradient_to_device))
|
||||
}
|
||||
|
||||
// TODO: Click targets can be removed from the render output, since the vector data is available in the vector modify data from Monitor nodes.
|
||||
@@ -547,6 +570,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(_) => (),
|
||||
Graphic::Color(list) => list.render_svg(render, render_params),
|
||||
Graphic::Gradient(list) => list.render_svg(render, render_params),
|
||||
Graphic::Text(list) => list.render_svg(render, render_params),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,6 +582,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::Color(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::Gradient(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
Graphic::Text(list) => list.render_to_vello(scene, transform, context, render_params),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -606,6 +631,14 @@ impl Render for Graphic {
|
||||
Graphic::Gradient(list) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
}
|
||||
}
|
||||
Graphic::Text(list) => {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
@@ -621,6 +654,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::Color(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::Gradient(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
Graphic::Text(list) => list.collect_metadata(metadata, footprint, element_id),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -632,6 +666,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::Color(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::Gradient(list) => list.add_upstream_click_targets(click_targets),
|
||||
Graphic::Text(list) => list.add_upstream_click_targets(click_targets),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -643,6 +678,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::Color(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::Gradient(list) => list.add_upstream_outline_targets(outlines),
|
||||
Graphic::Text(list) => list.add_upstream_outline_targets(outlines),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -654,6 +690,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(list) => list.contains_artboard(),
|
||||
Graphic::Color(list) => list.contains_artboard(),
|
||||
Graphic::Gradient(list) => list.contains_artboard(),
|
||||
Graphic::Text(list) => list.contains_artboard(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,6 +702,7 @@ impl Render for Graphic {
|
||||
Graphic::RasterGPU(_) => (),
|
||||
Graphic::Color(_) => (),
|
||||
Graphic::Gradient(_) => (),
|
||||
Graphic::Text(_) => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1044,7 +1082,7 @@ impl Render for List<Vector> {
|
||||
|
||||
// Only consider strokes with non-zero weight, since default strokes with zero weight would prevent assigning the correct stroke transform
|
||||
let has_real_stroke = vector.style.stroke().filter(|stroke| stroke.weight() > 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform.matrix2.determinant() != 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
|
||||
let applied_stroke_transform = set_stroke_transform.unwrap_or(item_transform);
|
||||
let applied_stroke_transform = render_params.alignment_parent_transform.unwrap_or(applied_stroke_transform);
|
||||
let element_transform = set_stroke_transform.map(|stroke_transform| item_transform * stroke_transform.inverse());
|
||||
@@ -1054,7 +1092,6 @@ impl Render for List<Vector> {
|
||||
let stroke_layer_bounds = vector.stroke_inclusive_bounding_box_with_transform(DAffine2::IDENTITY).unwrap_or(layer_bounds);
|
||||
|
||||
let bounds_matrix = DAffine2::from_scale_angle_translation(layer_bounds[1] - layer_bounds[0], 0., layer_bounds[0]);
|
||||
let transformed_bounds_matrix = element_transform * DAffine2::from_scale_angle_translation(transformed_bounds[1] - transformed_bounds[0], 0., transformed_bounds[0]);
|
||||
let stroke_bounds_matrix = DAffine2::from_scale_angle_translation(stroke_layer_bounds[1] - stroke_layer_bounds[0], 0., stroke_layer_bounds[0]);
|
||||
|
||||
let mut path = String::new();
|
||||
@@ -1096,7 +1133,6 @@ impl Render for List<Vector> {
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
bounds_matrix,
|
||||
transformed_bounds_matrix,
|
||||
render_params,
|
||||
);
|
||||
}
|
||||
@@ -1128,7 +1164,6 @@ impl Render for List<Vector> {
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
bounds_matrix,
|
||||
transformed_bounds_matrix,
|
||||
render_params,
|
||||
);
|
||||
}
|
||||
@@ -1177,16 +1212,7 @@ impl Render for List<Vector> {
|
||||
.stroke()
|
||||
.map(|stroke| {
|
||||
if stroke_graphic_list.as_ref().and_then(|l| l.element(0)).is_some() {
|
||||
stroke.render(
|
||||
defs,
|
||||
item_transform,
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
bounds_matrix,
|
||||
transformed_bounds_matrix,
|
||||
&render_params,
|
||||
PaintTarget::Stroke,
|
||||
)
|
||||
stroke.render(defs, item_transform, element_transform, applied_stroke_transform, bounds_matrix, &render_params, PaintTarget::Stroke)
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
@@ -1205,16 +1231,7 @@ impl Render for List<Vector> {
|
||||
Some(Graphic::Color(_)) | Some(Graphic::Gradient(_)) => bounds_matrix,
|
||||
_ => stroke_bounds_matrix,
|
||||
};
|
||||
list.render(
|
||||
defs,
|
||||
item_transform,
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
paint_bounds,
|
||||
transformed_bounds_matrix,
|
||||
&render_params,
|
||||
PaintTarget::Stroke,
|
||||
)
|
||||
list.render(defs, item_transform, element_transform, applied_stroke_transform, paint_bounds, &render_params, PaintTarget::Stroke)
|
||||
})
|
||||
.unwrap_or_else(|| r#" stroke="none""#.to_string())
|
||||
} else {
|
||||
@@ -1226,18 +1243,7 @@ impl Render for List<Vector> {
|
||||
} else {
|
||||
fill_graphic_list
|
||||
.as_deref()
|
||||
.map(|list| {
|
||||
list.render(
|
||||
defs,
|
||||
item_transform,
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
bounds_matrix,
|
||||
transformed_bounds_matrix,
|
||||
&render_params,
|
||||
PaintTarget::Fill,
|
||||
)
|
||||
})
|
||||
.map(|list| list.render(defs, item_transform, element_transform, applied_stroke_transform, bounds_matrix, &render_params, PaintTarget::Fill))
|
||||
.unwrap_or_else(|| r#" fill="none""#.to_string())
|
||||
};
|
||||
|
||||
@@ -1273,7 +1279,6 @@ impl Render for List<Vector> {
|
||||
element_transform,
|
||||
applied_stroke_transform,
|
||||
bounds_matrix,
|
||||
transformed_bounds_matrix,
|
||||
render_params,
|
||||
);
|
||||
}
|
||||
@@ -1291,14 +1296,14 @@ impl Render for List<Vector> {
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let multiplied_transform = parent_transform * item_transform;
|
||||
let has_real_stroke = element.style.stroke().filter(|stroke| stroke.weight() > 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform.matrix2.determinant() != 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
|
||||
let mut applied_stroke_transform = set_stroke_transform.unwrap_or(multiplied_transform);
|
||||
let mut element_transform = set_stroke_transform
|
||||
.map(|stroke_transform| multiplied_transform * stroke_transform.inverse())
|
||||
.unwrap_or(DAffine2::IDENTITY);
|
||||
if let Some(alignment_transform) = render_params.alignment_parent_transform {
|
||||
applied_stroke_transform = alignment_transform;
|
||||
element_transform = if alignment_transform.matrix2.determinant() != 0. {
|
||||
element_transform = if transform_is_invertible(alignment_transform) {
|
||||
multiplied_transform * alignment_transform.inverse()
|
||||
} else {
|
||||
multiplied_transform
|
||||
@@ -1328,9 +1333,9 @@ impl Render for List<Vector> {
|
||||
// Used by both the blend-layer clip rect inflation below (as `max_aabb_inflation`'s `path_is_closed` arg, equivalent here since
|
||||
// the function ignores the arg for Center align) and the `SrcIn`/`SrcOut` aligned-stroke branch further down.
|
||||
let stroke = element.style.stroke();
|
||||
let can_draw_aligned_stroke = !is_stroke_fully_transparent_at(self, index)
|
||||
&& stroke.as_ref().is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered())
|
||||
&& element.stroke_bezier_paths().all(|p| p.closed());
|
||||
let stroke_fully_transparent = stroke_graphic_list.as_ref().is_none_or(|l| l.element(0).is_none_or(|g| g.is_fully_transparent()));
|
||||
let can_draw_aligned_stroke =
|
||||
!stroke_fully_transparent && stroke.as_ref().is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) && element.stroke_bezier_paths().all(|p| p.closed());
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
if opacity < 1. || blend_mode_attr != BlendMode::default() {
|
||||
@@ -1367,19 +1372,19 @@ impl Render for List<Vector> {
|
||||
scene.fill(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), &fill, None, path);
|
||||
}
|
||||
Graphic::Gradient(list) => {
|
||||
let Some(brush) = create_peniko_gradient_brush(list, element, &parent_transform, &multiplied_transform) else {
|
||||
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(list, &parent_transform, &multiplied_transform) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let inverse_element_transform = if element_transform.matrix2.determinant() != 0. {
|
||||
let inverse_element_transform = if transform_is_invertible(element_transform) {
|
||||
element_transform.inverse()
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let brush_transform = kurbo::Affine::new((inverse_element_transform * parent_transform).to_cols_array());
|
||||
let brush_transform = kurbo::Affine::new((inverse_element_transform * gradient_to_device).to_cols_array());
|
||||
scene.fill(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), &brush, Some(brush_transform), path);
|
||||
}
|
||||
Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Graphic(_) => {
|
||||
Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Graphic(_) | Graphic::Text(_) => {
|
||||
scene.push_clip_layer(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), path);
|
||||
paint.render_to_vello(scene, multiplied_transform, context, render_params);
|
||||
scene.pop_layer();
|
||||
@@ -1449,19 +1454,19 @@ impl Render for List<Vector> {
|
||||
scene.stroke(&stroke, kurbo::Affine::new(element_transform.to_cols_array()), &brush, None, &path);
|
||||
}
|
||||
Graphic::Gradient(list) => {
|
||||
let Some(brush) = create_peniko_gradient_brush(list, element, &parent_transform, &multiplied_transform) else {
|
||||
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(list, &parent_transform, &multiplied_transform) else {
|
||||
continue;
|
||||
};
|
||||
let inverse_element_transform = if element_transform.matrix2.determinant() != 0. {
|
||||
let inverse_element_transform = if transform_is_invertible(element_transform) {
|
||||
element_transform.inverse()
|
||||
} else {
|
||||
Default::default()
|
||||
};
|
||||
let brush_transform = kurbo::Affine::new((inverse_element_transform * parent_transform).to_cols_array());
|
||||
let brush_transform = kurbo::Affine::new((inverse_element_transform * gradient_to_device).to_cols_array());
|
||||
|
||||
scene.stroke(&stroke, kurbo::Affine::new(element_transform.to_cols_array()), &brush, Some(brush_transform), &path);
|
||||
}
|
||||
Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Graphic(_) => {
|
||||
Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Graphic(_) | Graphic::Text(_) => {
|
||||
let stroked = peniko::kurbo::stroke(path.iter(), &stroke, &StrokeOpts::default(), 0.01);
|
||||
|
||||
scene.push_clip_layer(peniko::Fill::NonZero, kurbo::Affine::new(element_transform.to_cols_array()), &stroked);
|
||||
@@ -1564,7 +1569,7 @@ impl Render for List<Vector> {
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
let item_zero_inverse = if item_zero_transform.matrix2.determinant() != 0. {
|
||||
let item_zero_inverse = if transform_is_invertible(item_zero_transform) {
|
||||
item_zero_transform.inverse()
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
@@ -1675,13 +1680,7 @@ impl Render for List<Vector> {
|
||||
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
|
||||
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
|
||||
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, vector_list: &List<Vector>, index: usize, geometry: &Vector, transform: DAffine2) {
|
||||
let filled = if let Some(graphic_list) = graphic_list_at(vector_list, index, ATTR_FILL) {
|
||||
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||
} else if let Some(vector) = vector_list.element(index) {
|
||||
!matches!(vector.style.fill(), Fill::None)
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let filled = has_paint_at(vector_list, index, ATTR_FILL) || vector_list.element(index).is_some_and(|vector| !matches!(vector.style.fill(), Fill::None));
|
||||
|
||||
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
|
||||
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
|
||||
@@ -1714,8 +1713,14 @@ fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, vector_list: &List
|
||||
}
|
||||
|
||||
fn extend_free_point_targets(vector: &Vector, transform: DAffine2) -> impl Iterator<Item = ClickTarget> + '_ {
|
||||
vector.point_domain.ids().iter().filter_map(move |&point_id| {
|
||||
if vector.any_connected(point_id) {
|
||||
// Mark every point index touched by a segment endpoint in one `O(points + segments)` pass, avoiding a per-point `any_connected` scan
|
||||
let mut connected = vec![false; vector.point_domain.len()];
|
||||
for &point_index in vector.segment_domain.start_point().iter().chain(vector.segment_domain.end_point()) {
|
||||
connected[point_index] = true;
|
||||
}
|
||||
|
||||
vector.point_domain.ids().iter().enumerate().filter_map(move |(point_index, &point_id)| {
|
||||
if connected[point_index] {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -2238,6 +2243,376 @@ impl Render for List<GradientStops> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `kurbo::BezPath` from a glyph outline, baking in the glyph origin (`ox`, `oy`) and faux-italic shear (`tilt_tan`).
|
||||
struct GlyphOutlinePen<'a> {
|
||||
path: &'a mut BezPath,
|
||||
ox: f64,
|
||||
oy: f64,
|
||||
tilt_tan: f64,
|
||||
}
|
||||
|
||||
impl GlyphOutlinePen<'_> {
|
||||
#[inline]
|
||||
fn px(&self, x: f32, y: f32) -> f64 {
|
||||
self.ox + x as f64 + (y as f64 * self.tilt_tan)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn py(&self, y: f32) -> f64 {
|
||||
self.oy - y as f64
|
||||
}
|
||||
}
|
||||
|
||||
impl OutlinePen for GlyphOutlinePen<'_> {
|
||||
fn move_to(&mut self, x: f32, y: f32) {
|
||||
self.path.move_to((self.px(x, y), self.py(y)));
|
||||
}
|
||||
fn line_to(&mut self, x: f32, y: f32) {
|
||||
self.path.line_to((self.px(x, y), self.py(y)));
|
||||
}
|
||||
fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) {
|
||||
self.path.quad_to((self.px(cx, cy), self.py(cy)), (self.px(x, y), self.py(y)));
|
||||
}
|
||||
fn curve_to(&mut self, cx1: f32, cy1: f32, cx2: f32, cy2: f32, x: f32, y: f32) {
|
||||
self.path.curve_to((self.px(cx1, cy1), self.py(cy1)), (self.px(cx2, cy2), self.py(cy2)), (self.px(x, y), self.py(y)));
|
||||
}
|
||||
fn close(&mut self) {
|
||||
self.path.close_path();
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws each glyph of `glyph_run` into a `BezPath` (with the run's position and faux-italic `tilt_tan` baked in)
|
||||
/// and calls `emit` for each non-empty glyph. Zero-geometry glyphs advance by `space_extra` for justified spacing.
|
||||
fn draw_glyph_run_to_bezpaths(glyph_run: &parley::GlyphRun<'_, ()>, x_offset: f32, space_extra: f32, tilt_tan: f64, mut emit: impl FnMut(&BezPath)) {
|
||||
let mut run_x = glyph_run.offset() + x_offset;
|
||||
let run_y = glyph_run.baseline();
|
||||
let run = glyph_run.run();
|
||||
let font = run.font();
|
||||
let font_size_pts = run.font_size();
|
||||
let normalized_coords: Vec<NormalizedCoord> = run.normalized_coords().iter().map(|c| NormalizedCoord::from_bits(*c)).collect();
|
||||
|
||||
let Ok(font_ref) = SkrifaFontRef::from_index(font.data.as_ref(), font.index) else { return };
|
||||
let outlines = font_ref.outline_glyphs();
|
||||
|
||||
let mut bez_path = BezPath::new();
|
||||
for glyph in glyph_run.glyphs() {
|
||||
let ox = (run_x + glyph.x) as f64;
|
||||
let oy = (run_y - glyph.y) as f64;
|
||||
run_x += glyph.advance;
|
||||
|
||||
let Some(outline) = outlines.get(GlyphId::from(glyph.id)) else { continue };
|
||||
let settings = DrawSettings::unhinted(Size::new(font_size_pts), LocationRef::new(&normalized_coords));
|
||||
|
||||
bez_path.truncate(0);
|
||||
let path = &mut bez_path;
|
||||
let mut pen = GlyphOutlinePen { path, ox, oy, tilt_tan };
|
||||
if outline.draw(settings, &mut pen).is_ok() && !bez_path.elements().is_empty() {
|
||||
emit(&bez_path);
|
||||
} else if space_extra != 0. && glyph.advance > 0. {
|
||||
run_x += space_extra;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Lays out text item `index` of a styled `List<String>` and returns its local size and transform. The `BoundingBox` trait can't do
|
||||
/// this since a bare `String` carries no typography, so click-target and bounding-box computation share this. Falls back to an em
|
||||
/// square if the font isn't registered yet.
|
||||
fn text_item_size_and_transform(list: &List<String>, index: usize) -> Option<(DVec2, DAffine2)> {
|
||||
let text = list.element(index)?;
|
||||
let font: Resource = {
|
||||
let f: Resource = list.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = list.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = list.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = list.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = list.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = list.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let align: text_nodes::TextAlign = list.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
font_size,
|
||||
line_height_ratio: line_height,
|
||||
letter_spacing,
|
||||
letter_tilt: 0.,
|
||||
max_width,
|
||||
max_height,
|
||||
align,
|
||||
};
|
||||
|
||||
let (width, height) = text_nodes::TextContext::with_thread_local(|ctx| {
|
||||
ctx.layout_text(text, &font, typesetting).map(|layout| {
|
||||
let w = max_width.unwrap_or_else(|| layout.width() as f64);
|
||||
let h = max_height.unwrap_or_else(|| layout.height() as f64);
|
||||
(w, h)
|
||||
})
|
||||
})
|
||||
.unwrap_or((font_size, font_size));
|
||||
|
||||
Some((DVec2::new(width, height), transform))
|
||||
}
|
||||
|
||||
/// Union bounding box of a styled `List<String>`, laid out per item. The `BoundingBox` trait returns `None` for `List<String>`
|
||||
/// (a bare `String` has no extent), so text-layer thumbnails and bounds use this instead. Each item is laid out under `outer_transform`.
|
||||
pub fn text_list_bounding_box(list: &List<String>, outer_transform: DAffine2) -> RenderBoundingBox {
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
for index in 0..list.len() {
|
||||
let Some((size, transform)) = text_item_size_and_transform(list, index) else { continue };
|
||||
let full_transform = outer_transform * transform;
|
||||
for corner in [DVec2::ZERO, DVec2::new(size.x, 0.), DVec2::new(0., size.y), size] {
|
||||
let point = full_transform.transform_point2(corner);
|
||||
bounds = Some(match bounds {
|
||||
Some([min, max]) => [min.min(point), max.max(point)],
|
||||
None => [point, point],
|
||||
});
|
||||
}
|
||||
}
|
||||
match bounds {
|
||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||
None => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Like `List<Graphic>::thumbnail_bounding_box`, but lays out `Graphic::Text` items, which the `BoundingBox` trait reports as `None`.
|
||||
/// Used for layer thumbnails so text layers (whose content is a `List<Graphic>` wrapping the text) frame their content.
|
||||
pub fn graphic_list_bounding_box(list: &List<Graphic>, transform: DAffine2) -> RenderBoundingBox {
|
||||
let mut combined: Option<[DVec2; 2]> = None;
|
||||
let mut any_infinite = false;
|
||||
|
||||
for index in 0..list.len() {
|
||||
let item_transform = transform * list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
|
||||
let Some(graphic) = list.element(index) else { continue };
|
||||
let bounds = match graphic {
|
||||
Graphic::Text(text_list) => text_list_bounding_box(text_list, item_transform),
|
||||
Graphic::Graphic(sub_list) => graphic_list_bounding_box(sub_list, item_transform),
|
||||
other => other.thumbnail_bounding_box(item_transform, true),
|
||||
};
|
||||
match bounds {
|
||||
RenderBoundingBox::None => {}
|
||||
RenderBoundingBox::Infinite => any_infinite = true,
|
||||
RenderBoundingBox::Rectangle([min, max]) => {
|
||||
combined = Some(match combined {
|
||||
Some([existing_min, existing_max]) => [existing_min.min(min), existing_max.max(max)],
|
||||
None => [min, max],
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match (combined, any_infinite) {
|
||||
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||
(None, true) => RenderBoundingBox::Infinite,
|
||||
(None, false) => RenderBoundingBox::None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for List<String> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
let Some(text) = self.element(index) else { continue };
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let font: Resource = {
|
||||
let f: Resource = self.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = self.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = self.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = self.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = self.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = self.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let letter_tilt: f64 = self.attribute_cloned_or(ATTR_LETTER_TILT, index, 0.);
|
||||
let align: text_nodes::TextAlign = self.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
font_size,
|
||||
line_height_ratio: line_height,
|
||||
letter_spacing,
|
||||
letter_tilt,
|
||||
max_width,
|
||||
max_height,
|
||||
align,
|
||||
};
|
||||
|
||||
let mut glyph_paths: Vec<String> = Vec::new();
|
||||
|
||||
text_nodes::TextContext::with_thread_local(|ctx| {
|
||||
let Some(layout) = ctx.layout_text(text, &font, typesetting) else { return };
|
||||
let tilt_tan = letter_tilt.to_radians().tan();
|
||||
|
||||
text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
|
||||
draw_glyph_run_to_bezpaths(glyph_run, x_offset, space_extra, tilt_tan, |bez_path| {
|
||||
glyph_paths.push(bez_path.to_svg());
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if glyph_paths.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Wrap all glyph <path> elements in a <g> with the item's transform/opacity/blend-mode.
|
||||
render.parent_tag(
|
||||
"g",
|
||||
|attributes| {
|
||||
let matrix = format_transform_matrix(transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
if opacity < 1. {
|
||||
attributes.push("opacity", opacity.to_string());
|
||||
}
|
||||
if blend_mode_attr != BlendMode::default() {
|
||||
attributes.push("style", blend_mode_attr.render());
|
||||
}
|
||||
},
|
||||
|render| {
|
||||
for path_d in glyph_paths {
|
||||
render.leaf_tag("path", |attributes| {
|
||||
attributes.push("d", path_d);
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
attributes.push("fill", "none");
|
||||
attributes.push("stroke", "black");
|
||||
attributes.push("stroke-width", "1");
|
||||
} else {
|
||||
attributes.push("fill", "black");
|
||||
attributes.push("fill-rule", "nonzero");
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, _context: &mut RenderContext, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
let Some(text) = self.element(index) else { continue };
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let font: Resource = {
|
||||
let f: Resource = self.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = self.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = self.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = self.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = self.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = self.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let letter_tilt: f64 = self.attribute_cloned_or(ATTR_LETTER_TILT, index, 0.);
|
||||
let align: text_nodes::TextAlign = self.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
font_size,
|
||||
line_height_ratio: line_height,
|
||||
letter_spacing,
|
||||
letter_tilt,
|
||||
max_width,
|
||||
max_height,
|
||||
align,
|
||||
};
|
||||
|
||||
let affine = Affine::new((transform * item_transform).to_cols_array());
|
||||
|
||||
text_nodes::TextContext::with_thread_local(|ctx| {
|
||||
let Some(layout) = ctx.layout_text(text, &font, typesetting) else { return };
|
||||
|
||||
let needs_layer = opacity < 1. || blend_mode_attr != BlendMode::default();
|
||||
if needs_layer {
|
||||
let alignment_width = max_width.map(|w| w as f32).unwrap_or_else(|| layout.full_width());
|
||||
let blending = peniko::BlendMode::new(blend_mode_attr.to_peniko(), peniko::Compose::SrcOver);
|
||||
let padding = font_size;
|
||||
let bounds = kurbo::Rect::new(-padding, -padding, alignment_width as f64 + padding, layout.height() as f64 + padding);
|
||||
let transformed_bounds = affine.transform_rect_bbox(bounds);
|
||||
scene.push_layer(peniko::Fill::NonZero, blending, opacity, kurbo::Affine::IDENTITY, &transformed_bounds);
|
||||
}
|
||||
|
||||
let tilt_tan = letter_tilt.to_radians().tan();
|
||||
|
||||
text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
|
||||
draw_glyph_run_to_bezpaths(glyph_run, x_offset, space_extra, tilt_tan, |bez_path| {
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
let (outline_stroke, outline_color) = get_outline_styles(render_params);
|
||||
scene.stroke(&outline_stroke, affine, outline_color, None, bez_path);
|
||||
} else {
|
||||
scene.fill(peniko::Fill::NonZero, affine, peniko::Color::BLACK, None, bez_path);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if needs_layer {
|
||||
scene.pop_layer();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
// Click targets are baked relative to item 0's transform, which `Graphic::collect_metadata` records as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if !self.is_empty() {
|
||||
self.attribute_cloned_or_default(ATTR_TRANSFORM, 0)
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
let item_zero_inverse = if item_zero_transform.matrix2.determinant() != 0. {
|
||||
item_zero_transform.inverse()
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
|
||||
let mut accumulated_click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>> = HashMap::new();
|
||||
|
||||
for index in 0..self.len() {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let Some(element_id) = caller_element_id.or(layer) else { continue };
|
||||
|
||||
// When recovering element_id from the item's tag (caller passed None), also store the transform metadata.
|
||||
if caller_element_id.is_none() {
|
||||
metadata.upstream_footprints.entry(element_id).or_insert(footprint);
|
||||
metadata.local_transforms.entry(element_id).or_insert(item_zero_transform);
|
||||
}
|
||||
|
||||
let Some((size, item_transform)) = text_item_size_and_transform(self, index) else { continue };
|
||||
let subpath = Subpath::new_rectangle(DVec2::ZERO, size);
|
||||
let mut target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
target.apply_transform(item_zero_inverse * item_transform);
|
||||
accumulated_click_targets.entry(element_id).or_default().push(Arc::new(target));
|
||||
}
|
||||
|
||||
// One rectangle per text item, reused for the selection outline (there's no letterform geometry to outline at this stage).
|
||||
for (element_id, targets) in accumulated_click_targets {
|
||||
metadata.outlines.insert(element_id, targets.clone());
|
||||
metadata.click_targets.insert(element_id, targets);
|
||||
}
|
||||
}
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let Some((size, transform)) = text_item_size_and_transform(self, index) else { continue };
|
||||
let subpath = Subpath::new_rectangle(DVec2::ZERO, size);
|
||||
let mut target = ClickTarget::new_with_subpath(subpath, 0.);
|
||||
target.apply_transform(transform);
|
||||
click_targets.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum SvgSegment {
|
||||
Slice(&'static str),
|
||||
|
||||
@@ -32,6 +32,12 @@ impl Resource {
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Resource {
|
||||
fn default() -> Self {
|
||||
Self::empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&Resource> for Arc<dyn AsRef<[u8]> + Send + Sync> {
|
||||
fn from(val: &Resource) -> Self {
|
||||
val.inner.clone()
|
||||
@@ -229,7 +235,10 @@ pub trait LoadResource: Send + Sync {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_>;
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
pub type ResourceFuture<'a> = Pin<Box<dyn Future<Output = Option<Resource>> + Send + 'a>>;
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub type ResourceFuture<'a> = Pin<Box<dyn Future<Output = Option<Resource>> + 'a>>;
|
||||
|
||||
pub trait ResourceStorage: LoadResource {
|
||||
fn store(&self, data: &[u8]) -> ResourceHash;
|
||||
|
||||
@@ -2,7 +2,7 @@ use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
@@ -484,6 +484,18 @@ pub struct Gradient {
|
||||
pub end: DVec2,
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub spread_method: GradientSpreadMethod,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Whether `start`/`end` are absolute (layer-space) rather than in the legacy [0,1] bounding-box space.
|
||||
/// Documents predating the gradient migration deserialize this as `false`; the deferred migration converts
|
||||
/// them and sets it `true`. Once all documents are migrated, the legacy rendering path can be removed.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub absolute: bool,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// An extra frame adjustment composed onto the `start`/`end` frame (`transform * to_transform()`), letting the gradient
|
||||
/// describe shapes the endpoint pair cannot, such as an elliptical radial. It defaults to identity, so existing documents
|
||||
/// (which only have `start`/`end`) are unaffected; the migration stores a non-identity value only where it's needed.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub transform: DAffine2,
|
||||
}
|
||||
|
||||
impl Default for Gradient {
|
||||
@@ -494,6 +506,9 @@ impl Default for Gradient {
|
||||
start: DVec2::new(0., 0.5),
|
||||
end: DVec2::new(1., 0.5),
|
||||
spread_method: GradientSpreadMethod::Pad,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -512,6 +527,41 @@ impl std::fmt::Display for Gradient {
|
||||
}
|
||||
|
||||
impl Gradient {
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Converts a legacy bounding-box-relative gradient (`start`/`end` in [0,1]) into an absolute one in the geometry's local space.
|
||||
/// `bounding_box` maps [0,1] onto the geometry's bounding box; `layer_transform` is the layer's own transform,
|
||||
/// used to bake the elliptical adjustment that reproduces the legacy isotropic radial through a non-uniform layer.
|
||||
pub fn to_absolute(&self, bounding_box: DAffine2, layer_transform: DAffine2) -> Gradient {
|
||||
let start = bounding_box.transform_point2(self.start);
|
||||
let end = bounding_box.transform_point2(self.end);
|
||||
let direction = end - start;
|
||||
|
||||
// The legacy radial drew as a circle in the layer's own space; bake the adjustment that, composed with the
|
||||
// endpoint frame, makes the new pipeline reproduce that circle through the (possibly non-uniform) layer transform.
|
||||
let radial_invertible =
|
||||
self.gradient_type == GradientType::Radial && layer_transform.is_finite() && layer_transform.matrix2.determinant().recip().is_finite() && direction.length_squared() > 1e-20;
|
||||
let transform = if radial_invertible {
|
||||
let radius = (layer_transform.matrix2 * direction).length();
|
||||
let circle = DAffine2 {
|
||||
matrix2: DMat2::from_diagonal(DVec2::splat(radius)),
|
||||
translation: layer_transform.transform_point2(start),
|
||||
};
|
||||
let base = DAffine2::from_cols(direction, direction.perp(), start);
|
||||
(layer_transform.inverse() * circle) * base.inverse()
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
|
||||
Gradient {
|
||||
start,
|
||||
end,
|
||||
transform,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
..self.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Constructs a new gradient with the colors at 0 and 1 specified.
|
||||
pub fn new(start: DVec2, start_color: Color, end: DVec2, end_color: Color, gradient_type: GradientType, spread_method: GradientSpreadMethod) -> Self {
|
||||
let stops = GradientStops::new([
|
||||
@@ -533,6 +583,9 @@ impl Gradient {
|
||||
stops,
|
||||
gradient_type,
|
||||
spread_method,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,6 +607,9 @@ impl Gradient {
|
||||
stops,
|
||||
gradient_type,
|
||||
spread_method,
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: self.absolute,
|
||||
transform: if time < 0.5 { self.transform } else { other.transform },
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -153,6 +153,9 @@ impl From<List<GradientStops>> for Fill {
|
||||
spread_method,
|
||||
start: transform.transform_point2(DVec2::ZERO),
|
||||
end: transform.transform_point2(DVec2::X),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -668,6 +671,10 @@ impl PathStyle {
|
||||
&self.fill
|
||||
}
|
||||
|
||||
pub fn fill_mut(&mut self) -> &mut Fill {
|
||||
&mut self.fill
|
||||
}
|
||||
|
||||
/// Get the current path's [Stroke].
|
||||
///
|
||||
/// # Example
|
||||
|
||||
@@ -1223,7 +1223,15 @@ impl Vector {
|
||||
}
|
||||
|
||||
pub fn is_branching(&self) -> bool {
|
||||
(0..self.point_domain.len()).any(|point_index| self.segment_domain.connected_count(point_index) > 2)
|
||||
// Tally segment endpoints per point in one `O(points + segments)` pass, short-circuiting once any point exceeds two
|
||||
let mut connected_count = vec![0_u8; self.point_domain.len()];
|
||||
for &point_index in self.segment_domain.start_point().iter().chain(self.segment_domain.end_point()) {
|
||||
connected_count[point_index] += 1;
|
||||
if connected_count[point_index] > 2 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn has_regions(&self) -> bool {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use dyn_any::StaticType;
|
||||
use dyn_any::DynAny;
|
||||
use std::any::Any;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
@@ -39,7 +39,7 @@ impl<P: AsyncPipeline> Pipeline for P {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
#[derive(Default, Clone, DynAny)]
|
||||
pub struct PipelineCache {
|
||||
pipeline: Arc<OnceLock<Box<dyn Any + Send + Sync>>>,
|
||||
executor: Arc<OnceLock<WgpuExecutor>>,
|
||||
@@ -66,7 +66,3 @@ impl std::fmt::Debug for PipelineCache {
|
||||
f.debug_struct("PipelineCache").field("initialized", &self.pipeline.get().is_some()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl StaticType for PipelineCache {
|
||||
type Static = PipelineCache;
|
||||
}
|
||||
@@ -53,6 +53,11 @@ impl MultiplyAlpha for List<GradientStops> {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyAlpha for List<String> {
|
||||
fn multiply_alpha(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY, factor);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) trait MultiplyFill {
|
||||
fn multiply_fill(&mut self, factor: f64);
|
||||
@@ -87,6 +92,11 @@ impl MultiplyFill for List<GradientStops> {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
impl MultiplyFill for List<String> {
|
||||
fn multiply_fill(&mut self, factor: f64) {
|
||||
multiply_list_attribute(self, ATTR_OPACITY_FILL, factor);
|
||||
}
|
||||
}
|
||||
|
||||
trait SetBlendMode {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode);
|
||||
@@ -123,6 +133,11 @@ impl SetBlendMode for List<GradientStops> {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
impl SetBlendMode for List<String> {
|
||||
fn set_blend_mode(&mut self, blend_mode: BlendMode) {
|
||||
set_list_blend_mode(self, blend_mode);
|
||||
}
|
||||
}
|
||||
|
||||
trait SetClip {
|
||||
fn set_clip(&mut self, clip: bool);
|
||||
@@ -159,6 +174,11 @@ impl SetClip for List<GradientStops> {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
impl SetClip for List<String> {
|
||||
fn set_clip(&mut self, clip: bool) {
|
||||
set_list_clip(self, clip);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the blend mode to the input graphics. Setting this allows for customizing how overlapping content is composited together.
|
||||
#[node_macro::node(category("Blending"))]
|
||||
@@ -171,6 +191,7 @@ fn blend_mode<T: SetBlendMode>(
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
mut content: T,
|
||||
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
|
||||
@@ -194,6 +215,7 @@ fn opacity<T: MultiplyAlpha + MultiplyFill>(
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
mut content: T,
|
||||
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
|
||||
@@ -235,6 +257,7 @@ fn clipping_mask<T: SetClip>(
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
mut content: T,
|
||||
/// Whether the content inherits the alpha of the content beneath it.
|
||||
|
||||
@@ -7,7 +7,7 @@ use graphic_types::{Artboard, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
|
||||
/// Constructs a single-row `List<Artboard>` with the given content and metadata stored as row attributes.
|
||||
/// Constructs a single-element `Artboard[]` with the given content and metadata stored as row attributes.
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn create_artboard<T: IntoGraphicList + 'n>(
|
||||
ctx: impl ExtractAll + CloneVarArgs + Ctx,
|
||||
@@ -15,6 +15,7 @@ pub async fn create_artboard<T: IntoGraphicList + 'n>(
|
||||
#[implementations(
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<String>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
Context -> List<Color>,
|
||||
|
||||
@@ -116,6 +116,7 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
content: List<Item>,
|
||||
#[implementations(
|
||||
@@ -124,6 +125,7 @@ async fn map<Item: AnyHash + Send + Sync + CacheHash>(
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
mapped: impl Node<Context<'static>, Output = List<Item>>,
|
||||
) -> List<Item> {
|
||||
@@ -146,6 +148,7 @@ async fn mirror<T: 'n + Send + Clone>(
|
||||
#[implementations(
|
||||
List<Graphic>,
|
||||
List<Vector>,
|
||||
List<String>,
|
||||
List<Raster<CPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
@@ -280,7 +283,7 @@ fn attach_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
List<GradientSpreadMethod>,
|
||||
)]
|
||||
mut content: List<T>,
|
||||
/// The source values to attach. Any `List<U>` wired here is type-erased via an auto-inserted convert.
|
||||
/// The source values to attach.
|
||||
#[expose]
|
||||
source: AttributeDyn,
|
||||
/// The name to assign to the new destination attribute.
|
||||
@@ -293,7 +296,7 @@ fn attach_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
|
||||
content
|
||||
}
|
||||
|
||||
/// Reads a named `Vector` attribute from the input list, outputting each value as an element of a new `List<Vector>`.
|
||||
/// Reads a named `Vector` attribute from the input list, outputting each value as an element of a new `Vector[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_vector(
|
||||
_: impl Ctx,
|
||||
@@ -309,7 +312,7 @@ fn read_attribute_vector(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named numeric attribute (`f64`, `u64`, or `u32`) from the input list, outputting each value as an element of a new `List<f64>`. Integer values are converted to `f64`.
|
||||
/// Reads a named numeric attribute (`f64`, `u64`, or `u32`) from the input list, outputting each value as an element of a new `f64[]`. Integer values are converted to `f64`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_number(
|
||||
_: impl Ctx,
|
||||
@@ -330,7 +333,7 @@ fn read_attribute_number(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `bool` attribute from the input list, outputting each value as an element of a new `List<bool>`.
|
||||
/// Reads a named `bool` attribute from the input list, outputting each value as an element of a new `bool[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_bool(
|
||||
_: impl Ctx,
|
||||
@@ -346,7 +349,7 @@ fn read_attribute_bool(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `String` attribute from the input list, outputting each value as an element of a new `List<String>`.
|
||||
/// Reads a named `String` attribute from the input list, outputting each value as an element of a new `String[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_string(
|
||||
_: impl Ctx,
|
||||
@@ -362,7 +365,7 @@ fn read_attribute_string(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `DAffine2` transform attribute from the input list, outputting each value as an element of a new `List<DAffine2>`.
|
||||
/// Reads a named `DAffine2` transform attribute from the input list, outputting each value as an element of a new `DAffine2[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_transform(
|
||||
_: impl Ctx,
|
||||
@@ -378,7 +381,7 @@ fn read_attribute_transform(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Color` attribute from the input list, outputting each value as an element of a new `List<Color>`.
|
||||
/// Reads a named `Color` attribute from the input list, outputting each value as an element of a new `Color[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_color(
|
||||
_: impl Ctx,
|
||||
@@ -394,7 +397,7 @@ fn read_attribute_color(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `BlendMode` attribute from the input list, outputting each value as an element of a new `List<BlendMode>`.
|
||||
/// Reads a named `BlendMode` attribute from the input list, outputting each value as an element of a new `BlendMode[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_blend_mode(
|
||||
_: impl Ctx,
|
||||
@@ -410,7 +413,7 @@ fn read_attribute_blend_mode(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientType` attribute from the input list, outputting each value as an element of a new `List<GradientType>`.
|
||||
/// Reads a named `GradientType` attribute from the input list, outputting each value as an element of a new `GradientType[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_gradient_type(
|
||||
_: impl Ctx,
|
||||
@@ -426,7 +429,7 @@ fn read_attribute_gradient_type(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientSpreadMethod` attribute from the input list, outputting each value as an element of a new `List<GradientSpreadMethod>`.
|
||||
/// Reads a named `GradientSpreadMethod` attribute from the input list, outputting each value as an element of a new `GradientSpreadMethod[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_spread_method(
|
||||
_: impl Ctx,
|
||||
@@ -442,7 +445,7 @@ fn read_attribute_spread_method(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `GradientStops` attribute from the input list, outputting each value as an element of a new `List<GradientStops>`.
|
||||
/// Reads a named `GradientStops` attribute from the input list, outputting each value as an element of a new `GradientStops[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_gradient_stops(
|
||||
_: impl Ctx,
|
||||
@@ -458,7 +461,7 @@ fn read_attribute_gradient_stops(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Artboard` attribute from the input list, outputting each value as an element of a new `List<Artboard>`.
|
||||
/// Reads a named `Artboard` attribute from the input list, outputting each value as an element of a new `Artboard[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_artboard(
|
||||
_: impl Ctx,
|
||||
@@ -474,7 +477,7 @@ fn read_attribute_artboard(
|
||||
result
|
||||
}
|
||||
|
||||
/// Reads a named `Raster<CPU>` attribute from the input list, outputting each value as an element of a new `List<Raster<CPU>>`.
|
||||
/// Reads a named `Raster` attribute from the input list, outputting each value as an element of a new `Raster[]`.
|
||||
#[node_macro::node(category("Attributes: Read"))]
|
||||
fn read_attribute_raster(
|
||||
_: impl Ctx,
|
||||
@@ -495,11 +498,11 @@ fn read_attribute_raster(
|
||||
pub async fn extend<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
/// The `List` whose items will appear at the start of the extended `List`.
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
base: List<T>,
|
||||
/// The `List` whose items will appear at the end of the extended `List`.
|
||||
#[expose]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
new: List<T>,
|
||||
) -> List<T> {
|
||||
let mut base = base;
|
||||
@@ -514,9 +517,9 @@ pub async fn extend<T: 'n + Send + Clone>(
|
||||
#[node_macro::node(category(""))]
|
||||
pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
|
||||
_: impl Ctx,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] base: List<T>,
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)] base: List<T>,
|
||||
#[expose]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<GradientStops>)]
|
||||
new: List<T>,
|
||||
nested_node_path: List<NodeId>,
|
||||
) -> List<T> {
|
||||
@@ -548,6 +551,7 @@ pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
DAffine2,
|
||||
DVec2,
|
||||
)]
|
||||
@@ -556,8 +560,8 @@ pub async fn wrap_graphic<T: Into<Graphic> + 'n>(
|
||||
List::new_from_element(content.into())
|
||||
}
|
||||
|
||||
/// Converts a `List` of graphical content into a `List<Graphic>` by placing it into an element of a new wrapper `List<Graphic>`.
|
||||
/// If it is already a `List<Graphic>`, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired.
|
||||
/// Converts a list of graphical content into a `Graphic[]` by placing it into an element of a new wrapper `Graphic[]`.
|
||||
/// If it is already a `Graphic[]`, it is not wrapped again. Use the 'Wrap Graphic' node if wrapping is always desired.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn to_graphic<T: IntoGraphicList + 'n>(
|
||||
_: impl Ctx,
|
||||
@@ -568,13 +572,14 @@ pub async fn to_graphic<T: IntoGraphicList + 'n>(
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
List<String>,
|
||||
)]
|
||||
content: T,
|
||||
) -> List<Graphic> {
|
||||
content.into_graphic_list()
|
||||
}
|
||||
|
||||
/// Removes a level of nesting from a `List<Graphic>`, or all nesting if "Fully Flatten" is enabled.
|
||||
/// Removes a level of nesting from a `Graphic[]`, or all nesting if "Fully Flatten" is enabled.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten: bool) -> List<Graphic> {
|
||||
// TODO: Avoid mutable reference, instead return a new List<Graphic>?
|
||||
@@ -596,7 +601,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
|
||||
|
||||
flatten_list(output_graphic_list, current_element, fully_flatten, recursion_depth + 1);
|
||||
}
|
||||
// Push any leaf elements we encounter: either `Graphic::Graphic(...)` values beyond the recursion depth, or non-`Graphic::Graphic` variants (e.g. `Graphic::Vector`, `Graphic::Raster*`, `Graphic::Color`, `Graphic::Gradient`)
|
||||
// Push any leaf elements we encounter: either `Graphic::Graphic(...)` values beyond the recursion depth, or non-`Graphic::Graphic` variants (e.g. `Graphic::Vector`, `Graphic::Raster*`, `Graphic::Color`, `Graphic::Gradient`, `Graphic::Text`)
|
||||
_ => {
|
||||
let attributes = current_graphic_list.clone_item_attributes(index);
|
||||
output_graphic_list.push(Item::from_parts(current_element, attributes));
|
||||
@@ -611,7 +616,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
|
||||
output
|
||||
}
|
||||
|
||||
/// Converts a `List<Graphic>` into a `List<Vector>` by deeply flattening any vector content it contains, and discarding any non-vector content.
|
||||
/// Converts a `Graphic[]` into a `Vector[]` by deeply flattening any vector content it contains, and discarding any non-vector content.
|
||||
#[node_macro::node(category("Vector"))]
|
||||
pub async fn flatten_vector<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Vector>)] content: T) -> List<Vector> {
|
||||
let graphic_list = content.into_graphic_list();
|
||||
@@ -644,25 +649,25 @@ pub async fn flatten_vector<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx,
|
||||
output
|
||||
}
|
||||
|
||||
/// Converts a `List<Graphic>` into a `List<Raster>` by deeply flattening any raster content it contains, and discarding any non-raster content.
|
||||
/// Converts a `Graphic[]` into a `Raster[]` by deeply flattening any raster content it contains, and discarding any non-raster content.
|
||||
#[node_macro::node(category("Raster"))]
|
||||
pub async fn flatten_raster<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Raster<CPU>>)] content: T) -> List<Raster<CPU>> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// Converts a `List<Graphic>` into a `List<Color>` by deeply flattening any color content it contains, and discarding any non-color content.
|
||||
/// Converts a `Graphic[]` into a `Color[]` by deeply flattening any color content it contains, and discarding any non-color content.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn flatten_color<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] content: T) -> List<Color> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// Converts a `List<Graphic>` into a `List<GradientStops>` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
|
||||
/// Converts a `Graphic[]` into a `GradientStops[]` by deeply flattening any gradient content it contains, and discarding any non-gradient content.
|
||||
#[node_macro::node(category("General"))]
|
||||
pub async fn flatten_gradient<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<GradientStops>)] content: T) -> List<GradientStops> {
|
||||
content.into_flattened_list()
|
||||
}
|
||||
|
||||
/// Constructs a gradient from a `List<Color>`, where the colors are evenly distributed as gradient stops across the range from 0 to 1.
|
||||
/// Constructs a gradient from a `Color[]`, where the colors are evenly distributed as gradient stops across the range from 0 to 1.
|
||||
#[node_macro::node(category("Color"))]
|
||||
fn colors_to_gradient<T: IntoGraphicList + 'n + Send + Clone>(_: impl Ctx, #[implementations(List<Graphic>, List<Color>)] colors: T) -> List<GradientStops> {
|
||||
let colors = colors.into_flattened_list::<Color>();
|
||||
|
||||
@@ -137,7 +137,7 @@ fn image_to_bytes(_: impl Ctx, image: List<Raster<CPU>>) -> List<u8> {
|
||||
|
||||
/// Loads binary from URLs and local asset paths. Returns a transparent placeholder if the resource fails to load, allowing rendering to continue.
|
||||
#[node_macro::node(category("Web Request"))]
|
||||
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[scope("editor-api")] _editor: &'a PlatformEditorApi, #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
async fn load_resource<'a: 'n>(_: impl Ctx, _primary: (), #[name("URL")] url: String) -> Arc<[u8]> {
|
||||
let placeholder = || -> Arc<[u8]> { Arc::from(Vec::<u8>::new()) };
|
||||
|
||||
let response = match reqwest::Client::new().get(&url).send().await {
|
||||
@@ -276,10 +276,15 @@ pub async fn resource<'a: 'n>(_: impl Ctx, hash: ResourceHash, #[scope(editor_ap
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> &'a ::wgpu_executor::WgpuExecutor {
|
||||
editor_api.application_io.as_ref().unwrap().gpu_executor().expect("GPU executor not available")
|
||||
editor_api
|
||||
.application_io
|
||||
.as_ref()
|
||||
.expect("ApplicationIo not not available")
|
||||
.gpu_executor()
|
||||
.expect("GPU executor not available")
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), inject_scope)]
|
||||
pub async fn try_wgpu_executor<'a: 'n>(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: &'a PlatformEditorApi) -> Option<&'a ::wgpu_executor::WgpuExecutor> {
|
||||
editor_api.application_io.as_ref().unwrap().gpu_executor()
|
||||
editor_api.application_io.as_ref()?.gpu_executor()
|
||||
}
|
||||
@@ -32,6 +32,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Color>,
|
||||
Context -> List<GradientStops>,
|
||||
Context -> List<String>,
|
||||
)]
|
||||
data: impl Node<Context<'static>, Output = T>,
|
||||
) -> RenderIntermediate {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
use core_types::Ctx;
|
||||
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
|
||||
use core_types::list::List;
|
||||
use core_types::{ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, Ctx};
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graphic_types::Vector;
|
||||
pub use text_nodes::*;
|
||||
|
||||
/// Draws a text string as vector geometry with a choice of font and styling.
|
||||
/// Produces a styled `String[]` carrying all typographic attributes.
|
||||
///
|
||||
/// Use the **Text to Vector** node to convert this into vector geometry if desired.
|
||||
#[node_macro::node(category("Text"))]
|
||||
fn text(
|
||||
_: impl Ctx,
|
||||
@@ -32,8 +35,13 @@ fn text(
|
||||
/// Additional spacing, in pixels, added between each character.
|
||||
#[unit(" px")]
|
||||
#[step(0.1)]
|
||||
character_spacing: f64,
|
||||
/// Whether the *Max Width* property is enabled so that lines can wrap to fit its specified block width.
|
||||
letter_spacing: f64,
|
||||
/// The angle of faux italic slant applied to each glyph.
|
||||
#[unit("°")]
|
||||
#[hard_min(-85.)]
|
||||
#[hard_max(85.)]
|
||||
letter_tilt: f64,
|
||||
/// Enables the maximum width constraint so lines can wrap.
|
||||
#[widget(ParsedWidgetOverride::Hidden)]
|
||||
has_max_width: bool,
|
||||
/// The maximum width that the text block can occupy before wrapping to a new line. Otherwise, lines do not wrap.
|
||||
@@ -49,27 +57,49 @@ fn text(
|
||||
#[hard_min(1.)]
|
||||
#[widget(ParsedWidgetOverride::Custom = "optional_f64")]
|
||||
max_height: f64,
|
||||
/// The angle of faux italic slant applied to each glyph.
|
||||
#[unit("°")]
|
||||
#[hard_min(-85.)]
|
||||
#[hard_max(85.)]
|
||||
tilt: f64,
|
||||
/// The horizontal alignment of each line of text within its surrounding box.
|
||||
/// To have an effect on a single line of text, *Max Width* must be set.
|
||||
/// The horizontal alignment of each line of text within its surrounding box. To have an effect on a single line of text, *Max Width* must be set.
|
||||
#[widget(ParsedWidgetOverride::Custom = "text_align")]
|
||||
align: TextAlign,
|
||||
) -> List<String> {
|
||||
let mut list = List::new_from_element(text);
|
||||
|
||||
if font != Resource::default() {
|
||||
list.set_attribute(ATTR_FONT, 0, font);
|
||||
}
|
||||
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
|
||||
list.set_attribute(ATTR_FONT_SIZE, 0, size);
|
||||
}
|
||||
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
|
||||
list.set_attribute(ATTR_LINE_HEIGHT, 0, line_height);
|
||||
}
|
||||
if letter_spacing != 0. {
|
||||
list.set_attribute(ATTR_LETTER_SPACING, 0, letter_spacing);
|
||||
}
|
||||
if letter_tilt != 0. {
|
||||
list.set_attribute(ATTR_LETTER_TILT, 0, letter_tilt);
|
||||
}
|
||||
if has_max_width {
|
||||
list.set_attribute(ATTR_MAX_WIDTH, 0, Some(max_width));
|
||||
}
|
||||
if has_max_height {
|
||||
list.set_attribute(ATTR_MAX_HEIGHT, 0, Some(max_height));
|
||||
}
|
||||
if align != TextAlign::default() {
|
||||
list.set_attribute(ATTR_TEXT_ALIGN, 0, align);
|
||||
}
|
||||
|
||||
list
|
||||
}
|
||||
|
||||
/// Converts a styled `String[]` into vector geometry.
|
||||
#[node_macro::node(category("Text"), name("Text to Vector"))]
|
||||
fn text_to_vector(
|
||||
_: impl Ctx,
|
||||
/// A styled list of text strings produced by the **Text** node (or any other `String[]` source).
|
||||
#[implementations(List<String>)]
|
||||
strings: List<String>,
|
||||
/// Whether to split every letterform into its own vector item. Otherwise, a single vector compound path is produced.
|
||||
separate_glyphs: bool,
|
||||
) -> List<Vector> {
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size: size,
|
||||
line_height_ratio: line_height,
|
||||
character_spacing,
|
||||
max_width: has_max_width.then_some(max_width),
|
||||
max_height: has_max_height.then_some(max_height),
|
||||
tilt,
|
||||
align,
|
||||
};
|
||||
|
||||
to_path(&text, &font, typesetting, separate_glyphs)
|
||||
shape_text_list(&strings, separate_glyphs)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ license = "MIT OR Apache-2.0"
|
||||
# Local dependencies
|
||||
core-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
linesweeper = { workspace = true }
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color, Ctx};
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, BlendMode, Color,
|
||||
Ctx,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientSpreadMethod, GradientType};
|
||||
use graphic_types::vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use graphic_types::vector_types::vector::PointId;
|
||||
use graphic_types::vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
|
||||
@@ -125,13 +129,20 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
|
||||
};
|
||||
let mut row = if let Some(index) = copy_from_index {
|
||||
let mut attributes = vector.clone_item_attributes(index);
|
||||
let copy_from_transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
// The boolean op bakes input transforms into the output geometry, so the result item carries no transform of its own
|
||||
attributes.insert(ATTR_TRANSFORM, DAffine2::IDENTITY);
|
||||
let copy_from = vector.element(index).unwrap();
|
||||
let element = Vector {
|
||||
let mut element = Vector {
|
||||
style: copy_from.style.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
// An absolute gradient lives in the geometry's space, so bake the same transform into it to track the baked points
|
||||
if let Fill::Gradient(gradient) = element.style.fill_mut()
|
||||
&& gradient.absolute
|
||||
{
|
||||
gradient.transform = copy_from_transform * gradient.transform;
|
||||
}
|
||||
Item::from_parts(element, attributes)
|
||||
} else {
|
||||
Item::<Vector>::default()
|
||||
@@ -272,12 +283,34 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
.map(|row| {
|
||||
let (stops, attributes) = row.into_parts();
|
||||
let mut element = Vector::default();
|
||||
element.style.set_fill(Fill::Gradient(graphic_types::vector_types::gradient::Gradient { stops, ..Default::default() }));
|
||||
// Convert the gradient's transform to absolute endpoints, matching `From<List<GradientStops>> for Fill`
|
||||
let transform = attributes.get::<DAffine2>(ATTR_TRANSFORM).cloned().unwrap_or_default();
|
||||
element.style.set_fill(Fill::Gradient(Gradient {
|
||||
stops,
|
||||
gradient_type: attributes.get::<GradientType>(ATTR_GRADIENT_TYPE).cloned().unwrap_or_default(),
|
||||
spread_method: attributes.get::<GradientSpreadMethod>(ATTR_SPREAD_METHOD).cloned().unwrap_or_default(),
|
||||
start: transform.transform_point2(DVec2::ZERO),
|
||||
end: transform.transform_point2(DVec2::X),
|
||||
absolute: true,
|
||||
transform: DAffine2::IDENTITY,
|
||||
}));
|
||||
element.style.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
Item::from_parts(element, attributes)
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
Graphic::Text(text) => {
|
||||
// Shape the glyphs into vectors (each item's own transform is applied), then compose the parent's transform like the other arms
|
||||
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
text_nodes::shape_text_list(&text, false)
|
||||
.into_iter()
|
||||
.map(|mut sub_vector| {
|
||||
let current_transform: DAffine2 = sub_vector.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
*sub_vector.attribute_mut_or_insert_default(ATTR_TRANSFORM) = parent_transform * current_transform;
|
||||
sub_vector
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
use graphene_resource::Resource;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
const FALLBACK_FONT_BYTES: &[u8] = include_bytes!("source-sans-pro-regular.ttf");
|
||||
pub static FALLBACK_FONT_RESOURCE: LazyLock<Resource> = LazyLock::new(|| Resource::new(FALLBACK_FONT_BYTES));
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod fallback;
|
||||
mod font;
|
||||
pub mod json;
|
||||
mod path_builder;
|
||||
@@ -16,8 +17,9 @@ use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
// Re-export for convenience
|
||||
pub use core_types as gcore;
|
||||
pub use fallback::FALLBACK_FONT_RESOURCE;
|
||||
pub use font::*;
|
||||
pub use text_context::TextContext;
|
||||
pub use text_context::{TextContext, for_each_styled_glyph_run};
|
||||
pub use to_path::*;
|
||||
pub use vector_types;
|
||||
|
||||
@@ -92,10 +94,10 @@ impl TextAlign {
|
||||
pub struct TypesettingConfig {
|
||||
pub font_size: f64,
|
||||
pub line_height_ratio: f64,
|
||||
pub character_spacing: f64,
|
||||
pub letter_spacing: f64,
|
||||
pub letter_tilt: f64,
|
||||
pub max_width: Option<f64>,
|
||||
pub max_height: Option<f64>,
|
||||
pub tilt: f64,
|
||||
pub align: TextAlign,
|
||||
}
|
||||
|
||||
@@ -104,10 +106,10 @@ impl Default for TypesettingConfig {
|
||||
Self {
|
||||
font_size: 24.,
|
||||
line_height_ratio: 1.2,
|
||||
character_spacing: 0.,
|
||||
letter_spacing: 0.,
|
||||
letter_tilt: 0.,
|
||||
max_width: None,
|
||||
max_height: None,
|
||||
tilt: 0.,
|
||||
align: TextAlign::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,19 +105,19 @@ impl PathBuilder {
|
||||
has_geometry
|
||||
}
|
||||
|
||||
pub fn render_glyph_run(&mut self, glyph_run: &GlyphRun<'_, ()>, tilt: f64, per_glyph_items: bool, x_offset: f32, space_extra: f32) {
|
||||
pub fn render_glyph_run(&mut self, glyph_run: &GlyphRun<'_, ()>, letter_tilt: f64, per_glyph_items: bool, x_offset: f32, space_extra: f32) {
|
||||
let mut run_x = glyph_run.offset() + x_offset;
|
||||
let run_y = glyph_run.baseline();
|
||||
|
||||
let run = glyph_run.run();
|
||||
|
||||
// User-requested tilt applied around baseline to avoid vertical displacement
|
||||
// User-requested letter tilt applied around baseline to avoid vertical displacement
|
||||
// Translation ensures rotation point is at the baseline, not origin
|
||||
let skew = if per_glyph_items {
|
||||
DAffine2::from_cols_array(&[1., 0., -tilt.to_radians().tan(), 1., 0., 0.])
|
||||
DAffine2::from_cols_array(&[1., 0., -letter_tilt.to_radians().tan(), 1., 0., 0.])
|
||||
} else {
|
||||
DAffine2::from_translation(DVec2::new(0., run_y as f64))
|
||||
* DAffine2::from_cols_array(&[1., 0., -tilt.to_radians().tan(), 1., 0., 0.])
|
||||
* DAffine2::from_cols_array(&[1., 0., -letter_tilt.to_radians().tan(), 1., 0., 0.])
|
||||
* DAffine2::from_translation(DVec2::new(0., -run_y as f64))
|
||||
};
|
||||
|
||||
|
||||
File renamed without changes.
@@ -1,19 +1,71 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::path_builder::PathBuilder;
|
||||
use core::cell::RefCell;
|
||||
use core_types::list::List;
|
||||
use glam::DVec2;
|
||||
use graphene_resource::{Resource, ResourceHash};
|
||||
use parley::fontique::{Blob, FamilyId, FontInfo};
|
||||
use parley::{AlignmentOptions, FontContext, Layout, LayoutContext, LineHeight, PositionedLayoutItem, StyleProperty};
|
||||
use parley::{AlignmentOptions, FontContext, GlyphRun, Layout, LayoutContext, LineHeight, PositionedLayoutItem, StyleProperty};
|
||||
use std::collections::HashMap;
|
||||
use vector_types::Vector;
|
||||
|
||||
use super::path_builder::PathBuilder;
|
||||
|
||||
thread_local! {
|
||||
static THREAD_TEXT: RefCell<TextContext> = RefCell::new(TextContext::default());
|
||||
}
|
||||
|
||||
/// Iterates the glyph runs of a laid-out text in reading order, computing each line's last-line alignment correction
|
||||
/// (`x_offset` and per-space `space_extra`) and skipping runs clipped by `max_height`. Shared by the vector shaper and the
|
||||
/// SVG/Vello text renderers so the alignment logic lives in one place.
|
||||
pub fn for_each_styled_glyph_run(layout: &Layout<()>, text: &str, typesetting: TypesettingConfig, mut visit: impl FnMut(&GlyphRun<'_, ()>, f32, f32)) {
|
||||
let alignment_width = typesetting.max_width.map(|w| w as f32).unwrap_or_else(|| layout.full_width());
|
||||
let last_line_correction = typesetting.align.last_line_correction();
|
||||
|
||||
for line in layout.lines() {
|
||||
let range = line.text_range();
|
||||
// Parley always includes a hard-break `\n` as the last byte of the preceding line's range, so the line is at the end of
|
||||
// a paragraph if it's the very last line of the buffer or its text ends with `\n`.
|
||||
let is_last_para_line = range.end == text.len() || text.get(range.clone()).is_some_and(|s| s.ends_with('\n'));
|
||||
|
||||
let mut x_offset = 0.;
|
||||
let mut space_extra = 0.;
|
||||
|
||||
if is_last_para_line && let Some(correction) = last_line_correction {
|
||||
let metrics = line.metrics();
|
||||
let content_advance = metrics.advance - metrics.trailing_whitespace;
|
||||
let free_space = alignment_width - content_advance;
|
||||
|
||||
match correction {
|
||||
parley::Alignment::Center => x_offset = free_space * 0.5,
|
||||
parley::Alignment::Right => x_offset = free_space,
|
||||
parley::Alignment::Justify => {
|
||||
// Exclude trailing-whitespace clusters from the divisor so the redistribution stretches only the internal spaces.
|
||||
// Parley's `trailing_whitespace` is in advance units, not bytes, so we re-derive the byte boundary here to filter cluster ranges.
|
||||
let line_text = text.get(range.clone()).unwrap_or("");
|
||||
let trailing_len = line_text.len() - line_text.trim_end().len();
|
||||
let visible_end_index = range.end - trailing_len;
|
||||
|
||||
let space_count: usize = line
|
||||
.runs()
|
||||
.map(|run| run.clusters().filter(|c| c.is_space_or_nbsp() && c.text_range().start < visible_end_index).count())
|
||||
.sum();
|
||||
if space_count > 0 {
|
||||
space_extra = free_space / space_count as f32;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
for item in line.items() {
|
||||
if let PositionedLayoutItem::GlyphRun(glyph_run) = item
|
||||
&& typesetting.max_height.filter(|&max_height| glyph_run.baseline() > max_height as f32).is_none()
|
||||
{
|
||||
visit(&glyph_run, x_offset, space_extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Unified thread-local text processing context that combines font and layout management
|
||||
/// for efficient text rendering operations.
|
||||
#[derive(Default)]
|
||||
@@ -54,14 +106,14 @@ impl TextContext {
|
||||
}
|
||||
|
||||
/// Create a text layout from the given font resource and typesetting configuration.
|
||||
fn layout_text(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig) -> Option<Layout<()>> {
|
||||
pub fn layout_text(&mut self, text: &str, font: &Resource, typesetting: TypesettingConfig) -> Option<Layout<()>> {
|
||||
let (font_family, font_info) = self.get_font_info(font)?;
|
||||
|
||||
const DISPLAY_SCALE: f32 = 1.;
|
||||
let mut builder = self.layout_context.ranged_builder(&mut self.font_context, text, DISPLAY_SCALE, false);
|
||||
|
||||
builder.push_default(StyleProperty::FontSize(typesetting.font_size as f32));
|
||||
builder.push_default(StyleProperty::LetterSpacing(typesetting.character_spacing as f32));
|
||||
builder.push_default(StyleProperty::LetterSpacing(typesetting.letter_spacing as f32));
|
||||
builder.push_default(StyleProperty::FontFamily(parley::FontFamily::Single(parley::FontFamilyName::Named(std::borrow::Cow::Owned(
|
||||
font_family,
|
||||
)))));
|
||||
@@ -100,53 +152,11 @@ impl TextContext {
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
let alignment_width = typesetting.max_width.map(|w| w as f32).unwrap_or_else(|| layout.full_width());
|
||||
let last_line_correction = typesetting.align.last_line_correction();
|
||||
|
||||
let mut path_builder = PathBuilder::new(per_glyph_items, layout.scale() as f64, text_frame_size, first_glyph_offset);
|
||||
|
||||
for line in layout.lines() {
|
||||
let range = line.text_range();
|
||||
// Parley always includes a hard-break `\n` as the last byte of the preceding line's range, so the line
|
||||
// is at the end of a paragraph if it's the very last line of the buffer or its text ends with `\n`.
|
||||
let is_last_para_line = range.end == text.len() || text.get(range.clone()).is_some_and(|s| s.ends_with('\n'));
|
||||
|
||||
let (x_offset, space_extra) = if let (true, Some(correction)) = (is_last_para_line, last_line_correction) {
|
||||
let metrics = line.metrics();
|
||||
let content_advance = metrics.advance - metrics.trailing_whitespace;
|
||||
let free_space = alignment_width - content_advance;
|
||||
|
||||
match correction {
|
||||
parley::Alignment::Center => (free_space * 0.5, 0.),
|
||||
parley::Alignment::Right => (free_space, 0.),
|
||||
parley::Alignment::Justify => {
|
||||
// Exclude trailing-whitespace clusters from the divisor so the redistribution stretches only the internal spaces.
|
||||
// Parley's `trailing_whitespace` is in advance units, not bytes, so we re-derive the byte boundary here to filter cluster ranges.
|
||||
let line_text = text.get(range.clone()).unwrap_or("");
|
||||
let trailing_len = line_text.len() - line_text.trim_end().len();
|
||||
let visible_end_index = range.end - trailing_len;
|
||||
|
||||
let space_count: usize = line
|
||||
.runs()
|
||||
.map(|run| run.clusters().filter(|c| c.is_space_or_nbsp() && c.text_range().start < visible_end_index).count())
|
||||
.sum();
|
||||
let extra = if space_count > 0 { free_space / space_count as f32 } else { 0. };
|
||||
(0., extra)
|
||||
}
|
||||
_ => (0., 0.),
|
||||
}
|
||||
} else {
|
||||
(0., 0.)
|
||||
};
|
||||
|
||||
for item in line.items() {
|
||||
if let PositionedLayoutItem::GlyphRun(glyph_run) = item
|
||||
&& typesetting.max_height.filter(|&max_height| glyph_run.baseline() > max_height as f32).is_none()
|
||||
{
|
||||
path_builder.render_glyph_run(&glyph_run, typesetting.tilt, per_glyph_items, x_offset, space_extra);
|
||||
}
|
||||
}
|
||||
}
|
||||
for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
|
||||
path_builder.render_glyph_run(glyph_run, typesetting.letter_tilt, per_glyph_items, x_offset, space_extra);
|
||||
});
|
||||
|
||||
path_builder.finalize()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::text_context::TextContext;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::List;
|
||||
use glam::DVec2;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_EDITOR_LAYER_PATH, ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use vector_types::Vector;
|
||||
|
||||
@@ -16,3 +22,63 @@ pub fn bounding_box(text: &str, font: &Resource, typesetting: TypesettingConfig,
|
||||
pub fn lines_clipping(text: &str, font: &Resource, typesetting: TypesettingConfig) -> bool {
|
||||
TextContext::with_thread_local(|ctx| ctx.lines_clipping(text, font, typesetting))
|
||||
}
|
||||
|
||||
/// Shapes each string item of a styled `List<String>` into vector geometry, reading its font and typesetting
|
||||
/// from the item's attributes (as set by the 'Text' node) and re-applying its transform and blending
|
||||
/// attributes onto the produced paths. With `separate_glyphs`, each glyph becomes its own item.
|
||||
pub fn shape_text_list(strings: &List<String>, separate_glyphs: bool) -> List<Vector> {
|
||||
let mut result = List::new();
|
||||
|
||||
for index in 0..strings.len() {
|
||||
let Some(text) = strings.element(index) else { continue };
|
||||
if text.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Use fallback font when none is explicitly attached.
|
||||
let font: Resource = {
|
||||
let f: Resource = strings.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
if f.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
|
||||
let defaults = TypesettingConfig::default();
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size: strings.attribute_cloned_or(ATTR_FONT_SIZE, index, defaults.font_size),
|
||||
line_height_ratio: strings.attribute_cloned_or(ATTR_LINE_HEIGHT, index, defaults.line_height_ratio),
|
||||
letter_spacing: strings.attribute_cloned_or(ATTR_LETTER_SPACING, index, defaults.letter_spacing),
|
||||
letter_tilt: strings.attribute_cloned_or(ATTR_LETTER_TILT, index, defaults.letter_tilt),
|
||||
max_width: strings.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, index, defaults.max_width),
|
||||
max_height: strings.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, index, defaults.max_height),
|
||||
align: strings.attribute_cloned_or(ATTR_TEXT_ALIGN, index, defaults.align),
|
||||
};
|
||||
|
||||
let vectors = to_path(text, &font, typesetting, separate_glyphs);
|
||||
let transform = strings.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
|
||||
let layer_path = strings.attribute_cloned_or_default::<List<NodeId>>(ATTR_EDITOR_LAYER_PATH, index);
|
||||
let blend_mode = strings.attribute::<BlendMode>(ATTR_BLEND_MODE, index).copied();
|
||||
let opacity = strings.attribute::<f64>(ATTR_OPACITY, index).copied();
|
||||
let opacity_fill = strings.attribute::<f64>(ATTR_OPACITY_FILL, index).copied();
|
||||
|
||||
for mut item in vectors.into_iter() {
|
||||
if transform != DAffine2::IDENTITY {
|
||||
let local = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
item.set_attribute(ATTR_TRANSFORM, transform * local);
|
||||
}
|
||||
if !layer_path.is_empty() {
|
||||
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
}
|
||||
if let Some(blend_mode) = blend_mode {
|
||||
item.set_attribute(ATTR_BLEND_MODE, blend_mode);
|
||||
}
|
||||
if let Some(opacity) = opacity {
|
||||
item.set_attribute(ATTR_OPACITY, opacity);
|
||||
}
|
||||
if let Some(opacity_fill) = opacity_fill {
|
||||
item.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
|
||||
}
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
@@ -17,6 +17,7 @@ async fn transform<T: ApplyTransform + 'n + 'static>(
|
||||
Context -> DAffine2,
|
||||
Context -> DVec2,
|
||||
Context -> List<Graphic>,
|
||||
Context -> List<String>,
|
||||
Context -> List<Vector>,
|
||||
Context -> List<Raster<CPU>>,
|
||||
Context -> List<Raster<GPU>>,
|
||||
|
||||
@@ -259,7 +259,7 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
points: List<Vector>,
|
||||
/// Artwork to be copied and placed at each point.
|
||||
#[expose]
|
||||
#[implementations(List<Graphic>, List<Vector>, List<Raster<CPU>>, List<Color>, List<GradientStops>)]
|
||||
#[implementations(List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Color>, List<GradientStops>)]
|
||||
content: List<I>,
|
||||
/// Minimum range of randomized sizes given to each placed copy.
|
||||
#[default(1)]
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
# Summary
|
||||
|
||||
A document format (`.gdd`) for Graphite that decouples on-disk layout from the editor's in-memory runtime types. The format is a flat node registry plus a tree of operation-based CRDT deltas. The same delta type drives history, undo/redo, concurrent multi-user editing, migrations, and incremental compilation.
|
||||
|
||||
# Motivation
|
||||
|
||||
A delta-based, runtime-independent storage format addresses four problems with the legacy `.graphite` format (bincode/JSON of the editor's runtime structs):
|
||||
|
||||
- **Scattered migrations.** Three coexisting legacy mechanisms — global string replacement on serialized JSON (`document_migration_string_preprocessing`), per-field `#[serde(alias = ...)]` / `deserialize_with` on runtime structs, and post-deserialize fixups (`migrate_path_modify_node`, `migrate_node`) — each requires keeping old runtime shapes alive in the codebase.
|
||||
- **Snapshot undo/redo.** `document_undo_history: VecDeque<NodeNetworkInterface>` clones the whole interface on every gesture.
|
||||
- **No concurrent editing path.** Online multi-user editing and offline merge are blocked by the snapshot model.
|
||||
- **Recompiled-from-scratch graphs.** No diff signal to drive incremental compilation.
|
||||
|
||||
A single delta representation unifies the data needed to fix all four: history step, CRDT op, migration unit, and compilation invalidation signal.
|
||||
|
||||
# Guide-level explanation
|
||||
|
||||
A document is a `Registry` plus a tree of operations applied to it.
|
||||
|
||||
## Registry
|
||||
|
||||
The `Registry` is a **flat** node graph. All nodes from all nested networks live in a single map; each node carries a back-pointer to its network. Networks themselves only store their list of exports. Proto-node declarations are not a separate table — they are content-addressed resources like any other (see [Resources](#resources)), referenced by `ResourceId`.
|
||||
|
||||
```rs
|
||||
pub struct Registry {
|
||||
pub node_instances: HashMap<NodeId, Node>, // all nodes, flat
|
||||
pub networks: HashMap<NetworkId, Network>, // exports + per-network attrs
|
||||
pub exported_nodes: Vec<NodeId>, // library API surface
|
||||
pub peer_users: HashMap<PeerId, UserId>, // per-device → per-human identity
|
||||
pub resources: ResourceStore, // content-addressable resources (images, fonts, declarations)
|
||||
pub attributes: Attributes, // document-level metadata
|
||||
}
|
||||
|
||||
pub struct Node {
|
||||
pub implementation: Implementation, // ProtoNode(ResourceId) or Network(net)
|
||||
pub inputs: Vec<InputSlot>,
|
||||
pub inputs_attributes: Vec<Attributes>,
|
||||
pub attributes: Attributes,
|
||||
pub network: NetworkId,
|
||||
}
|
||||
|
||||
pub struct InputSlot {
|
||||
pub input: NodeInput,
|
||||
pub timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
pub struct Network {
|
||||
pub exports: Vec<ExportSlot>,
|
||||
pub attributes: Attributes, // per-network ui::* (navigation, previewing)
|
||||
}
|
||||
|
||||
pub struct ExportSlot {
|
||||
pub target: Option<NodeInput>, // None = removed/empty
|
||||
pub timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
pub const ROOT_NETWORK: NetworkId = 0;
|
||||
```
|
||||
|
||||
`peer_users` records the append-only `PeerId → UserId` mapping written by each device's first contribution (see [Concurrency model](#concurrency-model--cmrdt)).
|
||||
|
||||
The renderable graph lives in `networks[&ROOT_NETWORK]`. By convention the renderer consumes slot 0 of its exports; the editor can pick a different slot via type-based heuristics or user choice.
|
||||
|
||||
## Two exports concepts
|
||||
|
||||
- **`Network.exports`** — the outputs of a callable network. Used by parent networks and (on `ROOT_NETWORK`) by the renderer. High-frequency edits.
|
||||
- **`Registry.exported_nodes`** — the document's library API: nodes an importing document can reference. A node exposed here may itself be backed by a network via `Implementation::Network`. Library metadata (display name, category, ...) lives as `library::*` attributes on the referenced node. Low-frequency edits.
|
||||
|
||||
Library import (how `.gdd` files reference each other and surface library nodes) is the subject of a follow-up RFC.
|
||||
|
||||
## Attributes — the type-erased metadata bucket
|
||||
|
||||
All metadata that isn't structural — node positions, display names, `call_argument` overrides, visibility, `context_features`, locked/pinned flags, input type hints, reflection metadata — lives in a single `Attributes` bucket per node, per input, and at the document level:
|
||||
|
||||
```rs
|
||||
pub struct Value {
|
||||
pub value: serde_json::Value,
|
||||
pub timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
pub type Attributes = HashMap<String, Value>;
|
||||
```
|
||||
|
||||
Keys are namespaced (`ui::position`, `compute::call_argument`, `library::display_name`, ...). Values are JSON; the per-value `TimeStamp` drives LWW on concurrent edits.
|
||||
|
||||
Type-erasure exists for migrations: storage data can be transformed without keeping old Rust struct shapes alive just to deserialize them.
|
||||
|
||||
## Deltas
|
||||
|
||||
A `RegistryDelta` is one atomic change to the registry, simultaneously a history step, a CRDT op to broadcast to peers, and a recompilation signal:
|
||||
|
||||
```rs
|
||||
pub enum RegistryDelta {
|
||||
AddNode { node_id: NodeId, node: Node },
|
||||
RemoveNode { node_id: NodeId, snapshot: Node },
|
||||
ChangeNodeInput { node_id: NodeId, input_idx: usize, new_input: NodeInput },
|
||||
ChangeNodeAttribute { node_id: NodeId, delta: AttributeDelta },
|
||||
ChangeNodeInputAttribute { node_id: NodeId, input_idx: usize, delta: AttributeDelta },
|
||||
SetExport { network: NetworkId, slot: u32, target: Option<NodeInput> },
|
||||
ChangeNetworkAttribute { network: NetworkId, delta: AttributeDelta }, // per-network ui::nav::*, ...
|
||||
AddNetwork { network: NetworkId, contents: Network },
|
||||
RemoveNetwork { network: NetworkId, snapshot: Network },
|
||||
SetExportedNodes { nodes: Vec<NodeId> },
|
||||
ChangeDocumentAttribute { delta: AttributeDelta },
|
||||
RegisterPeer { peer: PeerId, user: UserId },
|
||||
// Resources (incl. proto-node declarations):
|
||||
SetResourceHash { id: ResourceId, hash: Option<ResourceHash> }, // LWW on the resolved hash
|
||||
AddSource { id: ResourceId, key: SourceKey, source: Value }, // add-wins entry in the source chain
|
||||
RemoveSource { id: ResourceId, key: SourceKey },
|
||||
AddResource { id: ResourceId, entry: ResourceEntry }, // whole-entry; reverse of RemoveResource
|
||||
RemoveResource { id: ResourceId, snapshot: ResourceEntry }, // snapshot for O(1) reverse
|
||||
}
|
||||
|
||||
/// `value: None` is the removal case. Timestamp lives on the wrapping `Delta`.
|
||||
pub struct AttributeDelta {
|
||||
pub key: String,
|
||||
pub value: Option<serde_json::Value>,
|
||||
}
|
||||
```
|
||||
|
||||
Each delta is wrapped with metadata for history, identity, and causality. `Rev` is content-addressed: `blake3` truncated to 128 bits of `(parents, author, timestamp, delta_type)`, so identical content always produces the same `Rev` and concurrent retirements that converge collapse by construction.
|
||||
|
||||
```rs
|
||||
pub type Rev = u128;
|
||||
|
||||
pub struct Delta {
|
||||
pub id: Rev,
|
||||
pub parents: Vec<Rev>, // multi-parent for JJ-style merges
|
||||
pub author: PeerId,
|
||||
pub timestamp: TimeStamp,
|
||||
pub delta_type: RegistryDelta,
|
||||
pub reverse: RegistryDelta, // precomputed for undo; excluded from id
|
||||
pub attributes: Attributes, // mutable local annotations; excluded from id
|
||||
}
|
||||
```
|
||||
|
||||
One timestamp per `Delta` applies to every LWW-eligible write inside its `delta_type` — slot writes, attribute writes, and whole-list writes all read the same `Delta.timestamp`.
|
||||
|
||||
`Delta.attributes` is a type-erased annotation bucket (same shape as the registry's attribute buckets) for mutable, local-only labels — the `compute::gesture_end` marker that bounds undo units, and later commit messages. It is **excluded from `id`** so annotating a delta never changes its content-addressed identity; an inline write sets it before the delta's history frame is persisted, while a later relabel rewrites that frame.
|
||||
|
||||
## History as a tree
|
||||
|
||||
History is a multi-parent DAG. Branching is implicit: every concurrent or out-of-sync edit creates a branch by virtue of sharing a parent with another delta. A user's first commit after observing remote work adds the remote tip as an additional parent, so merges ride on the user's own edit rather than introducing phantom merge commits.
|
||||
|
||||
```
|
||||
D1 ── D2 ── D3 (one user's session)
|
||||
/
|
||||
── root ──
|
||||
\
|
||||
D4 ── D5 (another peer, branched at root)
|
||||
```
|
||||
|
||||
Linear undo is the common case; branching falls out naturally when two peers (or two windows on one machine) edit from the same parent. A history UI lets users navigate this tree to recover from convoluted undo/redo sessions or revisit past exploration. History compression collapses similar consecutive deltas (e.g., three sequential "move shape" ops) into a single coarser delta.
|
||||
|
||||
## Two-tier history: hot ops and retired commits
|
||||
|
||||
History has two tiers:
|
||||
|
||||
- **Hot ops** — speculative, broadcast per-keystroke for live collaboration. Carry only a Lamport timestamp; no parents, no content-addressed `Rev`. Live in `Document.hot_log`, GC'd at retirement, persisted as a sidecar for crash recovery. May pass through non-compiling intermediate states.
|
||||
- **Retired commits** — coarser `Delta`s produced by retirement. Every retired commit compiles in the leader's local view. Content-addressed, multi-parent, durable, browseable, replayable.
|
||||
|
||||
A leader-elected peer periodically retires a window of hot ops into one or more semantically-equivalent retired commits (one per logical `(node, field)` group, not one giant commit per window). Retired commits use a single retirement timestamp for every field they write; the original hot-op timestamps are discarded. Leader election is gossip-based — lowest `PeerId` among peers whose `retirement_tip` matches the session max — and best-effort: there is no quorum, since content-addressed `Rev`s make concurrent retirements that converge dedupe by construction.
|
||||
|
||||
Do/undo pair collapse only happens when both land in the same retirement window, subject to dependency closure (collapse must not orphan a reference to `X`). The undo/redo mechanism itself is described below.
|
||||
|
||||
Solo retirement is the same mechanism with a session of one — history compaction during solo editing falls out for free.
|
||||
|
||||
## Undo/redo
|
||||
|
||||
Undo/redo operate on the delta history rather than full-interface snapshots. A commit's undo behavior depends on whether it has been broadcast to other peers, tracked by `last_broadcast_rev: Option<Rev>` on `Document` (the latest commit shared with at least one peer; `None`, and thus the entire history, during solo editing):
|
||||
|
||||
- **Silent zone** — commits after `last_broadcast_rev`. No other peer has seen them, so they can be rewound in place.
|
||||
- **Published zone** — commits at or before `last_broadcast_rev`. Shared history is never rewound; undoing one is a *new* forward commit applying the inverse with a fresh timestamp, so concurrent peers converge by LWW.
|
||||
|
||||
The silent zone is the implemented path (solo editing has no transport yet); the published-zone forward-undo lands with collaboration.
|
||||
|
||||
**Silent-zone cursor.** `head: Rev` is a movable pointer into the append-only DAG. Undo/redo move it; they never delete deltas (that would make redo impossible and discard branch history). The extra state is a redo stack `Vec<Rev>` — the checkpoints the user has undone past — because the DAG alone can't say which child a `head` was undone *from*. New state persists in `session.json` alongside `head`, so redo survives reopen. A new edit while the redo stack is non-empty clears it (the undone-forward branch stays physically in the DAG but is no longer reachable via redo).
|
||||
|
||||
**Gestures, not deltas.** One user action retires into several deltas (one per `(node, field)` group), so undo steps per *gesture*: the last delta of each gesture is tagged with the `compute::gesture_end` attribute, and undo reverts deltas walking the first-parent chain until the parent is a `gesture_end` boundary or the root. The starting `head` (the checkpoint) is pushed to the redo stack; redo re-applies forward to it.
|
||||
|
||||
**Force-apply.** Rewinding re-applies each delta's precomputed `reverse` (for redo, the forward `delta_type`). These carry the *original* timestamp, which would tie — and so lose — the LWW arms' strict `>` comparison, since the forward op already stamped each field at that timestamp. In the single-writer silent zone the rewind value is authoritative, so silent undo/redo apply in a **force** mode where LWW arms assign unconditionally and structural ops are idempotent. Undo and redo are symmetric (force-reverse, force-forward), so no clock advances and identities are unchanged.
|
||||
|
||||
**Two registries.** Computing a correct `reverse` for an LWW field means reading the field's *pre-op* value. But staged edits apply to the live registry immediately (for responsiveness), so by retirement time it already holds the *post*-op value. `Document` therefore keeps two registries: a **working** registry (committed state plus live un-retired ops, what reads and the cursor see) and a **retired snapshot** (committed deltas only). Retirement computes reverses against and forward-applies to the snapshot, so the reverse captures the true prior value; the working registry already reflects the ops and is left as-is. When there are no un-retired ops the two are equal *by value* (their LWW field timestamps can differ, since retirement re-stamps the snapshot at a fresh time); undo/redo restore that equality by resyncing the snapshot to the rewound working registry.
|
||||
|
||||
## Concurrency model — CmRDT
|
||||
|
||||
The format uses an operation-based CRDT. The transport layer delivers ops in causal order exactly once (TCP plus the multi-parent chain in each `Delta`); the storage layer assumes this and requires only that concurrent op pairs commute. It does not need idempotency, state-merge, or out-of-order replay.
|
||||
|
||||
Graph-shape invariants (the graph remaining a DAG, the result compiling) are best-effort: conflicts that produce a non-compiling graph surface as wiring or type errors rather than being masked by the CRDT.
|
||||
|
||||
Identity is two-tier: `PeerId` is per-device (stable per `(device, document)`, used for CRDT tiebreaking and `NodeId` scoping); `UserId` is per-human (stable across devices, used for identity display and undo-chain walking). Each device's first contribution emits `RegisterPeer { peer, user }`, which writes an append-only entry to `Registry.peer_users`. Causal delivery guarantees the registration arrives before any of that peer's other ops.
|
||||
|
||||
## Editor pipeline
|
||||
|
||||
The editor operates on its existing runtime types. Storage is a serialization layer for persistence, sync, and history:
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Editor (runtime) │
|
||||
│ NodeNetworkInterface │
|
||||
│ ├── NodeNetwork (compute graph) │
|
||||
│ └── NodeNetworkMetadata (editor UI) │
|
||||
└─────────────────────────────────────────┘
|
||||
▲ │
|
||||
│ to_runtime │ from_runtime
|
||||
│ ▼
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Storage layer (graph-storage crate) │
|
||||
│ Registry, RegistryDelta, Document │
|
||||
└─────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────────────┐
|
||||
│ On-disk (.gdd container) │
|
||||
│ named payloads: manifest, document, │
|
||||
│ history, resources/<hash> │
|
||||
│ served by a Container backend │
|
||||
│ (folder, in-memory, OPFS), optionally │
|
||||
│ encoded through an Archive codec │
|
||||
│ (zip, xz) │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The runtime is the source of truth during editing. Conversion runs on save, on load, and across the sync boundary when broadcasting or receiving ops. The editor-facing handle is `Session` (`graph_storage::Session`); `Document` is internal. `Session::stage_from_runtime(&NodeNetwork, &dyn NodeMetadataSource)` is the entry point: it diffs the stored registry against a fresh conversion, ticks the clock once per emitted op, and applies each as a hot op on the hot log. The `Gdd` handle then persists the hot frames and retires them into durable history.
|
||||
|
||||
Staging and retirement are split so one undo gesture maps to one retired gesture. The editor's undo unit is one legacy transaction boundary, but a single user action (e.g. a tool drag) re-commits the runtime many times within one such boundary. So the editor *stages* on every commit (keeping the working registry and autosave current) and *retires the pending hot ops as one gesture* only at the undo-step boundary and before any undo/redo. (`commit_from_runtime` — stage and retire atomically — remains for one-shot callers.) Solo editing thus flows through the same hot-op-then-retire path collaboration uses, exercising it before any transport lands.
|
||||
|
||||
## On-disk container
|
||||
|
||||
A `.gdd` document is a collection of named byte payloads. A `Container` backend (loose folder, in-memory, OPFS in the browser) provides the path-keyed read/write surface; an `Archive` codec (zip, xz-compressed tarball) optionally encodes a container into a single byte stream for compact distribution. The same logical document can be saved as a loose folder for VCS-friendly checkouts or as an archive for shipping, without any change above the container layer.
|
||||
|
||||
The two concerns live in downstream crates: `document-container` defines the `Container` and `AsyncContainer` traits, the backends, byte ownership (mmap regions, owned buffers, external file mmaps via `mmap-io`), and the `Archive` trait. `document-format` defines the typed `Gdd` handle, the layout (logical-payload-name → in-container path), the data codec (JSON or binary), the manifest, and the save/load orchestration. `graph-storage` itself stays disk-unaware.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ editor │
|
||||
└─────────────────────────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌───────────────┐ ┌──────────────────────────────┐
|
||||
│ graph-storage │ │ document-format │
|
||||
│ (disk-unaware)│◀─│ Gdd handle, Layout, codec, │
|
||||
└───────────────┘ │ ExportOptions │
|
||||
└──────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌──────────────────────────────┐
|
||||
│ document-container │
|
||||
│ Container backends + Archive│
|
||||
│ codecs (folder, memory, │
|
||||
│ OPFS / zip, xz) │
|
||||
└──────────────────────────────┘
|
||||
```
|
||||
|
||||
Arrows are "depends on": the editor uses `Session` from `graph-storage` at runtime and `Gdd` from `document-format` on save/load; `document-format` serializes `graph-storage`'s types and delegates byte I/O to `document-container`; `graph-storage` and `document-container` are independent leaves.
|
||||
|
||||
A document contains:
|
||||
|
||||
- `manifest.json` — always JSON, the bootstrap file. Carries the magic identifier `"gdd"`, a single `u32` `format_version`, a stable `document_uuid`, the saving session's `PeerId`, editor and stdlib versions, an optional save timestamp, and a record of which payloads this save included (registry / history / embedded resources).
|
||||
- `document.{json,bin}` — the serialized `Registry`. The codec is fixed per payload and recorded in the manifest (JSON for inspectable, MessagePack for compact; binary must be self-describing — see the codec rationale). Export reuses the working copy's recorded codecs rather than re-encoding.
|
||||
- `history.{jsonl,frames}` — the serialized delta DAG, appended a record at a time. JSON history is line-oriented (one delta per line); binary history is length-prefixed MessagePack frames, the prefix guarding against a torn final frame from a crash.
|
||||
- `resources/<hash>` — embedded resource bytes, keyed by `ResourceHash`.
|
||||
|
||||
The folder backend stores these as plain files on disk; an archive codec packs the same named entries into a single file.
|
||||
|
||||
```
|
||||
my-doc.gdd/
|
||||
├── manifest.json
|
||||
├── document.json
|
||||
├── history.jsonl
|
||||
└── resources/
|
||||
├── 7f3a...
|
||||
└── 2c91...
|
||||
```
|
||||
|
||||
The `Gdd` handle owns the loaded bytes and exposes them as zero-copy slices. On the folder backend, reads are direct mmap references; loading from an archive decompresses once on open into an in-memory backend. The working copy is mutated continuously (autosave); `export(dest, format, options, byte_store)` produces a separate artifact through an `ExportFormat` (`Folder`/`Zip`/`Xz`) without mutating the handle.
|
||||
|
||||
`ExportOptions` controls scope: `include_registry` (skip = rebuild from history on load), `include_history` (skip = state-only snapshot), and `embed_all_resources`. These compose freely except that `include_registry: false && include_history: false` is rejected. The `byte_store` resolves resource bytes the working copy doesn't physically hold (in the editor they live in the app-global cache). `Embedded`-sourced resources are always materialized into the export's `resources/`; `embed_all_resources` additionally promotes link-only resources (`Url`/`FilePath`/`Font`) by prepending an `Embedded` source. That promotion is committed as real `AddSource` deltas on a throwaway session clone so the exported registry and history stay consistent; history is serialized in deterministic topological order, so identical delta sets export byte-identically.
|
||||
|
||||
## Resources
|
||||
|
||||
Everything content-addressable — raster images, fonts, embedded WASM, **and proto-node declarations** — is a resource. The storage `Registry` holds `resources: ResourceStore` (references only); the bytes live in a content-addressed byte store keyed by `ResourceHash`, owned by the caller (the app-global cache in the editor, the `Gdd` container for standalone/export), not by `graph-storage`.
|
||||
|
||||
```rs
|
||||
pub type ResourceStore = HashMap<ResourceId, ResourceEntry>;
|
||||
|
||||
pub struct ResourceEntry {
|
||||
pub sources: Vec<(SourceKey, SourceValue)>, // fallback chain, sorted by key, add-wins OR-set
|
||||
pub hash: Option<ResourceHash>, // resolved content hash (LWW)
|
||||
pub hash_timestamp: TimeStamp,
|
||||
}
|
||||
|
||||
pub struct SourceKey { pub priority: Priority, pub peer: PeerId } // fractional priority + peer tiebreak
|
||||
pub struct SourceValue { pub source: serde_json::Value, pub timestamp: TimeStamp }
|
||||
```
|
||||
|
||||
A node references a resource by `ResourceId`; the entry maps it to a chain of `DataSource`s tried in order (`Embedded` bytes by hash, `FilePath`, `Url`, `Font`) plus the resolved `ResourceHash`. The chain is an **add-wins ordered OR-set**: each entry's `SourceKey` carries a fractional `Priority` so a peer can insert between two sources without renumbering, and concurrent insertions at the same priority converge via the `PeerId` tiebreak. The `hash` is **LWW** (content-derived, so concurrent resolves agree by construction).
|
||||
|
||||
Each `DataSource` is stored as `serde_json::Value` rather than a typed enum, with the same motivation as the `Attributes` bucket: type-erasure lets migrations restructure variants without keeping old enum shapes alive. `DataSource` stays typed at the runtime layer; conversion happens at the serialization boundary. Unknown variants are a hard error on load.
|
||||
|
||||
**Declarations as resources.** `Implementation::ProtoNode(ResourceId)` references a declaration resource. `from_runtime` serializes each `ProtoNode` through a self-describing `serde_json::Value` (MessagePack-encoded, via `encode_declaration`), hashes the bytes, derives the `ResourceId` from that hash (deterministic bootstrap; a future stable well-known-ID table would let the ID denote the function), and registers a `DataSource::Embedded` entry; the bytes go to the caller's byte store. `to_runtime` resolves declarations back via a `Declarations` (`ResourceId → ProtoNode`) map the caller builds from its byte store. The self-describing form keeps `ProtoNode`'s serde aliases working so the on-disk shape stays migratable.
|
||||
|
||||
A `NodeInput::Value` stores its `TaggedValue` as a self-describing `serde_json::Value` (the same type-erasure as `Attributes`/`DataSource`), so the `TaggedValue` serde aliases keep working and the on-disk shape stays migratable. Legacy documents with inline image `TaggedValue`s have those values extracted into resources at load time; new saves never embed inline image blobs in `NodeInput::Value`.
|
||||
|
||||
## Migrations
|
||||
|
||||
Migrations run on the type-erased `Registry`, after deserialization and before `to_runtime`. The pipeline reads the format version from the manifest, deserializes the registry with attributes as raw `serde_json::Value`, applies registered migrations scoped to the version range, and hands the result to `to_runtime`.
|
||||
|
||||
Migrations live in a dedicated crate so they are usable both from the editor and from a CLI for batch upgrades. A single global format version is used initially; per-library versioning is a future extension.
|
||||
|
||||
# Reference-level explanation
|
||||
|
||||
## Conversion: runtime ↔ storage
|
||||
|
||||
`from_runtime` flattens the recursive `NodeNetwork` into the flat `Registry`:
|
||||
|
||||
- Each node's path through the runtime nesting is hashed (blake3 truncated to 64 bits, with the document's `PeerId` mixed in) to produce a stable global `NodeId`. The original local ID is stashed in an attribute (`compute::original_node_id`) so the round-trip can rebuild the runtime's per-network local IDs. Subsequent live edits mint fresh peer-scoped IDs via `Document::next_node_id` (`blake3(peer, counter)`) instead of going through the path-hash bootstrap.
|
||||
- Each nested `NodeNetwork`'s `NetworkId` is derived from the owning node's path (blake3 of `(peer, path)` with a `"network"` domain tag), not assigned by a traversal counter. This makes it stable across a `to_runtime` → `from_runtime` round trip — load-bearing because node paths (and thus node-ID hashes) include `NetworkId`s, so an unstable network ID would cascade into unstable node IDs and break re-commit after open. Aliasing (multiple nodes referencing the same network) is structurally supported by the storage model — `Implementation::Network(NetworkId)` is a reference — but the converter does not exploit it yet. Aliasing is fixed at the runtime layer first; the converter then preserves sharing without an explicit dedup pass.
|
||||
- Non-structural `DocumentNode` fields (`call_argument`, `context_features`, `visible`, `skip_deduplication`, ...) become entries in the node's `attributes`. UI metadata from `DocumentNodeMetadata` (positions, display names, locked, pinned, ...) flows through the same bucket under `ui::*` keys.
|
||||
|
||||
`to_runtime` is the inverse: rebuild local IDs from the stashed attribute, restore typed fields from attribute values, follow `Implementation::Network` references to recursively materialize nested networks, and resolve `Implementation::ProtoNode(ResourceId)` against a `Declarations` map (`ResourceId → ProtoNode`) the caller supplies from its byte store. Since `graph-storage` is byte-unaware, `to_runtime` takes the resolved declarations as a parameter rather than reaching for bytes itself.
|
||||
|
||||
## Slots — inputs and exports
|
||||
|
||||
`Vec<InputSlot>` and `Vec<ExportSlot>` are positionally indexed at the storage layer. Each slot carries its own `TimeStamp`, giving LWW per slot on concurrent edits.
|
||||
|
||||
`ExportSlot` is sparse: `target == None` means the slot has been removed. `InputSlot` is dense. The runtime conversion compacts exports into a dense `Vec<NodeInput>` (preserving the runtime's "remove an export shifts later positions" semantics) and strips input timestamps.
|
||||
|
||||
Because inputs are stamped, `NodeInput::Node` references are set directly via `ChangeNodeInput` — there is no add/remove rewire workaround.
|
||||
|
||||
## CmRDT semantics
|
||||
|
||||
- **Timestamps.** `TimeStamp = (u64, PeerId)` — a Lamport counter with a peer-ID tiebreak. Comparison is lexicographic. Wall-clock time is not used.
|
||||
- **NodeId identity.** Every new `AddNode` issues a peer-scoped ID, so concurrent creates cannot collide.
|
||||
- **Causal delivery.** `apply_delta` requires every entry in `delta.parents` is already in local history. The storage layer does not buffer; out-of-order delivery is a transport concern. New peers initialize via snapshot transfer (`Registry` + history) before streaming deltas.
|
||||
- **Removal.** Physical, no tombstones. If a later op targets an absent node or network, the receiver replays the most recent `AddNode` / network creation from history before applying. `RemoveNode` and `RemoveNetwork` each carry a `snapshot` of the removed entity so their reverse can rebuild in O(1) without re-walking history — required because retirement recomputes an op's reverse *after* the hot op already applied the removal, when the live entity is gone. Removal is therefore non-durable under concurrent edits: any concurrent reference to a removed node revives it.
|
||||
- **LWW primitives.** Per-input (`InputSlot.timestamp`), per-export-slot (`ExportSlot.timestamp`), per-attribute-value (the `TimeStamp` in `Attributes`), and whole-list for `SetExportedNodes` via a sidecar timestamp in `Registry.attributes` under `library::exported_nodes_ts`. The timestamp driving every LWW arm comes from the wrapping `Delta`; `AttributeDelta` carries `value: Option<_>` so a single shape covers both `Set` (`Some`) and `Remove` (`None`) and `Set` vs. `Remove` has a defined winner.
|
||||
- **Resources.** A resource's `hash` is LWW (content-derived, so concurrent resolves agree). Its source chain is an add-wins ordered OR-set keyed by `SourceKey` (fractional priority + peer tiebreak): concurrent `AddSource`s at distinct keys all survive; a re-add at the same key is LWW. Whole-resource `AddResource`/`RemoveResource` mirror the node/network add-remove pairs (`RemoveResource` snapshots the entry for O(1) reverse).
|
||||
|
||||
The CRDT does not mask graph-shape conflicts. Concurrent same-slot `SetExport`s with different targets resolve by LWW, but the resulting wiring may be wrong; downstream consumers see it as a compile or wiring error.
|
||||
|
||||
## History storage
|
||||
|
||||
`HashMap<Rev, Delta>` plus a `head: Rev` (the local cursor; advances only on local commits) and a `hot_log: Vec<HotOp>` (in-flight unretired ops). Walking history follows `delta.parents`; the default walk follows the first parent to reconstruct a single peer's local chain. Branches are siblings under a shared parent; merges aren't modeled as nodes — they're implicit in a delta listing multiple parents.
|
||||
|
||||
## Editor metadata
|
||||
|
||||
`DocumentNodePersistentMetadata` and `NodeNetworkPersistentMetadata` from the runtime — display names, locked/pinned, navigation/PTZ state, selection undo/redo stacks, layer/node type metadata — flow through the storage `Attributes` bucket under `ui::*` keys. Transient runtime caches (`DocumentNodeTransientMetadata`, click targets, resolved types, `OriginalLocation`) stay runtime-only and are not stored.
|
||||
|
||||
Document-scoped editor settings (viewport view, render mode, overlay/ruler visibility, snapping, collapsed layers) ride the document-level `Registry.attributes` under `ui::doc::*` keys, supplied through `NodeMetadataSource::document_attributes`. This is what makes the `.gdd` a lossless replacement for the legacy format's document-handler fields.
|
||||
|
||||
# Drawbacks
|
||||
|
||||
- **Diffing two full `Registry`s on every autosave is O(N) in document size.** The interim cost of treating storage as a serialization layer derived from the runtime; currently triggered at autosave boundaries (`commit_storage_snapshot`) rather than per gesture, and addressed long-term by computing deltas directly on runtime mutations.
|
||||
- **Attributes as `serde_json::Value` carry per-value overhead.** Mitigable with a typed fast path for hot keys without changing the design. They also force a self-describing codec, ruling out the most compact binary formats.
|
||||
- **Single global format version is a sharp edge** when libraries diverge: a breaking change in one library bumps the version for documents that don't use it.
|
||||
- **`RemoveNode` is non-durable under concurrency.** Any concurrent reference to a removed node revives it from history.
|
||||
|
||||
# Rationale and alternatives
|
||||
|
||||
**Delta-based vs. cleaner snapshot format.** A delta is the right unit for history, CRDT sync, and incremental compilation. Picking one representation for all three eliminates conversion seams between subsystems that need to interoperate.
|
||||
|
||||
**CmRDT vs. state-based CRDT or OT.** State-based CRDTs require a merge function and large state vectors. OT requires a central server to mediate transforms. CmRDT only requires per-op commutativity plus a causal-order delivery layer, which the transport provides.
|
||||
|
||||
**Ad-hoc resurrection vs. tombstones.** Tombstones add a permanent footprint to the data model and a GC policy question. Resurrection reuses the history log already needed for undo as the recovery mechanism, keeping the live `Registry` lean. The cost is that `RemoveNode` is not durable under concurrent edits.
|
||||
|
||||
**Type-erased attributes vs. typed metadata fields.** Migrations operate on attribute values without keeping old Rust struct shapes alive. The cost is per-value overhead, mitigable without changing the model.
|
||||
|
||||
**Flat node storage vs. nested networks.** All CRDT ops target nodes via a single uniform `NodeId` address space regardless of nesting depth. A nested representation would require ops to carry a path, complicating commutativity.
|
||||
|
||||
**`.gdd` vs. reusing `.graphite`.** A distinct extension makes migration unambiguous and prevents older Graphite versions from trying to open a new-format file.
|
||||
|
||||
**One self-describing binary codec (MessagePack).** Every persisted body — deltas, the registry, node-input values, and `ProtoNode` declarations — is a type-erased `serde_json::Value`, so it needs a self-describing codec to deserialize and to keep the serde-alias migration path alive; MessagePack provides that at a few percent size cost. Hash preimages (`NodeId`, `Rev`, node-path hashes) use the same codec: a fixed serializer emits one deterministic byte form per value, which is all `blake3` needs, so the codec doubles as the canonical hash encoding without a second format.
|
||||
|
||||
**Source chain as a sorted `Vec` vs. `BTreeMap`.** `SourceKey` is a struct, so a `BTreeMap`-keyed chain can't serialize to JSON (string keys only). A sorted `Vec` of pairs keeps the same ordering and add-wins semantics losslessly across every codec.
|
||||
|
||||
# Future possibilities
|
||||
|
||||
- **Per-library format versioning** so a breaking change in one library doesn't bump the version for documents that don't use it.
|
||||
- **History linearization** — prune unused branches from a convoluted tree to produce a clean undo/redo history.
|
||||
- **Runtime-native deltas.** Move delta computation out of the storage layer into the runtime, eliminating per-edit `Registry` re-conversion.
|
||||
- **Incremental compilation driven by deltas.** The compiler consumes runtime deltas and recompiles only changed regions.
|
||||
- **Runtime-level aliasing for shared node-network definitions.** Storage already supports `Implementation::Network` as a reference; once the runtime supports sharing natively, the converter preserves it.
|
||||
- **Online migration service** — active editors drop migrations older than some threshold; old documents go through a remote upgrade pipeline first.
|
||||
- **Distributed / signed history.** Content-addressed `Rev` plus signing enables multi-author provenance and verifiable history.
|
||||
- **Libraries as files** — a follow-up RFC will specify how `.gdd` files act as importable libraries via `Registry.exported_nodes`.
|
||||
Reference in new issue
Block a user