mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
96a8e72fcf | ||
|
|
21910d242f | ||
|
|
c22fb0ec3a | ||
|
|
312dc1529b | ||
|
|
ccc32d6104 | ||
|
|
ba4b4812e7 | ||
|
|
1642bf38ce | ||
|
|
6684bd279f | ||
|
|
181c8e461c | ||
|
|
2e57be5aa1 | ||
|
|
7d6718dc67 | ||
|
|
49ecb3e695 | ||
|
|
73aeeee4d6 | ||
|
|
5cfe68dd32 | ||
|
|
db32addcb0 | ||
|
|
045cdfd5ee | ||
|
|
1d6b93a6d1 | ||
|
|
baced334ec | ||
|
|
4c4e0ba39b | ||
|
|
fbbae5876b | ||
|
|
fba33376bc | ||
|
|
a8104cf230 | ||
|
|
778e979c41 | ||
|
|
5ee999b847 | ||
|
|
9044a9c09a | ||
|
|
a1ff88ae30 | ||
|
|
d96f03fe90 | ||
|
|
708cca339d | ||
|
|
6e9208c004 | ||
|
|
412979278e | ||
|
|
7f7262c3cd | ||
|
|
8206b4cc88 | ||
|
|
b05af55d50 | ||
|
|
39b8d23a34 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/4e42efe8dbf2ae2d82e12123aa9c103d5740a465.tar.gz
|
||||
6b7883a26952c77aad56758a11207761c2fcd1b61bf6dd5996c3cf9d4eb1cb5e
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/70b260c21afad29140bbc63ddab952fec3dd024c.tar.gz
|
||||
5b05e7f4449b5f962755542e9b156891bbf2e0a87b7fc90798b8352d9225757d
|
||||
@@ -174,23 +174,12 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
run: cargo test --all-features
|
||||
|
||||
# The plain `cargo test` above only covers the workspace's default members, which leave these out
|
||||
- name: 🧪 Run document migration tests
|
||||
env:
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
||||
run: >-
|
||||
cargo test --all-features
|
||||
--package migration-core
|
||||
--package migration-runner
|
||||
--package migration-formats
|
||||
--package migration-nodes
|
||||
--package migration-snapshot
|
||||
--package document-graph-storage
|
||||
--package document-format
|
||||
--package graphene-cli
|
||||
--package regression
|
||||
cargo test --workspace --all-features
|
||||
--exclude 'graphite-desktop*'
|
||||
--exclude third-party-licenses
|
||||
&& cargo test --package third-party-licenses
|
||||
|
||||
# Render the documents of the regression corpus and compare them with their reference images
|
||||
regression-corpus:
|
||||
|
||||
Generated
+7
-5
@@ -2942,6 +2942,7 @@ dependencies = [
|
||||
"ash",
|
||||
"bytemuck",
|
||||
"cef",
|
||||
"dirs",
|
||||
"graphite-desktop-embedded-resources",
|
||||
"ipc-channel",
|
||||
"libc",
|
||||
@@ -2967,7 +2968,6 @@ name = "graphite-desktop-wrapper"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs",
|
||||
"graph-craft",
|
||||
"graphite-editor",
|
||||
"graphite-wasm-wrapper",
|
||||
@@ -5853,6 +5853,7 @@ dependencies = [
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7691,9 +7692,9 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsify"
|
||||
version = "0.5.5"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b2ec91b85e6c6592ed28636cb1dd1fac377ecbbeb170ff1d79f97aac5e38926d"
|
||||
checksum = "ea3af6b48c5c5624f7eb3c2f578d1335fadac433321980cae0063e8eb0acaa44"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde-wasm-bindgen",
|
||||
@@ -7703,9 +7704,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsify-macros"
|
||||
version = "0.5.6"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9fc2c44dc9fe4baf55b88e032621b7a11b215a1f0a7de8d0aa04367207d915bc"
|
||||
checksum = "ef1e2e93369379d0a527c7d6632b58c55d52db7a106d8afbde3b354f3a57a9f1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -8736,6 +8737,7 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
|
||||
@@ -45,11 +45,3 @@ pub(crate) fn app_resources_dir() -> PathBuf {
|
||||
ensure_dir_exists(&path);
|
||||
path
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
pub(crate) fn delete_old_cef_browser_directory() {
|
||||
let old_browser_dir = crate::dirs::app_data_dir().join("browser");
|
||||
if old_browser_dir.is_dir() {
|
||||
let _ = std::fs::remove_dir_all(&old_browser_dir);
|
||||
}
|
||||
}
|
||||
@@ -74,9 +74,6 @@ pub fn start() -> ExitCode {
|
||||
|
||||
dirs::clear_dir(&ui::temp_dir_root());
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
// Must be called before event loop initialization or native window integrations will break
|
||||
App::init();
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ wgpu-sync = { workspace = true }
|
||||
winit = { workspace = true, features = ["serde"] }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
rand = { workspace = true, features = ["thread_rng"] }
|
||||
|
||||
@@ -8,7 +8,7 @@ const APP_DIRECTORY_NAME: &str = "graphite";
|
||||
const APP_DIRECTORY_NAME: &str = "Graphite";
|
||||
|
||||
pub(crate) fn app_tmp_dir() -> PathBuf {
|
||||
let path = std::env::temp_dir().join(APP_DIRECTORY_NAME);
|
||||
let path = dirs::cache_dir().unwrap_or_else(std::env::temp_dir).join(APP_DIRECTORY_NAME).join("ui");
|
||||
if let Err(e) = fs::create_dir_all(&path) {
|
||||
tracing::error!("Failed to create temp directory at {path:?}: {e}");
|
||||
}
|
||||
|
||||
@@ -48,6 +48,10 @@ impl ImplApp for BrowserProcessAppImpl {
|
||||
cmd.append_switch(Some(&"disable-default-apps".into()));
|
||||
cmd.append_switch(Some(&"disable-breakpad".into()));
|
||||
cmd.append_switch_with_value(Some(&"disable-blink-features".into()), Some(&"WebBluetooth,WebUSB,Serial".into()));
|
||||
cmd.append_switch_with_value(
|
||||
Some(&"host-resolver-rules".into()),
|
||||
Some(&"MAP * ~NOTFOUND, EXCLUDE fonts.googleapis.com, EXCLUDE fonts.gstatic.com".into()),
|
||||
);
|
||||
|
||||
let extra_disabled_features = ["OptimizationHints", "OnDeviceModelService", "TranslateUI"];
|
||||
let disabled_features_switch = Some(&"disable-features".into());
|
||||
|
||||
@@ -27,7 +27,6 @@ wgpu-executor = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -181,6 +181,19 @@ impl<L: Layout> Gdd<L> {
|
||||
}
|
||||
export_session.embed_resource_sources(links_to_promote)?;
|
||||
|
||||
// If the export includes history, also embed every resource referenced by the history.
|
||||
if options.include_history {
|
||||
let current: std::collections::HashSet<ResourceHash> = export_session.registry().resources.values().filter_map(|entry| entry.hash).collect();
|
||||
for hash in export_session.all_referenced_resource_hashes() {
|
||||
if current.contains(&hash) || working_copy_hashes.contains(&hash) {
|
||||
continue;
|
||||
}
|
||||
if let Some(resource) = byte_store.load(hash).await {
|
||||
embedded_bytes.push((hash, resource));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Carry the per-peer cursor + view settings so a `.gdd` reopened elsewhere restores the viewport.
|
||||
let mut session_state = self.exported_session_state(&export_session);
|
||||
|
||||
|
||||
@@ -111,6 +111,9 @@ pub struct Gdd<L: Layout = GddV1Layout> {
|
||||
/// What peers changed since [`take_remote_changes`](Self::take_remote_changes) last took it.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) remote_changes: network::RemoteChanges,
|
||||
/// The step a guest asked the host to undo, with the head it asked under. A repeat waits until the head moves.
|
||||
#[cfg(feature = "network")]
|
||||
pub(crate) undo_requested: Option<(document_graph_storage::Rev, Option<document_graph_storage::Rev>)>,
|
||||
pub(crate) interactions_seen: std::collections::HashMap<document_graph_storage::HotOpId, f64>,
|
||||
pub(crate) own_last_staged_ms: Option<f64>,
|
||||
pub(crate) own_staged_since_tick: bool,
|
||||
@@ -175,6 +178,8 @@ impl<L: Layout> Gdd<L> {
|
||||
pending_persist: PendingPersist::default(),
|
||||
#[cfg(feature = "network")]
|
||||
remote_changes: network::RemoteChanges::default(),
|
||||
#[cfg(feature = "network")]
|
||||
undo_requested: None,
|
||||
interactions_seen: Default::default(),
|
||||
own_last_staged_ms: None,
|
||||
own_staged_since_tick: false,
|
||||
@@ -232,16 +237,16 @@ impl<L: Layout> Gdd<L> {
|
||||
Self::open_in_with(working, layout, byte_store, host).await
|
||||
}
|
||||
|
||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
|
||||
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
/// Reads the manifest without opening the copy, which may be another writer's.
|
||||
pub async fn read_manifest(working: &AnyContainer, layout: &L) -> Result<Manifest, Error> {
|
||||
Ok(io::read_single(working, layout.manifest_basename(), MANIFEST_CODEC).await?)
|
||||
}
|
||||
|
||||
/// Backend-agnostic open. Splits out so tests can supply a [`document_container::backends::memory::MemoryBackend`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::MissingManifest`] if the container holds no manifest, [`Error::WrongFormat`] / [`Error::UnsupportedVersion`]
|
||||
/// if it fails validation, plus the usual [`Error::Read`] / [`Error::Codec`] / [`Error::Crdt`] if a payload is malformed.
|
||||
pub async fn open_in(working: AnyContainer, layout: L) -> Result<Self, Error> {
|
||||
Self::open_stored(working, layout, MigrationInputs::default()).await
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ impl<L: Layout> Gdd<L> {
|
||||
/// Drop the connection but keep the document shared, so a reopen reconnects. A host first retires every closed
|
||||
/// interaction with no ops still on their way.
|
||||
pub fn disconnect(&mut self) {
|
||||
self.undo_requested = None;
|
||||
let closed = self.contiguous_interactions();
|
||||
if let Err(error) = self.retire_interactions(&closed) {
|
||||
log::error!("Retiring before leaving failed: {error}");
|
||||
|
||||
@@ -427,7 +427,13 @@ impl<L: Layout> Gdd<L> {
|
||||
let Some(rev) = self.session.latest_own_interaction() else {
|
||||
return Ok(None);
|
||||
};
|
||||
// A peer promoted to host drops the step itself, so an unanswered request no longer blocks it
|
||||
let asked = (!self.retires_locally()).then_some((rev, self.session.head_rev()));
|
||||
if asked.is_some() && self.undo_requested == asked {
|
||||
return Ok(None);
|
||||
}
|
||||
self.drop_step(rev)?;
|
||||
self.undo_requested = asked;
|
||||
Ok(Some(rev))
|
||||
}
|
||||
|
||||
@@ -452,23 +458,6 @@ impl<L: Layout> Gdd<L> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Move the head back to an ancestor, keeping the later line as a branch. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn move_head(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
if self.retires_locally() {
|
||||
let (moved, touched) = self.session.move_head_to(rev)?;
|
||||
self.remote_changes.touched.extend(touched);
|
||||
self.persist_registry_snapshot()?;
|
||||
self.persist_session_state()?;
|
||||
if let Some(replica) = &mut self.network {
|
||||
replica.broadcast_head_move(moved)?;
|
||||
}
|
||||
} else if let Some(replica) = &mut self.network {
|
||||
replica.request_move(rev)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Redo a dropped step as a copy on top of the line. A non-retiring peer asks the retirer.
|
||||
#[cfg(feature = "network")]
|
||||
pub fn redo_retired_step(&mut self, rev: Rev) -> Result<(), Error> {
|
||||
|
||||
@@ -137,12 +137,6 @@ impl<L: Layout + Send + Sync> LoadResource for Gdd<L> {
|
||||
|
||||
pub struct ResourceProxy<T: Layout>(AnyContainer, T);
|
||||
|
||||
impl<T: Layout + Clone> Clone for ResourceProxy<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone(), self.1.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl<L: Layout + Send + Sync> LoadResource for ResourceProxy<L> {
|
||||
fn load(&self, hash: ResourceHash) -> ResourceFuture<'_> {
|
||||
Box::pin(async move {
|
||||
|
||||
@@ -538,6 +538,46 @@ fn export_materializes_embedded_resource_from_byte_store() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An export with history carries the bytes of a resource only history still names, so undoing its removal
|
||||
/// after a reopen finds them, even when they live in the byte store rather than the working copy.
|
||||
#[test]
|
||||
fn export_with_history_carries_history_only_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::NoMetadata;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
|
||||
let payload = b"bytes of a removed resource";
|
||||
let hash = ResourceHash::from(&payload[..]);
|
||||
let byte_store = empty_byte_store();
|
||||
byte_store.store(payload);
|
||||
|
||||
let mut resources = ResourceRegistry::new();
|
||||
let id = ResourceId::new();
|
||||
resources.push_source_back(&id, DataSource::Embedded);
|
||||
resources.resolve(&id, hash);
|
||||
gdd.commit_from_runtime(&network_referencing_resource(id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
gdd.commit_from_runtime(&graph_craft::document::NodeNetwork::default(), &NoMetadata, &ResourceRegistry::new(), &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
assert!(!gdd.registry().resources.contains_key(&id), "the resource should only be named by history");
|
||||
assert!(!gdd.has_resource(&hash).await, "bytes should not be in the working copy");
|
||||
|
||||
let archive = gdd
|
||||
.export_to_bytes(ExportFormat::Zip, ExportOptions::default(), &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&hash).await, "history-only bytes should travel with the export");
|
||||
});
|
||||
}
|
||||
|
||||
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
|
||||
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
|
||||
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout, ResourceProxy};
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
@@ -10,7 +10,7 @@ use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
pub use document_graph_storage::to_runtime::ConversionError;
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, Role, SessionToken};
|
||||
pub use peer_transport::{DEFAULT_SIGNALING_SERVER, Event, MessageLoopFuture, SessionToken};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LiveError {
|
||||
@@ -58,10 +58,6 @@ impl LiveDocument {
|
||||
self.token
|
||||
}
|
||||
|
||||
pub fn role(&self) -> Option<Role> {
|
||||
self.gdd.role()
|
||||
}
|
||||
|
||||
pub fn is_synced(&self) -> bool {
|
||||
self.gdd.is_synced()
|
||||
}
|
||||
@@ -101,17 +97,12 @@ impl LiveDocument {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
/// Async because proto-node declarations are resources.
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations)?;
|
||||
Ok(network)
|
||||
}
|
||||
|
||||
pub fn resource_proxy(&self) -> ResourceProxy<GddV1Layout> {
|
||||
self.gdd.resource_proxy()
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
self.gdd.leave();
|
||||
}
|
||||
|
||||
@@ -2,4 +2,10 @@
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
|
||||
/// The scope input of nodes that came to take the GPU pipeline, the identifier frozen as it was when they did.
|
||||
fn raster_kernel_pipeline() -> migration_core::NodeInput {
|
||||
migration_core::NodeInput::Scope("raster_nodes::raster_kernel::RasterKernelPipelineNode".into())
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
use migration_core::{Node, Target, decl, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const EXPRESSION: usize = 1;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration reads.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
String(String),
|
||||
}
|
||||
|
||||
/// The lone operators 'Math f(…)' applied across its items, in every spelling its classifier read when the node was split.
|
||||
const OPERATORS: &[&str] = &["+", "-", "*", "/", "^", "&&", "∧", "||", "∨", "<", "<=", "≤", ">", ">=", "≥", "==", "!=", "≠"];
|
||||
|
||||
/// The variadic functions 'Math f(…)' called with all its items when given a lone name, also spelled with a leading `\`.
|
||||
const FUNCTIONS: &[&str] = &[
|
||||
"hypot",
|
||||
"min",
|
||||
"max",
|
||||
"mean",
|
||||
"median",
|
||||
"variance",
|
||||
"variancepop",
|
||||
"stdev",
|
||||
"stdevpop",
|
||||
"geomean",
|
||||
"harmmean",
|
||||
"rms",
|
||||
"mode",
|
||||
"count",
|
||||
"xor",
|
||||
"gcd",
|
||||
"lcm",
|
||||
];
|
||||
|
||||
/// 'Math f(…)' split by the kind of string it held: a lone operator or function name, which it applied across its items, moves to
|
||||
/// 'Math Aggregate', and an expression stays as 'Math Formula'. A wired string can't be read before it runs, so it stays an expression.
|
||||
#[migration("math_nodes::MathFNode"@1 => "math_nodes::MathFormulaNode"@2)]
|
||||
pub fn math_formula_from_math_f(node: &Node, target: &mut Target) {
|
||||
let Some(slot) = node.inputs().get(EXPRESSION) else { return };
|
||||
let Some(Tagged::String(expression)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||
|
||||
let token = expression.trim();
|
||||
let function = token.strip_prefix('\\').unwrap_or(token);
|
||||
if OPERATORS.contains(&token) || FUNCTIONS.contains(&function) {
|
||||
target.set(decl!("math_nodes::MathAggregateNode"@1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{Declaration, NodeInput, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const MATH_F: Declaration = decl!("math_nodes::MathFNode"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
// Only the items can read another 'Math f(…)', since the expression and output type don't take its number
|
||||
SourceContract {
|
||||
reads_own_output: |slot| slot == 0,
|
||||
..SourceContract::new(3, |random, slot| match slot {
|
||||
EXPRESSION => literal(Tagged::String(["+", "a * b", "\\max", " ≤ ", "min(a, b)"][random.below(5)].to_string())),
|
||||
_ => literal(random.below(4) as f64),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn migrated_declaration(expression: NodeInput) -> Option<Declaration> {
|
||||
let mut fixture = Fixture::new(&MathFormulaFromMathF);
|
||||
let anchor = fixture.add(MATH_F, vec![literal(1.), expression, literal(0.)]);
|
||||
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
|
||||
fixture.declaration_of(&migrated, anchor)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MathFormulaFromMathF, &contract());
|
||||
check_undo(&MathFormulaFromMathF, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lone_operators_and_functions_become_aggregates() {
|
||||
let aggregate = Some(decl!("math_nodes::MathAggregateNode"@1));
|
||||
let formula = Some(decl!("math_nodes::MathFormulaNode"@2));
|
||||
let expression = |text: &str| literal(Tagged::String(text.to_string()));
|
||||
|
||||
assert_eq!(migrated_declaration(expression("+")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression(" ≠ ")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("max")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("\\mean")), aggregate);
|
||||
assert_eq!(migrated_declaration(expression("a + b")), formula);
|
||||
assert_eq!(migrated_declaration(expression("max(a, b)")), formula);
|
||||
assert_eq!(migrated_declaration(expression("")), formula);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_expression_becomes_a_formula() {
|
||||
let mut fixture = Fixture::new(&MathFormulaFromMathF);
|
||||
let source = fixture.add(MATH_F, vec![literal(1.), literal(Tagged::String("+".to_string())), literal(0.)]);
|
||||
let anchor = fixture.add(MATH_F, vec![literal(1.), NodeInput::Node { id: source, index: 0 }, literal(0.)]);
|
||||
let migrated = fixture.migrate(&MathFormulaFromMathF).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, anchor), Some(decl!("math_nodes::MathFormulaNode"@2)));
|
||||
assert_eq!(fixture.declaration_of(&migrated, source), Some(decl!("math_nodes::MathAggregateNode"@1)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("math_nodes::MathFxNode"@1 => "math_nodes::MathFunctionNode"@2);
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::BlackAndWhiteNode"@1 => @2)]
|
||||
pub fn black_and_white_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlackAndWhiteV1, &contract());
|
||||
check_undo(&BlackAndWhiteV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::filter::BlurNode"@1 => @2)]
|
||||
pub fn blur_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlurV1, &contract());
|
||||
check_undo(&BlurV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::BrightnessContrastNode"@1 => @2)]
|
||||
pub fn brightness_contrast_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BrightnessContrastV1, &contract());
|
||||
check_undo(&BrightnessContrastV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::ChannelMixerNode"@1 => @2)]
|
||||
pub fn channel_mixer_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(19, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ChannelMixerV1, &contract());
|
||||
check_undo(&ChannelMixerV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::std_nodes::ChannelsToImageNode"@1 => @2)]
|
||||
pub fn channels_to_image_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ChannelsToImageV1, &contract());
|
||||
check_undo(&ChannelsToImageV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::ColorBalanceNode"@1 => @2)]
|
||||
pub fn color_balance_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(12, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ColorBalanceV1, &contract());
|
||||
check_undo(&ColorBalanceV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::ColorLookupNode"@1 => @2)]
|
||||
pub fn color_lookup_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ColorLookupV1, &contract());
|
||||
check_undo(&ColorLookupV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => @2)]
|
||||
pub fn color_overlay_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ColorOverlayV1, &contract());
|
||||
check_undo(&ColorOverlayV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::CurvesNode"@1 => @2)]
|
||||
pub fn curves_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(7, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&CurvesV1, &contract());
|
||||
check_undo(&CurvesV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::dehaze::DehazeNode"@1 => @2)]
|
||||
pub fn dehaze_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DehazeV1, &contract());
|
||||
check_undo(&DehazeV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::DesaturateNode"@1 => @2)]
|
||||
pub fn desaturate_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&DesaturateV1, &contract());
|
||||
check_undo(&DesaturateV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::ExposureNode"@1 => @2)]
|
||||
pub fn exposure_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ExposureV1, &contract());
|
||||
check_undo(&ExposureV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => @2)]
|
||||
pub fn extend_image_to_bounds_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ExtendImageToBoundsV1, &contract());
|
||||
check_undo(&ExtendImageToBoundsV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::GammaCorrectionNode"@1 => @2)]
|
||||
pub fn gamma_correction_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GammaCorrectionV1, &contract());
|
||||
check_undo(&GammaCorrectionV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::GradientMapNode"@1 => @2)]
|
||||
pub fn gradient_map_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GradientMapV1, &contract());
|
||||
check_undo(&GradientMapV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::HueSaturationNode"@1 => @2)]
|
||||
pub fn hue_saturation_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(51, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&HueSaturationV1, &contract());
|
||||
check_undo(&HueSaturationV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::image_color_palette::ImageColorPaletteNode"@1 => @2)]
|
||||
pub fn image_color_palette_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ImageColorPaletteV1, &contract());
|
||||
check_undo(&ImageColorPaletteV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::InvertNode"@1 => @2)]
|
||||
pub fn invert_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InvertV1, &contract());
|
||||
check_undo(&InvertV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::LevelsNode"@1 => @2)]
|
||||
pub fn levels_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(27, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&LevelsV1, &contract());
|
||||
check_undo(&LevelsV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
|
||||
pub fn make_opaque_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MakeOpaqueV1, &contract());
|
||||
check_undo(&MakeOpaqueV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::std_nodes::MaskNode"@1 => @2)]
|
||||
pub fn mask_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MaskV1, &contract());
|
||||
check_undo(&MaskV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::filter::MedianFilterNode"@1 => @2)]
|
||||
pub fn median_filter_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MedianFilterV1, &contract());
|
||||
check_undo(&MedianFilterV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,31 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod black_and_white_v1;
|
||||
mod blur_v1;
|
||||
mod brightness_contrast_v1;
|
||||
mod channel_mixer_v1;
|
||||
mod channels_to_image_v1;
|
||||
mod color_balance_v1;
|
||||
mod color_lookup_v1;
|
||||
mod color_overlay_v1;
|
||||
mod curves_v1;
|
||||
mod dehaze_v1;
|
||||
mod desaturate_v1;
|
||||
mod exposure_v1;
|
||||
mod extend_image_to_bounds_v1;
|
||||
mod gamma_correction_v1;
|
||||
mod gradient_map_v1;
|
||||
mod hue_saturation_v1;
|
||||
mod image_color_palette_v1;
|
||||
mod invert_v1;
|
||||
mod levels_v1;
|
||||
mod make_opaque_v1;
|
||||
mod mask_v1;
|
||||
mod median_filter_v1;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod photo_filter_v1;
|
||||
mod posterize_v1;
|
||||
mod renames;
|
||||
mod selective_color_v1;
|
||||
mod threshold_v1;
|
||||
mod vibrance_v1;
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::PhotoFilterNode"@1 => @2)]
|
||||
pub fn photo_filter_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PhotoFilterV1, &contract());
|
||||
check_undo(&PhotoFilterV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::PosterizeNode"@1 => @2)]
|
||||
pub fn posterize_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PosterizeV1, &contract());
|
||||
check_undo(&PosterizeV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::SelectiveColorNode"@1 => @2)]
|
||||
pub fn selective_color_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(39, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&SelectiveColorV1, &contract());
|
||||
check_undo(&SelectiveColorV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::ThresholdNode"@1 => @2)]
|
||||
pub fn threshold_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ThresholdV1, &contract());
|
||||
check_undo(&ThresholdV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use crate::raster_kernel_pipeline;
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// It now also takes GPU rasters, and the GPU pipeline they run on in a new scope input.
|
||||
#[migration("raster_nodes::adjustments::VibranceNode"@1 => @2)]
|
||||
pub fn vibrance_v1(inputs: &mut Inputs) {
|
||||
inputs.push(raster_kernel_pipeline());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::literal;
|
||||
use migration_runner::testing::{SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&VibranceV1, &contract());
|
||||
check_undo(&VibranceV1, &contract());
|
||||
}
|
||||
}
|
||||
@@ -405,6 +405,12 @@ impl Replica {
|
||||
}
|
||||
|
||||
pub fn send_resource(&mut self, to: TransportPeerId, hash: ResourceHash, bytes: Vec<u8>) -> Result<(), PacketError> {
|
||||
if let Some(recipients) = self.owed_resources.get_mut(&hash) {
|
||||
recipients.remove(&to);
|
||||
if recipients.is_empty() {
|
||||
self.owed_resources.remove(&hash);
|
||||
}
|
||||
}
|
||||
self.transport.send(to, &SyncPacket::Resource { hash, bytes })
|
||||
}
|
||||
|
||||
@@ -1126,4 +1132,18 @@ mod tests {
|
||||
host.poll(&mut session);
|
||||
assert!(host.owed_resources.is_empty(), "nothing is owed to a link that closed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answered_request_is_owed_no_more() {
|
||||
let (mut network, mut host, host_link, mut session) = hosted_room();
|
||||
let mut bare = connect_bare_peer(&mut network, &mut host, &mut session);
|
||||
let hash = ResourceHash::from(b"bytes".as_slice());
|
||||
|
||||
bare.send(host_link, &hello(0)).unwrap();
|
||||
bare.send(host_link, &SyncPacket::ResourceRequest(vec![hash])).unwrap();
|
||||
network.deliver_all();
|
||||
host.poll(&mut session);
|
||||
host.send_resource(bare.id(), hash, b"bytes".to_vec()).unwrap();
|
||||
assert!(host.owed_resources.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -307,7 +307,6 @@ impl Dispatcher {
|
||||
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
|
||||
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
|
||||
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
|
||||
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
|
||||
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
|
||||
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
|
||||
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
|
||||
|
||||
+24
-1
@@ -330,6 +330,29 @@ impl PreferencesDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let save_with_history_description = "
|
||||
Include the document's edit history in saved files. Only applies with \"Save as .gdd\" enabled.\n\
|
||||
\n\
|
||||
*Default: Off.*
|
||||
"
|
||||
.trim();
|
||||
let save_with_history_checkbox_id = CheckboxId::new();
|
||||
let save_with_history = vec![
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(preferences.save_with_history)
|
||||
.tooltip_label("Save with History")
|
||||
.tooltip_description(save_with_history_description)
|
||||
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveWithHistory { enabled: checkbox_input.checked }.into())
|
||||
.for_label(save_with_history_checkbox_id)
|
||||
.widget_instance(),
|
||||
TextLabel::new("Save with History")
|
||||
.tooltip_label("Save with History")
|
||||
.tooltip_description(save_with_history_description)
|
||||
.for_checkbox(save_with_history_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let validate_description = "
|
||||
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
|
||||
\n\
|
||||
@@ -353,7 +376,7 @@ impl PreferencesDialogMessageHandler {
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
rows.extend_from_slice(&[header, save_as_gdd, validate_storage_round_trip]);
|
||||
rows.extend_from_slice(&[header, save_as_gdd, save_with_history, validate_storage_round_trip]);
|
||||
}
|
||||
|
||||
// =============
|
||||
|
||||
@@ -33,18 +33,18 @@ impl LayoutHolder for DocumentsOpenElsewhereDialog {
|
||||
]),
|
||||
];
|
||||
rows.extend(self.documents.iter().cloned().map(|(source, name, shared)| {
|
||||
let label = TextLabel::new(name.clone()).widget_instance();
|
||||
let button = TextButton::new(if shared { "Join in This Tab" } else { "Open a Copy" })
|
||||
.on_update(move |_| {
|
||||
let followup = if shared {
|
||||
PortfolioMessage::JoinStoredSession { source }
|
||||
} else {
|
||||
PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() }
|
||||
};
|
||||
DialogMessage::CloseAndThen { followups: vec![followup.into()] }.into()
|
||||
})
|
||||
.widget_instance();
|
||||
LayoutGroup::row(vec![label, Separator::new(SeparatorStyle::Unrelated).widget_instance(), button])
|
||||
let button = |label: &str, followup: Box<dyn Fn() -> PortfolioMessage + Send + Sync>| {
|
||||
TextButton::new(label)
|
||||
.on_update(move |_| DialogMessage::CloseAndThen { followups: vec![followup().into()] }.into())
|
||||
.widget_instance()
|
||||
};
|
||||
let mut widgets = vec![TextLabel::new(name.clone()).widget_instance(), Separator::new(SeparatorStyle::Unrelated).widget_instance()];
|
||||
// A copy stays possible, since joining needs the other tab to be connected
|
||||
if shared {
|
||||
widgets.push(button("Join in This Tab", Box::new(move || PortfolioMessage::JoinStoredSession { source })));
|
||||
}
|
||||
widgets.push(button("Open a Copy", Box::new(move || PortfolioMessage::OpenDocumentCopy { source, document_name: name.clone() })));
|
||||
LayoutGroup::row(widgets)
|
||||
}));
|
||||
|
||||
Layout(rows)
|
||||
|
||||
@@ -196,9 +196,6 @@ pub enum FrontendMessage {
|
||||
UpdateDocumentCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
UpdateHistoryPanel {
|
||||
state: crate::messages::portfolio::history::utility_types::HistoryPanelState,
|
||||
},
|
||||
UpdateNodeGraphCursors {
|
||||
cursors: Vec<FrontendRemoteCursor>,
|
||||
},
|
||||
|
||||
@@ -25,7 +25,7 @@ pub enum SessionStatus {
|
||||
Disconnected,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedState {
|
||||
pub documents: Vec<DocumentInfo>,
|
||||
@@ -62,7 +62,7 @@ pub enum RenderStatus {
|
||||
Panic,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FileType {
|
||||
#[default]
|
||||
|
||||
@@ -118,7 +118,7 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
};
|
||||
|
||||
// The reply carries the source it read, so the frontend can drop one that a later keystroke has outdated
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(&source, input.operator_only);
|
||||
let completions = caret.map(|caret| math_expression_completions(&source, caret, asked));
|
||||
responses.add(FrontendMessage::UpdateMathExpressionAnalysis {
|
||||
widget_id,
|
||||
@@ -371,9 +371,9 @@ impl LayoutMessageHandler {
|
||||
};
|
||||
|
||||
// The widget is resent as stored, so its tokens and errors must be for its new value rather than its old one
|
||||
let accepts_reducers = math_expression_input.accepts_reducers;
|
||||
let error = math_expression_error(update_value, accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, accepts_reducers);
|
||||
let operator_only = math_expression_input.operator_only;
|
||||
let error = math_expression_error(update_value, operator_only);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(update_value, operator_only);
|
||||
math_expression_input.tokens = tokens;
|
||||
math_expression_input.tooltips = tooltips;
|
||||
math_expression_input.errors = math_expression_error_ranges(update_value, error.as_ref());
|
||||
|
||||
@@ -24,7 +24,7 @@ impl core::fmt::Display for WidgetId {
|
||||
|
||||
macro_rules! define_layout_target {
|
||||
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[repr(u8)]
|
||||
pub enum LayoutTarget {
|
||||
|
||||
@@ -16,13 +16,16 @@ fn utf16_offsets(source: &str) -> Vec<u32> {
|
||||
units
|
||||
}
|
||||
|
||||
/// Why a math expression fails to parse, or `None` when it parses. Where the node applies a lone operator or function name like
|
||||
/// `+` or `min` across its items, that counts as valid too.
|
||||
pub fn math_expression_error(expression: &str, accepts_reducers: bool) -> Option<ParseError> {
|
||||
/// Why a math expression fails to parse, or `None` when it parses. Where the node takes only a lone operator or function name like
|
||||
/// `+` or `min` to apply across its items, anything else is the error instead.
|
||||
pub fn math_expression_error(expression: &str, operator_only: bool) -> Option<ParseError> {
|
||||
// A blank expression is unfinished rather than wrong, so it goes unflagged like any empty field
|
||||
if expression.trim().is_empty() || (accepts_reducers && math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()) {
|
||||
if expression.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
if operator_only {
|
||||
return math_parser::reducer::reducer_error(expression);
|
||||
}
|
||||
math_parser::ast::Node::try_parse_from_str(expression).err()
|
||||
}
|
||||
|
||||
@@ -143,11 +146,11 @@ pub struct MathExpressionTokens {
|
||||
}
|
||||
|
||||
/// The tokens of a math expression for the frontend to color and typeset, with the parser's byte offsets converted to code units.
|
||||
pub fn math_expression_tokens(source: &str, accepts_reducers: bool) -> MathExpressionTokens {
|
||||
pub fn math_expression_tokens(source: &str, operator_only: bool) -> MathExpressionTokens {
|
||||
let units = utf16_offsets(source);
|
||||
let mut tooltips: Vec<MathExpressionTooltip> = Vec::new();
|
||||
|
||||
let tokens = math_parser::highlight::highlight(source, accepts_reducers).into_iter().map(|token| {
|
||||
let tokens = math_parser::highlight::highlight(source, operator_only).into_iter().map(|token| {
|
||||
let tooltip = token.tooltip.map(|tooltip| MathExpressionTooltip {
|
||||
label: tooltip.label,
|
||||
form: tooltip.form,
|
||||
|
||||
@@ -502,9 +502,9 @@ pub struct MathExpressionInput {
|
||||
pub tooltips: Vec<MathExpressionTooltip>,
|
||||
/// The stretches of the value its parse errors point at, which the frontend underlines.
|
||||
pub errors: Vec<MathExpressionRange>,
|
||||
/// Whether a lone operator or function name like `+` or `max` is an expression, applied across a list as by the Math node.
|
||||
/// Whether the value is a lone operator or function name like `+` or `max`, applied across a list, rather than an expression.
|
||||
#[serde(skip)]
|
||||
pub accepts_reducers: bool,
|
||||
pub operator_only: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
// Tooltips
|
||||
|
||||
@@ -25,7 +25,6 @@ pub struct MenuBarMessageHandler {
|
||||
pub make_path_editable_is_allowed: bool,
|
||||
pub data_panel_open: bool,
|
||||
pub session_panel_open: bool,
|
||||
pub history_panel_open: bool,
|
||||
pub layers_panel_open: bool,
|
||||
pub inspector_open: bool,
|
||||
pub focus_document: bool,
|
||||
@@ -694,11 +693,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
MenuListEntry::new("History")
|
||||
.label("History")
|
||||
.icon(if self.history_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
|
||||
.on_commit(|_| WorkspaceMessage::ToggleHistoryPanelOpen.into())
|
||||
.disabled(self.focus_document),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
|
||||
@@ -18,7 +18,7 @@ use graphene_std::raster::{
|
||||
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
|
||||
SelectiveColorChoice, TonalRange,
|
||||
};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
|
||||
use graphene_std::text::TextAlign;
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
@@ -944,9 +944,15 @@ impl TableItemLayout for Raster<GPU> {
|
||||
"Raster"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("Raster ({} x {})", self.data().width(), self.data().height())
|
||||
let size = self.size();
|
||||
format!("Raster ({} x {})", size.x, size.y)
|
||||
}
|
||||
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
if self.is_empty() {
|
||||
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
|
||||
return vec![LayoutGroup::row(widgets)];
|
||||
}
|
||||
|
||||
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
|
||||
vec![LayoutGroup::row(widgets)]
|
||||
}
|
||||
|
||||
@@ -141,7 +141,15 @@ impl DocumentHistory {
|
||||
if self.legacy_undo_stack.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let note = if let Some(ops) = self.retract_storage_interaction() {
|
||||
// A failed retract may already have taken the step back, so no older step is undone after it
|
||||
let retracted = match self.retract_storage_interaction() {
|
||||
Ok(retracted) => retracted,
|
||||
Err(error) => {
|
||||
log::error!("Taking the storage interaction back failed: {error}");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let note = if let Some(ops) = retracted {
|
||||
UndoNote::Retracted(ops)
|
||||
} else if in_session && let Some(rev) = self.undo_retired_step() {
|
||||
UndoNote::Dropped(rev)
|
||||
@@ -169,16 +177,19 @@ impl DocumentHistory {
|
||||
return false;
|
||||
};
|
||||
|
||||
let redone = match ¬e {
|
||||
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
|
||||
UndoNote::Dropped(rev) => self.redo_retired_step(*rev),
|
||||
UndoNote::Cursor => true,
|
||||
};
|
||||
if !redone {
|
||||
// The note stays paired with its redo snapshot
|
||||
self.undo_notes.push(note);
|
||||
return false;
|
||||
}
|
||||
if let Some(snapshot) = self.pop_redo() {
|
||||
self.push_undo(snapshot);
|
||||
}
|
||||
match note {
|
||||
UndoNote::Retracted(ops) => self.restage_ops(ops),
|
||||
UndoNote::Dropped(rev) => {
|
||||
self.redo_retired_step(rev);
|
||||
}
|
||||
UndoNote::Cursor => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -196,18 +207,16 @@ impl DocumentHistory {
|
||||
self.undo_notes.drain(..evicted);
|
||||
}
|
||||
|
||||
fn retract_storage_interaction(&mut self) -> Option<Vec<document_graph_storage::RegistryDelta>> {
|
||||
self.storage.as_mut()?.retract_interaction().unwrap_or_else(|error| {
|
||||
log::error!("Taking the storage interaction back failed: {error}");
|
||||
None
|
||||
})
|
||||
fn retract_storage_interaction(&mut self) -> Result<Option<Vec<document_graph_storage::RegistryDelta>>, document_format::Error> {
|
||||
match self.storage.as_mut() {
|
||||
Some(storage) => storage.retract_interaction(),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) {
|
||||
let Some(storage) = self.storage.as_mut() else { return };
|
||||
if let Err(error) = storage.restage_ops(ops) {
|
||||
log::error!("Staging the redone step failed: {error}");
|
||||
}
|
||||
fn restage_ops(&mut self, ops: Vec<document_graph_storage::RegistryDelta>) -> bool {
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
storage.restage_ops(ops).inspect_err(|error| log::error!("Staging the redone step failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
fn undo_retired_step(&mut self) -> Option<document_graph_storage::Rev> {
|
||||
@@ -222,29 +231,8 @@ impl DocumentHistory {
|
||||
}
|
||||
|
||||
pub fn redo_retired_step(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
self.change_line(|storage| storage.redo_retired_step(rev), "Redoing the dropped step failed")
|
||||
}
|
||||
|
||||
pub fn drop_step(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
self.change_line(|storage| storage.drop_step(rev), "Removing the step failed")
|
||||
}
|
||||
|
||||
pub fn move_head_to(&mut self, rev: document_graph_storage::Rev) -> bool {
|
||||
self.change_line(|storage| storage.move_head(rev), "Moving the head failed")
|
||||
}
|
||||
|
||||
fn change_line(&mut self, change: impl FnOnce(&mut document_format::GddV1) -> Result<(), document_format::Error>, failure: &str) -> bool {
|
||||
let Some(storage) = self.storage.as_mut().filter(|storage| storage.can_change_line()) else {
|
||||
return false;
|
||||
};
|
||||
change(storage).inspect_err(|error| log::error!("{failure}: {error}")).is_ok()
|
||||
}
|
||||
|
||||
/// Forgets the legacy snapshots once the head has moved off their line.
|
||||
pub fn clear_legacy(&mut self) {
|
||||
self.legacy_undo_stack.clear();
|
||||
self.legacy_redo_stack.clear();
|
||||
self.undo_notes.clear();
|
||||
let Some(storage) = self.storage.as_mut() else { return false };
|
||||
storage.redo_retired_step(rev).inspect_err(|error| log::error!("Redoing the dropped step failed: {error}")).is_ok()
|
||||
}
|
||||
|
||||
pub fn retire_storage_interaction(&mut self) {
|
||||
|
||||
@@ -56,17 +56,6 @@ pub enum DocumentMessage {
|
||||
DeselectAllLayers,
|
||||
DocumentHistoryBackward,
|
||||
DocumentHistoryForward,
|
||||
/// Moves the shared head to an earlier interaction and keeps the later steps as a branch.
|
||||
HistoryMoveHead {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
/// Drops a retired interaction and mints the later ones again on its parent.
|
||||
HistoryRemoveStep {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
HistoryRestoreStep {
|
||||
rev: document_graph_storage::Rev,
|
||||
},
|
||||
DocumentStructureChanged,
|
||||
DrawArtboardOverlays {
|
||||
context: OverlayContext,
|
||||
|
||||
@@ -473,27 +473,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
|
||||
}
|
||||
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
|
||||
DocumentMessage::HistoryMoveHead { rev } => self.apply_history_action(
|
||||
document_id,
|
||||
|history| history.move_head_to(rev),
|
||||
&resource_storage.resources_mut(),
|
||||
preferences.validate_storage_round_trip,
|
||||
responses,
|
||||
),
|
||||
DocumentMessage::HistoryRemoveStep { rev } => self.apply_history_action(
|
||||
document_id,
|
||||
|history| history.drop_step(rev),
|
||||
&resource_storage.resources_mut(),
|
||||
preferences.validate_storage_round_trip,
|
||||
responses,
|
||||
),
|
||||
DocumentMessage::HistoryRestoreStep { rev } => self.apply_history_action(
|
||||
document_id,
|
||||
|history| history.redo_retired_step(rev),
|
||||
&resource_storage.resources_mut(),
|
||||
preferences.validate_storage_round_trip,
|
||||
responses,
|
||||
),
|
||||
DocumentMessage::DocumentStructureChanged => {
|
||||
if layers_panel_open {
|
||||
self.network_interface.load_structure();
|
||||
@@ -1275,6 +1254,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
|
||||
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
|
||||
let save_as_gdd = preferences.save_as_gdd;
|
||||
let include_history = preferences.save_with_history;
|
||||
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
|
||||
let name = format!("{}.{}", self.name.clone(), extension);
|
||||
|
||||
@@ -1310,7 +1290,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.export_to_bytes(
|
||||
document_format::ExportFormat::Xz,
|
||||
document_format::ExportOptions {
|
||||
include_history: false,
|
||||
include_history,
|
||||
..Default::default()
|
||||
},
|
||||
export_load_handle.as_ref(),
|
||||
@@ -2224,6 +2204,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
document.apply_stored_document_settings(storage.view_settings());
|
||||
document.set_storage(storage, declarations, byte_store);
|
||||
document.refresh_resource_registry();
|
||||
|
||||
document
|
||||
}
|
||||
@@ -2460,7 +2441,6 @@ impl DocumentMessageHandler {
|
||||
pub fn set_storage(&mut self, mut storage: document_format::GddV1, declarations: Declarations, byte_store: Arc<dyn ResourceStorage>) {
|
||||
storage.set_byte_store(byte_store);
|
||||
self.history.set_storage(storage, declarations);
|
||||
self.refresh_resource_registry();
|
||||
}
|
||||
|
||||
pub(crate) fn end_storage_interaction(&mut self) {
|
||||
@@ -3018,32 +2998,6 @@ impl DocumentMessageHandler {
|
||||
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
|
||||
}
|
||||
|
||||
/// Performs a History panel action in storage and drops the legacy snapshots, which are off the head's line.
|
||||
fn apply_history_action(
|
||||
&mut self,
|
||||
document_id: DocumentId,
|
||||
action: impl FnOnce(&mut DocumentHistory) -> bool,
|
||||
byte_store: &dyn ResourceStorage,
|
||||
validate: bool,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
}
|
||||
responses.add(EventMessage::ToolAbort);
|
||||
self.stage_edits_outside_transaction(byte_store, validate);
|
||||
self.history.retire_storage_interaction();
|
||||
let stored_name = self.stored_name().map(str::to_string);
|
||||
if !action(&mut self.history) {
|
||||
return;
|
||||
}
|
||||
self.history.clear_legacy();
|
||||
self.follow_storage_changes(stored_name, responses);
|
||||
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
|
||||
/// Reconciles the interface with storage. The tab takes the stored name only if it changed from `name_before`.
|
||||
fn follow_storage_changes(&mut self, name_before: Option<String>, responses: &mut VecDeque<Message>) {
|
||||
if let Some(gdd) = self.history.storage_mut() {
|
||||
|
||||
@@ -1394,8 +1394,8 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// Like `math_expression`, where a lone reducer token like `+` or `min` applied across the node's items is also valid
|
||||
"math_expression_or_reducer".to_string(),
|
||||
// Like `math_expression`, but taking only a lone operator or function name like `+` or `min` to apply across the node's items
|
||||
"math_operator".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![LayoutGroup::row(node_inspector::math_expression_widget(info, true))])
|
||||
|
||||
@@ -208,6 +208,7 @@ pub enum NodeGraphMessage {
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
SendGraph,
|
||||
SendNodePositions,
|
||||
SetInputValue {
|
||||
node_id: NodeId,
|
||||
input_index: usize,
|
||||
|
||||
@@ -131,9 +131,9 @@ pub struct NodeGraphMessageHandler {
|
||||
reordering_export: Option<usize>,
|
||||
/// The end index of the moved connector
|
||||
end_index: Option<usize>,
|
||||
/// Used to keep track of what nodes are sent to the front end so that only visible ones are sent to the frontend
|
||||
frontend_nodes: Vec<NodeId>,
|
||||
/// Used to keep track of what wires are sent to the front end so the old ones can be removed
|
||||
/// The nodes the frontend currently knows about
|
||||
frontend_nodes: Vec<FrontendNode>,
|
||||
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
|
||||
frontend_wires: HashSet<(NodeId, usize)>,
|
||||
evaluation_errors: Vec<NodeEvaluationError>,
|
||||
}
|
||||
@@ -2017,7 +2017,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
let document_bbox: [DVec2; 2] = viewport_bbox.map(|p| network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(p));
|
||||
|
||||
let mut nodes = Vec::new();
|
||||
for node_id in &self.frontend_nodes {
|
||||
for node_id in self.frontend_nodes.iter().map(|node| &node.id) {
|
||||
let Some(node_bbox) = network_interface.node_bounding_box(node_id, breadcrumb_network_path) else {
|
||||
log::error!("Could not get bbox for node: {node_id:?}");
|
||||
continue;
|
||||
@@ -2052,9 +2052,8 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(InspectorMessage::Refresh);
|
||||
responses.add(EventMessage::GraphChanged);
|
||||
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
|
||||
let nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
|
||||
self.frontend_nodes = nodes.iter().map(|node| node.id).collect();
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes });
|
||||
self.frontend_nodes = self.collect_nodes(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
|
||||
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
@@ -2071,6 +2070,36 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
self.update_node_graph_hints(responses);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::SendNodePositions => {
|
||||
if breadcrumb_network_path != selection_network_path || !graph_view_overlay_open {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(network) = network_interface.nested_network(breadcrumb_network_path) else { return };
|
||||
let same_nodes = network.nodes.len() == self.frontend_nodes.len() && self.frontend_nodes.iter().all(|node| network.nodes.contains_key(&node.id));
|
||||
if !same_nodes {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
return;
|
||||
}
|
||||
|
||||
for node in &mut self.frontend_nodes {
|
||||
if let Some(position) = network_interface.position(&node.id, breadcrumb_network_path) {
|
||||
node.position = position.into();
|
||||
}
|
||||
}
|
||||
responses.add(FrontendMessage::UpdateNodeGraphNodes { nodes: self.frontend_nodes.clone() });
|
||||
|
||||
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
|
||||
|
||||
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
|
||||
responses.add(FrontendMessage::UpdateLayerWidths {
|
||||
layer_widths,
|
||||
chain_widths,
|
||||
has_left_input_wire,
|
||||
});
|
||||
responses.add(NodeGraphMessage::UpdateImportsExports);
|
||||
}
|
||||
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
|
||||
use graphene_std::vector::generator_nodes::*;
|
||||
|
||||
@@ -2134,12 +2163,15 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
|
||||
if graph_view_overlay_open {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
if !rubber_band {
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::ShiftSelectedNodesByAmount { mut graph_delta, rubber_band, glide } => {
|
||||
let moved = graph_delta != IVec2::ZERO;
|
||||
while graph_delta != IVec2::ZERO {
|
||||
match graph_delta.x.cmp(&0) {
|
||||
Ordering::Greater => {
|
||||
@@ -2183,6 +2215,9 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SendWires);
|
||||
if rubber_band && moved {
|
||||
responses.add(NodeGraphMessage::SendNodePositions);
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::ToggleSelectedAsLayersOrNodes => {
|
||||
let Some(selected_nodes) = network_interface.selected_nodes_in_nested_network(selection_network_path) else {
|
||||
@@ -3410,7 +3445,8 @@ impl NodeGraphMessageHandler {
|
||||
.exports
|
||||
.iter()
|
||||
.any(|export| matches!(export, NodeInput::Node { node_id: export_node_id, .. } if *export_node_id == node_id));
|
||||
if selection_is_not_already_the_output && no_other_selections {
|
||||
let has_outputs = network_interface.number_of_outputs(&node_id, breadcrumb_network_path) > 0;
|
||||
if selection_is_not_already_the_output && no_other_selections && has_outputs {
|
||||
let button = TextButton::new("Preview")
|
||||
.icon("FrameAll")
|
||||
.tooltip_label("Preview")
|
||||
|
||||
@@ -481,16 +481,16 @@ pub fn text_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<WidgetIn
|
||||
}
|
||||
|
||||
/// A math expression's typeset text field, with a warning icon in the assist area giving the error in its tooltip while the expression fails to parse.
|
||||
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, accepts_reducers: bool) -> Vec<WidgetInstance> {
|
||||
pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo, operator_only: bool) -> Vec<WidgetInstance> {
|
||||
let Some(TaggedValue::String(expression)) = parameter_widgets_info.input().and_then(|input| input.as_non_exposed_value()) else {
|
||||
return text_widget(parameter_widgets_info);
|
||||
};
|
||||
let error = math_expression_error(expression, accepts_reducers);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, accepts_reducers);
|
||||
let error = math_expression_error(expression, operator_only);
|
||||
let MathExpressionTokens { tokens, tooltips } = math_expression_tokens(expression, operator_only);
|
||||
let input = MathExpressionInput::new(expression.clone())
|
||||
.tokens(tokens)
|
||||
.tooltips(tooltips)
|
||||
.accepts_reducers(accepts_reducers)
|
||||
.operator_only(operator_only)
|
||||
.errors(math_expression_error_ranges(expression, error.as_ref()))
|
||||
.on_update(parameter_widgets_info.update_value(|x: &MathExpressionInput| TaggedValue::String(x.value.clone())))
|
||||
.on_commit(commit_value)
|
||||
@@ -500,7 +500,7 @@ pub fn math_expression_widget(mut parameter_widgets_info: ParameterWidgetsInfo,
|
||||
// padded to a checkbox's 16px so the field lines up with the rows around it
|
||||
let icon = match &error {
|
||||
Some(error) => IconLabel::new("Warning")
|
||||
.tooltip_label("Invalid Math Expression")
|
||||
.tooltip_label(if operator_only { "Invalid Operator" } else { "Invalid Math Expression" })
|
||||
.tooltip_description(math_expression_error_description(error)),
|
||||
None => IconLabel::new("Empty12px"),
|
||||
};
|
||||
@@ -3942,12 +3942,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn math_expressions_are_flagged_only_when_they_fail_to_parse() {
|
||||
for (expression, accepts_reducers) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true)] {
|
||||
assert!(math_expression_error(expression, accepts_reducers).is_none(), "`{expression}`");
|
||||
for (expression, operator_only) in [("x * 2", false), ("", false), (" ", true), ("min", false), ("+", true), ("min", true), (" ≤ ", true)] {
|
||||
assert!(math_expression_error(expression, operator_only).is_none(), "`{expression}`");
|
||||
}
|
||||
|
||||
assert!(math_expression_error("2 +", false).is_some());
|
||||
assert!(math_expression_error("+", false).is_some(), "a lone reducer is an error where the node applies none");
|
||||
assert!(math_expression_error("+", false).is_some(), "a lone operator is an error where the node takes an expression");
|
||||
assert!(math_expression_error("a + b", true).is_some(), "an expression is an error where the node takes a lone operator");
|
||||
assert_eq!(description("sin(I)").as_deref(), Some("A matrix stands where a value is needed"));
|
||||
}
|
||||
|
||||
|
||||
@@ -664,6 +664,39 @@ fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasted_image_resource_survives_inserting_a_node() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER)).await;
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let document = editor.active_document();
|
||||
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pasted_image_resource_survives_storage_mounting_after_the_paste() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
editor.handle_message(paste_named_image()).await;
|
||||
let byte_store = mount_in_memory_storage(&mut editor);
|
||||
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
|
||||
|
||||
let document = editor.active_document();
|
||||
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
|
||||
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
|
||||
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
|
||||
}
|
||||
|
||||
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
|
||||
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
|
||||
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
|
||||
|
||||
+15
@@ -3532,3 +3532,18 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
||||
"The evaluated network should fall back to the document's own export"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cannot_preview_node_without_outputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||
|
||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||
network_interface.toggle_preview(custom_node, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
}
|
||||
@@ -1408,8 +1408,10 @@ impl NodeNetworkInterface {
|
||||
let primary_output = RootNode { node_id: toggle_id, output_index: 0 };
|
||||
let previewing = if self.previewing(network_path).previews(toggle_id) || self.root_node(network_path) == Some(primary_output) {
|
||||
Previewing::No
|
||||
} else {
|
||||
} else if self.number_of_outputs(&toggle_id, network_path) > 0 {
|
||||
Previewing::Yes { previewed: primary_output }
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
self.set_previewing(previewing, network_path);
|
||||
}
|
||||
|
||||
@@ -376,6 +376,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_math_nodes::LogicalOrNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::math_function::IDENTIFIER,
|
||||
aliases: &["math_nodes::MathFxNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::max::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::MaxNode", "graphene_core::ops::MaxNode"],
|
||||
@@ -1266,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
|
||||
}
|
||||
|
||||
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1384,8 +1392,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
|
||||
}
|
||||
|
||||
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math f(x)"
|
||||
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math f(…)", which reads the pair as `a` and `b`.
|
||||
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math Function"
|
||||
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math Formula", which reads the pair as `a` and `b`.
|
||||
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
@@ -1416,7 +1424,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
})
|
||||
.is_some();
|
||||
|
||||
// The rewritten "Math f(x)" expression, or `None` when only the Extend + "Math f(…)" form can preserve the node's meaning
|
||||
// The rewritten "Math Function" expression, or `None` when only the Extend + "Math Formula" form can preserve the node's meaning
|
||||
let inline_b_constant = match operand_b.as_value() {
|
||||
Some(TaggedValue::Number(constant)) => Some(*constant),
|
||||
_ => None,
|
||||
@@ -1436,8 +1444,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
};
|
||||
|
||||
if let Some(fx_expression) = fx_expression {
|
||||
// "Math f(x)": forward the old `A` input and the rewritten expression; the old `B` input is dropped
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER)) else {
|
||||
// "Math Function": forward the old `A` input and the rewritten expression; the old `B` input is dropped
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
@@ -1451,7 +1459,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::String(fx_expression), false), network_path);
|
||||
} else {
|
||||
// "Extend" joins the two operands into the list "Math f(…)" reads; an unwired constant operand becomes a one-item list value
|
||||
// "Extend" joins the two operands into the list "Math Formula" reads; an unwired constant operand becomes a one-item list value
|
||||
let as_list_input = |input: &NodeInput| match input.as_value() {
|
||||
Some(TaggedValue::Number(value)) => NodeInput::value(TaggedValue::Numbers(vec![*value]), input.is_exposed()),
|
||||
_ => input.clone(),
|
||||
@@ -1461,7 +1469,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
};
|
||||
let extend_template = extend_definition.default_node_template();
|
||||
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_f::IDENTIFIER)) else {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_formula::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
@@ -1854,6 +1862,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
|
||||
migrate_assign_colors_nodes(document);
|
||||
migrate_math_f_nodes(document);
|
||||
|
||||
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
|
||||
migrate_copy_to_points_nodes(document);
|
||||
@@ -1976,10 +1985,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
let mut inputs_count = node.inputs.len();
|
||||
|
||||
// The expression nodes gained an output-type input, a type witness the Inspector edits. A node from before it
|
||||
// takes the definition's default choice, Number, which is the output type every such node had.
|
||||
let expression_node_identifiers = [graphene_std::math_nodes::math_fx::IDENTIFIER, graphene_std::math_nodes::math_f::IDENTIFIER];
|
||||
if expression_node_identifiers.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && inputs_count == 2 {
|
||||
// The expression nodes gained an output-type input, a type witness the Inspector edits. A node from before it takes the definition's
|
||||
// default choice, Number, which is the output type every such node had. Math f(…) nodes get it as `migrate_math_f` splits them.
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER) && inputs_count == 2 {
|
||||
let definition = resolve_document_node_type(&reference)?;
|
||||
let mut template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut template);
|
||||
@@ -3511,6 +3519,49 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
let raster_kernel_pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
|
||||
let raster_kernel_nodes = {
|
||||
use graphene_std::raster_nodes::adjustments::*;
|
||||
[
|
||||
desaturate::IDENTIFIER,
|
||||
gamma_correction::IDENTIFIER,
|
||||
make_opaque::IDENTIFIER,
|
||||
brightness_contrast::IDENTIFIER,
|
||||
levels::IDENTIFIER,
|
||||
curves::IDENTIFIER,
|
||||
black_and_white::IDENTIFIER,
|
||||
hue_saturation::IDENTIFIER,
|
||||
invert::IDENTIFIER,
|
||||
threshold::IDENTIFIER,
|
||||
gradient_map::IDENTIFIER,
|
||||
vibrance::IDENTIFIER,
|
||||
channel_mixer::IDENTIFIER,
|
||||
selective_color::IDENTIFIER,
|
||||
posterize::IDENTIFIER,
|
||||
exposure::IDENTIFIER,
|
||||
color_balance::IDENTIFIER,
|
||||
photo_filter::IDENTIFIER,
|
||||
color_lookup::IDENTIFIER,
|
||||
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
|
||||
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
|
||||
graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
|
||||
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
|
||||
]
|
||||
};
|
||||
if raster_kernel_nodes.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && !node.inputs.contains(&raster_kernel_pipeline) {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let value_inputs = node_template.inputs.iter().position(|input| *input == raster_kernel_pipeline)?;
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.into_iter().take(value_inputs).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
|
||||
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
|
||||
if let Some(definition) = resolve_document_node_type(&reference) {
|
||||
@@ -3840,6 +3891,46 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(_, node, _)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::MathFNode")))
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in math_f_nodes {
|
||||
migrate_math_f(&node_id, &network_path, document);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds a removed Math f(…) node as Math Aggregate if its string was a lone operator or function name it applied across its items, or as
|
||||
/// Math Formula otherwise, including when the string is wired, since a wired string can't be read before it runs.
|
||||
fn migrate_math_f(node_id: &NodeId, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
|
||||
use graphene_std::math_nodes::{math_aggregate, math_formula};
|
||||
|
||||
let old_node = document.network_interface.document_node(node_id, network_path)?;
|
||||
let applies_operator = matches!(
|
||||
old_node.inputs.get(1).and_then(|input| input.as_value()),
|
||||
Some(TaggedValue::String(expression)) if math_parser::reducer::classify_reducer(expression, math_parser::context::NothingMap).is_some()
|
||||
);
|
||||
|
||||
let identifier = if applies_operator { math_aggregate::IDENTIFIER } else { math_formula::IDENTIFIER };
|
||||
let mut node_template = resolve_proto_node_type(identifier)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
reset_default_display_name(document, node_id, network_path, "Math f(…)");
|
||||
|
||||
// The items, string, and output type keep their places, where a node from before the output type takes its default, Number
|
||||
for (index, input) in old_inputs.into_iter().enumerate().take(3) {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Splits each removed Assign Colors node into the Vary Fill Colors and Vary Stroke Colors nodes its Fill and Stroke toggles call for.
|
||||
fn migrate_assign_colors_nodes(document: &mut DocumentMessageHandler) {
|
||||
let assign_colors_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -4430,7 +4521,8 @@ mod tests {
|
||||
|
||||
let desaturate_node = node(1);
|
||||
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
|
||||
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method]);
|
||||
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
|
||||
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
|
||||
|
||||
let brightness_contrast = node(2);
|
||||
assert_eq!(
|
||||
@@ -4556,7 +4648,7 @@ mod tests {
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -4591,7 +4683,7 @@ mod tests {
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_fx::IDENTIFIER),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::math_function::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::Number(4.), false), NodeInput::value(TaggedValue::String("x^2".into()), false)],
|
||||
..Default::default()
|
||||
},
|
||||
@@ -4614,8 +4706,44 @@ mod tests {
|
||||
assert_eq!(outward_wires.as_deref(), Some([InputConnector::node_at_index(node_id, 0)].as_slice()));
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math f(x)",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math f(…)"
|
||||
// Math f(…) either applied a lone operator across its items or evaluated an expression over them, which are now two nodes
|
||||
#[test]
|
||||
fn math_f_nodes_split_into_aggregate_and_formula() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::math_nodes::{math_aggregate, math_formula};
|
||||
|
||||
let migrated_implementation = |inputs: Vec<NodeInput>| {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
document.network_interface.insert_node(
|
||||
node_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::MathFNode")),
|
||||
inputs,
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(node.inputs.len(), 3, "the output type is kept, or added to a node from before it");
|
||||
match &node.implementation {
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => identifier.clone(),
|
||||
other => panic!("expected a proto node implementation, got {other:?}"),
|
||||
}
|
||||
};
|
||||
let items = || NodeInput::value(TaggedValue::None, false);
|
||||
let expression = |text: &str| NodeInput::value(TaggedValue::String(text.into()), false);
|
||||
let output_type = || NodeInput::value(TaggedValue::Number(0.), false);
|
||||
|
||||
assert_eq!(migrated_implementation(vec![items(), expression(" max "), output_type()]), math_aggregate::IDENTIFIER);
|
||||
assert_eq!(migrated_implementation(vec![items(), expression("+")]), math_aggregate::IDENTIFIER);
|
||||
assert_eq!(migrated_implementation(vec![items(), expression("a * b + c"), output_type()]), math_formula::IDENTIFIER);
|
||||
}
|
||||
|
||||
// The old Math node's expression decides its replacement: a static string that never reads `B` becomes "Math Function",
|
||||
// while a wired `B` or an uninspectable expression becomes "Extend" feeding "Math Formula"
|
||||
#[test]
|
||||
fn old_math_nodes_split_into_the_expression_node_pair() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
@@ -4666,7 +4794,7 @@ mod tests {
|
||||
.expect("an Extend node should be spliced in")
|
||||
};
|
||||
|
||||
// A static expression that never reads `B` becomes "Math f(x)" with `A` renamed to `x` and the `B` input dropped
|
||||
// A static expression that never reads `B` becomes "Math Function" with `A` renamed to `x` and the `B` input dropped
|
||||
{
|
||||
let inputs = vec![
|
||||
NodeInput::node(source_a_id, 0),
|
||||
@@ -4676,7 +4804,7 @@ mod tests {
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_function::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.len(),
|
||||
@@ -4698,7 +4826,7 @@ mod tests {
|
||||
let mut document = build_document("graphene_core::ops::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_fx::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_function::IDENTIFIER);
|
||||
let node = &document.network_interface.document_network().nodes[&math_id];
|
||||
assert_eq!(
|
||||
node.inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
@@ -4717,7 +4845,7 @@ mod tests {
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_formula::IDENTIFIER);
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.first(), Some(&NodeInput::node(extend_id, 0)));
|
||||
@@ -4739,7 +4867,7 @@ mod tests {
|
||||
let mut document = build_document("math_nodes::MathNode", inputs);
|
||||
migrate(&mut document);
|
||||
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_f::IDENTIFIER);
|
||||
assert_eq!(implementation_of(&document, math_id), graphene_std::math_nodes::math_formula::IDENTIFIER);
|
||||
let extend_id = find_extend(&document);
|
||||
let network = document.network_interface.document_network();
|
||||
assert_eq!(network.nodes[&math_id].inputs.get(1), Some(&NodeInput::node(source_expression_id, 0)));
|
||||
|
||||
@@ -143,6 +143,10 @@ pub(super) async fn remove_stored_document(store: DocumentStoreHandle, document_
|
||||
/// Joins the session of a stored document another tab holds, as a document and peer of this tab's own.
|
||||
pub(super) async fn join_stored_session(store: DocumentStoreHandle, source: DocumentId) -> Message {
|
||||
let manifest = async {
|
||||
// Opening a missing key creates it, and the other tab may have closed the document since
|
||||
if !store.list().await.map_err(|error| error.to_string())?.contains(&document_key(source)) {
|
||||
return Err("the other tab closed it".to_string());
|
||||
}
|
||||
let container = store.open(document_key(source)).await.map_err(|error| error.to_string())?;
|
||||
GddV1::read_manifest(&container, &GddV1Layout).await.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, PortfolioMessage, History)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum HistoryMessage {
|
||||
Refresh,
|
||||
Tick,
|
||||
Expand { id: String, expanded: bool },
|
||||
LoadMore,
|
||||
GoBack { id: String },
|
||||
RemoveStep { id: String },
|
||||
BringBack { id: String },
|
||||
Follow { id: Option<String> },
|
||||
Rename { id: String, label: String },
|
||||
Tag { id: String, tag: String, on: bool },
|
||||
}
|
||||
@@ -1,508 +0,0 @@
|
||||
use super::utility_types::{HistoryBranch, HistoryDeltaRow, HistoryPanelState, HistoryProgressRow, HistoryRow};
|
||||
use crate::messages::portfolio::document::DocumentMessageHandler;
|
||||
use crate::messages::portfolio::sync::identity::{anonymous_name, user_color};
|
||||
use crate::messages::portfolio::sync::now_ms;
|
||||
use crate::messages::prelude::*;
|
||||
use document_format::GddV1;
|
||||
use document_graph_storage::{Delta, HistoryMetadata, HotOpId, PeerId, RegistryDelta, Rev, Session, Subject, UserId, rev_attr};
|
||||
use peer_transport::RemotePeer;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct HistoryMessageContext<'a> {
|
||||
pub documents: &'a mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
pub active_document_id: Option<DocumentId>,
|
||||
pub panel_open: bool,
|
||||
}
|
||||
|
||||
/// Sends the History panel the active document's history and turns its actions into head moves.
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct HistoryMessageHandler {
|
||||
ticking: bool,
|
||||
expanded: HashSet<Rev>,
|
||||
limit: usize,
|
||||
following: Option<Rev>,
|
||||
last_sent: Option<u64>,
|
||||
}
|
||||
|
||||
/// How many interactions each request adds.
|
||||
const PAGE: usize = 100;
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<HistoryMessage, HistoryMessageContext<'_>> for HistoryMessageHandler {
|
||||
fn process_message(&mut self, message: HistoryMessage, responses: &mut VecDeque<Message>, mut context: HistoryMessageContext) {
|
||||
match message {
|
||||
HistoryMessage::Refresh => {
|
||||
if !self.ticking {
|
||||
self.ticking = true;
|
||||
responses.add(BroadcastMessage::SubscribeEvent {
|
||||
on: EventMessage::AnimationFrame,
|
||||
send: Box::new(HistoryMessage::Tick.into()),
|
||||
});
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Tick => {
|
||||
if context.panel_open {
|
||||
self.send(&context, responses, false);
|
||||
}
|
||||
}
|
||||
HistoryMessage::Expand { id, expanded } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
match expanded {
|
||||
true => self.expanded.insert(rev),
|
||||
false => self.expanded.remove(&rev),
|
||||
};
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::LoadMore => {
|
||||
self.limit = self.limit.max(PAGE) + PAGE;
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Follow { id } => {
|
||||
self.following = id.as_deref().and_then(parse_rev);
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::GoBack { id } => {
|
||||
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
|
||||
match place(gdd.session(), rev) {
|
||||
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
|
||||
Some(Place::Line(0)) => {}
|
||||
// A session moves the head for everyone at once. Alone, undo each interaction to keep undo in step
|
||||
Some(Place::Line(steps)) => match gdd.role().is_some() {
|
||||
true => responses.add(DocumentMessage::HistoryMoveHead { rev }),
|
||||
false => (0..steps).for_each(|_| responses.add(DocumentMessage::Undo)),
|
||||
},
|
||||
None => log::warn!("The History panel asked to go to {rev:?}, which is not on the head's line"),
|
||||
}
|
||||
}
|
||||
HistoryMessage::RemoveStep { id } => {
|
||||
if let Some(rev) = parse_rev(&id) {
|
||||
responses.add(DocumentMessage::HistoryRemoveStep { rev });
|
||||
}
|
||||
}
|
||||
HistoryMessage::BringBack { id } => {
|
||||
let Some((gdd, rev)) = active_storage(&context).zip(parse_rev(&id)) else { return };
|
||||
match place(gdd.session(), rev) {
|
||||
Some(Place::Undone(steps)) => (0..steps).for_each(|_| responses.add(DocumentMessage::Redo)),
|
||||
Some(Place::Line(_)) => {}
|
||||
None => responses.add(DocumentMessage::HistoryRestoreStep { rev }),
|
||||
}
|
||||
}
|
||||
HistoryMessage::Rename { id, label } => {
|
||||
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
|
||||
if let Err(error) = gdd.record(Subject::Rev(rev), rev_attr::LABEL, serde_json::Value::from(label.trim()), now_ms()) {
|
||||
log::warn!("Naming the step failed: {error}");
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
HistoryMessage::Tag { id, tag, on } => {
|
||||
let tag = tag.trim();
|
||||
if tag.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some((gdd, rev)) = active_storage_mut(&mut context).zip(parse_rev(&id)) else { return };
|
||||
if let Err(error) = gdd.record(Subject::Rev(rev), &format!("{}{tag}", rev_attr::TAG_PREFIX), serde_json::Value::Bool(on), now_ms()) {
|
||||
log::warn!("Tagging the step failed: {error}");
|
||||
}
|
||||
self.send(&context, responses, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
advertise_actions!(HistoryMessageDiscriminant;);
|
||||
}
|
||||
|
||||
impl HistoryMessageHandler {
|
||||
fn send(&mut self, context: &HistoryMessageContext, responses: &mut VecDeque<Message>, force: bool) {
|
||||
let Some(gdd) = active_storage(context) else {
|
||||
if force || self.last_sent.is_some() {
|
||||
self.last_sent = None;
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state: HistoryPanelState::default() });
|
||||
}
|
||||
return;
|
||||
};
|
||||
if self.following.is_some_and(|tip| gdd.session().delta(tip).is_none()) {
|
||||
self.following = None;
|
||||
}
|
||||
let limit = self.limit.max(PAGE);
|
||||
let fingerprint = fingerprint(context.active_document_id, gdd, limit, &self.expanded, self.following);
|
||||
if !force && self.last_sent == Some(fingerprint) {
|
||||
return;
|
||||
}
|
||||
self.last_sent = Some(fingerprint);
|
||||
let state = panel_state(gdd, limit, &self.expanded, self.following);
|
||||
responses.add(FrontendMessage::UpdateHistoryPanel { state });
|
||||
}
|
||||
}
|
||||
|
||||
fn active_storage<'a>(context: &'a HistoryMessageContext) -> Option<&'a GddV1> {
|
||||
context.active_document_id.and_then(|id| context.documents.get(&id)).and_then(|document| document.storage())
|
||||
}
|
||||
|
||||
fn active_storage_mut<'a>(context: &'a mut HistoryMessageContext) -> Option<&'a mut GddV1> {
|
||||
context.active_document_id.and_then(|id| context.documents.get_mut(&id)).and_then(|document| document.storage_mut())
|
||||
}
|
||||
|
||||
fn parse_rev(id: &str) -> Option<Rev> {
|
||||
id.parse::<u128>().ok().and_then(Rev::new)
|
||||
}
|
||||
|
||||
/// Where an interaction sits relative to the head.
|
||||
enum Place {
|
||||
/// On the head's line, this many interactions back.
|
||||
Line(usize),
|
||||
/// Undone above the head, this many redos forward.
|
||||
Undone(usize),
|
||||
}
|
||||
|
||||
fn place(session: &Session, rev: Rev) -> Option<Place> {
|
||||
let head = session.head_rev();
|
||||
let (kept, _) = line(session, head, None, usize::MAX);
|
||||
if let Some(steps) = interactions(&kept).iter().position(|group| group[0].id == rev) {
|
||||
return Some(Place::Line(steps));
|
||||
}
|
||||
// The stack's first entry is the farthest undone, so its line holds every undone step
|
||||
let checkpoint = *session.redo_stack().first()?;
|
||||
let (undone, _) = line(session, Some(checkpoint), head, usize::MAX);
|
||||
let groups = interactions(&undone);
|
||||
let index = groups.iter().position(|group| group[0].id == rev)?;
|
||||
Some(Place::Undone(groups.len() - index))
|
||||
}
|
||||
|
||||
/// A hash of the panel's inputs, cheap enough for every frame.
|
||||
fn fingerprint(document_id: Option<DocumentId>, gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> u64 {
|
||||
let session = gdd.session();
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
document_id.hash(&mut hasher);
|
||||
session.history_len().hash(&mut hasher);
|
||||
session.head_rev().hash(&mut hasher);
|
||||
session.redo_stack().hash(&mut hasher);
|
||||
session.hot_log().len().hash(&mut hasher);
|
||||
gdd.role().is_some().hash(&mut hasher);
|
||||
for remote in gdd.peers() {
|
||||
remote.user.hash(&mut hasher);
|
||||
remote.name.hash(&mut hasher);
|
||||
}
|
||||
for fact in gdd.metadata().facts() {
|
||||
fact.subject.hash(&mut hasher);
|
||||
fact.key.hash(&mut hasher);
|
||||
fact.stamp.hash(&mut hasher);
|
||||
}
|
||||
limit.hash(&mut hasher);
|
||||
expanded.len().hash(&mut hasher);
|
||||
following.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
fn panel_state(gdd: &GddV1, limit: usize, expanded: &HashSet<Rev>, following: Option<Rev>) -> HistoryPanelState {
|
||||
let session = gdd.session();
|
||||
let people = People {
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
peers: gdd.peers().collect(),
|
||||
};
|
||||
|
||||
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
|
||||
for delta in session.history() {
|
||||
for parent in delta.all_parents() {
|
||||
children.entry(parent).or_default().push(delta.id);
|
||||
}
|
||||
}
|
||||
|
||||
let head = session.head_rev();
|
||||
let (head_line, _) = line(session, head, None, usize::MAX);
|
||||
let head_line_revs: HashSet<Rev> = head_line.iter().map(|delta| delta.id).collect();
|
||||
|
||||
let undone = match (following, session.redo_stack().first()) {
|
||||
(None, Some(&checkpoint)) => line(session, Some(checkpoint), head, usize::MAX).0,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let (shown, more) = line(session, following.or(head), None, limit);
|
||||
let on_line: HashSet<Rev> = undone.iter().chain(&shown).map(|delta| delta.id).collect();
|
||||
|
||||
let view = View {
|
||||
children: &children,
|
||||
on_line: &on_line,
|
||||
head_line: &head_line_revs,
|
||||
head,
|
||||
people: &people,
|
||||
expanded,
|
||||
session,
|
||||
metadata: gdd.metadata(),
|
||||
};
|
||||
let undone_rows = interactions(&undone).into_iter().map(|group| view.row(&group, true));
|
||||
let shown_rows = interactions(&shown).into_iter().map(|group| view.row(&group, false));
|
||||
let rows = undone_rows.chain(shown_rows).collect();
|
||||
|
||||
// Open interactions first, then closed ones waiting to retire, newest first
|
||||
let hot_log = session.hot_log();
|
||||
let closed = session.closed_interactions();
|
||||
let in_closed: HashSet<HotOpId> = closed.iter().flat_map(|interaction| interaction.ops.iter().copied()).collect();
|
||||
let mut open_by_peer: Vec<(PeerId, Vec<&RegistryDelta>)> = Vec::new();
|
||||
for hot_op in hot_log.iter().filter(|hot_op| !in_closed.contains(&hot_op.id())) {
|
||||
match open_by_peer.iter_mut().find(|(peer, _)| *peer == hot_op.timestamp.peer) {
|
||||
Some((_, ops)) => ops.push(&hot_op.op),
|
||||
None => open_by_peer.push((hot_op.timestamp.peer, vec![&hot_op.op])),
|
||||
}
|
||||
}
|
||||
let mut progress: Vec<HistoryProgressRow> = open_by_peer.into_iter().map(|(peer, ops)| progress_row(&people, peer, &ops, true)).collect();
|
||||
for interaction in closed.iter().rev() {
|
||||
let ids: HashSet<HotOpId> = interaction.ops.iter().copied().collect();
|
||||
let ops: Vec<&RegistryDelta> = hot_log.iter().filter(|hot_op| ids.contains(&hot_op.id())).map(|hot_op| &hot_op.op).collect();
|
||||
progress.push(progress_row(&people, interaction.author, &ops, false));
|
||||
}
|
||||
|
||||
HistoryPanelState {
|
||||
rows,
|
||||
progress,
|
||||
more,
|
||||
following: following.map(|tip| tip.to_string()),
|
||||
session: gdd.role().is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The deltas from `from` back along first parents to `until` (exclusive) or the root, newest first. Stops after
|
||||
/// `limit` interaction ends, and the flag says whether it did.
|
||||
fn line(session: &Session, from: Option<Rev>, until: Option<Rev>, limit: usize) -> (Vec<Delta>, bool) {
|
||||
let mut deltas = Vec::new();
|
||||
let mut ends = 0;
|
||||
let mut current = from;
|
||||
while let Some(rev) = current
|
||||
&& Some(rev) != until
|
||||
{
|
||||
let Some(delta) = session.delta(rev) else { break };
|
||||
if delta.is_interaction_end() {
|
||||
if ends == limit {
|
||||
return (deltas, true);
|
||||
}
|
||||
ends += 1;
|
||||
}
|
||||
deltas.push(delta.clone());
|
||||
current = delta.parent;
|
||||
}
|
||||
(deltas, false)
|
||||
}
|
||||
|
||||
/// Groups a newest-first line into interactions. Newest deltas without an end, retired mid-interaction, form their own.
|
||||
fn interactions(deltas: &[Delta]) -> Vec<Vec<&Delta>> {
|
||||
let mut groups: Vec<Vec<&Delta>> = Vec::new();
|
||||
for delta in deltas {
|
||||
match groups.last_mut() {
|
||||
Some(group) if !delta.is_interaction_end() => group.push(delta),
|
||||
_ => groups.push(vec![delta]),
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
struct View<'a> {
|
||||
children: &'a HashMap<Rev, Vec<Rev>>,
|
||||
on_line: &'a HashSet<Rev>,
|
||||
head_line: &'a HashSet<Rev>,
|
||||
head: Option<Rev>,
|
||||
people: &'a People<'a>,
|
||||
expanded: &'a HashSet<Rev>,
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
}
|
||||
|
||||
impl View<'_> {
|
||||
fn row(&self, group: &[&Delta], undone: bool) -> HistoryRow {
|
||||
let closing = group[0];
|
||||
let person = self.people.person(closing.author);
|
||||
let branches = group
|
||||
.iter()
|
||||
.flat_map(|delta| self.children.get(&delta.id).into_iter().flatten())
|
||||
.filter(|child| !self.on_line.contains(child))
|
||||
.map(|&child| self.branch(child))
|
||||
.collect();
|
||||
let is_expanded = self.expanded.contains(&closing.id);
|
||||
let details = match is_expanded {
|
||||
true => group
|
||||
.iter()
|
||||
.map(|delta| {
|
||||
let author = self.people.person(delta.author);
|
||||
HistoryDeltaRow {
|
||||
id: delta.id.to_string(),
|
||||
label: describe(&delta.kind),
|
||||
author: author.name,
|
||||
color: author.color,
|
||||
time: delta.retired_at().map(|ms| ms as f64),
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
false => Vec::new(),
|
||||
};
|
||||
let given = self.metadata.rev_label(closing.id);
|
||||
HistoryRow {
|
||||
id: closing.id.to_string(),
|
||||
label: given.map(str::to_string).unwrap_or_else(|| summarize(group.iter().map(|delta| &delta.kind))),
|
||||
named: given.is_some(),
|
||||
tags: self.metadata.rev_tags(closing.id).into_iter().map(str::to_string).collect(),
|
||||
author: person.name,
|
||||
anonymous: person.anonymous,
|
||||
mine: person.mine,
|
||||
color: person.color,
|
||||
time: group.iter().find_map(|delta| delta.retired_at()).map(|ms| ms as f64),
|
||||
deltas: group.len(),
|
||||
branches,
|
||||
undone,
|
||||
abandoned: !undone && !self.head_line.contains(&closing.id),
|
||||
head: Some(closing.id) == self.head,
|
||||
expanded: is_expanded,
|
||||
details,
|
||||
}
|
||||
}
|
||||
|
||||
fn branch(&self, first: Rev) -> HistoryBranch {
|
||||
let mut tip = first;
|
||||
while let Some(&next) = self.children.get(&tip).and_then(|children| children.first()) {
|
||||
tip = next;
|
||||
}
|
||||
let (newest, _) = line(self.session, Some(tip), None, 1);
|
||||
let label = self
|
||||
.metadata
|
||||
.rev_label(tip)
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| interactions(&newest).first().map(|group| summarize(group.iter().map(|delta| &delta.kind))).unwrap_or_default());
|
||||
HistoryBranch { id: tip.to_string(), label }
|
||||
}
|
||||
}
|
||||
|
||||
fn progress_row(people: &People, peer: PeerId, ops: &[&RegistryDelta], open: bool) -> HistoryProgressRow {
|
||||
let person = people.person(peer);
|
||||
HistoryProgressRow {
|
||||
label: summarize(ops.iter().copied()),
|
||||
author: person.name,
|
||||
anonymous: person.anonymous,
|
||||
mine: person.mine,
|
||||
color: person.color,
|
||||
ops: ops.len(),
|
||||
open,
|
||||
}
|
||||
}
|
||||
|
||||
/// One line for a run of changes, most frequent kind first. Peer registrations and markers are named only when alone.
|
||||
fn summarize<'a>(kinds: impl IntoIterator<Item = &'a RegistryDelta>) -> String {
|
||||
let is_bookkeeping = |kind: &RegistryDelta| matches!(kind, RegistryDelta::RegisterPeer { .. } | RegistryDelta::Meta);
|
||||
let mut kinds: Vec<&RegistryDelta> = kinds.into_iter().collect();
|
||||
if kinds.iter().any(|kind| !is_bookkeeping(kind)) {
|
||||
kinds.retain(|kind| !is_bookkeeping(kind));
|
||||
}
|
||||
let mut counts: Vec<(String, usize)> = Vec::new();
|
||||
for kind in kinds {
|
||||
let label = describe(kind);
|
||||
match counts.iter_mut().find(|(known, _)| *known == label) {
|
||||
Some((_, count)) => *count += 1,
|
||||
None => counts.push((label, 1)),
|
||||
}
|
||||
}
|
||||
counts.sort_by_key(|(_, count)| std::cmp::Reverse(*count));
|
||||
let mut parts: Vec<String> = counts
|
||||
.iter()
|
||||
.take(2)
|
||||
.map(|(label, count)| match count {
|
||||
1 => label.clone(),
|
||||
count => format!("{label} ×{count}"),
|
||||
})
|
||||
.collect();
|
||||
if counts.len() > 2 {
|
||||
parts.push(format!("{} more", counts.len() - 2));
|
||||
}
|
||||
parts.join(", ")
|
||||
}
|
||||
|
||||
fn describe(kind: &RegistryDelta) -> String {
|
||||
match kind {
|
||||
RegistryDelta::AddNode { .. } => "Added a node".into(),
|
||||
RegistryDelta::RemoveNode { .. } => "Removed a node".into(),
|
||||
RegistryDelta::ChangeNodeInput { .. } => "Changed an input".into(),
|
||||
RegistryDelta::SetNodeInputs { .. } => "Set a node's inputs".into(),
|
||||
RegistryDelta::SetNodeImplementation { .. } => "Changed what a node does".into(),
|
||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => format!("Set node {}", delta.key),
|
||||
RegistryDelta::ChangeNodeInputAttribute { delta, .. } => format!("Set input {}", delta.key),
|
||||
RegistryDelta::SetNetworkExport { .. } => "Changed an export".into(),
|
||||
RegistryDelta::ChangeNetworkAttribute { delta, .. } => format!("Set network {}", delta.key),
|
||||
RegistryDelta::AddNetwork { .. } => "Added a network".into(),
|
||||
RegistryDelta::RemoveNetwork { .. } => "Removed a network".into(),
|
||||
RegistryDelta::AddResource { .. } => "Added a resource".into(),
|
||||
RegistryDelta::SetResourceHash { .. } => "Updated a resource".into(),
|
||||
RegistryDelta::RemoveResource { .. } => "Removed a resource".into(),
|
||||
RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => "Changed where a resource comes from".into(),
|
||||
RegistryDelta::RegisterPeer { .. } => "Joined the document".into(),
|
||||
RegistryDelta::ChangeDocumentAttribute { delta } => format!("Set document {}", delta.key),
|
||||
RegistryDelta::Merge { .. } => "Joined two lines of work".into(),
|
||||
RegistryDelta::Meta => "Marked a step".into(),
|
||||
RegistryDelta::Other(_) => "Changed something".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Names and colours authors by user id. The document's record wins, then the announced name, then the stand-in.
|
||||
struct People<'a> {
|
||||
session: &'a Session,
|
||||
metadata: &'a HistoryMetadata,
|
||||
peers: Vec<&'a RemotePeer>,
|
||||
}
|
||||
|
||||
struct Person {
|
||||
name: String,
|
||||
anonymous: bool,
|
||||
mine: bool,
|
||||
color: String,
|
||||
}
|
||||
|
||||
impl People<'_> {
|
||||
fn person(&self, peer: PeerId) -> Person {
|
||||
// A peer that never registered is its own user
|
||||
let user = self.session.user_of(peer).unwrap_or(UserId(peer.0));
|
||||
let recorded = self.metadata.user_name(user).map(str::to_string);
|
||||
let announced = || self.peers.iter().find(|remote| remote.user == user && !remote.name.is_empty()).map(|remote| remote.name.clone());
|
||||
let (name, anonymous) = match recorded.or_else(announced) {
|
||||
Some(name) => (name, false),
|
||||
None => (anonymous_name(user), true),
|
||||
};
|
||||
Person {
|
||||
name,
|
||||
anonymous,
|
||||
mine: self.session.is_mine(peer),
|
||||
color: user_color(user),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Undoing pushes each step's head, so undone steps must be read from the first entry.
|
||||
#[test]
|
||||
fn every_undone_step_stays_on_the_panel() {
|
||||
use document_container::AnyContainer;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::GddV1Layout;
|
||||
use document_graph_storage::{Network, NetworkId};
|
||||
|
||||
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), UserId(1), 1, "editor".into(), "stdlib".into()).expect("create");
|
||||
for id in 1..=3 {
|
||||
let network = Network::default();
|
||||
gdd.stage_ops([RegistryDelta::AddNetwork { id: NetworkId(id), network }]).expect("stage");
|
||||
gdd.retire_pending_interaction().expect("retire");
|
||||
}
|
||||
gdd.undo().expect("undo");
|
||||
gdd.undo().expect("undo");
|
||||
|
||||
assert_eq!(panel_state(&gdd, PAGE, &HashSet::new(), None).rows.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_of_only_markers_is_named_by_them() {
|
||||
let register = RegistryDelta::RegisterPeer { peer: PeerId(1), user: UserId(1) };
|
||||
let merge = RegistryDelta::Merge { extra_parents: Vec::new() };
|
||||
assert_eq!(summarize([&RegistryDelta::Meta, &RegistryDelta::Meta]), "Marked a step ×2");
|
||||
assert_eq!(summarize([®ister, &RegistryDelta::Meta]), "Joined the document, Marked a step");
|
||||
assert_eq!(summarize([&RegistryDelta::Meta, &merge, ®ister]), "Joined two lines of work");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
mod history_message;
|
||||
mod history_message_handler;
|
||||
pub mod utility_types;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use history_message::{HistoryMessage, HistoryMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use history_message_handler::{HistoryMessageContext, HistoryMessageHandler};
|
||||
@@ -1,72 +0,0 @@
|
||||
//! What the History panel shows, as the frontend receives it.
|
||||
|
||||
/// The panel's content, newest first. The head's line with undone interactions above it, or a followed branch's line.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryPanelState {
|
||||
pub rows: Vec<HistoryRow>,
|
||||
/// Work not yet in history. One row per person's open work and per closed interaction waiting to retire.
|
||||
pub progress: Vec<HistoryProgressRow>,
|
||||
pub more: bool,
|
||||
pub following: Option<String>,
|
||||
/// In a session, a head move affects everyone.
|
||||
pub session: bool,
|
||||
}
|
||||
|
||||
/// One interaction, a run of deltas that undo takes back together.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryRow {
|
||||
/// The rev closing the interaction, in decimal.
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub named: bool,
|
||||
pub tags: Vec<String>,
|
||||
pub author: String,
|
||||
/// `author` is a stand-in.
|
||||
pub anonymous: bool,
|
||||
pub mine: bool,
|
||||
pub color: String,
|
||||
/// Milliseconds since the Unix epoch, if the retirer recorded it.
|
||||
pub time: Option<f64>,
|
||||
pub deltas: usize,
|
||||
/// Branches off the shown line, each by its tip.
|
||||
pub branches: Vec<HistoryBranch>,
|
||||
pub undone: bool,
|
||||
/// On a followed branch, off the head's line.
|
||||
pub abandoned: bool,
|
||||
pub head: bool,
|
||||
pub expanded: bool,
|
||||
pub details: Vec<HistoryDeltaRow>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryBranch {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryDeltaRow {
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub color: String,
|
||||
pub time: Option<f64>,
|
||||
}
|
||||
|
||||
/// A person with unretired work in the room's hot log.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct HistoryProgressRow {
|
||||
pub label: String,
|
||||
pub author: String,
|
||||
pub anonymous: bool,
|
||||
pub mine: bool,
|
||||
pub color: String,
|
||||
pub ops: usize,
|
||||
/// Still being made, not closed and waiting.
|
||||
pub open: bool,
|
||||
}
|
||||
@@ -206,7 +206,7 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
|
||||
|
||||
/// Determine the size of an SVG file (the viewBox is already applied by the SVG importer so can be ignored)
|
||||
fn svg_canvas(svg: &str) -> Option<(IVec2, IVec2)> {
|
||||
usvg::Tree::from_str(&svg, &usvg::Options::default()).ok().map(|tree| {
|
||||
usvg::Tree::from_str(svg, &usvg::Options::default()).ok().map(|tree| {
|
||||
let size = tree.size();
|
||||
(glam::IVec2::ZERO, glam::IVec2::new(size.width().round() as i32, size.height().round() as i32))
|
||||
})
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::path::Path;
|
||||
const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
pub enum IngestAction {
|
||||
Open,
|
||||
/// Open a distributed file such as a demo artwork as a copy with its own session room.
|
||||
|
||||
@@ -7,7 +7,6 @@ pub mod document_migration;
|
||||
pub mod document_storage_io;
|
||||
pub mod failed_documents;
|
||||
pub mod fonts;
|
||||
pub mod history;
|
||||
pub mod ingest;
|
||||
pub mod persistent_state;
|
||||
pub mod sync;
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::history::HistoryMessage;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::sync::SyncMessage;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
@@ -23,8 +22,6 @@ pub enum PortfolioMessage {
|
||||
#[child]
|
||||
PersistentState(PersistentStateMessage),
|
||||
#[child]
|
||||
History(HistoryMessage),
|
||||
#[child]
|
||||
Sync(SyncMessage),
|
||||
#[child]
|
||||
Workspace(WorkspaceMessage),
|
||||
|
||||
@@ -60,7 +60,6 @@ pub struct PortfolioMessageHandler {
|
||||
persistent_state: PersistentStateMessageHandler,
|
||||
pub fonts: FontsMessageHandler,
|
||||
ingest: IngestMessageHandler,
|
||||
history: HistoryMessageHandler,
|
||||
sync: SyncMessageHandler,
|
||||
pub executor: NodeGraphExecutor,
|
||||
pub selection_mode: SelectionMode,
|
||||
@@ -139,14 +138,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
};
|
||||
self.ingest.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::History(message) => {
|
||||
let context = HistoryMessageContext {
|
||||
documents: &mut self.documents,
|
||||
active_document_id: self.active_document_id,
|
||||
panel_open: self.workspace.panel_layout.is_panel_visible(PanelType::History) && !self.workspace.panel_layout.focus_document,
|
||||
};
|
||||
self.history.process_message(message, responses, context);
|
||||
}
|
||||
PortfolioMessage::Sync(message) => {
|
||||
let context = SyncMessageContext {
|
||||
documents: &mut self.documents,
|
||||
@@ -431,14 +422,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
PortfolioMessage::LoadPersistedState { state } => {
|
||||
if let Some(layout) = state.workspace_layout {
|
||||
self.workspace.panel_layout = layout;
|
||||
// Add the Session panel beside the Inspector, unless the user closed it
|
||||
let panel_layout = &mut self.workspace.panel_layout;
|
||||
if !panel_layout.is_panel_present(PanelType::Session) && !panel_layout.was_closed(PanelType::Session) {
|
||||
match panel_layout.find_panel(PanelType::Inspector).and_then(|group_id| panel_layout.panel_group_mut(group_id)) {
|
||||
Some(group) => group.tabs.push(PanelType::Session),
|
||||
None => panel_layout.restore_panel(PanelType::Session),
|
||||
}
|
||||
}
|
||||
responses.add(WorkspaceMessage::UpdatePanelsLayout);
|
||||
|
||||
// Refill panels whose content was lost when the layout load remounted their frontend components
|
||||
@@ -1201,7 +1184,6 @@ impl PortfolioMessageHandler {
|
||||
persistent_state: Default::default(),
|
||||
fonts: Default::default(),
|
||||
ingest: Default::default(),
|
||||
history: Default::default(),
|
||||
sync: Default::default(),
|
||||
executor,
|
||||
selection_mode: Default::default(),
|
||||
|
||||
@@ -4,6 +4,5 @@ mod sync_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use sync_message::{SyncMessage, SyncMessageDiscriminant};
|
||||
pub(crate) use sync_message_handler::now_ms;
|
||||
#[doc(inline)]
|
||||
pub use sync_message_handler::{SyncMessageContext, SyncMessageHandler};
|
||||
@@ -37,6 +37,8 @@ pub struct SyncMessageContext<'a> {
|
||||
#[derive(Debug, Default, ExtractField)]
|
||||
pub struct SyncMessageHandler {
|
||||
pending_joins: HashMap<DocumentId, SessionToken>,
|
||||
/// Rooms joined by link until the host's state arrives, since the document's own id names another room.
|
||||
joined: HashMap<DocumentId, SessionToken>,
|
||||
polling: bool,
|
||||
incoming: HashMap<DocumentId, (u32, Incoming)>,
|
||||
connections: u32,
|
||||
@@ -78,6 +80,12 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
|
||||
if gdd.role().is_some() {
|
||||
return;
|
||||
}
|
||||
if gdd.is_shared() {
|
||||
// A reconnect leaves the clipboard and the panels alone
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
self.connect_document(document_id, gdd, preferences, responses);
|
||||
return;
|
||||
}
|
||||
document.stage_name_attribute();
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
self.host(document_id, gdd, preferences, responses);
|
||||
@@ -115,6 +123,7 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
|
||||
return;
|
||||
}
|
||||
announce_name(gdd, &preferences.user_name);
|
||||
self.joined.insert(document_id, token);
|
||||
self.attach(document_id, incoming, driver, responses);
|
||||
refresh_session_views(responses);
|
||||
} else if gdd.is_shared() && gdd.role().is_none() {
|
||||
@@ -130,6 +139,7 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
|
||||
};
|
||||
gdd.leave();
|
||||
self.detach(document_id);
|
||||
self.joined.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
SyncMessage::Fork => {
|
||||
@@ -139,6 +149,7 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
|
||||
let Some(gdd) = document.storage_mut() else { return };
|
||||
gdd.leave();
|
||||
self.detach(document_id);
|
||||
self.joined.remove(&document_id);
|
||||
// The room derives from the manifest's document id, so a fresh id is a fresh room
|
||||
if let Err(error) = gdd.update_manifest(|manifest| manifest.document_id = generate_uuid()) {
|
||||
log::error!("Forking the session failed: {error}");
|
||||
@@ -168,14 +179,14 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
|
||||
}
|
||||
SyncMessage::Poll => {
|
||||
let cursor = active_cursor(documents, active_document_id, ipp, viewport, tools);
|
||||
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
|
||||
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, None, responses);
|
||||
}
|
||||
SyncMessage::Wake { document_id, generation } => {
|
||||
if !self.is_current(document_id, generation) {
|
||||
return;
|
||||
}
|
||||
let cursor = active_cursor(documents, active_document_id, ipp, viewport, tools);
|
||||
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, responses);
|
||||
self.poll(documents, active_document_id, resource_storage.resources_mut(), preferences, cursor, Some(document_id), responses);
|
||||
// The poll drained the inbox, so the next arrival wakes the next poll
|
||||
self.arm(document_id, responses);
|
||||
}
|
||||
@@ -219,7 +230,7 @@ impl SyncMessageHandler {
|
||||
}
|
||||
|
||||
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
|
||||
let token = SessionToken::for_document(gdd.manifest().document_id);
|
||||
let token = self.joined.get(&document_id).copied().unwrap_or_else(|| SessionToken::for_document(gdd.manifest().document_id));
|
||||
let (room, driver) = Room::connect(&token.signaling_url(DEFAULT_SIGNALING_SERVER));
|
||||
let incoming = room.incoming();
|
||||
if let Err(error) = gdd.connect(room, UserId(preferences.user_id)) {
|
||||
@@ -249,6 +260,7 @@ impl SyncMessageHandler {
|
||||
self.reconnect_at.remove(&document_id);
|
||||
self.retry_at.remove(&document_id);
|
||||
self.undecided_since.remove(&document_id);
|
||||
self.decoding.retain(|&(id, _)| id != document_id);
|
||||
}
|
||||
|
||||
fn is_current(&self, document_id: DocumentId, generation: u32) -> bool {
|
||||
@@ -277,6 +289,8 @@ impl SyncMessageHandler {
|
||||
});
|
||||
}
|
||||
|
||||
/// Polls `only`, or every document when it is `None`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn poll(
|
||||
&mut self,
|
||||
documents: &mut HashMap<DocumentId, DocumentMessageHandler>,
|
||||
@@ -284,9 +298,10 @@ impl SyncMessageHandler {
|
||||
resources: ResourcesHandle,
|
||||
preferences: &PreferencesMessageHandler,
|
||||
active_cursor: Option<CursorPosition>,
|
||||
only: Option<DocumentId>,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) {
|
||||
for (&document_id, document) in documents.iter_mut() {
|
||||
for (&document_id, document) in documents.iter_mut().filter(|(id, _)| only.is_none_or(|only| only == **id)) {
|
||||
let cursor = (Some(document_id) == active_document_id).then(|| active_cursor.clone()).flatten();
|
||||
self.poll_document(document_id, document, &resources, preferences, cursor, responses);
|
||||
}
|
||||
@@ -337,7 +352,9 @@ impl SyncMessageHandler {
|
||||
None => return,
|
||||
Some(Role::Undecided) => {
|
||||
let since = *self.undecided_since.entry(document_id).or_insert_with(now_ms);
|
||||
if now_ms() - since >= ROLE_GRACE_MS && gdd.decide_role().is_some() {
|
||||
// A joiner holds nothing yet, so it waits for a host instead of taking the room
|
||||
let may_host = !self.joined.contains_key(&document_id);
|
||||
if may_host && now_ms() - since >= ROLE_GRACE_MS && gdd.decide_role().is_some() {
|
||||
self.undecided_since.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
@@ -370,6 +387,7 @@ impl SyncMessageHandler {
|
||||
match event {
|
||||
Event::Synced => {
|
||||
log::debug!("Synced with the host, applying its state");
|
||||
self.joined.remove(&document_id);
|
||||
refresh_session_views(responses);
|
||||
self.dirty.insert(document_id);
|
||||
self.fit_after_sync.insert(document_id);
|
||||
@@ -397,10 +415,7 @@ impl SyncMessageHandler {
|
||||
refresh_session_views(responses);
|
||||
}
|
||||
Event::PeerLeft { .. } | Event::ProfileChanged { .. } => refresh_session_views(responses),
|
||||
Event::MetadataChanged => {
|
||||
refresh_session_views(responses);
|
||||
responses.add(HistoryMessage::Refresh);
|
||||
}
|
||||
Event::MetadataChanged => refresh_session_views(responses),
|
||||
Event::CursorMoved { .. } => {}
|
||||
}
|
||||
}
|
||||
@@ -414,11 +429,11 @@ impl SyncMessageHandler {
|
||||
self.dirty.remove(&document_id);
|
||||
continue;
|
||||
};
|
||||
let Some(gdd) = document.storage() else { continue };
|
||||
let missing = SyncTarget::missing_resources(gdd).len();
|
||||
if self.retry_at.get(&document_id).is_some_and(|&due| now_ms() < due) {
|
||||
continue;
|
||||
}
|
||||
let Some(gdd) = document.storage() else { continue };
|
||||
let missing = SyncTarget::missing_resources(gdd).len();
|
||||
let transaction = document.network_interface.transaction_status();
|
||||
if missing > 0 || transaction != TransactionStatus::Finished {
|
||||
self.wait(document_id, format!("missing {missing} transaction {transaction:?}"));
|
||||
@@ -500,7 +515,7 @@ fn load_resource_future(document_id: DocumentId, to: TransportPeerId, hash: Reso
|
||||
future.into()
|
||||
}
|
||||
|
||||
pub(crate) fn now_ms() -> f64 {
|
||||
fn now_ms() -> f64 {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
js_sys::Date::now()
|
||||
|
||||
@@ -3,7 +3,7 @@ const DOCUMENT_PANEL_SHARE: f64 = 0.8;
|
||||
/// Proportional share for each side when neither (or both) contain the document panel.
|
||||
const EQUAL_PANEL_SHARE: f64 = 0.5;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PanelType {
|
||||
Welcome,
|
||||
@@ -13,7 +13,6 @@ pub enum PanelType {
|
||||
Inspector,
|
||||
Data,
|
||||
Session,
|
||||
History,
|
||||
}
|
||||
|
||||
impl From<String> for PanelType {
|
||||
@@ -25,7 +24,6 @@ impl From<String> for PanelType {
|
||||
"Inspector" | "Properties" => PanelType::Inspector,
|
||||
"Data" => PanelType::Data,
|
||||
"Session" => PanelType::Session,
|
||||
"History" => PanelType::History,
|
||||
_ => panic!("Unknown panel type: {value}"),
|
||||
}
|
||||
}
|
||||
@@ -33,7 +31,7 @@ impl From<String> for PanelType {
|
||||
|
||||
impl PanelType {
|
||||
pub fn non_document_panels() -> &'static [PanelType] {
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session, PanelType::History]
|
||||
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +42,7 @@ impl PanelType {
|
||||
pub struct PanelGroupId(pub u64);
|
||||
|
||||
/// Which edge of a panel group to split on when docking a dragged panel.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DockingSplitDirection {
|
||||
Left,
|
||||
@@ -256,10 +254,6 @@ impl WorkspacePanelLayout {
|
||||
});
|
||||
}
|
||||
|
||||
pub fn was_closed(&self, panel_type: PanelType) -> bool {
|
||||
self.saved_positions.iter().any(|saved| saved.panel_type == panel_type)
|
||||
}
|
||||
|
||||
/// Restore a panel to its previous position if available, otherwise to its default position.
|
||||
pub fn restore_panel(&mut self, panel_type: PanelType) {
|
||||
let saved = self.saved_positions.iter().find(|s| s.panel_type == panel_type).copied();
|
||||
@@ -309,11 +303,10 @@ impl WorkspacePanelLayout {
|
||||
/// - Data: below the document in the left column (root child 0)
|
||||
/// - Inspector: top of the right column (root child 1)
|
||||
/// - Layers: bottom of the right column (root child 1)
|
||||
/// - Session, History: a tab beside the Inspector or Layers, otherwise placed like that panel
|
||||
/// - Session: a tab in the Inspector's group, otherwise placed like the Inspector
|
||||
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
|
||||
let beside = match panel_type {
|
||||
PanelType::Session => Some(PanelType::Inspector),
|
||||
PanelType::History => Some(PanelType::Layers),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(beside) = beside
|
||||
@@ -340,7 +333,7 @@ impl WorkspacePanelLayout {
|
||||
let (root_child_index, insert_at_end) = match panel_type {
|
||||
PanelType::Data => (0, true), // Left column, after document
|
||||
PanelType::Inspector | PanelType::Session => (1, false), // Right column, at top
|
||||
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
|
||||
PanelType::Layers => (1, true), // Right column, at bottom
|
||||
_ => (1, true),
|
||||
};
|
||||
|
||||
|
||||
@@ -35,7 +35,6 @@ pub enum WorkspaceMessage {
|
||||
},
|
||||
ToggleDataPanelOpen,
|
||||
ToggleSessionPanelOpen,
|
||||
ToggleHistoryPanelOpen,
|
||||
ToggleInspectorOpen,
|
||||
ToggleLayersPanelOpen,
|
||||
UpdatePanelsLayout,
|
||||
|
||||
@@ -296,14 +296,6 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
|
||||
let panel_type = PanelType::Session;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::ToggleHistoryPanelOpen => {
|
||||
if self.panel_layout.focus_document {
|
||||
return;
|
||||
}
|
||||
|
||||
let panel_type = PanelType::History;
|
||||
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
|
||||
}
|
||||
WorkspaceMessage::UpdatePanelsLayout => {
|
||||
let panel_layout = match self.panel_layout.focus_document {
|
||||
true => self.panel_layout.document_only_layout(),
|
||||
@@ -420,7 +412,7 @@ impl WorkspaceMessageHandler {
|
||||
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
|
||||
PanelType::Data => &[LayoutTarget::DataPanel, LayoutTarget::DataPanelContext, LayoutTarget::DataPanelPath],
|
||||
PanelType::Session => &[LayoutTarget::SessionPanel],
|
||||
PanelType::Document | PanelType::Welcome | PanelType::History => return,
|
||||
PanelType::Document | PanelType::Welcome => return,
|
||||
};
|
||||
|
||||
for &layout_target in targets {
|
||||
@@ -449,9 +441,6 @@ impl WorkspaceMessageHandler {
|
||||
PanelType::Session => {
|
||||
responses.add(SyncMessage::RefreshPanel);
|
||||
}
|
||||
PanelType::History => {
|
||||
responses.add(HistoryMessage::Refresh);
|
||||
}
|
||||
PanelType::Document | PanelType::Welcome => {
|
||||
// Re-send the welcome screen buttons layout to repopulate after a remount
|
||||
if has_no_documents {
|
||||
|
||||
@@ -39,6 +39,9 @@ pub enum PreferencesMessage {
|
||||
SaveAsGdd {
|
||||
enabled: bool,
|
||||
},
|
||||
SaveWithHistory {
|
||||
enabled: bool,
|
||||
},
|
||||
ToggleShowStoragePreferences,
|
||||
UserName {
|
||||
name: String,
|
||||
|
||||
@@ -23,6 +23,7 @@ pub struct PreferencesMessageHandler {
|
||||
pub disable_ui_acceleration: bool,
|
||||
pub validate_storage_round_trip: bool,
|
||||
pub save_as_gdd: bool,
|
||||
pub save_with_history: bool,
|
||||
pub show_storage_preferences: bool,
|
||||
/// This person's id across documents. A decimal string, since the browser's JSON loses 64-bit precision.
|
||||
#[serde(with = "u64_as_string")]
|
||||
@@ -59,6 +60,7 @@ impl Default for PreferencesMessageHandler {
|
||||
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
|
||||
validate_storage_round_trip: false,
|
||||
save_as_gdd: false,
|
||||
save_with_history: false,
|
||||
show_storage_preferences: false,
|
||||
user_id: crate::application::generate_uuid(),
|
||||
user_name: String::new(),
|
||||
@@ -99,8 +101,10 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
responses.add(ToolMessage::RefreshToolShelf);
|
||||
}
|
||||
PreferencesMessage::ResetToDefaults => {
|
||||
// The identity isn't a setting, and documents would record the cleared name
|
||||
let preferences = Self {
|
||||
user_id: self.user_id,
|
||||
user_name: self.user_name.clone(),
|
||||
..Self::default()
|
||||
};
|
||||
responses.add(PreferencesMessage::Load { preferences });
|
||||
@@ -147,6 +151,9 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
|
||||
PreferencesMessage::SaveAsGdd { enabled } => {
|
||||
self.save_as_gdd = enabled;
|
||||
}
|
||||
PreferencesMessage::SaveWithHistory { enabled } => {
|
||||
self.save_with_history = enabled;
|
||||
}
|
||||
PreferencesMessage::ToggleShowStoragePreferences => {
|
||||
self.show_storage_preferences = !self.show_storage_preferences;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
|
||||
@@ -33,7 +33,6 @@ pub use crate::messages::portfolio::document::resource::{ResourceMessage, Resour
|
||||
pub use crate::messages::portfolio::document::{DocumentMessage, DocumentMessageContext, DocumentMessageDiscriminant, DocumentMessageHandler};
|
||||
pub use crate::messages::portfolio::failed_documents::{FailedDocumentsMessage, FailedDocumentsMessageContext, FailedDocumentsMessageDiscriminant, FailedDocumentsMessageHandler};
|
||||
pub use crate::messages::portfolio::fonts::{FontsMessage, FontsMessageContext, FontsMessageDiscriminant, FontsMessageHandler};
|
||||
pub use crate::messages::portfolio::history::{HistoryMessage, HistoryMessageContext, HistoryMessageDiscriminant, HistoryMessageHandler};
|
||||
pub use crate::messages::portfolio::ingest::{IngestMessage, IngestMessageContext, IngestMessageDiscriminant, IngestMessageHandler};
|
||||
pub use crate::messages::portfolio::persistent_state::{PersistentStateMessage, PersistentStateMessageContext, PersistentStateMessageDiscriminant, PersistentStateMessageHandler};
|
||||
pub use crate::messages::portfolio::sync::{SyncMessage, SyncMessageContext, SyncMessageDiscriminant, SyncMessageHandler};
|
||||
|
||||
@@ -448,7 +448,7 @@ impl NodeGraphExecutor {
|
||||
|
||||
let mut all_dropped_thumbnails = Vec::new();
|
||||
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
|
||||
while let Some(response) = results.next() {
|
||||
for response in results.by_ref() {
|
||||
match response {
|
||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||
let ExecutionResponse {
|
||||
@@ -1236,3 +1236,71 @@ mod test {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod raster_path_tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId};
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::raster_nodes::adjustments::invert;
|
||||
use graphene_std::raster_nodes::dehaze::dehaze;
|
||||
use graphene_std::raster_nodes::filter::median_filter;
|
||||
use graphene_std::raster_nodes::std_nodes::eager;
|
||||
use graphene_std::raster_types::{CPU, Raster};
|
||||
|
||||
/// A document whose image feeds `nodes` in turn, ending in the export.
|
||||
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) {
|
||||
editor.new_document().await;
|
||||
editor.create_raster_image(Image::new(4, 4, color), None).await;
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
||||
.map(|(id, _)| *id)
|
||||
.expect("the pasted image should be an Image node");
|
||||
|
||||
let mut previous = OutputConnector::node(image, 0);
|
||||
for (index, identifier) in nodes.iter().enumerate() {
|
||||
let id: NodeId = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
|
||||
let input = InputConnector::node_at_index(id, 0);
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
|
||||
previous = OutputConnector::node(id, 0);
|
||||
}
|
||||
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_reaches_a_filter_as_a_cpu_raster() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::WHITE, &[median_filter::IDENTIFIER]).await;
|
||||
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the image should render through Median");
|
||||
let _: Item<Raster<CPU>> = instrumented
|
||||
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the image should arrive at Median as a CPU raster");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_feeding_dehaze_renders() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
|
||||
|
||||
// A compile error or a failed render fails this
|
||||
editor.eval_graph_uninstrumented().await.expect("the image should render through Dehaze");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_image_uploaded_by_eager_renders_through_a_kernel() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
image_through(&mut editor, Color::WHITE, &[eager::IDENTIFIER, invert::IDENTIFIER]).await;
|
||||
|
||||
// A compile error or a failed render fails this
|
||||
editor.eval_graph_uninstrumented().await.expect("the image should render through Eager and Invert");
|
||||
}
|
||||
}
|
||||
+28
-10
@@ -66,22 +66,30 @@ impl EditorTestUtils {
|
||||
}
|
||||
|
||||
/// Submit an evaluation to the executor, run the runtime, and process the results.
|
||||
/// With `instrument`, the graph is compiled with the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
|
||||
///
|
||||
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
|
||||
async fn eval_graph_once(&mut self) -> Result<Instrumented, TestGraphError> {
|
||||
async fn eval_graph_once(&mut self, instrument: bool) -> Result<Option<Instrumented>, TestGraphError> {
|
||||
let portfolio = &mut self.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).unwrap();
|
||||
|
||||
let instrumented = match executor.update_node_graph_instrumented(document) {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
|
||||
let instrumented = if instrument {
|
||||
let instrumented = match executor.update_node_graph_instrumented(document) {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
|
||||
};
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
|
||||
}
|
||||
Some(instrumented)
|
||||
} else {
|
||||
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO) {
|
||||
return Err(TestGraphError::Other(format!("submit_node_graph_evaluation failed\n\n{e}")));
|
||||
}
|
||||
None
|
||||
};
|
||||
|
||||
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
|
||||
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
|
||||
}
|
||||
self.runtime.update();
|
||||
self.runtime.run().await;
|
||||
|
||||
@@ -105,16 +113,26 @@ impl EditorTestUtils {
|
||||
|
||||
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
|
||||
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
|
||||
let instrumented = self.eval_graph_repeatedly(true).await?;
|
||||
Ok(instrumented.expect("an instrumented evaluation returns its monitors"))
|
||||
}
|
||||
|
||||
/// Like [`Self::eval_graph_until_finished`], but compiles the graph without monitors so that it can contain asynchronous nodes.
|
||||
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), TestGraphError> {
|
||||
self.eval_graph_repeatedly(false).await.map(|_| ())
|
||||
}
|
||||
|
||||
async fn eval_graph_repeatedly(&mut self, instrument: bool) -> Result<Option<Instrumented>, TestGraphError> {
|
||||
const MAX_ITERATIONS: usize = 16;
|
||||
for _iteration in 0..MAX_ITERATIONS {
|
||||
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
|
||||
let result = self.eval_graph_once().await?;
|
||||
let result = self.eval_graph_once(instrument).await?;
|
||||
// If there have been no other executions queued (other than the one we just queued ourselves above) then finish
|
||||
if execution_id + 1 >= self.portfolio_message_handler().executor.current_execution_id() {
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
return Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")));
|
||||
Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")))
|
||||
}
|
||||
|
||||
pub async fn handle_message(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
import { createDialogStore, destroyDialogStore } from "/src/stores/dialog";
|
||||
import { createDocumentStore, destroyDocumentStore } from "/src/stores/document";
|
||||
import { createFullscreenStore, destroyFullscreenStore } from "/src/stores/fullscreen";
|
||||
import { createHistoryStore, destroyHistoryStore } from "/src/stores/history";
|
||||
import { createMathExpressionStore, destroyMathExpressionStore } from "/src/stores/math-expression";
|
||||
import { createNodeGraphStore, destroyNodeGraphStore } from "/src/stores/node-graph";
|
||||
import { createPortfolioStore, destroyPortfolioStore } from "/src/stores/portfolio";
|
||||
@@ -32,7 +31,6 @@
|
||||
document: createDocumentStore(subscriptions),
|
||||
fullscreen: createFullscreenStore(subscriptions),
|
||||
nodeGraph: createNodeGraphStore(subscriptions),
|
||||
history: createHistoryStore(subscriptions),
|
||||
portfolio: createPortfolioStore(subscriptions, editor),
|
||||
appWindow: createAppWindowStore(subscriptions),
|
||||
colorPicker: createColorPickerStore(subscriptions),
|
||||
@@ -63,7 +61,6 @@
|
||||
destroyDocumentStore();
|
||||
destroyFullscreenStore();
|
||||
destroyNodeGraphStore();
|
||||
destroyHistoryStore();
|
||||
destroyPortfolioStore();
|
||||
destroyAppWindowStore();
|
||||
destroyColorPickerStore();
|
||||
|
||||
@@ -1,405 +0,0 @@
|
||||
<script lang="ts">
|
||||
import { getContext, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
|
||||
import TextInput from "/src/components/widgets/inputs/TextInput.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import type { HistoryStore } from "/src/stores/history";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const history = getContext<HistoryStore>("history");
|
||||
|
||||
// Relative times age while the panel stays open
|
||||
let now = Date.now();
|
||||
const clock = setInterval(() => (now = Date.now()), 15_000);
|
||||
onDestroy(() => clearInterval(clock));
|
||||
|
||||
// Relative for the past week, a date before that
|
||||
function when(ms: number | undefined, now: number): string {
|
||||
if (ms === undefined) return "";
|
||||
const seconds = Math.max(0, Math.round((now - ms) / 1000));
|
||||
if (seconds < 45) return "just now";
|
||||
const minutes = Math.round(seconds / 60);
|
||||
if (minutes < 60) return `${minutes} min ago`;
|
||||
const hours = Math.round(minutes / 60);
|
||||
if (hours < 24) return `${hours} h ago`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 7) return days === 1 ? "yesterday" : `${days} days ago`;
|
||||
return new Date(ms).toLocaleDateString();
|
||||
}
|
||||
|
||||
function count(n: number, one: string, many: string): string {
|
||||
return `${n} ${n === 1 ? one : many}`;
|
||||
}
|
||||
|
||||
function authorLabel(row: { author: string; mine: boolean }): string {
|
||||
return row.mine ? `${row.author} (you)` : row.author;
|
||||
}
|
||||
|
||||
let renamingId: string | undefined = undefined;
|
||||
let taggingId: string | undefined = undefined;
|
||||
|
||||
function commitName(id: string, label: string) {
|
||||
editor.renameHistoryInteraction(id, label);
|
||||
renamingId = undefined;
|
||||
}
|
||||
|
||||
function commitTag(id: string, tag: string) {
|
||||
if (tag.trim()) editor.tagHistoryInteraction(id, tag, true);
|
||||
taggingId = undefined;
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutCol class="history-panel">
|
||||
{#if $history.following}
|
||||
<LayoutRow class="following">
|
||||
<TextLabel>Viewing a branch</TextLabel>
|
||||
<TextButton label="Back to now" action={() => editor.followHistoryBranch(undefined)} />
|
||||
</LayoutRow>
|
||||
{/if}
|
||||
<LayoutCol class="body" scrollableY={true}>
|
||||
{#each $history.progress as row}
|
||||
<div class="row progress">
|
||||
<span class="rail"><span class="dot hollow" style:border-color={row.color}></span></span>
|
||||
<div class="text">
|
||||
<span class="label">{row.label || (row.open ? "In progress" : "Waiting to enter history")}</span>
|
||||
<span class="meta">
|
||||
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
|
||||
· {count(row.ops, "change", "changes")}
|
||||
· {row.open ? "in progress" : "not yet in history"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#each $history.rows as row (row.id)}
|
||||
<div class="row" class:head={row.head} class:undone={row.undone} class:abandoned={row.abandoned}>
|
||||
<button
|
||||
class="expand"
|
||||
class:expanded={row.expanded}
|
||||
data-tooltip-label={row.expanded ? "Hide the changes" : "Show the changes"}
|
||||
on:click={() => editor.expandHistoryInteraction(row.id, !row.expanded)}
|
||||
></button>
|
||||
<span class="rail"><span class="dot" style:background={row.color}></span></span>
|
||||
<div class="text">
|
||||
{#if renamingId === row.id}
|
||||
<TextInput value={row.named ? row.label : ""} placeholder={row.label} on:commitText={({ detail }) => commitName(row.id, detail)} />
|
||||
{:else}
|
||||
<span class="label" class:named={row.named}>{row.label}</span>
|
||||
{/if}
|
||||
<span class="meta">
|
||||
<span class="author" class:anonymous={row.anonymous}>{authorLabel(row)}</span>
|
||||
{#if row.time}· {when(row.time, now)}{/if}
|
||||
· {count(row.deltas, "change", "changes")}
|
||||
</span>
|
||||
{#if row.tags.length > 0 || taggingId === row.id}
|
||||
<span class="tags">
|
||||
{#each row.tags as tag (tag)}
|
||||
<span class="tag">{tag}<button class="remove" data-tooltip-label="Remove the tag" on:click={() => editor.tagHistoryInteraction(row.id, tag, false)}>×</button></span>
|
||||
{/each}
|
||||
{#if taggingId === row.id}
|
||||
<TextInput value="" placeholder="Tag name" narrow={true} on:commitText={({ detail }) => commitTag(row.id, detail)} />
|
||||
{/if}
|
||||
</span>
|
||||
{/if}
|
||||
{#if row.branches.length > 0}
|
||||
<span class="branches">
|
||||
{#each row.branches as branch (branch.id)}
|
||||
<button class="branch" data-tooltip-label="Show this branch" on:click={() => editor.followHistoryBranch(branch.id)}>↳ {branch.label}</button>
|
||||
{/each}
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<span class="actions">
|
||||
<button class="small" data-tooltip-label="Name this step" on:click={() => (renamingId = renamingId === row.id ? undefined : row.id)}>Name</button>
|
||||
<button class="small" data-tooltip-label="Tag this step" on:click={() => (taggingId = taggingId === row.id ? undefined : row.id)}>Tag</button>
|
||||
{#if row.undone || row.abandoned}
|
||||
<IconButton
|
||||
icon="HistoryRedo"
|
||||
size={16}
|
||||
tooltipLabel="Bring back"
|
||||
tooltipDescription={row.undone ? "Redo up to and including this step." : "Do this step again on top of the current line."}
|
||||
action={() => editor.bringBackHistoryInteraction(row.id)}
|
||||
/>
|
||||
{:else}
|
||||
{#if !row.head}
|
||||
<IconButton
|
||||
icon="HistoryUndo"
|
||||
size={16}
|
||||
tooltipLabel="Go back to here"
|
||||
tooltipDescription={$history.session ? "Move everyone's document back to this step. The steps since stay as a branch." : "Undo up to this step."}
|
||||
action={() => editor.goBackToHistoryInteraction(row.id)}
|
||||
/>
|
||||
{/if}
|
||||
<IconButton
|
||||
icon="Trash"
|
||||
size={16}
|
||||
tooltipLabel="Remove this step"
|
||||
tooltipDescription="Take this step out and keep the ones after it."
|
||||
action={() => editor.removeHistoryInteraction(row.id)}
|
||||
/>
|
||||
{/if}
|
||||
</span>
|
||||
{#if row.head}<span class="marker">Now</span>{/if}
|
||||
{#if row.undone}<span class="marker">Undone</span>{/if}
|
||||
{#if row.abandoned}<span class="marker">Branch</span>{/if}
|
||||
</div>
|
||||
{#if row.expanded}
|
||||
{#each row.details as delta (delta.id)}
|
||||
<div class="row delta" class:undone={row.undone}>
|
||||
<span class="rail"><span class="tick"></span></span>
|
||||
<div class="text">
|
||||
<span class="label">{delta.label}</span>
|
||||
<span class="meta">
|
||||
<span class="author">{delta.author}</span>
|
||||
{#if delta.time}· {when(delta.time, now)}{/if}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{/if}
|
||||
{/each}
|
||||
{#if $history.more}
|
||||
<div class="more">
|
||||
<TextButton label="Show older" action={() => editor.loadMoreHistory()} />
|
||||
</div>
|
||||
{/if}
|
||||
{#if $history.rows.length === 0 && $history.progress.length === 0}
|
||||
<TextLabel italic={true}>Nothing in the history yet.</TextLabel>
|
||||
{/if}
|
||||
</LayoutCol>
|
||||
</LayoutCol>
|
||||
|
||||
<style lang="scss">
|
||||
.history-panel {
|
||||
flex-grow: 1;
|
||||
padding: 4px 0;
|
||||
|
||||
.following {
|
||||
flex: 0 0 auto;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 0 8px 4px 8px;
|
||||
}
|
||||
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
min-height: 32px;
|
||||
padding: 2px 8px 2px 4px;
|
||||
gap: 6px;
|
||||
|
||||
&.head {
|
||||
background: var(--color-3-darkgray);
|
||||
}
|
||||
|
||||
&.undone,
|
||||
&.abandoned {
|
||||
.rail,
|
||||
.text {
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
&.delta {
|
||||
min-height: 24px;
|
||||
padding-left: 28px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.actions {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
visibility: hidden;
|
||||
|
||||
.small {
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
background: var(--color-4-dimgray);
|
||||
color: var(--color-c-brightgray);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background: var(--color-5-dullgray);
|
||||
color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&:hover .actions {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.expand {
|
||||
flex: 0 0 auto;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 5px;
|
||||
top: 4px;
|
||||
border: 4px solid transparent;
|
||||
border-left: 5px solid var(--color-8-uppergray);
|
||||
}
|
||||
|
||||
&.expanded::after {
|
||||
left: 3px;
|
||||
top: 6px;
|
||||
border: 4px solid transparent;
|
||||
border-top: 5px solid var(--color-8-uppergray);
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
border-left-color: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
&.expanded:hover::after {
|
||||
border-left-color: transparent;
|
||||
border-top-color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
|
||||
.rail {
|
||||
flex: 0 0 12px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
|
||||
&.hollow {
|
||||
background: none;
|
||||
border: 2px solid;
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.tick {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-6-lowergray);
|
||||
}
|
||||
}
|
||||
|
||||
.text {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 16px;
|
||||
|
||||
.label {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.meta {
|
||||
color: var(--color-a-softgray);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
.anonymous {
|
||||
font-style: italic;
|
||||
}
|
||||
}
|
||||
|
||||
.label.named {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-top: 2px;
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
padding: 0 2px 0 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--color-accent-hover);
|
||||
color: var(--color-f-white);
|
||||
|
||||
.remove {
|
||||
border: none;
|
||||
background: none;
|
||||
color: inherit;
|
||||
padding: 0 2px;
|
||||
cursor: pointer;
|
||||
line-height: 14px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.branches {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 2px;
|
||||
|
||||
.branch {
|
||||
font-size: 11px;
|
||||
line-height: 14px;
|
||||
padding: 0 4px;
|
||||
border: none;
|
||||
border-radius: 2px;
|
||||
background: var(--color-4-dimgray);
|
||||
color: var(--color-c-brightgray);
|
||||
cursor: pointer;
|
||||
max-width: 100%;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
|
||||
&:hover {
|
||||
background: var(--color-5-dullgray);
|
||||
color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.marker {
|
||||
flex: 0 0 auto;
|
||||
font-size: 10px;
|
||||
line-height: 14px;
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--color-5-dullgray);
|
||||
color: var(--color-e-nearwhite);
|
||||
}
|
||||
}
|
||||
|
||||
.more {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
padding: 8px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -4,7 +4,6 @@
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import Data from "/src/components/panels/Data.svelte";
|
||||
import Document from "/src/components/panels/Document.svelte";
|
||||
import History from "/src/components/panels/History.svelte";
|
||||
import Inspector from "/src/components/panels/Inspector.svelte";
|
||||
import Layers from "/src/components/panels/Layers.svelte";
|
||||
import Session from "/src/components/panels/Session.svelte";
|
||||
@@ -19,7 +18,6 @@
|
||||
Welcome,
|
||||
Document,
|
||||
Layers,
|
||||
History,
|
||||
Inspector,
|
||||
Data,
|
||||
Session,
|
||||
|
||||
+14
-4
@@ -228,6 +228,7 @@ import NodeInvertTransform from "/../branding/assets/16x16-nodes/node-invert-tra
|
||||
import NodeInvert from "/../branding/assets/16x16-nodes/node-invert.svg";
|
||||
import NodeIsNonzero from "/../branding/assets/16x16-nodes/node-is-nonzero.svg";
|
||||
import NodeItemAtIndex from "/../branding/assets/16x16-nodes/node-item-at-index.svg";
|
||||
import NodeIterate from "/../branding/assets/16x16-nodes/node-iterate.svg";
|
||||
import NodeJitterPoints from "/../branding/assets/16x16-nodes/node-jitter-points.svg";
|
||||
import NodeLeastCommonMultiple from "/../branding/assets/16x16-nodes/node-least-common-multiple.svg";
|
||||
import NodeLerp from "/../branding/assets/16x16-nodes/node-lerp.svg";
|
||||
@@ -247,8 +248,10 @@ import NodeMandelbrot from "/../branding/assets/16x16-nodes/node-mandelbrot.svg"
|
||||
import NodeMapPoints from "/../branding/assets/16x16-nodes/node-map-points.svg";
|
||||
import NodeMap from "/../branding/assets/16x16-nodes/node-map.svg";
|
||||
import NodeMask from "/../branding/assets/16x16-nodes/node-mask.svg";
|
||||
import NodeMathF from "/../branding/assets/16x16-nodes/node-math-f.svg";
|
||||
import NodeMathFx from "/../branding/assets/16x16-nodes/node-math-fx.svg";
|
||||
import NodeMathAggregate from "/../branding/assets/16x16-nodes/node-math-aggregate.svg";
|
||||
import NodeMathFormula from "/../branding/assets/16x16-nodes/node-math-formula.svg";
|
||||
import NodeMathFunction from "/../branding/assets/16x16-nodes/node-math-function.svg";
|
||||
import NodeMathRunning from "/../branding/assets/16x16-nodes/node-math-running.svg";
|
||||
import NodeMax from "/../branding/assets/16x16-nodes/node-max.svg";
|
||||
import NodeMaximum from "/../branding/assets/16x16-nodes/node-maximum.svg";
|
||||
import NodeMedianFilter from "/../branding/assets/16x16-nodes/node-median-filter.svg";
|
||||
@@ -270,6 +273,7 @@ import NodeNumbersToVec2 from "/../branding/assets/16x16-nodes/node-numbers-to-v
|
||||
import NodeOffsetPath from "/../branding/assets/16x16-nodes/node-offset-path.svg";
|
||||
import NodeOffsetPoints from "/../branding/assets/16x16-nodes/node-offset-points.svg";
|
||||
import NodeOpacity from "/../branding/assets/16x16-nodes/node-opacity.svg";
|
||||
import NodeOpenEnds from "/../branding/assets/16x16-nodes/node-open-ends.svg";
|
||||
import NodeOriginsToPolyline from "/../branding/assets/16x16-nodes/node-origins-to-polyline.svg";
|
||||
import NodePackStrips from "/../branding/assets/16x16-nodes/node-pack-strips.svg";
|
||||
import NodePassthrough from "/../branding/assets/16x16-nodes/node-passthrough.svg";
|
||||
@@ -373,6 +377,7 @@ import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
|
||||
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
|
||||
import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg";
|
||||
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
|
||||
import NodeUploadTexture from "/../branding/assets/16x16-nodes/node-upload-texture.svg";
|
||||
import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg";
|
||||
import NodeVaryStrokeColors from "/../branding/assets/16x16-nodes/node-vary-stroke-colors.svg";
|
||||
import NodeVec2ToNumbers from "/../branding/assets/16x16-nodes/node-vec2-to-numbers.svg";
|
||||
@@ -506,6 +511,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeInvertTransform: { svg: NodeInvertTransform, size: 16 },
|
||||
NodeIsNonzero: { svg: NodeIsNonzero, size: 16 },
|
||||
NodeItemAtIndex: { svg: NodeItemAtIndex, size: 16 },
|
||||
NodeIterate: { svg: NodeIterate, size: 16 },
|
||||
NodeJitterPoints: { svg: NodeJitterPoints, size: 16 },
|
||||
NodeLeastCommonMultiple: { svg: NodeLeastCommonMultiple, size: 16 },
|
||||
NodeLerp: { svg: NodeLerp, size: 16 },
|
||||
@@ -525,8 +531,10 @@ export const ICON_16X16_NODES = {
|
||||
NodeMap: { svg: NodeMap, size: 16 },
|
||||
NodeMapPoints: { svg: NodeMapPoints, size: 16 },
|
||||
NodeMask: { svg: NodeMask, size: 16 },
|
||||
NodeMathF: { svg: NodeMathF, size: 16 },
|
||||
NodeMathFx: { svg: NodeMathFx, size: 16 },
|
||||
NodeMathAggregate: { svg: NodeMathAggregate, size: 16 },
|
||||
NodeMathFormula: { svg: NodeMathFormula, size: 16 },
|
||||
NodeMathFunction: { svg: NodeMathFunction, size: 16 },
|
||||
NodeMathRunning: { svg: NodeMathRunning, size: 16 },
|
||||
NodeMax: { svg: NodeMax, size: 16 },
|
||||
NodeMaximum: { svg: NodeMaximum, size: 16 },
|
||||
NodeMedianFilter: { svg: NodeMedianFilter, size: 16 },
|
||||
@@ -548,6 +556,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeOffsetPath: { svg: NodeOffsetPath, size: 16 },
|
||||
NodeOffsetPoints: { svg: NodeOffsetPoints, size: 16 },
|
||||
NodeOpacity: { svg: NodeOpacity, size: 16 },
|
||||
NodeOpenEnds: { svg: NodeOpenEnds, size: 16 },
|
||||
NodeOriginsToPolyline: { svg: NodeOriginsToPolyline, size: 16 },
|
||||
NodePackStrips: { svg: NodePackStrips, size: 16 },
|
||||
NodePassthrough: { svg: NodePassthrough, size: 16 },
|
||||
@@ -651,6 +660,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
|
||||
NodeUngroup: { svg: NodeUngroup, size: 16 },
|
||||
NodeUnweld: { svg: NodeUnweld, size: 16 },
|
||||
NodeUploadTexture: { svg: NodeUploadTexture, size: 16 },
|
||||
NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 },
|
||||
NodeVaryRotations: { svg: NodeVaryRotations, size: 16 },
|
||||
NodeVaryScales: { svg: NodeVaryScales, size: 16 },
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { writable } from "svelte/store";
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { HistoryPanelState } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type HistoryStore = ReturnType<typeof createHistoryStore>;
|
||||
|
||||
const initialState: HistoryPanelState = { rows: [], progress: [], more: false, following: undefined, session: false };
|
||||
|
||||
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
|
||||
const store: Writable<HistoryPanelState> = import.meta.hot?.data?.store || writable<HistoryPanelState>(initialState);
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
|
||||
const { subscribe, set } = store;
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
|
||||
export function createHistoryStore(subscriptions: SubscriptionsRouter) {
|
||||
destroyHistoryStore();
|
||||
subscriptionsRouter = subscriptions;
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateHistoryPanel", (data) => {
|
||||
set(data.state);
|
||||
});
|
||||
|
||||
return { subscribe };
|
||||
}
|
||||
|
||||
export function destroyHistoryStore() {
|
||||
const subscriptions = subscriptionsRouter;
|
||||
if (!subscriptions) return;
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateHistoryPanel");
|
||||
subscriptionsRouter = undefined;
|
||||
}
|
||||
@@ -7,6 +7,8 @@
|
||||
use crate::editor_wrapper::EditorWrapper;
|
||||
use graphite_proc_macros::editor_commands;
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use tsify::Ts;
|
||||
use tsify::Tsify;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
@@ -94,7 +96,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
||||
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
|
||||
fn widget_value_update(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>, resend_widget: bool) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let update = LayoutMessage::WidgetValueUpdate {
|
||||
layout_target,
|
||||
@@ -111,7 +113,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Commit the value of a given UI widget to the history
|
||||
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
|
||||
fn widget_value_commit(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>) -> Message {
|
||||
LayoutMessage::WidgetValueCommit {
|
||||
layout_target,
|
||||
widget_id: WidgetId(widget_id),
|
||||
@@ -121,7 +123,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, and commit it to the history
|
||||
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
|
||||
fn widget_value_commit_and_update(layout_target: Ts<LayoutTarget>, widget_id: u64, value: Ts<Any>, resend_widget: bool) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let mut messages: Vec<Message> = vec![
|
||||
LayoutMessage::WidgetValueCommit {
|
||||
@@ -147,13 +149,13 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
|
||||
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
|
||||
fn widget_value_drag_drop(layout_target: Ts<LayoutTarget>, widget_id: u64) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
|
||||
}
|
||||
|
||||
/// Hand a file dropped on a UI widget to the widget's file drop callback
|
||||
fn widget_value_file_drop(layout_target: LayoutTarget, widget_id: u64, name: String, mime_type: String, data: Vec<u8>) -> Message {
|
||||
fn widget_value_file_drop(layout_target: Ts<LayoutTarget>, widget_id: u64, name: String, mime_type: String, data: Vec<u8>) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let file = DroppedFile { name, mime_type, data };
|
||||
LayoutMessage::WidgetValueFileDrop { layout_target, widget_id, file }.into()
|
||||
@@ -161,7 +163,7 @@ mod editor_commands {
|
||||
|
||||
/// Tokenizes a math expression widget's text as it is typed, for the reply to color and typeset it, and offers names to finish
|
||||
/// the one at the caret, where the caret is given. Unless they're `asked` for, names are offered only once part of one is typed.
|
||||
fn analyze_math_expression(layout_target: LayoutTarget, widget_id: u64, source: String, caret: Option<u32>, asked: bool) -> Message {
|
||||
fn analyze_math_expression(layout_target: Ts<LayoutTarget>, widget_id: u64, source: String, caret: Option<u32>, asked: bool) -> Message {
|
||||
LayoutMessage::AnalyzeMathExpression {
|
||||
layout_target,
|
||||
widget_id: WidgetId(widget_id),
|
||||
@@ -257,48 +259,11 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Bring a panel to the front, reopening it if closed
|
||||
fn focus_panel(panel_type: PanelType) -> Message {
|
||||
fn focus_panel(panel_type: Ts<PanelType>) -> Message {
|
||||
WorkspaceMessage::FocusPanel { panel_type }.into()
|
||||
}
|
||||
|
||||
/// Show or hide an interaction's deltas
|
||||
fn expand_history_interaction(id: String, expanded: bool) -> Message {
|
||||
HistoryMessage::Expand { id, expanded }.into()
|
||||
}
|
||||
|
||||
fn load_more_history() -> Message {
|
||||
HistoryMessage::LoadMore.into()
|
||||
}
|
||||
|
||||
fn go_back_to_history_interaction(id: String) -> Message {
|
||||
HistoryMessage::GoBack { id }.into()
|
||||
}
|
||||
|
||||
/// Remove one interaction and keep the later ones
|
||||
fn remove_history_interaction(id: String) -> Message {
|
||||
HistoryMessage::RemoveStep { id }.into()
|
||||
}
|
||||
|
||||
/// Redo an undone interaction, or reapply an abandoned one
|
||||
fn bring_back_history_interaction(id: String) -> Message {
|
||||
HistoryMessage::BringBack { id }.into()
|
||||
}
|
||||
|
||||
/// Show a branch's line, or the head's line when `id` is `None`
|
||||
fn follow_history_branch(id: Option<String>) -> Message {
|
||||
HistoryMessage::Follow { id }.into()
|
||||
}
|
||||
|
||||
/// Name an interaction. An empty label removes the name
|
||||
fn rename_history_interaction(id: String, label: String) -> Message {
|
||||
HistoryMessage::Rename { id, label }.into()
|
||||
}
|
||||
|
||||
fn tag_history_interaction(id: String, tag: String, on: bool) -> Message {
|
||||
HistoryMessage::Tag { id, tag, on }.into()
|
||||
}
|
||||
|
||||
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
|
||||
fn split_panel_group(target_group: u64, direction: Ts<DockingSplitDirection>, tabs: Vec<Ts<PanelType>>, active_tab_index: usize) -> Message {
|
||||
WorkspaceMessage::SplitPanelGroup {
|
||||
target_group: PanelGroupId(target_group),
|
||||
direction,
|
||||
@@ -478,7 +443,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
|
||||
fn update_primary_color(color: SRGBA8) -> Message {
|
||||
fn update_primary_color(color: Ts<SRGBA8>) -> Message {
|
||||
ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: true,
|
||||
@@ -487,7 +452,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
|
||||
fn update_secondary_color(color: SRGBA8) -> Message {
|
||||
fn update_secondary_color(color: Ts<SRGBA8>) -> Message {
|
||||
ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: false,
|
||||
@@ -496,7 +461,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
|
||||
fn open_color_picker(initial_value: FillChoiceSRGBA8, allow_none: bool, disabled: bool) -> Message {
|
||||
fn open_color_picker(initial_value: Ts<FillChoiceSRGBA8>, allow_none: bool, disabled: bool) -> Message {
|
||||
ColorPickerMessage::Open {
|
||||
initial_value: FillChoice::from(&initial_value.0),
|
||||
allow_none,
|
||||
@@ -511,7 +476,7 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
|
||||
fn update_gradient_stop_color(color: SRGBA8) -> Message {
|
||||
fn update_gradient_stop_color(color: Ts<SRGBA8>) -> Message {
|
||||
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
|
||||
}
|
||||
|
||||
@@ -703,12 +668,12 @@ mod editor_commands {
|
||||
}
|
||||
|
||||
/// The pixels of an export that `TriggerExportImage` had the frontend rasterize, which the editor encodes and saves as the chosen file type
|
||||
fn save_rasterized_export(name: String, file_type: FileType, width: u32, height: u32, data: Vec<u8>) -> Message {
|
||||
fn save_rasterized_export(name: String, file_type: Ts<FileType>, width: u32, height: u32, data: Vec<u8>) -> Message {
|
||||
PortfolioMessage::SaveRasterizedExport { name, file_type, width, height, data }.into()
|
||||
}
|
||||
|
||||
/// A file headed for a known action, picked in the dialog that `TriggerBrowse` opened
|
||||
fn ingest_picked(name: String, mime_type: String, data: Vec<u8>, action: IngestAction) -> Message {
|
||||
fn ingest_picked(name: String, mime_type: String, data: Vec<u8>, action: Ts<IngestAction>) -> Message {
|
||||
IngestMessage::Ingest {
|
||||
data,
|
||||
action,
|
||||
@@ -926,7 +891,6 @@ mod editor_commands {
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct FillChoiceSRGBA8(
|
||||
/// Concrete wasm boundary form of the generic [`FillChoice`], since a `#[wasm_bindgen]` argument's TS declaration names its type without the generic's argument.
|
||||
#[tsify(type = "FillChoice<SRGBA8>")]
|
||||
@@ -936,7 +900,6 @@ pub struct FillChoiceSRGBA8(
|
||||
pub type FillChoiceSRGBA8 = Any;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct Any(#[tsify(type = "any")] serde_json::Value);
|
||||
impl Any {
|
||||
#[cfg(feature = "editor")]
|
||||
@@ -962,6 +925,5 @@ editor_proxy_types! {
|
||||
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
|
||||
PanelType = editor::messages::portfolio::utility_types::PanelType;
|
||||
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
|
||||
SRGBA8 = graphene_std::color::SRGBA8;
|
||||
}
|
||||
@@ -250,7 +250,14 @@ impl EditorWrapper {
|
||||
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
|
||||
#[cfg(all(feature = "web", not(feature = "native")))]
|
||||
#[wasm_bindgen(js_name = loadPersistedState)]
|
||||
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
|
||||
pub fn load_persisted_state(&self, state: tsify::Ts<editor::messages::frontend::utility_types::PersistedState>) {
|
||||
let state = match state.to_rust() {
|
||||
Ok(state) => state,
|
||||
Err(e) => {
|
||||
log::error!("Cannot convert state to type utility_types::PersistedState: {e:?}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
self.dispatch(PersistentStateMessage::LoadState { state });
|
||||
}
|
||||
#[cfg(feature = "native")]
|
||||
|
||||
@@ -213,13 +213,13 @@ unsafe impl<T: StaticTypeSized> StaticType for [T] {
|
||||
type Static = [<T as StaticTypeSized>::Static];
|
||||
}
|
||||
|
||||
unsafe impl StaticType for dyn for<'i> DynAny<'_> + '_ {
|
||||
unsafe impl StaticType for dyn DynAny<'_> + '_ {
|
||||
type Static = dyn DynAny<'static>;
|
||||
}
|
||||
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + Sync + '_ {
|
||||
unsafe impl StaticType for dyn DynAny<'_> + Send + Sync + '_ {
|
||||
type Static = dyn DynAny<'static> + Send + Sync;
|
||||
}
|
||||
unsafe impl StaticType for dyn for<'i> DynAny<'_> + Send + '_ {
|
||||
unsafe impl StaticType for dyn DynAny<'_> + Send + '_ {
|
||||
type Static = dyn DynAny<'static> + Sync;
|
||||
}
|
||||
unsafe impl<T: StaticTypeSized> StaticType for dyn core::future::Future<Output = T> + Send + Sync + '_ {
|
||||
|
||||
@@ -17,6 +17,12 @@ impl ParseError {
|
||||
pub fn messages(&self) -> &[ErrorMessage] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// The error of a source that should be a lone operator or function name but isn't, spanning the given range of it.
|
||||
pub(crate) fn lone_reducer_expected(span: Range<usize>) -> Self {
|
||||
let message = ErrorMessage::from_prose("Expected a lone operator like `+` or a function name like `max`");
|
||||
Self(vec![ErrorMessage { span: Some(span), ..message }])
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ParseError {
|
||||
|
||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user