mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e380b8cd7 | ||
|
|
634c30bebf | ||
|
|
1e912de804 | ||
|
|
ea9c44e003 | ||
|
|
6a28b82b91 |
No files matched your search
@@ -150,14 +150,20 @@ jobs:
|
|||||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||||
|
|
||||||
- name: 📤 Publish to Cloudflare Pages
|
- name: 📤 Publish to Cloudflare Pages
|
||||||
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
|
if: inputs.merge_queue == false
|
||||||
id: cloudflare
|
id: cloudflare
|
||||||
|
continue-on-error: ${{ github.event_name != 'push' }}
|
||||||
env:
|
env:
|
||||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||||
# Passed through the environment so a branch name can't inject shell syntax
|
# Passed through the environment so a branch name can't inject shell syntax
|
||||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||||
run: |
|
run: |
|
||||||
|
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||||
|
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
if [ "${{ github.event_name }}" = "push" ]; then
|
if [ "${{ github.event_name }}" = "push" ]; then
|
||||||
DEPLOY_BRANCH="master"
|
DEPLOY_BRANCH="master"
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
|
|
||||||
workflow_dispatch: {}
|
|
||||||
|
|
||||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
||||||
concurrency:
|
concurrency:
|
||||||
@@ -247,8 +245,7 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
env:
|
env:
|
||||||
# A manual run has no base commit of its own, so it compares against master
|
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
||||||
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
|
|
||||||
steps:
|
steps:
|
||||||
- name: 📥 Clone repository
|
- name: 📥 Clone repository
|
||||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||||
@@ -262,9 +259,7 @@ jobs:
|
|||||||
rustflags: ""
|
rustflags: ""
|
||||||
|
|
||||||
- name: 📥 Fetch the base commit
|
- name: 📥 Fetch the base commit
|
||||||
run: |
|
run: git fetch --depth=1 origin "$BASE_SHA"
|
||||||
git fetch --depth=1 origin "$BASE_REF"
|
|
||||||
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
|
|
||||||
|
|
||||||
- name: 🔬 Check migrations against the base commit
|
- name: 🔬 Check migrations against the base commit
|
||||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||||
|
|||||||
@@ -51,8 +51,6 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
# Cache on Cargo.lock file
|
# Cache on Cargo.lock file
|
||||||
cache-on-failure: true
|
cache-on-failure: true
|
||||||
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
|
|
||||||
save-if: ${{ github.event_name == 'push' }}
|
|
||||||
|
|
||||||
- name: Install gungraun-runner and valgrind
|
- name: Install gungraun-runner and valgrind
|
||||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||||
|
|||||||
Generated
+13
-15
@@ -590,7 +590,6 @@ dependencies = [
|
|||||||
"node-macro",
|
"node-macro",
|
||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"serde",
|
"serde",
|
||||||
"text-nodes",
|
|
||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1227,6 +1226,7 @@ dependencies = [
|
|||||||
"kurbo",
|
"kurbo",
|
||||||
"log",
|
"log",
|
||||||
"lyon_geom",
|
"lyon_geom",
|
||||||
|
"math-parser",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"num-derive",
|
"num-derive",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
@@ -2746,9 +2746,8 @@ dependencies = [
|
|||||||
"fd-lock",
|
"fd-lock",
|
||||||
"futures",
|
"futures",
|
||||||
"glam",
|
"glam",
|
||||||
"graphite-desktop-ui-cef",
|
"graphite-desktop-ui",
|
||||||
"graphite-desktop-wrapper",
|
"graphite-desktop-wrapper",
|
||||||
"graphite-wasm-wrapper",
|
|
||||||
"interprocess",
|
"interprocess",
|
||||||
"lzma-rust2",
|
"lzma-rust2",
|
||||||
"muda",
|
"muda",
|
||||||
@@ -2779,6 +2778,13 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "graphite-desktop-embedded-resources"
|
||||||
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"include_dir",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "graphite-desktop-platform-linux"
|
name = "graphite-desktop-platform-linux"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
@@ -2791,7 +2797,7 @@ name = "graphite-desktop-platform-mac"
|
|||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"graphite-desktop",
|
"graphite-desktop",
|
||||||
"graphite-desktop-ui-cef",
|
"graphite-desktop-ui",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2803,14 +2809,14 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "graphite-desktop-ui-cef"
|
name = "graphite-desktop-ui"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"ash",
|
"ash",
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"cef",
|
"cef",
|
||||||
"dirs",
|
"dirs",
|
||||||
"graphite-desktop-ui-cef-embedded-resources",
|
"graphite-desktop-embedded-resources",
|
||||||
"ipc-channel",
|
"ipc-channel",
|
||||||
"libc",
|
"libc",
|
||||||
"mach2",
|
"mach2",
|
||||||
@@ -2830,13 +2836,6 @@ dependencies = [
|
|||||||
"winit",
|
"winit",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "graphite-desktop-ui-cef-embedded-resources"
|
|
||||||
version = "0.0.0"
|
|
||||||
dependencies = [
|
|
||||||
"include_dir",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "graphite-desktop-wrapper"
|
name = "graphite-desktop-wrapper"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
@@ -2844,6 +2843,7 @@ dependencies = [
|
|||||||
"base64 0.23.1",
|
"base64 0.23.1",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphite-editor",
|
"graphite-editor",
|
||||||
|
"graphite-wasm-wrapper",
|
||||||
"image",
|
"image",
|
||||||
"keyboard-types",
|
"keyboard-types",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -5746,7 +5746,6 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"half",
|
|
||||||
"log",
|
"log",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
@@ -6021,7 +6020,6 @@ dependencies = [
|
|||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"kurbo",
|
"kurbo",
|
||||||
"linesweeper",
|
|
||||||
"log",
|
"log",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"parley",
|
"parley",
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ members = [
|
|||||||
"desktop",
|
"desktop",
|
||||||
"desktop/wrapper",
|
"desktop/wrapper",
|
||||||
"desktop/ui",
|
"desktop/ui",
|
||||||
"desktop/ui/embedded-resources",
|
"desktop/embedded-resources",
|
||||||
"desktop/bundle",
|
"desktop/bundle",
|
||||||
"desktop/platform/linux",
|
"desktop/platform/linux",
|
||||||
"desktop/platform/mac",
|
"desktop/platform/mac",
|
||||||
|
|||||||
+3
-4
@@ -21,14 +21,13 @@ path = "src/main.rs"
|
|||||||
[features]
|
[features]
|
||||||
default = ["recommended", "embedded_resources"]
|
default = ["recommended", "embedded_resources"]
|
||||||
recommended = ["accelerated_paint"]
|
recommended = ["accelerated_paint"]
|
||||||
embedded_resources = ["graphite-desktop-ui-cef/embedded_resources"]
|
embedded_resources = ["graphite-desktop-ui/embedded_resources"]
|
||||||
accelerated_paint = ["graphite-desktop-ui-cef/accelerated_paint"]
|
accelerated_paint = ["graphite-desktop-ui/accelerated_paint"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
graphite-desktop-wrapper = { path = "wrapper" }
|
graphite-desktop-wrapper = { path = "wrapper" }
|
||||||
graphite-desktop-ui-cef = { path = "ui" }
|
graphite-desktop-ui = { path = "ui" }
|
||||||
graphite-wasm-wrapper = { path = "../frontend/wrapper", default-features = false, features = ["editor"] }
|
|
||||||
|
|
||||||
wgpu = { workspace = true }
|
wgpu = { workspace = true }
|
||||||
winit = { workspace = true, features = [
|
winit = { workspace = true, features = [
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "graphite-desktop-ui-cef-embedded-resources"
|
name = "graphite-desktop-embedded-resources"
|
||||||
description = "Graphite Desktop Embedded Resources"
|
description = "Graphite Desktop Embedded Resources"
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
const EMBEDDED_RESOURCES_ENV: &str = "EMBEDDED_RESOURCES";
|
const EMBEDDED_RESOURCES_ENV: &str = "EMBEDDED_RESOURCES";
|
||||||
const DEFAULT_RESOURCES_DIR: &str = "../../../frontend/dist";
|
const DEFAULT_RESOURCES_DIR: &str = "../../frontend/dist";
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
let mut embedded_resources: Option<String> = None;
|
let mut embedded_resources: Option<String> = None;
|
||||||
File renamed without changes.
@@ -16,7 +16,7 @@ workspace = true
|
|||||||
|
|
||||||
[features]
|
[features]
|
||||||
main = ["dep:graphite-desktop"]
|
main = ["dep:graphite-desktop"]
|
||||||
helper = ["dep:graphite-desktop-ui-cef"]
|
helper = ["dep:graphite-desktop-ui"]
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
name = "graphite"
|
name = "graphite"
|
||||||
@@ -30,4 +30,4 @@ required-features = ["helper"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
graphite-desktop = { path = "../..", optional = true }
|
graphite-desktop = { path = "../..", optional = true }
|
||||||
graphite-desktop-ui-cef = { path = "../../ui", optional = true }
|
graphite-desktop-ui = { path = "../../ui", optional = true }
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
fn main() -> std::process::ExitCode {
|
fn main() -> std::process::ExitCode {
|
||||||
graphite_desktop_ui_cef::run_helper()
|
graphite_desktop_ui::run_helper()
|
||||||
}
|
}
|
||||||
+18
-11
@@ -20,13 +20,13 @@ use crate::dirs;
|
|||||||
use crate::event::{AppEvent, AppEventScheduler};
|
use crate::event::{AppEvent, AppEventScheduler};
|
||||||
use crate::input::InputState;
|
use crate::input::InputState;
|
||||||
use crate::persist;
|
use crate::persist;
|
||||||
use crate::preferences::{self, Acceleration};
|
use crate::preferences;
|
||||||
use crate::render::{RenderError, RenderState};
|
use crate::render::{RenderError, RenderState};
|
||||||
use crate::spawner::TokioSpawner;
|
use crate::spawner::TokioSpawner;
|
||||||
use crate::ui::{InputEvent, Ui, UiBackend, UiCommand};
|
use crate::ui::{Acceleration, InputEvent, UiCommand, UiConfig, UiInstance};
|
||||||
use crate::window::Window;
|
use crate::window::Window;
|
||||||
use crate::wrapper::messages::{DataTransfer, DesktopFrontendMessage, DesktopWrapperMessage, FrontendMessage, IngestAction};
|
use crate::wrapper::messages::{DataTransfer, DesktopFrontendMessage, DesktopWrapperMessage, IngestAction};
|
||||||
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor};
|
use crate::wrapper::{DesktopWrapper, FolderStore, MmapResourceStorage, WgpuContext, WgpuExecutor, serialize_frontend_messages};
|
||||||
|
|
||||||
pub(crate) struct App {
|
pub(crate) struct App {
|
||||||
render_state: Option<RenderState>,
|
render_state: Option<RenderState>,
|
||||||
@@ -43,10 +43,10 @@ pub(crate) struct App {
|
|||||||
app_event_scheduler: AppEventScheduler,
|
app_event_scheduler: AppEventScheduler,
|
||||||
desktop_wrapper: DesktopWrapper,
|
desktop_wrapper: DesktopWrapper,
|
||||||
runtime_command_sender: Sender<RuntimeCommand>,
|
runtime_command_sender: Sender<RuntimeCommand>,
|
||||||
ui: Ui,
|
ui: UiInstance,
|
||||||
ui_initialized: Option<Instant>,
|
ui_initialized: Option<Instant>,
|
||||||
ui_frame_received: bool,
|
ui_frame_received: bool,
|
||||||
ui_startup_buffer: Vec<Vec<FrontendMessage>>,
|
ui_startup_buffer: Vec<Vec<u8>>,
|
||||||
preferences: preferences::DesktopPreferences,
|
preferences: preferences::DesktopPreferences,
|
||||||
launch_documents: Option<Vec<PathBuf>>,
|
launch_documents: Option<Vec<PathBuf>>,
|
||||||
exiting: bool,
|
exiting: bool,
|
||||||
@@ -59,7 +59,7 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
ui: Ui,
|
ui: UiInstance,
|
||||||
wgpu_context: WgpuContext,
|
wgpu_context: WgpuContext,
|
||||||
app_event_receiver: Receiver<AppEvent>,
|
app_event_receiver: Receiver<AppEvent>,
|
||||||
app_event_scheduler: AppEventScheduler,
|
app_event_scheduler: AppEventScheduler,
|
||||||
@@ -181,7 +181,8 @@ impl App {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn restart_ui(&mut self) {
|
fn restart_ui(&mut self) {
|
||||||
if let Err(error) = self.ui.restart(&self.preferences) {
|
let acceleration = self.preferences.acceleration;
|
||||||
|
if let Err(error) = self.ui.restart(UiConfig { acceleration }) {
|
||||||
tracing::error!("Failed to restart the UI: {error}");
|
tracing::error!("Failed to restart the UI: {error}");
|
||||||
self.exit(Some(ExitReason::Shutdown));
|
self.exit(Some(ExitReason::Shutdown));
|
||||||
return;
|
return;
|
||||||
@@ -247,7 +248,13 @@ impl App {
|
|||||||
|
|
||||||
fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage, responses: &mut Vec<DesktopWrapperMessage>) {
|
fn handle_desktop_frontend_message(&mut self, message: DesktopFrontendMessage, responses: &mut Vec<DesktopWrapperMessage>) {
|
||||||
match message {
|
match message {
|
||||||
DesktopFrontendMessage::ToUi(messages) => self.send_or_queue_ui_message(messages),
|
DesktopFrontendMessage::ToWeb(messages) => {
|
||||||
|
let Some(bytes) = serialize_frontend_messages(messages) else {
|
||||||
|
tracing::error!("Failed to serialize frontend messages");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.send_or_queue_web_message(bytes);
|
||||||
|
}
|
||||||
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
|
DesktopFrontendMessage::OpenFileDialog { title, options, action } => {
|
||||||
let app_event_scheduler = self.app_event_scheduler.clone();
|
let app_event_scheduler = self.app_event_scheduler.clone();
|
||||||
let _ = thread::spawn(move || {
|
let _ = thread::spawn(move || {
|
||||||
@@ -458,7 +465,7 @@ impl App {
|
|||||||
self.handle_desktop_frontend_messages(responses);
|
self.handle_desktop_frontend_messages(responses);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_or_queue_ui_message(&mut self, message: Vec<FrontendMessage>) {
|
fn send_or_queue_web_message(&mut self, message: Vec<u8>) {
|
||||||
if self.ui_initialized.is_some() {
|
if self.ui_initialized.is_some() {
|
||||||
self.ui.send(UiCommand::Message(message));
|
self.ui.send(UiCommand::Message(message));
|
||||||
} else {
|
} else {
|
||||||
@@ -468,7 +475,7 @@ impl App {
|
|||||||
|
|
||||||
fn user_event(&mut self, event_loop: &dyn ActiveEventLoop, event: AppEvent) {
|
fn user_event(&mut self, event_loop: &dyn ActiveEventLoop, event: AppEvent) {
|
||||||
match event {
|
match event {
|
||||||
AppEvent::UiInitialized => {
|
AppEvent::WebCommunicationInitialized => {
|
||||||
self.ui_initialized = Some(Instant::now());
|
self.ui_initialized = Some(Instant::now());
|
||||||
self.ui_frame_received = false;
|
self.ui_frame_received = false;
|
||||||
for message in self.ui_startup_buffer.drain(..) {
|
for message in self.ui_startup_buffer.drain(..) {
|
||||||
|
|||||||
@@ -9,6 +9,25 @@ pub(crate) fn ensure_dir_exists(path: &PathBuf) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn clear_dir(path: &PathBuf) {
|
||||||
|
let Ok(entries) = fs::read_dir(path) else {
|
||||||
|
tracing::error!("Failed to read directory at {path:?}");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let entry_path = entry.path();
|
||||||
|
if entry_path.is_dir() {
|
||||||
|
if let Err(e) = fs::remove_dir_all(&entry_path) {
|
||||||
|
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
|
||||||
|
}
|
||||||
|
} else if entry_path.is_file()
|
||||||
|
&& let Err(e) = fs::remove_file(&entry_path)
|
||||||
|
{
|
||||||
|
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn app_data_dir() -> PathBuf {
|
pub(crate) fn app_data_dir() -> PathBuf {
|
||||||
let path = dirs::data_dir().expect("Failed to get data directory").join(APP_DIRECTORY_NAME);
|
let path = dirs::data_dir().expect("Failed to get data directory").join(APP_DIRECTORY_NAME);
|
||||||
ensure_dir_exists(&path);
|
ensure_dir_exists(&path);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::wrapper::messages::{DataTransfer, DesktopWrapperMessage};
|
|||||||
pub(crate) enum AppEvent {
|
pub(crate) enum AppEvent {
|
||||||
UiUpdate(wgpu::Texture),
|
UiUpdate(wgpu::Texture),
|
||||||
CursorChange(Cursor),
|
CursorChange(Cursor),
|
||||||
UiInitialized,
|
WebCommunicationInitialized,
|
||||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||||
ViewportTexture(Option<Texture>),
|
ViewportTexture(Option<Texture>),
|
||||||
ClipboardRead,
|
ClipboardRead,
|
||||||
|
|||||||
+29
-9
@@ -3,13 +3,13 @@ use crate::cli::Cli;
|
|||||||
use crate::consts::APP_LOCK_FILE_NAME;
|
use crate::consts::APP_LOCK_FILE_NAME;
|
||||||
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
|
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use preferences::Acceleration;
|
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::process::ExitCode;
|
use std::process::ExitCode;
|
||||||
use tracing_subscriber::EnvFilter;
|
use tracing_subscriber::EnvFilter;
|
||||||
use ui::{Ui, UiBackend, UiEvent};
|
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
|
||||||
use winit::event_loop::EventLoop;
|
use winit::event_loop::EventLoop;
|
||||||
|
|
||||||
|
pub(crate) use graphite_desktop_ui as ui;
|
||||||
pub(crate) use graphite_desktop_wrapper as wrapper;
|
pub(crate) use graphite_desktop_wrapper as wrapper;
|
||||||
|
|
||||||
mod app;
|
mod app;
|
||||||
@@ -24,7 +24,6 @@ mod preferences;
|
|||||||
mod render;
|
mod render;
|
||||||
mod socket;
|
mod socket;
|
||||||
mod spawner;
|
mod spawner;
|
||||||
mod ui;
|
|
||||||
mod window;
|
mod window;
|
||||||
|
|
||||||
pub(crate) mod consts;
|
pub(crate) mod consts;
|
||||||
@@ -32,9 +31,14 @@ pub(crate) mod consts;
|
|||||||
pub fn start() -> ExitCode {
|
pub fn start() -> ExitCode {
|
||||||
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
|
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
|
||||||
|
|
||||||
if let Some(code) = ui::setup() {
|
let ui_context = match UiContext::setup() {
|
||||||
return code;
|
UiSetupResult::Ready(context) => context,
|
||||||
}
|
UiSetupResult::Helper(code) => return code,
|
||||||
|
UiSetupResult::Failed => {
|
||||||
|
tracing::error!("Failed to set up the UI runtime");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
let cli = Cli::parse();
|
let cli = Cli::parse();
|
||||||
|
|
||||||
@@ -69,6 +73,8 @@ pub fn start() -> ExitCode {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
dirs::clear_dir(&ui::temp_dir_root());
|
||||||
|
|
||||||
// Must be called before event loop initialization or native window integrations will break
|
// Must be called before event loop initialization or native window integrations will break
|
||||||
App::init();
|
App::init();
|
||||||
|
|
||||||
@@ -92,7 +98,14 @@ pub fn start() -> ExitCode {
|
|||||||
println!("UI acceleration is disabled");
|
println!("UI acceleration is disabled");
|
||||||
}
|
}
|
||||||
|
|
||||||
let ui = match Ui::start(&prefs, &wgpu_context) {
|
let ui_context = match ui_context.start(UiConfig { acceleration: prefs.acceleration }) {
|
||||||
|
Ok(context) => context,
|
||||||
|
Err(error) => {
|
||||||
|
tracing::error!("Failed to start the UI runtime: {error}");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let ui = match ui_context.instance(&wgpu_context.device, &wgpu_context.queue) {
|
||||||
Ok(ui) => ui,
|
Ok(ui) => ui,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
tracing::error!("Failed to start the UI: {error}");
|
tracing::error!("Failed to start the UI: {error}");
|
||||||
@@ -107,10 +120,17 @@ pub fn start() -> ExitCode {
|
|||||||
let spawned = std::thread::Builder::new().name("ui-events".to_string()).spawn(move || {
|
let spawned = std::thread::Builder::new().name("ui-events".to_string()).spawn(move || {
|
||||||
while let Some(event) = ui.recv() {
|
while let Some(event) = ui.recv() {
|
||||||
match event {
|
match event {
|
||||||
UiEvent::Ready => scheduler.schedule(AppEvent::UiInitialized),
|
UiEvent::Ready => scheduler.schedule(AppEvent::WebCommunicationInitialized),
|
||||||
UiEvent::Frame(texture) => scheduler.schedule(AppEvent::UiUpdate(texture)),
|
UiEvent::Frame(texture) => scheduler.schedule(AppEvent::UiUpdate(texture)),
|
||||||
UiEvent::Cursor(cursor) => scheduler.schedule(AppEvent::CursorChange(cursor)),
|
UiEvent::Cursor(cursor) => scheduler.schedule(AppEvent::CursorChange(cursor)),
|
||||||
UiEvent::Message(message) => scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
|
UiEvent::Message(message) => match wrapper::deserialize_editor_message(&message) {
|
||||||
|
Some(message) => scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
|
||||||
|
None => tracing::error!("Failed to deserialize web message"),
|
||||||
|
},
|
||||||
|
UiEvent::Failure(error) => {
|
||||||
|
tracing::error!("UI failure: {error}");
|
||||||
|
scheduler.schedule(AppEvent::UiCrashed);
|
||||||
|
}
|
||||||
UiEvent::Crashed => scheduler.schedule(AppEvent::UiCrashed),
|
UiEvent::Crashed => scheduler.schedule(AppEvent::UiCrashed),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
use graphite_desktop_wrapper::messages::Preferences;
|
use graphite_desktop_wrapper::messages::Preferences;
|
||||||
use wgpu::PresentMode;
|
use wgpu::PresentMode;
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
use crate::ui::Acceleration;
|
||||||
pub(crate) enum Acceleration {
|
|
||||||
Auto,
|
|
||||||
Disabled,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub(crate) struct DesktopPreferences {
|
pub(crate) struct DesktopPreferences {
|
||||||
|
|||||||
@@ -1,32 +0,0 @@
|
|||||||
use crate::preferences::DesktopPreferences;
|
|
||||||
use crate::wrapper::WgpuContext;
|
|
||||||
use crate::wrapper::messages::{DesktopWrapperMessage, FrontendMessage};
|
|
||||||
|
|
||||||
mod cef;
|
|
||||||
pub(crate) use cef::*;
|
|
||||||
|
|
||||||
pub(crate) trait UiBackend: Sized {
|
|
||||||
fn start(preferences: &DesktopPreferences, wgpu_context: &WgpuContext) -> Result<Self, UiError>;
|
|
||||||
fn send(&self, command: UiCommand);
|
|
||||||
fn recv(&self) -> Option<UiEvent>;
|
|
||||||
fn restart(&self, preferences: &DesktopPreferences) -> Result<(), UiError>;
|
|
||||||
fn shutdown(&self);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) type UiError = Box<dyn std::error::Error + Send + Sync>;
|
|
||||||
|
|
||||||
pub(crate) enum UiCommand {
|
|
||||||
Input(InputEvent),
|
|
||||||
Resized { width: u32, height: u32 },
|
|
||||||
ScaleChanged(f64),
|
|
||||||
Refresh,
|
|
||||||
Message(Vec<FrontendMessage>),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) enum UiEvent {
|
|
||||||
Ready,
|
|
||||||
Frame(wgpu::Texture),
|
|
||||||
Cursor(Cursor),
|
|
||||||
Message(DesktopWrapperMessage),
|
|
||||||
Crashed,
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
use super::{UiBackend, UiCommand, UiError, UiEvent};
|
|
||||||
use crate::preferences::{Acceleration, DesktopPreferences};
|
|
||||||
use crate::wrapper::WgpuContext;
|
|
||||||
use crate::wrapper::messages::DesktopWrapperMessage;
|
|
||||||
use graphite_desktop_ui_cef as cef;
|
|
||||||
use graphite_wasm_wrapper::native_communication::{decode_editor_command, encode_frontend_messages};
|
|
||||||
use std::fs;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
use std::process::ExitCode;
|
|
||||||
use std::sync::Mutex;
|
|
||||||
|
|
||||||
pub(crate) use cef::{Cursor, InputEvent, InputEventBuilder, MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub(crate) struct Ui {
|
|
||||||
instance: cef::UiInstance,
|
|
||||||
}
|
|
||||||
|
|
||||||
static SETUP: Mutex<Option<cef::UiContext<cef::Setup>>> = Mutex::new(None);
|
|
||||||
|
|
||||||
pub(crate) fn setup() -> Option<ExitCode> {
|
|
||||||
match cef::UiContext::setup() {
|
|
||||||
cef::UiSetupResult::Ready(context) => {
|
|
||||||
*SETUP.lock().unwrap() = Some(context);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
cef::UiSetupResult::Failed => {
|
|
||||||
tracing::error!("Failed to set up the UI runtime");
|
|
||||||
Some(ExitCode::FAILURE)
|
|
||||||
}
|
|
||||||
cef::UiSetupResult::Helper(code) => Some(code),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl UiBackend for Ui {
|
|
||||||
fn start(preferences: &DesktopPreferences, wgpu_context: &WgpuContext) -> Result<Self, UiError> {
|
|
||||||
let setup = SETUP.lock().unwrap().take().ok_or("The UI was started before it was set up")?;
|
|
||||||
|
|
||||||
clear_dir(&cef::temp_dir_root());
|
|
||||||
|
|
||||||
let context = setup.start(config(preferences))?;
|
|
||||||
let instance = context.instance(&wgpu_context.device, &wgpu_context.queue)?;
|
|
||||||
Ok(Self { instance })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send(&self, command: UiCommand) {
|
|
||||||
let command = match command {
|
|
||||||
UiCommand::Input(event) => cef::UiCommand::Input(event),
|
|
||||||
UiCommand::Resized { width, height } => cef::UiCommand::Resized { width, height },
|
|
||||||
UiCommand::ScaleChanged(scale) => cef::UiCommand::ScaleChanged(scale),
|
|
||||||
UiCommand::Refresh => cef::UiCommand::Refresh,
|
|
||||||
UiCommand::Message(messages) => {
|
|
||||||
let Some(bytes) = encode_frontend_messages(messages) else {
|
|
||||||
tracing::error!("Failed to serialize frontend messages");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
cef::UiCommand::Message(bytes)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
self.instance.send(command);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn recv(&self) -> Option<UiEvent> {
|
|
||||||
loop {
|
|
||||||
let event = match self.instance.recv()? {
|
|
||||||
cef::UiEvent::Ready => UiEvent::Ready,
|
|
||||||
cef::UiEvent::Frame(texture) => UiEvent::Frame(texture),
|
|
||||||
cef::UiEvent::Cursor(cursor) => UiEvent::Cursor(cursor),
|
|
||||||
cef::UiEvent::Message(bytes) => {
|
|
||||||
let Some(message) = decode_editor_command(&bytes) else {
|
|
||||||
tracing::error!("Failed to deserialize web message");
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
UiEvent::Message(DesktopWrapperMessage::FromUi(message.into()))
|
|
||||||
}
|
|
||||||
cef::UiEvent::Failure(error) => {
|
|
||||||
tracing::error!("UI failure: {error}");
|
|
||||||
UiEvent::Crashed
|
|
||||||
}
|
|
||||||
cef::UiEvent::Crashed => UiEvent::Crashed,
|
|
||||||
};
|
|
||||||
return Some(event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn restart(&self, preferences: &DesktopPreferences) -> Result<(), UiError> {
|
|
||||||
Ok(self.instance.restart(config(preferences))?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn shutdown(&self) {
|
|
||||||
self.instance.shutdown();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn config(preferences: &DesktopPreferences) -> cef::UiConfig {
|
|
||||||
let acceleration = match preferences.acceleration {
|
|
||||||
Acceleration::Auto => cef::Acceleration::Auto,
|
|
||||||
Acceleration::Disabled => cef::Acceleration::Disabled,
|
|
||||||
};
|
|
||||||
cef::UiConfig { acceleration }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clear_dir(path: &PathBuf) {
|
|
||||||
let Ok(entries) = fs::read_dir(path) else {
|
|
||||||
tracing::error!("Failed to read directory at {path:?}");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
for entry in entries.flatten() {
|
|
||||||
let entry_path = entry.path();
|
|
||||||
if entry_path.is_dir() {
|
|
||||||
if let Err(e) = fs::remove_dir_all(&entry_path) {
|
|
||||||
tracing::error!("Failed to remove directory at {:?}: {}", entry_path, e);
|
|
||||||
}
|
|
||||||
} else if entry_path.is_file()
|
|
||||||
&& let Err(e) = fs::remove_file(&entry_path)
|
|
||||||
{
|
|
||||||
tracing::error!("Failed to remove file at {:?}: {}", entry_path, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "graphite-desktop-ui-cef"
|
name = "graphite-desktop-ui"
|
||||||
description = "Renders the Graphite editor frontend UI into wgpu textures"
|
description = "Renders the Graphite editor frontend UI into wgpu textures"
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
license.workspace = true
|
license.workspace = true
|
||||||
@@ -16,12 +16,12 @@ workspace = true
|
|||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
embedded_resources = ["dep:graphite-desktop-ui-cef-embedded-resources"]
|
embedded_resources = ["dep:graphite-desktop-embedded-resources"]
|
||||||
accelerated_paint = ["dep:ash", "dep:bytemuck", "dep:objc2-io-surface", "dep:objc2-metal", "dep:mach2"]
|
accelerated_paint = ["dep:ash", "dep:bytemuck", "dep:objc2-io-surface", "dep:objc2-metal", "dep:mach2"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
graphite-desktop-ui-cef-embedded-resources = { path = "embedded-resources", optional = true }
|
graphite-desktop-embedded-resources = { path = "../embedded-resources", optional = true }
|
||||||
|
|
||||||
wgpu = { workspace = true }
|
wgpu = { workspace = true }
|
||||||
wgpu-sync = { workspace = true }
|
wgpu-sync = { workspace = true }
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ pub(crate) fn load(path: PathBuf) -> Option<Resource> {
|
|||||||
WebResources::Embedded => {
|
WebResources::Embedded => {
|
||||||
#[cfg(feature = "embedded_resources")]
|
#[cfg(feature = "embedded_resources")]
|
||||||
{
|
{
|
||||||
if let Some(resources) = &graphite_desktop_ui_cef_embedded_resources::EMBEDDED_RESOURCES
|
if let Some(resources) = &graphite_desktop_embedded_resources::EMBEDDED_RESOURCES
|
||||||
&& let Some(file) = resources.get_file(&path)
|
&& let Some(file) = resources.get_file(&path)
|
||||||
{
|
{
|
||||||
return Some(Resource {
|
return Some(Resource {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ workspace = true
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
graphite-editor = { workspace = true }
|
graphite-editor = { workspace = true }
|
||||||
|
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
|
||||||
graph-craft = { workspace = true }
|
graph-craft = { workspace = true }
|
||||||
wgpu-executor = { workspace = true }
|
wgpu-executor = { workspace = true }
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use super::messages::{DesktopFrontendMessage, DesktopWrapperMessage, EditorMessa
|
|||||||
|
|
||||||
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
|
pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMessageDispatcher, message: DesktopWrapperMessage) {
|
||||||
match message {
|
match message {
|
||||||
DesktopWrapperMessage::FromUi(message) => {
|
DesktopWrapperMessage::FromWeb(message) => {
|
||||||
dispatcher.queue_editor_message(*message);
|
dispatcher.queue_editor_message(*message);
|
||||||
}
|
}
|
||||||
DesktopWrapperMessage::Wake => {
|
DesktopWrapperMessage::Wake => {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use graph_craft::application_io::PlatformApplicationIo;
|
|||||||
use graph_craft::application_io::resource::ResourceStorage;
|
use graph_craft::application_io::resource::ResourceStorage;
|
||||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||||
use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder};
|
use graphite_editor::builder::{Builder, EditorBuilder, RuntimeBuilder};
|
||||||
|
use graphite_editor::messages::frontend::FrontendMessage;
|
||||||
use graphite_editor::node_graph_executor::NodeRuntime;
|
use graphite_editor::node_graph_executor::NodeRuntime;
|
||||||
|
|
||||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||||
@@ -79,3 +80,12 @@ impl DesktopWrapper {
|
|||||||
executor.execute()
|
executor.execute()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
|
||||||
|
let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
|
||||||
|
Some(DesktopWrapperMessage::FromWeb(message.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
|
||||||
|
graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
|
||||||
|
}
|
||||||
@@ -60,7 +60,7 @@ impl<'a> DesktopWrapperMessageDispatcher<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !frontend_messages.is_empty() {
|
if !frontend_messages.is_empty() {
|
||||||
self.respond(DesktopFrontendMessage::ToUi(frontend_messages));
|
self.respond(DesktopFrontendMessage::ToWeb(frontend_messages));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
pub use graphite_editor::messages::prelude::FrontendMessage;
|
use graphite_editor::messages::prelude::FrontendMessage;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
|
||||||
@@ -12,7 +12,7 @@ pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMes
|
|||||||
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
|
||||||
|
|
||||||
pub enum DesktopFrontendMessage {
|
pub enum DesktopFrontendMessage {
|
||||||
ToUi(Vec<FrontendMessage>),
|
ToWeb(Vec<FrontendMessage>),
|
||||||
OpenLaunchDocuments,
|
OpenLaunchDocuments,
|
||||||
OpenFileDialog {
|
OpenFileDialog {
|
||||||
title: String,
|
title: String,
|
||||||
@@ -69,7 +69,7 @@ pub enum DesktopFrontendMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub enum DesktopWrapperMessage {
|
pub enum DesktopWrapperMessage {
|
||||||
FromUi(Box<EditorMessage>),
|
FromWeb(Box<EditorMessage>),
|
||||||
Wake,
|
Wake,
|
||||||
Input(InputMessage),
|
Input(InputMessage),
|
||||||
Ingest { content: DataTransfer, action: IngestAction },
|
Ingest { content: DataTransfer, action: IngestAction },
|
||||||
|
|||||||
@@ -57,6 +57,10 @@ pub mod network {
|
|||||||
pub const IMPORT_METADATA: &str = "ui::import_metadata";
|
pub const IMPORT_METADATA: &str = "ui::import_metadata";
|
||||||
pub const EXPORT_NAMES: &str = "ui::export_names";
|
pub const EXPORT_NAMES: &str = "ui::export_names";
|
||||||
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
|
pub const EXPORT_DESCRIPTIONS: &str = "ui::export_descriptions";
|
||||||
|
|
||||||
|
/// How many pixels make an inch in the network's document, which sizes lengths typed in a physical unit. Absent where it
|
||||||
|
/// is the default, CSS's 96. Only the root network's applies.
|
||||||
|
pub const PIXELS_PER_INCH: &str = "pixels_per_inch";
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod delta {
|
pub mod delta {
|
||||||
|
|||||||
@@ -473,6 +473,12 @@ fn write_ui_network_attributes<M: NodeMetadataSource + ?Sized>(
|
|||||||
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
.map_err(map_serialization_error(network::PINNED_ORDER))?;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if let Some(pixels_per_inch) = metadata.pixels_per_inch(location) {
|
||||||
|
attributes
|
||||||
|
.set_serialized(network::PIXELS_PER_INCH, &pixels_per_inch, timestamp)
|
||||||
|
.map_err(map_serialization_error(network::PIXELS_PER_INCH))?;
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ pub struct NetworkMetadataEntry {
|
|||||||
pub import_metadata: Vec<InputMetadataEntry>,
|
pub import_metadata: Vec<InputMetadataEntry>,
|
||||||
pub export_names: Vec<String>,
|
pub export_names: Vec<String>,
|
||||||
pub export_descriptions: Vec<String>,
|
pub export_descriptions: Vec<String>,
|
||||||
|
/// The document's pixels per inch, where it differs from the default.
|
||||||
|
pub pixels_per_inch: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
/// Editor metadata for one import of a subgraph. Mirrors `InputPersistentMetadata` but wraps strings in `Option` so
|
||||||
@@ -78,6 +80,11 @@ pub trait NodeMetadataSource {
|
|||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The network's pixels per inch, where it differs from the default.
|
||||||
|
fn pixels_per_inch(&self, _network: NetworkLocation) -> Option<f64> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
|
fn import_metadata(&self, _network: NetworkLocation) -> Vec<InputMetadataEntry> {
|
||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -406,11 +406,9 @@ fn set(registry: &mut Registry, ops: &mut Vec<RegistryDelta>, slot: Slot, input:
|
|||||||
match slot {
|
match slot {
|
||||||
Slot::Input(id, index) => {
|
Slot::Input(id, index) => {
|
||||||
let Some(input) = input else { return };
|
let Some(input) = input else { return };
|
||||||
// A chain the line no longer holds the slot for, as shrinking a node's inputs leaves, is not written back
|
if let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) {
|
||||||
let Some(slot) = registry.node_instances.get_mut(&id).and_then(|node| node.inputs.get_mut(index as usize)) else {
|
slot.input = input.clone();
|
||||||
return;
|
}
|
||||||
};
|
|
||||||
slot.input = input.clone();
|
|
||||||
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
|
ops.push(RegistryDelta::ChangeNodeInput { id, index, new_input: input });
|
||||||
}
|
}
|
||||||
Slot::Export(id, index) => {
|
Slot::Export(id, index) => {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
//! operation mixed in. After every operation nothing may name a node the document no longer has.
|
||||||
|
|
||||||
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
use super::simulation::{LEAF, Random, Scenario, below, empty_export, from_env, on, simulate, stack, value};
|
||||||
use crate::{Implementation, InputSlot, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session, TimeStamp};
|
use crate::{Implementation, Network, Node, NodeId, NodeInput, ROOT_NETWORK, Registry, RegistryDelta, Session};
|
||||||
|
|
||||||
/// A slot that can name a node.
|
/// A slot that can name a node.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
@@ -94,16 +94,14 @@ impl Scenario for Branching {
|
|||||||
node.inputs[1].input = second;
|
node.inputs[1].input = second;
|
||||||
node
|
node
|
||||||
};
|
};
|
||||||
// Nodes that still have an input past the primary one, the only ones an edit may write there
|
|
||||||
let wide: Vec<NodeId> = nodes.iter().copied().filter(|id| registry.node_instances[id].inputs.len() > 1).collect();
|
|
||||||
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
// Nodes with nothing hanging off their second input, so taking one does not leave a chain behind
|
||||||
let plain: Vec<NodeId> = wide
|
let plain: Vec<NodeId> = nodes
|
||||||
.iter()
|
.iter()
|
||||||
.copied()
|
.copied()
|
||||||
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
.filter(|id| !matches!(place_value(®istry, Place::Input(*id, 1)), Some(NodeInput::Node { .. })))
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
match random.below(14) {
|
match random.below(12) {
|
||||||
// Draw a node on top of the chain off the export
|
// Draw a node on top of the chain off the export
|
||||||
0..=2 => {
|
0..=2 => {
|
||||||
let id = session.next_node_id();
|
let id = session.next_node_id();
|
||||||
@@ -124,7 +122,7 @@ impl Scenario for Branching {
|
|||||||
}
|
}
|
||||||
// Hang a node on an input past the primary one, over whatever is there already
|
// Hang a node on an input past the primary one, over whatever is there already
|
||||||
3..=5 => {
|
3..=5 => {
|
||||||
let Some(host) = random.pick(&wide) else { return Vec::new() };
|
let Some(host) = random.pick(&nodes) else { return Vec::new() };
|
||||||
let id = session.next_node_id();
|
let id = session.next_node_id();
|
||||||
let first = match place_value(®istry, Place::Input(host, 1)) {
|
let first = match place_value(®istry, Place::Input(host, 1)) {
|
||||||
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
Some(NodeInput::Node { id: under, index }) => NodeInput::Node { id: under, index },
|
||||||
@@ -181,25 +179,6 @@ impl Scenario for Branching {
|
|||||||
new_input: value(random.below(100)),
|
new_input: value(random.below(100)),
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
// Rewrite a node's whole input list, which an index-addressed write cannot express
|
|
||||||
11..=12 => {
|
|
||||||
let Some(node) = random.pick(&nodes) else { return Vec::new() };
|
|
||||||
let mut inputs = registry.node_instances[&node].inputs.clone();
|
|
||||||
match random.below(3) {
|
|
||||||
// Swap the first two, so what the node rested on moves past its primary input
|
|
||||||
0 if inputs.len() > 1 => inputs.swap(0, 1),
|
|
||||||
// One input more, holding a value
|
|
||||||
1 if inputs.len() < 4 => inputs.push(InputSlot {
|
|
||||||
input: value(random.below(100)),
|
|
||||||
timestamp: TimeStamp::ORIGIN,
|
|
||||||
attributes: Default::default(),
|
|
||||||
}),
|
|
||||||
// One input fewer, as removing a subgraph's import slot leaves the nodes wrapping it
|
|
||||||
_ if inputs.len() > 1 => _ = inputs.pop(),
|
|
||||||
_ => return Vec::new(),
|
|
||||||
}
|
|
||||||
vec![RegistryDelta::SetNodeInputs { id: node, inputs }]
|
|
||||||
}
|
|
||||||
// Cut the chain off an input past the primary one, taking its nodes with it
|
// Cut the chain off an input past the primary one, taking its nodes with it
|
||||||
_ => {
|
_ => {
|
||||||
let hosts: Vec<NodeId> = nodes
|
let hosts: Vec<NodeId> = nodes
|
||||||
|
|||||||
@@ -12,9 +12,25 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry, from_valu
|
|||||||
/// Note: This only works for complete networks with all inputs resolved.
|
/// Note: This only works for complete networks with all inputs resolved.
|
||||||
/// Test networks with Import inputs will fail compilation (which is expected).
|
/// Test networks with Import inputs will fail compilation (which is expected).
|
||||||
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
|
||||||
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
|
||||||
let mut network = network.clone();
|
let mut network = network.clone();
|
||||||
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
|
network.inline_definitions().map_err(|e| format!("Inlining failed: {e}"))?;
|
||||||
|
|
||||||
|
// Nodes measuring in physical units read the document's resolution from the scope the runtime wraps every document in
|
||||||
|
let resolution_node = NodeId(u64::MAX);
|
||||||
|
network.nodes.insert(
|
||||||
|
resolution_node,
|
||||||
|
DocumentNode {
|
||||||
|
inputs: vec![NodeInput::value(TaggedValue::Number(core_types::units::DEFAULT_PIXELS_PER_INCH), false)],
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::ops::PassthroughNode")),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
network
|
||||||
|
.scope_injections
|
||||||
|
.insert(core_types::units::PIXELS_PER_INCH_SCOPE.to_string(), (resolution_node, core_types::item!(f64)));
|
||||||
|
|
||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
compiler.compile_single(network).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -417,6 +417,7 @@ fn extract_network_metadata(registry: &Registry, attributes: &crate::Attributes,
|
|||||||
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
|
import_metadata: attributes.get_or_default(network::IMPORT_METADATA),
|
||||||
export_names: attributes.get_or_default(network::EXPORT_NAMES),
|
export_names: attributes.get_or_default(network::EXPORT_NAMES),
|
||||||
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
|
export_descriptions: attributes.get_or_default(network::EXPORT_DESCRIPTIONS),
|
||||||
|
pixels_per_inch: attributes.get_typed(network::PIXELS_PER_INCH),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,53 +0,0 @@
|
|||||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Bool(bool),
|
|
||||||
DAffine2([f64; 6]),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
|
|
||||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
|
|
||||||
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
|
|
||||||
for input in added_inputs() {
|
|
||||||
inputs.push(input);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
|
||||||
fn added_inputs() -> [NodeInput; 2] {
|
|
||||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&BevelAndEmbossV2, &contract());
|
|
||||||
check_undo(&BevelAndEmbossV2, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
|
|
||||||
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&BevelAndEmbossV2);
|
|
||||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
|
|
||||||
|
|
||||||
let mut expected = inputs;
|
|
||||||
expected.extend(added_inputs());
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
use migration_core::{Inputs, NodeInput, encode, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
TypeDefault(Type),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Frozen mirror of the `Type` an empty list of graphics stores.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Type {
|
|
||||||
Concrete(TypeDescriptor),
|
|
||||||
List(Box<Type>),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
struct TypeDescriptor {
|
|
||||||
name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
|
|
||||||
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
|
||||||
pub fn blur_v2(inputs: &mut Inputs) {
|
|
||||||
inputs.insert(2, empty_radius_mask());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
|
|
||||||
fn empty_radius_mask() -> NodeInput {
|
|
||||||
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
|
|
||||||
name: "graphic_types::graphic::Graphic".to_string(),
|
|
||||||
}))));
|
|
||||||
NodeInput::Value {
|
|
||||||
value: encode(&no_graphics),
|
|
||||||
exposed: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::{decl, literal};
|
|
||||||
use migration_runner::testing::{Fixture, 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(&BlurV2, &contract());
|
|
||||||
check_undo(&BlurV2, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
|
|
||||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&BlurV2);
|
|
||||||
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&BlurV2).unwrap();
|
|
||||||
|
|
||||||
let mut expected = inputs;
|
|
||||||
expected.insert(2, empty_radius_mask());
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, blur), expected);
|
|
||||||
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
use migration_core::{Inputs, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Bool(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
|
|
||||||
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
|
|
||||||
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
|
|
||||||
inputs.push(literal(Tagged::Bool(false)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, 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(&ConvolutionKernelV1, &contract());
|
|
||||||
check_undo(&ConvolutionKernelV1, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
|
|
||||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&ConvolutionKernelV1);
|
|
||||||
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
use migration_core::{Inputs, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Number(f64),
|
|
||||||
Integer(i64),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Inner Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
|
|
||||||
#[migration("blending_nodes::effects::InnerGlowNode"@2 => @3)]
|
|
||||||
pub fn inner_glow_v2(inputs: &mut Inputs) {
|
|
||||||
inputs.insert(8, literal(Tagged::Number(0.)));
|
|
||||||
inputs.insert(9, literal(Tagged::Number(0.)));
|
|
||||||
inputs.insert(10, literal(Tagged::Integer(0)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, 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(&InnerGlowV2, &contract());
|
|
||||||
check_undo(&InnerGlowV2, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
|
||||||
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&InnerGlowV2);
|
|
||||||
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@2), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&InnerGlowV2).unwrap();
|
|
||||||
|
|
||||||
let mut expected = inputs;
|
|
||||||
expected.splice(8..8, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@3)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,13 @@
|
|||||||
//! Migrations of the nodes in `blending_nodes`.
|
//! Migrations of the nodes in `blending_nodes`.
|
||||||
|
|
||||||
mod bevel_and_emboss_v1;
|
mod bevel_and_emboss_v1;
|
||||||
mod bevel_and_emboss_v2;
|
|
||||||
mod blur_v2;
|
|
||||||
mod convolution_kernel_v1;
|
|
||||||
mod drop_shadow_v1;
|
mod drop_shadow_v1;
|
||||||
mod inner_glow_v1;
|
mod inner_glow_v1;
|
||||||
mod inner_glow_v2;
|
|
||||||
mod inner_shadow_v1;
|
mod inner_shadow_v1;
|
||||||
mod mask_by_any_graphic;
|
mod mask_by_any_graphic;
|
||||||
mod outer_glow_v1;
|
mod outer_glow_v1;
|
||||||
mod outer_glow_v2;
|
|
||||||
mod outline_v1;
|
mod outline_v1;
|
||||||
mod outline_v2;
|
mod outline_v2;
|
||||||
mod outline_v3;
|
|
||||||
mod paint_overlay_from_color_overlay;
|
mod paint_overlay_from_color_overlay;
|
||||||
mod paint_overlay_v2;
|
|
||||||
mod radial_blur_v1;
|
|
||||||
mod renames;
|
mod renames;
|
||||||
mod satin_v1;
|
mod satin_v1;
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
use migration_core::{Inputs, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Number(f64),
|
|
||||||
Integer(i64),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Outer Glow' gained Jitter, Noise, and a seed before its contour, set to none to keep the glow smooth.
|
|
||||||
#[migration("blending_nodes::effects::OuterGlowNode"@2 => @3)]
|
|
||||||
pub fn outer_glow_v2(inputs: &mut Inputs) {
|
|
||||||
inputs.insert(7, literal(Tagged::Number(0.)));
|
|
||||||
inputs.insert(8, literal(Tagged::Number(0.)));
|
|
||||||
inputs.insert(9, literal(Tagged::Integer(0)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&OuterGlowV2, &contract());
|
|
||||||
check_undo(&OuterGlowV2, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
|
||||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&OuterGlowV2);
|
|
||||||
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@2), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&OuterGlowV2).unwrap();
|
|
||||||
|
|
||||||
let mut expected = inputs;
|
|
||||||
expected.splice(7..7, [literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@3)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Bool(bool),
|
|
||||||
DAffine2([f64; 6]),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Outline' defaults to fitting gradients without a transform across the content.
|
|
||||||
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
|
|
||||||
pub fn outline_v3(inputs: &mut Inputs) {
|
|
||||||
for input in added_inputs() {
|
|
||||||
inputs.push(input);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
|
||||||
fn added_inputs() -> [NodeInput; 2] {
|
|
||||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&OutlineV3, &contract());
|
|
||||||
check_undo(&OutlineV3, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
|
||||||
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&OutlineV3);
|
|
||||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&OutlineV3).unwrap();
|
|
||||||
|
|
||||||
let mut expected = inputs;
|
|
||||||
expected.extend(added_inputs());
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,53 +0,0 @@
|
|||||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Bool(bool),
|
|
||||||
DAffine2([f64; 6]),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
|
|
||||||
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
|
|
||||||
pub fn paint_overlay_v2(inputs: &mut Inputs) {
|
|
||||||
for input in added_inputs() {
|
|
||||||
inputs.push(input);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
|
||||||
fn added_inputs() -> [NodeInput; 2] {
|
|
||||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, 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(&PaintOverlayV2, &contract());
|
|
||||||
check_undo(&PaintOverlayV2, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
|
||||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&PaintOverlayV2);
|
|
||||||
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
|
|
||||||
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
|
|
||||||
|
|
||||||
let mut expected = inputs;
|
|
||||||
expected.extend(added_inputs());
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, overlay), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
const CENTER: u32 = 3;
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
DVec2([f64; 2]),
|
|
||||||
DAffine2([f64; 6]),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps.
|
|
||||||
/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin.
|
|
||||||
#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)]
|
|
||||||
pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
|
|
||||||
let Some(center) = node.inputs().get(CENTER as usize) else {
|
|
||||||
return Err(MigrationError::invariant("Radial Blur has a Center input"));
|
|
||||||
};
|
|
||||||
|
|
||||||
inputs.set(CENTER, transform_input(¢er.input));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired.
|
|
||||||
fn transform_input(center: &NodeInput) -> NodeInput {
|
|
||||||
let ([x, y], exposed) = match center {
|
|
||||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(center) {
|
|
||||||
Some(Tagged::DVec2(center)) => (center, *exposed),
|
|
||||||
_ => ([0., 0.], *exposed),
|
|
||||||
},
|
|
||||||
_ => ([0., 0.], true),
|
|
||||||
};
|
|
||||||
|
|
||||||
NodeInput::Value {
|
|
||||||
value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])),
|
|
||||||
exposed,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::{decl, literal};
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
const CENTER_SLOT: usize = CENTER as usize;
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(5, |random, slot| match slot {
|
|
||||||
CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])),
|
|
||||||
_ => literal(random.below(10) as f64),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn radial_blur_inputs(center: NodeInput) -> Vec<NodeInput> {
|
|
||||||
let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
|
||||||
inputs[CENTER_SLOT] = center;
|
|
||||||
inputs
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&RadialBlurV1, &contract());
|
|
||||||
check_undo(&RadialBlurV1, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_center_becomes_the_translation_of_the_transform_in_its_place() {
|
|
||||||
let mut fixture = Fixture::new(&RadialBlurV1);
|
|
||||||
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.]))));
|
|
||||||
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
|
||||||
|
|
||||||
let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.])));
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, radial_blur), expected);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wired_center_becomes_the_identity_shown_in_the_graph() {
|
|
||||||
let mut fixture = Fixture::new(&RadialBlurV1);
|
|
||||||
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
|
||||||
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 }));
|
|
||||||
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
|
||||||
|
|
||||||
let identity = NodeInput::Value {
|
|
||||||
value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
|
||||||
exposed: true,
|
|
||||||
};
|
|
||||||
assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
use migration_core::{Inputs, NodeInput, migration};
|
||||||
|
|
||||||
|
/// Reads the document's resolution from the scope, which sizes the physical lengths an expression measures.
|
||||||
|
#[migration("math_nodes::MathFunctionNode"@2 => @3)]
|
||||||
|
pub fn math_function_v2(inputs: &mut Inputs) {
|
||||||
|
inputs.push(NodeInput::Scope("pixels-per-inch".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::{decl, literal};
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants the node's inputs hold in version 2.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
Number(f64),
|
||||||
|
String(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(3, |random, slot| match slot {
|
||||||
|
1 => literal(Tagged::String("x".to_string())),
|
||||||
|
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&MathFunctionV2, &contract());
|
||||||
|
check_undo(&MathFunctionV2, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_resolution_is_read_from_the_scope() {
|
||||||
|
let inputs = vec![literal(Tagged::Number(2.)), literal(Tagged::String("x * 2".to_string())), literal(Tagged::Number(0.))];
|
||||||
|
|
||||||
|
let mut fixture = Fixture::new(&MathFunctionV2);
|
||||||
|
let function = fixture.add(decl!("math_nodes::MathFunctionNode"@2), inputs.clone());
|
||||||
|
let migrated = fixture.migrate(&MathFunctionV2).unwrap();
|
||||||
|
|
||||||
|
let expected: Vec<NodeInput> = inputs.into_iter().chain([NodeInput::Scope("pixels-per-inch".into())]).collect();
|
||||||
|
assert_eq!(fixture.inputs(&migrated, function), expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
//! Migrations of the nodes in `math_nodes`.
|
//! Migrations of the nodes in `math_nodes`.
|
||||||
|
|
||||||
mod math_formula_from_math_f;
|
mod math_formula_from_math_f;
|
||||||
|
mod math_function_v2;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
use migration_core::{Inputs, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Number(f64),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Make Opaque' gained a Strength percentage, set to 100% to keep making the content fully opaque.
|
|
||||||
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
|
|
||||||
pub fn make_opaque_v1(inputs: &mut Inputs) {
|
|
||||||
inputs.push(literal(Tagged::Number(100.)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::decl;
|
|
||||||
use migration_runner::testing::{Fixture, 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());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_content_and_adds_full_strength() {
|
|
||||||
let content = literal(1.);
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&MakeOpaqueV1);
|
|
||||||
let make_opaque = fixture.add(decl!("raster_nodes::adjustments::MakeOpaqueNode"@1), vec![content.clone()]);
|
|
||||||
let migrated = fixture.migrate(&MakeOpaqueV1).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, make_opaque), Some(decl!("raster_nodes::adjustments::MakeOpaqueNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, make_opaque), [content, literal(Tagged::Number(100.))]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
//! Migrations of the nodes in `raster_nodes`.
|
//! Migrations of the nodes in `raster_nodes`.
|
||||||
|
|
||||||
mod make_opaque_v1;
|
|
||||||
mod mandelbrot_v1;
|
mod mandelbrot_v1;
|
||||||
mod mandelbrot_v2;
|
mod mandelbrot_v2;
|
||||||
mod mix_colors_from_mix_node;
|
mod mix_colors_from_mix_node;
|
||||||
mod noise_pattern_v1;
|
mod noise_pattern_v1;
|
||||||
mod noise_pattern_v2;
|
|
||||||
mod pattern_square;
|
mod pattern_square;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
use migration_core::attr::node::VISIBLE;
|
|
||||||
use migration_core::attr::node::ui::POSITION;
|
|
||||||
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Number(f64),
|
|
||||||
Bool(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
|
|
||||||
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
|
|
||||||
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
|
|
||||||
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
|
|
||||||
let consumers = downstream.consumers(0);
|
|
||||||
if consumers.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let gamma_correction = downstream.add_node(NewNode {
|
|
||||||
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
|
|
||||||
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
|
|
||||||
});
|
|
||||||
for consumer in consumers {
|
|
||||||
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
|
|
||||||
if !node.attributes().get_or(VISIBLE, true) {
|
|
||||||
attributes.set(gamma_correction, VISIBLE, &false);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The Gamma Correction takes the pattern's place, with the pattern before it
|
|
||||||
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
|
|
||||||
attributes.set(gamma_correction, POSITION, &stored);
|
|
||||||
}
|
|
||||||
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
|
|
||||||
use migration_core::Declaration;
|
|
||||||
use migration_core::attr::node::ui::IS_LAYER;
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
|
|
||||||
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
|
|
||||||
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn noise_inputs() -> Vec<NodeInput> {
|
|
||||||
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wire(id: NodeId) -> NodeInput {
|
|
||||||
NodeInput::Node { id, index: 0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&NoisePatternV2, &contract());
|
|
||||||
check_undo(&NoisePatternV2, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
|
|
||||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
|
||||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
|
||||||
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
|
|
||||||
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
|
|
||||||
fixture.export(wire(noise));
|
|
||||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
|
|
||||||
|
|
||||||
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
|
|
||||||
panic!("the consumer should read a node")
|
|
||||||
};
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
|
|
||||||
|
|
||||||
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
|
|
||||||
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
|
|
||||||
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
|
|
||||||
assert_eq!(migrated.node_instances.len(), 4);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
|
|
||||||
let visibility_of_gamma_correction = |visible: bool| {
|
|
||||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
|
||||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
|
||||||
if !visible {
|
|
||||||
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
|
|
||||||
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
|
|
||||||
}
|
|
||||||
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
|
|
||||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
|
||||||
|
|
||||||
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
|
|
||||||
panic!("the consumer should read a node")
|
|
||||||
};
|
|
||||||
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
|
|
||||||
};
|
|
||||||
|
|
||||||
// Visible is the default, so only a disabled pattern writes it
|
|
||||||
assert_eq!(visibility_of_gamma_correction(false), Some(false));
|
|
||||||
assert_eq!(visibility_of_gamma_correction(true), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_unread_pattern_gains_no_gamma_correction() {
|
|
||||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
|
||||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
|
||||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
|
|
||||||
assert_eq!(migrated.node_instances.len(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
|
|
||||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
|
||||||
|
|
||||||
// A custom subgraph exporting the pattern, read by the root network's export
|
|
||||||
let (subgraph, instance) = (NetworkId(100), NodeId(100));
|
|
||||||
fixture.registry.networks.insert(subgraph, Network::default());
|
|
||||||
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
|
|
||||||
fixture.registry.node_instances.insert(instance, instance_node);
|
|
||||||
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
|
|
||||||
fixture.export_from(subgraph, wire(noise));
|
|
||||||
fixture.export(wire(instance));
|
|
||||||
|
|
||||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
|
||||||
|
|
||||||
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
|
|
||||||
panic!("the subgraph's export should read a node")
|
|
||||||
};
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
|
||||||
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
|
|
||||||
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
|
|
||||||
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
|
|
||||||
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
|
|
||||||
let mut fixture = Fixture::new(&NoisePatternV2);
|
|
||||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
|
|
||||||
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
|
|
||||||
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
|
|
||||||
|
|
||||||
let (reader, slot) = if read_by_layer {
|
|
||||||
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
|
|
||||||
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
|
|
||||||
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
|
|
||||||
(layer, 1)
|
|
||||||
} else {
|
|
||||||
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
|
|
||||||
};
|
|
||||||
|
|
||||||
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
|
|
||||||
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
|
|
||||||
panic!("slot {slot} of the reader should read a node")
|
|
||||||
};
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
|
|
||||||
|
|
||||||
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
|
|
||||||
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
|
|
||||||
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
|
|
||||||
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
use migration_core::{Inputs, Node, literal, literal_of, migration};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
const RADIUS: usize = 1;
|
||||||
|
|
||||||
|
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum Tagged {
|
||||||
|
None,
|
||||||
|
Number(f64),
|
||||||
|
Length(TypedLength),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
struct TypedLength {
|
||||||
|
value: f64,
|
||||||
|
unit: LengthUnit,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
enum LengthUnit {
|
||||||
|
Pixel,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The radius is a length, which keeps the number of pixels it held. A wired number still feeds it, read as pixels.
|
||||||
|
#[migration("vector_nodes::generator_nodes::CircleNode"@1 => @2)]
|
||||||
|
pub fn circle_v1(node: &Node, inputs: &mut Inputs) {
|
||||||
|
let Some(slot) = node.inputs().get(RADIUS) else { return };
|
||||||
|
let Some(Tagged::Number(pixels)) = literal_of::<Tagged>(&slot.input) else { return };
|
||||||
|
|
||||||
|
inputs.set(
|
||||||
|
RADIUS as u32,
|
||||||
|
literal(Tagged::Length(TypedLength {
|
||||||
|
value: pixels,
|
||||||
|
unit: LengthUnit::Pixel,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use migration_core::decl;
|
||||||
|
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||||
|
|
||||||
|
fn contract() -> SourceContract {
|
||||||
|
SourceContract::new(2, |random, slot| if slot == 0 { literal(Tagged::None) } else { literal(Tagged::Number(random.below(100) as f64)) })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_history() {
|
||||||
|
check_commutation(&CircleV1, &contract());
|
||||||
|
check_undo(&CircleV1, &contract());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_number_of_pixels_becomes_a_length_in_pixels() {
|
||||||
|
let mut fixture = Fixture::new(&CircleV1);
|
||||||
|
let circle = fixture.add(decl!("vector_nodes::generator_nodes::CircleNode"@1), vec![literal(Tagged::None), literal(Tagged::Number(50.))]);
|
||||||
|
let migrated = fixture.migrate(&CircleV1).unwrap();
|
||||||
|
|
||||||
|
let radius = literal(Tagged::Length(TypedLength { value: 50., unit: LengthUnit::Pixel }));
|
||||||
|
assert_eq!(fixture.inputs(&migrated, circle), [literal(Tagged::None), radius]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
//! Migrations of the nodes in `vector_nodes`.
|
//! Migrations of the nodes in `vector_nodes`.
|
||||||
|
|
||||||
|
mod circle_v1;
|
||||||
mod path_from_path_network;
|
mod path_from_path_network;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -6,6 +6,8 @@ use crate::messages::prelude::*;
|
|||||||
pub enum DialogMessage {
|
pub enum DialogMessage {
|
||||||
// Sub-messages
|
// Sub-messages
|
||||||
#[child]
|
#[child]
|
||||||
|
DocumentSetupDialog(DocumentSetupDialogMessage),
|
||||||
|
#[child]
|
||||||
ExportDialog(ExportDialogMessage),
|
ExportDialog(ExportDialogMessage),
|
||||||
#[child]
|
#[child]
|
||||||
NewDocumentDialog(NewDocumentDialogMessage),
|
NewDocumentDialog(NewDocumentDialogMessage),
|
||||||
@@ -34,6 +36,7 @@ pub enum DialogMessage {
|
|||||||
localized_commit_year: String,
|
localized_commit_year: String,
|
||||||
},
|
},
|
||||||
RequestDemoArtworkDialog,
|
RequestDemoArtworkDialog,
|
||||||
|
RequestDocumentSetupDialog,
|
||||||
RequestExportDialog,
|
RequestExportDialog,
|
||||||
RequestLicensesDialogWithLocalizedCommitDate {
|
RequestLicensesDialogWithLocalizedCommitDate {
|
||||||
localized_commit_year: String,
|
localized_commit_year: String,
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
|
|||||||
use crate::messages::frontend::utility_types::ExportBounds;
|
use crate::messages::frontend::utility_types::ExportBounds;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
|
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, TypedLength};
|
||||||
|
|
||||||
#[derive(ExtractField)]
|
#[derive(ExtractField)]
|
||||||
pub struct DialogMessageContext<'a> {
|
pub struct DialogMessageContext<'a> {
|
||||||
@@ -16,6 +17,7 @@ pub struct DialogMessageContext<'a> {
|
|||||||
pub struct DialogMessageHandler {
|
pub struct DialogMessageHandler {
|
||||||
on_dismiss: Option<Message>,
|
on_dismiss: Option<Message>,
|
||||||
redisplay: Option<Message>,
|
redisplay: Option<Message>,
|
||||||
|
document_setup_dialog: DocumentSetupDialogMessageHandler,
|
||||||
export_dialog: ExportDialogMessageHandler,
|
export_dialog: ExportDialogMessageHandler,
|
||||||
new_document_dialog: NewDocumentDialogMessageHandler,
|
new_document_dialog: NewDocumentDialogMessageHandler,
|
||||||
preferences_dialog: PreferencesDialogMessageHandler,
|
preferences_dialog: PreferencesDialogMessageHandler,
|
||||||
@@ -27,6 +29,7 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
|||||||
let DialogMessageContext { portfolio, preferences } = context;
|
let DialogMessageContext { portfolio, preferences } = context;
|
||||||
|
|
||||||
match message {
|
match message {
|
||||||
|
DialogMessage::DocumentSetupDialog(message) => self.document_setup_dialog.process_message(message, responses, ()),
|
||||||
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
||||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
||||||
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
||||||
@@ -100,6 +103,15 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
|||||||
let dialog = DemoArtworkDialog;
|
let dialog = DemoArtworkDialog;
|
||||||
dialog.send_dialog_to_frontend(responses);
|
dialog.send_dialog_to_frontend(responses);
|
||||||
}
|
}
|
||||||
|
DialogMessage::RequestDocumentSetupDialog => {
|
||||||
|
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||||
|
if let Some(document) = portfolio.active_document() {
|
||||||
|
self.document_setup_dialog = DocumentSetupDialogMessageHandler {
|
||||||
|
pixels_per_inch: document.network_interface.pixels_per_inch(),
|
||||||
|
};
|
||||||
|
self.document_setup_dialog.send_dialog_to_frontend(responses);
|
||||||
|
}
|
||||||
|
}
|
||||||
DialogMessage::RequestExportDialog => {
|
DialogMessage::RequestExportDialog => {
|
||||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||||
if let Some(document) = portfolio.active_document() {
|
if let Some(document) = portfolio.active_document() {
|
||||||
@@ -145,7 +157,9 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
|||||||
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
self.new_document_dialog = NewDocumentDialogMessageHandler {
|
||||||
name: portfolio.generate_new_document_name(None),
|
name: portfolio.generate_new_document_name(None),
|
||||||
infinite: false,
|
infinite: false,
|
||||||
dimensions: glam::UVec2::new(1920, 1080),
|
width: TypedLength::pixels(1920.),
|
||||||
|
height: TypedLength::pixels(1080.),
|
||||||
|
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||||
};
|
};
|
||||||
self.new_document_dialog.send_dialog_to_frontend(responses);
|
self.new_document_dialog.send_dialog_to_frontend(responses);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
use crate::messages::prelude::*;
|
||||||
|
|
||||||
|
#[impl_message(Message, DialogMessage, DocumentSetupDialog)]
|
||||||
|
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub enum DocumentSetupDialogMessage {
|
||||||
|
Resolution { pixels_per_inch: f64 },
|
||||||
|
|
||||||
|
Submit,
|
||||||
|
}
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::prelude::*;
|
||||||
|
use graphene_std::units::DEFAULT_PIXELS_PER_INCH;
|
||||||
|
|
||||||
|
/// A dialog to allow users to change the settings of the active document.
|
||||||
|
#[derive(Debug, Clone, ExtractField)]
|
||||||
|
pub struct DocumentSetupDialogMessageHandler {
|
||||||
|
pub pixels_per_inch: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DocumentSetupDialogMessageHandler {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[message_handler_data]
|
||||||
|
impl MessageHandler<DocumentSetupDialogMessage, ()> for DocumentSetupDialogMessageHandler {
|
||||||
|
fn process_message(&mut self, message: DocumentSetupDialogMessage, responses: &mut VecDeque<Message>, _: ()) {
|
||||||
|
match message {
|
||||||
|
DocumentSetupDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||||
|
|
||||||
|
DocumentSetupDialogMessage::Submit => {
|
||||||
|
// The settings apply as one undo step, which ending the transaction drops if nothing changed
|
||||||
|
responses.add(DocumentMessage::StartTransaction);
|
||||||
|
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||||
|
pixels_per_inch: self.pixels_per_inch,
|
||||||
|
});
|
||||||
|
responses.add(DocumentMessage::EndTransaction);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.send_dialog_to_frontend(responses);
|
||||||
|
}
|
||||||
|
|
||||||
|
advertise_actions!(DocumentSetupDialogUpdate;
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DialogLayoutHolder for DocumentSetupDialogMessageHandler {
|
||||||
|
const ICON: &'static str = "File";
|
||||||
|
const TITLE: &'static str = "Document Setup";
|
||||||
|
|
||||||
|
fn layout_buttons(&self) -> Layout {
|
||||||
|
let widgets = vec![
|
||||||
|
TextButton::new("OK")
|
||||||
|
.emphasized(true)
|
||||||
|
.on_update(|_| {
|
||||||
|
DialogMessage::CloseAndThen {
|
||||||
|
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
})
|
||||||
|
.widget_instance(),
|
||||||
|
TextButton::new("Cancel").on_update(|_| DialogMessage::Close.into()).widget_instance(),
|
||||||
|
];
|
||||||
|
|
||||||
|
Layout(vec![LayoutGroup::row(widgets)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LayoutHolder for DocumentSetupDialogMessageHandler {
|
||||||
|
fn layout(&self) -> Layout {
|
||||||
|
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| DocumentSetupDialogMessage::Resolution { pixels_per_inch }.into());
|
||||||
|
|
||||||
|
Layout(vec![LayoutGroup::row(resolution)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The labeled field for a document's resolution in pixels per inch, shared by the dialogs that set it.
|
||||||
|
pub fn resolution_row(pixels_per_inch: f64, on_update: impl Fn(f64) -> Message + Send + Sync + 'static) -> Vec<WidgetInstance> {
|
||||||
|
let description = "How many pixels make an inch, which sizes the lengths typed in physical units like millimeters and inches, and the physical size of exported files.";
|
||||||
|
|
||||||
|
vec![
|
||||||
|
TextLabel::new("Resolution")
|
||||||
|
.table_align(true)
|
||||||
|
.sizing(WidgetSizing::fixed(90))
|
||||||
|
.tooltip_label("Resolution")
|
||||||
|
.tooltip_description(description)
|
||||||
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
NumberInput::new(Some(pixels_per_inch))
|
||||||
|
.unit(" PPI")
|
||||||
|
.min(1.)
|
||||||
|
.max(100_000.)
|
||||||
|
.tooltip_label("Resolution")
|
||||||
|
.tooltip_description(description)
|
||||||
|
// Matches the width of the New Document dialog's Name field
|
||||||
|
.sizing(WidgetSizing::default().min_width(204))
|
||||||
|
.on_update(move |number_input: &NumberInput| on_update(number_input.value.unwrap_or(DEFAULT_PIXELS_PER_INCH)))
|
||||||
|
.widget_instance(),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
|
||||||
|
fn pixels_per_inch(editor: &EditorTestUtils) -> f64 {
|
||||||
|
editor.active_document().network_interface.pixels_per_inch()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn open_and_set_resolution(editor: &mut EditorTestUtils, pixels_per_inch: f64) {
|
||||||
|
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||||
|
editor.handle_message(DocumentSetupDialogMessage::Resolution { pixels_per_inch }).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn confirm(editor: &mut EditorTestUtils) {
|
||||||
|
editor
|
||||||
|
.handle_message(DialogMessage::CloseAndThen {
|
||||||
|
followups: vec![DocumentSetupDialogMessage::Submit.into()],
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn confirming_a_resolution_applies_it_as_one_undo_step() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.draw_rect(0., 0., 100., 100.).await;
|
||||||
|
let layer_count = editor.active_document().metadata().all_layers().count();
|
||||||
|
|
||||||
|
open_and_set_resolution(&mut editor, 300.).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 96., "the dialog applies nothing before it is confirmed");
|
||||||
|
confirm(&mut editor).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||||
|
|
||||||
|
// Undoing reverts only the resolution, leaving the rectangle drawn before it
|
||||||
|
editor.handle_message(DocumentMessage::Undo).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 96.);
|
||||||
|
assert_eq!(editor.active_document().metadata().all_layers().count(), layer_count);
|
||||||
|
|
||||||
|
editor.handle_message(DocumentMessage::Redo).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn canceling_or_confirming_an_unchanged_resolution_adds_no_undo_step() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
open_and_set_resolution(&mut editor, 300.).await;
|
||||||
|
confirm(&mut editor).await;
|
||||||
|
|
||||||
|
open_and_set_resolution(&mut editor, 150.).await;
|
||||||
|
editor.handle_message(DialogMessage::Close).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300., "canceling discards the dialog's resolution");
|
||||||
|
|
||||||
|
// Reopening starts from the document's resolution, so confirming it unchanged has nothing to apply
|
||||||
|
editor.handle_message(DialogMessage::RequestDocumentSetupDialog).await;
|
||||||
|
confirm(&mut editor).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 300.);
|
||||||
|
|
||||||
|
editor.handle_message(DocumentMessage::Undo).await;
|
||||||
|
assert_eq!(pixels_per_inch(&editor), 96., "the one undo step is the resolution's first change");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
mod document_setup_dialog_message;
|
||||||
|
mod document_setup_dialog_message_handler;
|
||||||
|
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use document_setup_dialog_message::{DocumentSetupDialogMessage, DocumentSetupDialogMessageDiscriminant};
|
||||||
|
#[doc(inline)]
|
||||||
|
pub use document_setup_dialog_message_handler::{DocumentSetupDialogMessageHandler, resolution_row};
|
||||||
@@ -8,6 +8,7 @@
|
|||||||
mod dialog_message;
|
mod dialog_message;
|
||||||
mod dialog_message_handler;
|
mod dialog_message_handler;
|
||||||
|
|
||||||
|
pub mod document_setup_dialog;
|
||||||
pub mod export_dialog;
|
pub mod export_dialog;
|
||||||
pub mod new_document_dialog;
|
pub mod new_document_dialog;
|
||||||
pub mod preferences_dialog;
|
pub mod preferences_dialog;
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
|
use graphene_std::units::TypedLength;
|
||||||
|
|
||||||
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
|
#[impl_message(Message, DialogMessage, NewDocumentDialog)]
|
||||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum NewDocumentDialogMessage {
|
pub enum NewDocumentDialogMessage {
|
||||||
Name { name: String },
|
Name { name: String },
|
||||||
Infinite { infinite: bool },
|
Infinite { infinite: bool },
|
||||||
DimensionsX { width: f64 },
|
DimensionsX { width: TypedLength },
|
||||||
DimensionsY { height: f64 },
|
DimensionsY { height: TypedLength },
|
||||||
|
Resolution { pixels_per_inch: f64 },
|
||||||
|
|
||||||
Submit,
|
Submit,
|
||||||
}
|
}
|
||||||
+177
-29
@@ -1,16 +1,33 @@
|
|||||||
|
use crate::messages::dialog::document_setup_dialog::resolution_row;
|
||||||
|
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||||
use glam::UVec2;
|
use glam::DVec2;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::Color;
|
use graphene_std::Color;
|
||||||
|
use graphene_std::units::{DEFAULT_PIXELS_PER_INCH, LengthUnit, TypedLength};
|
||||||
|
|
||||||
/// A dialog to allow users to set some initial options about a new document.
|
/// A dialog to allow users to set some initial options about a new document.
|
||||||
#[derive(Debug, Clone, Default, ExtractField)]
|
#[derive(Debug, Clone, ExtractField)]
|
||||||
pub struct NewDocumentDialogMessageHandler {
|
pub struct NewDocumentDialogMessageHandler {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub infinite: bool,
|
pub infinite: bool,
|
||||||
pub dimensions: UVec2,
|
pub width: TypedLength,
|
||||||
|
pub height: TypedLength,
|
||||||
|
pub pixels_per_inch: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for NewDocumentDialogMessageHandler {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
name: String::new(),
|
||||||
|
infinite: false,
|
||||||
|
width: TypedLength::default(),
|
||||||
|
height: TypedLength::default(),
|
||||||
|
pixels_per_inch: DEFAULT_PIXELS_PER_INCH,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[message_handler_data]
|
#[message_handler_data]
|
||||||
@@ -19,24 +36,37 @@ impl MessageHandler<NewDocumentDialogMessage, ()> for NewDocumentDialogMessageHa
|
|||||||
match message {
|
match message {
|
||||||
NewDocumentDialogMessage::Name { name } => self.name = name,
|
NewDocumentDialogMessage::Name { name } => self.name = name,
|
||||||
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
NewDocumentDialogMessage::Infinite { infinite } => self.infinite = infinite,
|
||||||
NewDocumentDialogMessage::DimensionsX { width } => self.dimensions.x = width as u32,
|
NewDocumentDialogMessage::DimensionsX { width } => {
|
||||||
NewDocumentDialogMessage::DimensionsY { height } => self.dimensions.y = height as u32,
|
self.width = whole_pixels(width);
|
||||||
|
self.height = self.in_unit(self.height, self.width.unit);
|
||||||
|
}
|
||||||
|
NewDocumentDialogMessage::DimensionsY { height } => {
|
||||||
|
self.height = whole_pixels(height);
|
||||||
|
self.width = self.in_unit(self.width, self.height.unit);
|
||||||
|
}
|
||||||
|
NewDocumentDialogMessage::Resolution { pixels_per_inch } => self.pixels_per_inch = pixels_per_inch,
|
||||||
NewDocumentDialogMessage::Submit => {
|
NewDocumentDialogMessage::Submit => {
|
||||||
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
|
responses.add(PortfolioMessage::NewDocumentWithName { name: self.name.clone() });
|
||||||
|
|
||||||
|
// Like the artboard, the resolution is part of the document's starting state rather than an undo step
|
||||||
|
responses.add(DocumentMessage::SetPixelsPerInch {
|
||||||
|
pixels_per_inch: self.pixels_per_inch,
|
||||||
|
});
|
||||||
|
|
||||||
|
let dimensions = self.artboard_dimensions();
|
||||||
if self.infinite {
|
if self.infinite {
|
||||||
// Infinite canvas: add a locked white background layer
|
// Infinite canvas: add a locked white background layer
|
||||||
graph_modification_utils::new_background_layer(0, responses);
|
graph_modification_utils::new_background_layer(0, responses);
|
||||||
} else if self.dimensions.x > 0 && self.dimensions.y > 0 {
|
} else if dimensions.x > 0. && dimensions.y > 0. {
|
||||||
// Finite canvas: create an artboard with the specified dimensions
|
// Finite canvas: create an artboard with the specified dimensions
|
||||||
responses.add(GraphOperationMessage::NewArtboard {
|
responses.add(GraphOperationMessage::NewArtboard {
|
||||||
id: NodeId::new(),
|
id: NodeId::new(),
|
||||||
location: glam::DVec2::ZERO,
|
location: DVec2::ZERO,
|
||||||
dimensions: self.dimensions.as_dvec2(),
|
dimensions,
|
||||||
background: Color::WHITE,
|
background: Color::WHITE,
|
||||||
clip: true,
|
clip: true,
|
||||||
});
|
});
|
||||||
responses.add(NavigationMessage::CanvasPan { delta: self.dimensions.as_dvec2() });
|
responses.add(NavigationMessage::CanvasPan { delta: dimensions });
|
||||||
}
|
}
|
||||||
|
|
||||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||||
@@ -107,32 +137,150 @@ impl LayoutHolder for NewDocumentDialogMessageHandler {
|
|||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|
||||||
let scale = vec![
|
// Each dimension shows the unit it was typed in and keeps any length unit typed into it
|
||||||
|
let dimension_field = |length: TypedLength, label: &str| {
|
||||||
|
NumberInput::new(Some(length.value))
|
||||||
|
.label(label)
|
||||||
|
.unit(unit_suffix(length.unit.symbol()))
|
||||||
|
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.pixels_per_inch(self.pixels_per_inch)
|
||||||
|
.min(0.)
|
||||||
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
|
.disabled(self.infinite)
|
||||||
|
.sizing(WidgetSizing::default().min_width(100))
|
||||||
|
};
|
||||||
|
let dimensions = vec![
|
||||||
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
TextLabel::new("Dimensions").table_align(true).sizing(WidgetSizing::fixed(90)).widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
NumberInput::new(Some(self.dimensions.x as f64))
|
dimension_field(self.width, "W")
|
||||||
.label("W")
|
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: typed_length(number_input) }.into())
|
||||||
.unit(" px")
|
|
||||||
.min(0.)
|
|
||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
|
||||||
.is_integer(true)
|
|
||||||
.disabled(self.infinite)
|
|
||||||
.sizing(WidgetSizing::default().min_width(100))
|
|
||||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsX { width: number_input.value.unwrap() }.into())
|
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
NumberInput::new(Some(self.dimensions.y as f64))
|
dimension_field(self.height, "H")
|
||||||
.label("H")
|
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: typed_length(number_input) }.into())
|
||||||
.unit(" px")
|
|
||||||
.min(0.)
|
|
||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
|
||||||
.is_integer(true)
|
|
||||||
.disabled(self.infinite)
|
|
||||||
.sizing(WidgetSizing::default().min_width(100))
|
|
||||||
.on_update(|number_input: &NumberInput| NewDocumentDialogMessage::DimensionsY { height: number_input.value.unwrap() }.into())
|
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
];
|
];
|
||||||
|
|
||||||
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(scale)])
|
let resolution = resolution_row(self.pixels_per_inch, |pixels_per_inch| NewDocumentDialogMessage::Resolution { pixels_per_inch }.into());
|
||||||
|
|
||||||
|
Layout(vec![LayoutGroup::row(name), LayoutGroup::row(infinite), LayoutGroup::row(dimensions), LayoutGroup::row(resolution)])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NewDocumentDialogMessageHandler {
|
||||||
|
/// A dimension converted into `unit` at the chosen resolution, keeping its size.
|
||||||
|
fn in_unit(&self, length: TypedLength, unit: LengthUnit) -> TypedLength {
|
||||||
|
whole_pixels(TypedLength {
|
||||||
|
value: length.unit.convert(length.value, unit, self.pixels_per_inch),
|
||||||
|
unit,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The artboard's size in whole pixels, converting a dimension typed in a physical unit at the chosen resolution.
|
||||||
|
pub fn artboard_dimensions(&self) -> DVec2 {
|
||||||
|
let pixels = |length: TypedLength| length.to_length(self.pixels_per_inch).pixels().round();
|
||||||
|
DVec2::new(pixels(self.width), pixels(self.height))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The length a dimension field holds, in the unit it shows.
|
||||||
|
fn typed_length(number_input: &NumberInput) -> TypedLength {
|
||||||
|
let unit = math_parser::units::Unit::named(number_input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||||
|
TypedLength {
|
||||||
|
value: number_input.value.unwrap_or_default(),
|
||||||
|
unit,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rounds a dimension typed in pixels to a whole number of them, leaving one in a physical unit as typed.
|
||||||
|
fn whole_pixels(length: TypedLength) -> TypedLength {
|
||||||
|
if length.unit == LengthUnit::Pixel { TypedLength::pixels(length.value.round()) } else { length }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::NewDocumentDialogMessageHandler;
|
||||||
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_DIMENSIONS_INPUT_INDEX;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Commits text into the dialog's number field with this label or tooltip label, as the frontend sends a typed entry.
|
||||||
|
fn type_into_field(editor: &mut EditorTestUtils, label: &str, text: &str) {
|
||||||
|
// A widget's ID follows from its place in the layout, which the dialog's state doesn't change
|
||||||
|
let mut layout = NewDocumentDialogMessageHandler::default().layout();
|
||||||
|
layout.replace_widget_ids(LayoutTarget::DialogColumn1, &mut Vec::new(), &HashMap::new());
|
||||||
|
let widget_id = layout.iter().find_map(|instance| match &*instance.widget {
|
||||||
|
Widget::NumberInput(number_input) if number_input.label == label || number_input.tooltip_label == label => Some(instance.widget_id),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
let Some(widget_id) = widget_id else {
|
||||||
|
panic!("the dialog has no number field labeled \"{label}\"")
|
||||||
|
};
|
||||||
|
|
||||||
|
editor.dispatch(LayoutMessage::WidgetValueUpdate {
|
||||||
|
layout_target: LayoutTarget::DialogColumn1,
|
||||||
|
widget_id,
|
||||||
|
value: serde_json::Value::String(text.into()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_document(editor: &mut EditorTestUtils) {
|
||||||
|
editor
|
||||||
|
.handle_message(DialogMessage::CloseAndThen {
|
||||||
|
followups: vec![NewDocumentDialogMessage::Submit.into()],
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn artboard_dimensions(editor: &EditorTestUtils) -> Option<DVec2> {
|
||||||
|
let network_interface = &editor.active_document().network_interface;
|
||||||
|
let artboard = network_interface.all_artboards().into_iter().next()?;
|
||||||
|
let node = network_interface.document_network().nodes.get(&artboard.to_node())?;
|
||||||
|
|
||||||
|
match node.inputs.get(ARTBOARD_DIMENSIONS_INPUT_INDEX)?.as_value()? {
|
||||||
|
TaggedValue::DVec2(dimensions) => Some(*dimensions),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_new_document_starts_at_the_chosen_resolution_without_an_undo_step() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "Resolution", "300");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||||
|
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(1920., 1080.)));
|
||||||
|
|
||||||
|
editor.handle_message(DocumentMessage::Undo).await;
|
||||||
|
assert_eq!(editor.active_document().network_interface.pixels_per_inch(), 300.);
|
||||||
|
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(1920., 1080.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn typing_a_unit_into_one_dimension_converts_the_other_into_it() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "W", "210mm");
|
||||||
|
|
||||||
|
// The height of 1080 px at 96 PPI became 285.75 mm, so it grows with the resolution like the width
|
||||||
|
type_into_field(&mut editor, "Resolution", "300");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(2480., 3375.)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dimensions_typed_in_millimeters_convert_to_pixels_at_the_chosen_resolution() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.dispatch(DialogMessage::RequestNewDocumentDialog);
|
||||||
|
type_into_field(&mut editor, "W", "210mm");
|
||||||
|
type_into_field(&mut editor, "H", "297mm");
|
||||||
|
|
||||||
|
// The lengths stay in millimeters, so their size in pixels follows a resolution chosen after them
|
||||||
|
type_into_field(&mut editor, "Resolution", "300");
|
||||||
|
create_document(&mut editor).await;
|
||||||
|
assert_eq!(artboard_dimensions(&editor), Some(DVec2::new(2480., 3508.)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
|||||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||||
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||||
@@ -196,6 +196,10 @@ pub enum FrontendMessage {
|
|||||||
#[serde(rename = "contextMenuInformation")]
|
#[serde(rename = "contextMenuInformation")]
|
||||||
context_menu_information: Option<ContextMenuInformation>,
|
context_menu_information: Option<ContextMenuInformation>,
|
||||||
},
|
},
|
||||||
|
UpdateClickTargets {
|
||||||
|
#[serde(rename = "clickTargets")]
|
||||||
|
click_targets: Option<FrontendClickTargets>,
|
||||||
|
},
|
||||||
UpdateGraphViewOverlay {
|
UpdateGraphViewOverlay {
|
||||||
open: bool,
|
open: bool,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -87,7 +87,9 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
|||||||
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
||||||
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
||||||
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
||||||
|
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
||||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||||
|
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||||
|
|||||||
@@ -417,16 +417,20 @@ impl LayoutMessageHandler {
|
|||||||
}
|
}
|
||||||
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
|
// A text-field commit sends the user's raw entry as a math expression to evaluate and validate.
|
||||||
Value::String(expression) => {
|
Value::String(expression) => {
|
||||||
let Some(evaluated) = evaluate_and_validate_number_input(&expression, number_input) else { return };
|
let Some((evaluated, kept_unit)) = evaluate_and_validate_number_input(&expression, number_input) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let unit = kept_unit.map_or_else(|| number_input.unit.clone(), |symbol| unit_suffix(&symbol));
|
||||||
|
|
||||||
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
|
// Skip the update (and its history transaction) when the value is unchanged, since the network interface would short-circuit it anyway.
|
||||||
if number_input.value == Some(evaluated) {
|
if number_input.value == Some(evaluated) && number_input.unit == unit {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
|
// Snapshot the pre-change state for undo via `on_commit`, then apply the new value via `on_update`.
|
||||||
responses.add((number_input.on_commit.callback)(&()));
|
responses.add((number_input.on_commit.callback)(&()));
|
||||||
number_input.value = Some(evaluated);
|
number_input.value = Some(evaluated);
|
||||||
|
number_input.unit = unit;
|
||||||
responses.add((number_input.on_update.callback)(number_input));
|
responses.add((number_input.on_update.callback)(number_input));
|
||||||
}
|
}
|
||||||
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
|
// The increment arrows send `{ "increment": "Increase" | "Decrease" }` to invoke the backend's directional step callback.
|
||||||
@@ -704,21 +708,41 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints.
|
/// The suffix a field shows after a number in this unit: a space before a word like `mm`, and none before a symbol like `°` or `%`.
|
||||||
/// Returns `None` if the expression fails to parse, fails to evaluate, or yields a non-real number (such as `sqrt(-1)`).
|
pub fn unit_suffix(symbol: &str) -> String {
|
||||||
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<f64> {
|
if symbol.starts_with(char::is_alphabetic) { format!(" {symbol}") } else { symbol.to_string() }
|
||||||
let value = math_parser::evaluate(expression)
|
}
|
||||||
|
|
||||||
|
/// Evaluates a math expression committed in a `NumberInput`'s text field, then clamps and rounds it to the widget's constraints, giving
|
||||||
|
/// the unit it keeps where the field keeps the unit a value is typed in. Returns `None` if the expression fails to parse, fails to
|
||||||
|
/// evaluate, yields a non-real number (such as `sqrt(-1)`), or measures something the field doesn't (such as `5s` in a length field).
|
||||||
|
fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInput) -> Option<(f64, Option<String>)> {
|
||||||
|
let context = math_parser::context::EvalContext::default().with_pixels_per_inch(number_input.pixels_per_inch);
|
||||||
|
let value = math_parser::ast::Node::try_parse_from_str(expression)
|
||||||
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
|
.inspect_err(|err| error!("Math parser error on \"{expression}\": {err}"))
|
||||||
.ok()?
|
.ok()?
|
||||||
|
.eval(&context)
|
||||||
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
|
.inspect_err(|err| error!("Math evaluate error on \"{expression}\": {err}"))
|
||||||
.ok()?;
|
.ok()?;
|
||||||
|
|
||||||
let real = value.as_real()?;
|
// The result reads in the field's unit, where a plain number is already in it and a unit like `mm` converts into it
|
||||||
if real.is_nan() {
|
let field_unit = math_parser::units::Unit::named(number_input.unit.trim());
|
||||||
|
let (in_field_unit, quantity) = match (value.as_quantity(), field_unit) {
|
||||||
|
(Some(quantity), Some(unit)) => {
|
||||||
|
let read = quantity
|
||||||
|
.read_in(unit, number_input.pixels_per_inch)
|
||||||
|
.inspect_err(|_| error!("\"{expression}\" is {}, which a field in `{unit}` can't hold", quantity.dimension().description()))
|
||||||
|
.ok()?
|
||||||
|
.as_real()?;
|
||||||
|
(read, Some(*quantity))
|
||||||
|
}
|
||||||
|
_ => (value.as_real()?, None),
|
||||||
|
};
|
||||||
|
if in_field_unit.is_nan() {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut validated = real;
|
let mut validated = in_field_unit;
|
||||||
if let Some(min) = number_input.min {
|
if let Some(min) = number_input.min {
|
||||||
validated = validated.max(min);
|
validated = validated.max(min);
|
||||||
}
|
}
|
||||||
@@ -729,5 +753,17 @@ fn evaluate_and_validate_number_input(expression: &str, number_input: &NumberInp
|
|||||||
validated = validated.round();
|
validated = validated.round();
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(validated)
|
// A value typed in a unit the field keeps stays in it, unless the field's limits moved it
|
||||||
|
let kept_unit = quantity.and_then(|quantity| {
|
||||||
|
let symbol = quantity.unit.single()?.definition().symbol;
|
||||||
|
number_input.kept_units.iter().any(|kept| kept == symbol).then_some((quantity, symbol))
|
||||||
|
});
|
||||||
|
if let Some((quantity, symbol)) = kept_unit
|
||||||
|
&& validated == in_field_unit
|
||||||
|
&& let Some(kept_value) = quantity.value.as_real()
|
||||||
|
{
|
||||||
|
return Some((kept_value, Some(symbol.to_string())));
|
||||||
|
}
|
||||||
|
|
||||||
|
Some((validated, None))
|
||||||
}
|
}
|
||||||
@@ -247,6 +247,14 @@ pub struct NumberInput {
|
|||||||
#[serde(rename = "unitIsHiddenWhenEditing")]
|
#[serde(rename = "unitIsHiddenWhenEditing")]
|
||||||
#[derivative(Default(value = "true"))]
|
#[derivative(Default(value = "true"))]
|
||||||
pub unit_is_hidden_when_editing: bool,
|
pub unit_is_hidden_when_editing: bool,
|
||||||
|
/// The units, by symbol, that a typed value keeps rather than converting into the field's `unit`, like `mm` in a length field
|
||||||
|
/// that remembers the unit a length was typed in. A kept unit becomes the field's `unit`.
|
||||||
|
#[serde(skip)]
|
||||||
|
pub kept_units: Vec<String>,
|
||||||
|
/// The size of a pixel against an inch for converting a typed physical length, the document's resolution.
|
||||||
|
#[serde(skip)]
|
||||||
|
#[derivative(Default(value = "96."))]
|
||||||
|
pub pixels_per_inch: f64,
|
||||||
|
|
||||||
// Tooltips
|
// Tooltips
|
||||||
#[serde(rename = "tooltipLabel")]
|
#[serde(rename = "tooltipLabel")]
|
||||||
@@ -607,6 +615,7 @@ pub enum MathExpressionRole {
|
|||||||
Function,
|
Function,
|
||||||
Keyword,
|
Keyword,
|
||||||
Operator,
|
Operator,
|
||||||
|
Unit,
|
||||||
Bracket,
|
Bracket,
|
||||||
MatrixLiteral,
|
MatrixLiteral,
|
||||||
Error,
|
Error,
|
||||||
@@ -623,6 +632,7 @@ impl From<math_parser::highlight::Role> for MathExpressionRole {
|
|||||||
Role::Function => Self::Function,
|
Role::Function => Self::Function,
|
||||||
Role::Keyword => Self::Keyword,
|
Role::Keyword => Self::Keyword,
|
||||||
Role::Operator => Self::Operator,
|
Role::Operator => Self::Operator,
|
||||||
|
Role::Unit => Self::Unit,
|
||||||
Role::Bracket => Self::Bracket,
|
Role::Bracket => Self::Bracket,
|
||||||
Role::MatrixLiteral => Self::MatrixLiteral,
|
Role::MatrixLiteral => Self::MatrixLiteral,
|
||||||
Role::Error => Self::Error,
|
Role::Error => Self::Error,
|
||||||
@@ -878,22 +888,6 @@ pub struct SliderMarker {
|
|||||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||||
#[serde(rename = "betweenNeighbors")]
|
#[serde(rename = "betweenNeighbors")]
|
||||||
between_neighbors: bool,
|
between_neighbors: bool,
|
||||||
/// How this marker and the next may pass each other.
|
|
||||||
#[serde(rename = "overlapNext")]
|
|
||||||
overlap_next: MarkerOverlap,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
|
||||||
pub enum MarkerOverlap {
|
|
||||||
/// Neither may pass the other.
|
|
||||||
#[default]
|
|
||||||
Never,
|
|
||||||
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
|
|
||||||
NextOnly,
|
|
||||||
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
|
|
||||||
Freely,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SliderMarker {
|
impl SliderMarker {
|
||||||
@@ -906,7 +900,6 @@ impl SliderMarker {
|
|||||||
paired_with_next: false,
|
paired_with_next: false,
|
||||||
dashed_to_next: false,
|
dashed_to_next: false,
|
||||||
between_neighbors: false,
|
between_neighbors: false,
|
||||||
overlap_next: MarkerOverlap::Never,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -924,11 +917,6 @@ impl SliderMarker {
|
|||||||
self.dashed_to_next = true;
|
self.dashed_to_next = true;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
|
||||||
self.overlap_next = overlap;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
|||||||
@@ -181,6 +181,13 @@ impl LayoutHolder for MenuBarMessageHandler {
|
|||||||
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
||||||
.disabled(no_active_document),
|
.disabled(no_active_document),
|
||||||
],
|
],
|
||||||
|
vec![
|
||||||
|
MenuListEntry::new("Document Setup…")
|
||||||
|
.label("Document Setup…")
|
||||||
|
.icon("Settings")
|
||||||
|
.on_commit(|_| DialogMessage::RequestDocumentSetupDialog.into())
|
||||||
|
.disabled(no_active_document),
|
||||||
|
],
|
||||||
#[cfg(not(target_os = "macos"))]
|
#[cfg(not(target_os = "macos"))]
|
||||||
vec![preferences],
|
vec![preferences],
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -1,153 +0,0 @@
|
|||||||
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
|
|
||||||
|
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
|
||||||
use crate::test_utils::gpu_executor;
|
|
||||||
use crate::test_utils::test_prelude::*;
|
|
||||||
use glam::{DAffine2, UVec2};
|
|
||||||
use graph_craft::document::value::TaggedValue;
|
|
||||||
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
|
||||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
|
||||||
use graphene_std::list::{Item, List};
|
|
||||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
|
||||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
enum Base {
|
|
||||||
VectorLayer,
|
|
||||||
ImageLayer,
|
|
||||||
/// A group holding a vector layer, with the effect on the group.
|
|
||||||
Group,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
|
|
||||||
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
|
|
||||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
|
||||||
|
|
||||||
if effect == blur::IDENTIFIER {
|
|
||||||
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
|
|
||||||
.upstream_node_id_from_protonode(effect)
|
|
||||||
.expect("the layer has its blur");
|
|
||||||
let value = Box::new(TaggedValue::Number(10.));
|
|
||||||
editor
|
|
||||||
.handle_message(NodeGraphMessage::SetInputValue {
|
|
||||||
node_id,
|
|
||||||
input_index: blur::RadiusInput::INDEX,
|
|
||||||
value,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
|
|
||||||
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
|
|
||||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
|
||||||
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
|
|
||||||
|
|
||||||
match base {
|
|
||||||
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
|
|
||||||
Base::VectorLayer | Base::Group => {
|
|
||||||
editor.select_primary_color(blue).await;
|
|
||||||
editor.select_secondary_color(blue).await;
|
|
||||||
editor.draw_rect(50., 50., 130., 130.).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
|
|
||||||
if !matches!(base, Base::Group) {
|
|
||||||
add_effect(&mut editor, base_layer, effect.clone()).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
editor.select_tool(ToolType::Select).await;
|
|
||||||
editor.select_primary_color(red).await;
|
|
||||||
editor.select_secondary_color(red).await;
|
|
||||||
editor.draw_rect(20., 20., 200., 200.).await;
|
|
||||||
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::FillColorSet {
|
|
||||||
layer: clipped_layer,
|
|
||||||
color: Some(red),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
|
|
||||||
|
|
||||||
// Grouped once the red is clipped, the group takes the base's place beneath it
|
|
||||||
if let Base::Group = base {
|
|
||||||
let nodes = vec![base_layer.to_node()];
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
|
||||||
let group_folder_type = GroupFolderType::Layer;
|
|
||||||
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
|
||||||
let group = editor.get_selected_layer().await.expect("the group is selected");
|
|
||||||
add_effect(&mut editor, group, effect).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
|
|
||||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
|
||||||
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
|
|
||||||
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
|
|
||||||
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
|
|
||||||
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
|
|
||||||
stack.push(clipped);
|
|
||||||
stack
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
|
|
||||||
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
|
||||||
// The clip's def in SVG carries out the blur but not the shadow
|
|
||||||
let mut render = SvgRender::new();
|
|
||||||
graphic.render_svg(
|
|
||||||
&mut render,
|
|
||||||
&RenderParams {
|
|
||||||
for_export: true,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
);
|
|
||||||
let body = render.svg.to_svg_string();
|
|
||||||
let reference = body.rfind("url(#mask-").expect("the red is clipped");
|
|
||||||
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
|
|
||||||
let defs = &render.svg_defs;
|
|
||||||
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
|
|
||||||
let def_end = ["</mask>", "</clipPath>"]
|
|
||||||
.iter()
|
|
||||||
.filter_map(|closing| defs[def_start..].find(closing))
|
|
||||||
.min()
|
|
||||||
.expect("the clip's def is closed");
|
|
||||||
let clip = &defs[def_start..def_start + def_end];
|
|
||||||
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
|
|
||||||
|
|
||||||
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
|
|
||||||
let size = UVec2::new(256, 256);
|
|
||||||
let executor = gpu_executor();
|
|
||||||
let texture = executor
|
|
||||||
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
|
||||||
.expect("the clip renders");
|
|
||||||
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
|
|
||||||
let pixel = |x: u32, y: u32| -> [u8; 4] {
|
|
||||||
let index = (y * size.x + x) as usize * 4;
|
|
||||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
|
||||||
};
|
|
||||||
|
|
||||||
let within = pixel(90, 90);
|
|
||||||
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
|
|
||||||
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
|
|
||||||
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
|
|
||||||
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
|
|
||||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
|
||||||
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
|
||||||
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
|
|
||||||
let stack = clipped_stack(base, effect.clone()).await;
|
|
||||||
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
|
|
||||||
|
|
||||||
// Flattened into one list of vectors, the base clips its sibling by the same rule
|
|
||||||
if let Base::VectorLayer = base {
|
|
||||||
let flattened: List<Vector> = stack.into_flattened_list();
|
|
||||||
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,7 +7,6 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
|||||||
use crate::node_graph_executor::InspectedContext;
|
use crate::node_graph_executor::InspectedContext;
|
||||||
use glam::{Affine2, DAffine2, Vec2};
|
use glam::{Affine2, DAffine2, Vec2};
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::WarpStyle;
|
|
||||||
use graphene_std::animation::RealTimeMode;
|
use graphene_std::animation::RealTimeMode;
|
||||||
use graphene_std::blending::BlendMode;
|
use graphene_std::blending::BlendMode;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
@@ -26,6 +25,7 @@ use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
|||||||
use graphene_std::transfer_curve::TransferCurve;
|
use graphene_std::transfer_curve::TransferCurve;
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||||
|
use graphene_std::units::{Angle, Length};
|
||||||
use graphene_std::vector::misc::{
|
use graphene_std::vector::misc::{
|
||||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
@@ -35,10 +35,9 @@ use graphene_std::vector::style::{
|
|||||||
};
|
};
|
||||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||||
use graphene_std::{
|
use graphene_std::{
|
||||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
|
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||||
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
|
MaskMode,
|
||||||
};
|
};
|
||||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
|
||||||
use kurbo::BezPath;
|
use kurbo::BezPath;
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
@@ -403,6 +402,8 @@ macro_rules! inspectable_types {
|
|||||||
List<Generator>,
|
List<Generator>,
|
||||||
List<String>,
|
List<String>,
|
||||||
List<f64>,
|
List<f64>,
|
||||||
|
List<Length>,
|
||||||
|
List<Angle>,
|
||||||
List<i64>,
|
List<i64>,
|
||||||
List<bool>,
|
List<bool>,
|
||||||
List<DVec2>,
|
List<DVec2>,
|
||||||
@@ -463,6 +464,8 @@ macro_rules! inspectable_types {
|
|||||||
Item<Generator>,
|
Item<Generator>,
|
||||||
Item<String>,
|
Item<String>,
|
||||||
Item<f64>,
|
Item<f64>,
|
||||||
|
Item<Length>,
|
||||||
|
Item<Angle>,
|
||||||
Item<i64>,
|
Item<i64>,
|
||||||
Item<bool>,
|
Item<bool>,
|
||||||
Item<DVec2>,
|
Item<DVec2>,
|
||||||
@@ -1102,6 +1105,30 @@ impl TableItemLayout for f64 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl TableItemLayout for Length {
|
||||||
|
fn type_name() -> &'static str {
|
||||||
|
"Length"
|
||||||
|
}
|
||||||
|
fn identifier(&self) -> String {
|
||||||
|
format!("{} px", format_f64(round_away_float_noise(self.pixels())))
|
||||||
|
}
|
||||||
|
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||||
|
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TableItemLayout for Angle {
|
||||||
|
fn type_name() -> &'static str {
|
||||||
|
"Angle"
|
||||||
|
}
|
||||||
|
fn identifier(&self) -> String {
|
||||||
|
format!("{}°", format_f64(round_away_float_noise(self.degrees())))
|
||||||
|
}
|
||||||
|
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
|
||||||
|
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl TableItemLayout for u8 {
|
impl TableItemLayout for u8 {
|
||||||
fn type_name() -> &'static str {
|
fn type_name() -> &'static str {
|
||||||
"Byte"
|
"Byte"
|
||||||
@@ -1273,23 +1300,16 @@ impl_table_item_layout_for_choice_enum!(
|
|||||||
BevelDirection,
|
BevelDirection,
|
||||||
BevelTechnique,
|
BevelTechnique,
|
||||||
BevelStyle,
|
BevelStyle,
|
||||||
RadialBlurMethod,
|
|
||||||
WarpStyle,
|
|
||||||
WaveType,
|
|
||||||
DisplaceMode,
|
|
||||||
BlendIfChannel,
|
|
||||||
EffectKind,
|
EffectKind,
|
||||||
Generator,
|
Generator,
|
||||||
GlowSource,
|
GlowSource,
|
||||||
MaskMode,
|
MaskMode,
|
||||||
MinimumMaximumMode,
|
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
GradientInterpolation,
|
GradientInterpolation,
|
||||||
GlowTechnique,
|
GlowTechnique,
|
||||||
NoiseDistribution,
|
|
||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
@@ -1465,15 +1485,9 @@ macro_rules! known_item_types {
|
|||||||
EffectKind,
|
EffectKind,
|
||||||
GlowSource,
|
GlowSource,
|
||||||
MaskMode,
|
MaskMode,
|
||||||
MinimumMaximumMode,
|
|
||||||
BevelStyle,
|
BevelStyle,
|
||||||
BevelDirection,
|
BevelDirection,
|
||||||
BevelTechnique,
|
BevelTechnique,
|
||||||
RadialBlurMethod,
|
|
||||||
WarpStyle,
|
|
||||||
WaveType,
|
|
||||||
DisplaceMode,
|
|
||||||
BlendIfChannel,
|
|
||||||
DashPattern,
|
DashPattern,
|
||||||
BoxCorners,
|
BoxCorners,
|
||||||
TransferCurve,
|
TransferCurve,
|
||||||
@@ -1484,7 +1498,6 @@ macro_rules! known_item_types {
|
|||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
GradientInterpolation,
|
GradientInterpolation,
|
||||||
GlowTechnique,
|
GlowTechnique,
|
||||||
NoiseDistribution,
|
|
||||||
StrokeJoin,
|
StrokeJoin,
|
||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate,
|
|||||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||||
use crate::messages::portfolio::utility_types::PanelType;
|
use crate::messages::portfolio::utility_types::PanelType;
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
use glam::{DAffine2, IVec2, UVec2};
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::Appearance;
|
use graphene_std::Appearance;
|
||||||
use graphene_std::list::Item;
|
use graphene_std::list::Item;
|
||||||
@@ -266,6 +266,11 @@ pub enum DocumentMessage {
|
|||||||
SetRenderMode {
|
SetRenderMode {
|
||||||
render_mode: RenderMode,
|
render_mode: RenderMode,
|
||||||
},
|
},
|
||||||
|
/// Sets how many pixels make an inch, which sizes the lengths typed in a physical unit and the physical size of exports.
|
||||||
|
/// The caller wraps it in a transaction to make it one undo step.
|
||||||
|
SetPixelsPerInch {
|
||||||
|
pixels_per_inch: f64,
|
||||||
|
},
|
||||||
ShowNodeInGraph {
|
ShowNodeInGraph {
|
||||||
node_id: NodeId,
|
node_id: NodeId,
|
||||||
},
|
},
|
||||||
@@ -334,7 +339,6 @@ pub enum DocumentMessage {
|
|||||||
},
|
},
|
||||||
UpdateEffectsReach {
|
UpdateEffectsReach {
|
||||||
effects_reach: HashMap<NodeId, f64>,
|
effects_reach: HashMap<NodeId, f64>,
|
||||||
effects_frames: HashMap<NodeId, [DVec2; 2]>,
|
|
||||||
},
|
},
|
||||||
Undo,
|
Undo,
|
||||||
UngroupSelectedLayers,
|
UngroupSelectedLayers,
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ use graphene_std::vector::misc::dvec2_to_point;
|
|||||||
use graphene_std::vector::style::{GradientStops, RenderMode};
|
use graphene_std::vector::style::{GradientStops, RenderMode};
|
||||||
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
|
||||||
use std::collections::HashSet;
|
use std::collections::HashSet;
|
||||||
|
use std::hash::{Hash, Hasher};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
@@ -304,15 +305,8 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
|||||||
let visibility_settings = self.overlays_visibility_settings;
|
let visibility_settings = self.overlays_visibility_settings;
|
||||||
|
|
||||||
// Send the overlays message to the overlays message handler
|
// Send the overlays message to the overlays message handler
|
||||||
self.overlays_message_handler.process_message(
|
self.overlays_message_handler
|
||||||
message,
|
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||||
responses,
|
|
||||||
OverlaysMessageContext {
|
|
||||||
visibility_settings,
|
|
||||||
viewport,
|
|
||||||
graph_open: self.graph_view_overlay_open,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
DocumentMessage::Inspector(message) => {
|
DocumentMessage::Inspector(message) => {
|
||||||
let context = InspectorMessageContext {
|
let context = InspectorMessageContext {
|
||||||
@@ -1701,6 +1695,16 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
|||||||
self.render_mode = render_mode;
|
self.render_mode = render_mode;
|
||||||
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
||||||
}
|
}
|
||||||
|
DocumentMessage::SetPixelsPerInch { pixels_per_inch } => {
|
||||||
|
if !pixels_per_inch.is_finite() || pixels_per_inch <= 0. || pixels_per_inch == self.network_interface.pixels_per_inch() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.network_interface.set_pixels_per_inch(pixels_per_inch);
|
||||||
|
|
||||||
|
// Lengths typed in a physical unit change their size in pixels, so the graph runs again
|
||||||
|
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||||
|
responses.add(InspectorMessage::Refresh);
|
||||||
|
}
|
||||||
DocumentMessage::ShowNodeInGraph { node_id } => {
|
DocumentMessage::ShowNodeInGraph { node_id } => {
|
||||||
// The node is in the document network, so the graph first leaves any nested network it's showing
|
// The node is in the document network, so the graph first leaves any nested network it's showing
|
||||||
if !self.breadcrumb_network_path.is_empty() {
|
if !self.breadcrumb_network_path.is_empty() {
|
||||||
@@ -1952,20 +1956,13 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
|||||||
.collect();
|
.collect();
|
||||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||||
}
|
}
|
||||||
DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames } => {
|
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||||
let is_document_layer = |node_id: &NodeId| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]);
|
|
||||||
|
|
||||||
let layer_effects_reach = effects_reach
|
let layer_effects_reach = effects_reach
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||||
.collect();
|
.collect();
|
||||||
let layer_effects_frames = effects_frames
|
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||||
.into_iter()
|
|
||||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
|
||||||
.map(|(node_id, frames)| (LayerNodeIdentifier::new(node_id, &self.network_interface), frames))
|
|
||||||
.collect();
|
|
||||||
self.network_interface.update_effects_reach(layer_effects_reach, layer_effects_frames);
|
|
||||||
}
|
}
|
||||||
DocumentMessage::Undo => {
|
DocumentMessage::Undo => {
|
||||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||||
@@ -2694,6 +2691,7 @@ impl DocumentMessageHandler {
|
|||||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
||||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||||
self.network_interface.unload_import_export_ports(&path);
|
self.network_interface.unload_import_export_ports(&path);
|
||||||
|
self.network_interface.unload_all_nodes_bounding_box(&path);
|
||||||
self.network_interface.unload_outward_wires(&path);
|
self.network_interface.unload_outward_wires(&path);
|
||||||
}
|
}
|
||||||
self.network_interface.load_structure();
|
self.network_interface.load_structure();
|
||||||
@@ -3243,7 +3241,10 @@ impl DocumentMessageHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn current_hash(&self) -> u64 {
|
pub fn current_hash(&self) -> u64 {
|
||||||
self.network_interface.document_network().current_hash()
|
// The resolution lives in the network's metadata rather than the network, but changing it changes the document
|
||||||
|
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||||
|
(self.network_interface.document_network().current_hash(), self.network_interface.pixels_per_inch().to_bits()).hash(&mut hasher);
|
||||||
|
hasher.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_auto_saved(&self) -> bool {
|
pub fn is_auto_saved(&self) -> bool {
|
||||||
|
|||||||
+3
@@ -807,6 +807,9 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
|||||||
// Set positions for all imported descendants in a single O(n) pass
|
// Set positions for all imported descendants in a single O(n) pass
|
||||||
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
||||||
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
||||||
|
|
||||||
|
// Invalidate caches once after all positions are set
|
||||||
|
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
|
||||||
}
|
}
|
||||||
usvg::Node::Path(path) => {
|
usvg::Node::Path(path) => {
|
||||||
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod clipping_tests;
|
|
||||||
#[cfg(test)]
|
|
||||||
pub(crate) mod document_diff;
|
pub(crate) mod document_diff;
|
||||||
mod document_history;
|
mod document_history;
|
||||||
mod document_message;
|
mod document_message;
|
||||||
|
|||||||
@@ -139,6 +139,18 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
|||||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||||
let custom = vec![
|
let custom = vec![
|
||||||
|
DocumentNodeDefinition {
|
||||||
|
identifier: "Custom Node",
|
||||||
|
version: 1,
|
||||||
|
category: "Routing",
|
||||||
|
icon: Some("NodeCustomNode"),
|
||||||
|
node_template: NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
||||||
|
inspector: None,
|
||||||
|
},
|
||||||
DocumentNodeDefinition {
|
DocumentNodeDefinition {
|
||||||
identifier: "Merge",
|
identifier: "Merge",
|
||||||
version: 1,
|
version: 1,
|
||||||
@@ -676,7 +688,6 @@ fn static_node_inspector() -> NodeInspector {
|
|||||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||||
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
|
|
||||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||||
@@ -690,8 +701,6 @@ fn static_node_inspector() -> NodeInspector {
|
|||||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||||
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
|
|
||||||
map.insert("displace_inspector".to_string(), Box::new(node_inspector::displace_inspector));
|
|
||||||
map
|
map
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -700,15 +709,6 @@ type InputInspector = HashMap<String, Box<dyn Fn(NodeId, usize, &mut NodeInspect
|
|||||||
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
// TODO: Replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>) or similar
|
||||||
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
static INPUT_OVERRIDES: once_cell::sync::Lazy<InputInspector> = once_cell::sync::Lazy::new(static_input_inspector);
|
||||||
|
|
||||||
/// The metadata of the proto node's field at `index`, cloned so the lock is released before the row is built, which locks the node metadata again.
|
|
||||||
fn proto_node_field(node_id: NodeId, index: usize, context: &mut NodeInspectorContext) -> Option<registry::FieldMetadata> {
|
|
||||||
context
|
|
||||||
.network_interface
|
|
||||||
.implementation(&node_id, context.selection_network_path)
|
|
||||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
|
||||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Defines the logic for inputs to display a custom Inspector widget.
|
/// Defines the logic for inputs to display a custom Inspector widget.
|
||||||
fn static_input_inspector() -> InputInspector {
|
fn static_input_inspector() -> InputInspector {
|
||||||
let mut map: InputInspector = HashMap::new();
|
let mut map: InputInspector = HashMap::new();
|
||||||
@@ -873,10 +873,15 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
map.insert(
|
||||||
// A slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
// A range slider for a periodic number like an angle, whose soft bounds span one period, wrapping a typed number past either end back into them
|
||||||
"wrapping_slider".to_string(),
|
"wrapping_range_slider".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let field = proto_node_field(node_id, index, context);
|
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||||
|
let field = context
|
||||||
|
.network_interface
|
||||||
|
.implementation(&node_id, context.selection_network_path)
|
||||||
|
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||||
|
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().ok()?.get(proto_node_identifier)?.fields.get(index).cloned());
|
||||||
|
|
||||||
let mut number_input = NumberInput::default().mode_increment();
|
let mut number_input = NumberInput::default().mode_increment();
|
||||||
let mut period = None;
|
let mut period = None;
|
||||||
@@ -897,51 +902,10 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
let row = match period {
|
let row = match period {
|
||||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
||||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
||||||
node_inspector::wrapping_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
node_inspector::wrapping_range_slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
||||||
}
|
}
|
||||||
_ => {
|
_ => {
|
||||||
log::error!("A wrapping slider needs finite soft bounds at both ends");
|
log::error!("A wrapping range slider needs finite soft bounds at both ends");
|
||||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(vec![LayoutGroup::row(row)])
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
map.insert(
|
|
||||||
// A slider across the soft bounds (or the hard ones where a soft one is absent), beside a number input that types past them up to the hard bounds
|
|
||||||
"slider".to_string(),
|
|
||||||
Box::new(|node_id, index, context| {
|
|
||||||
let field = proto_node_field(node_id, index, context);
|
|
||||||
|
|
||||||
let mut number_input = NumberInput::default().mode_increment();
|
|
||||||
let mut extent = None;
|
|
||||||
if let Some(field) = field {
|
|
||||||
if let Some(unit) = field.unit {
|
|
||||||
number_input = number_input.unit(unit);
|
|
||||||
}
|
|
||||||
if let Some(display_decimal_places) = field.number_display_decimal_places {
|
|
||||||
number_input = number_input.display_decimal_places(display_decimal_places);
|
|
||||||
}
|
|
||||||
if let Some(number_step) = field.number_step {
|
|
||||||
number_input = number_input.step(number_step);
|
|
||||||
}
|
|
||||||
if let Some(min) = field.number_hard_min {
|
|
||||||
number_input = number_input.min(min);
|
|
||||||
}
|
|
||||||
if let Some(max) = field.number_hard_max {
|
|
||||||
number_input = number_input.max(max);
|
|
||||||
}
|
|
||||||
extent = field.number_soft_min.or(field.number_hard_min).zip(field.number_soft_max.or(field.number_hard_max));
|
|
||||||
}
|
|
||||||
|
|
||||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
|
||||||
let row = match extent {
|
|
||||||
Some((min, max)) if min.is_finite() && max.is_finite() && min < max => {
|
|
||||||
let default = node_inspector::definition_default_number(¶meter_widgets_info);
|
|
||||||
node_inspector::slider_widget(parameter_widgets_info, number_input, SliderRange { min, max, default })
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
log::error!("A slider needs finite bounds at both ends");
|
|
||||||
node_inspector::number_widget(parameter_widgets_info, number_input)
|
node_inspector::number_widget(parameter_widgets_info, number_input)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1106,7 +1070,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"noise_inspector_fractal_weighted_strength".to_string(),
|
"noise_inspector_fractal_weighted_strength".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
let (fractal_active, coherent_noise_active, _, _, _, domain_warp_only_fractal_type_wrongly_active) = node_inspector::query_noise_pattern_state(node_id, context)?;
|
||||||
let fractal_weighted_strength = node_inspector::slider_widget(
|
let fractal_weighted_strength = node_inspector::range_slider_widget(
|
||||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||||
NumberInput::default()
|
NumberInput::default()
|
||||||
.min(0.)
|
.min(0.)
|
||||||
|
|||||||
@@ -45,11 +45,6 @@ pub enum NodeGraphMessage {
|
|||||||
xy: Option<(i32, i32)>,
|
xy: Option<(i32, i32)>,
|
||||||
add_transaction: bool,
|
add_transaction: bool,
|
||||||
},
|
},
|
||||||
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
|
||||||
CreateEmptySubgraph {
|
|
||||||
node_id: Option<NodeId>,
|
|
||||||
xy: Option<(i32, i32)>,
|
|
||||||
},
|
|
||||||
CreateWire {
|
CreateWire {
|
||||||
output_connector: OutputConnector,
|
output_connector: OutputConnector,
|
||||||
input_connector: InputConnector,
|
input_connector: InputConnector,
|
||||||
@@ -207,6 +202,8 @@ pub enum NodeGraphMessage {
|
|||||||
SelectedNodesSet {
|
SelectedNodesSet {
|
||||||
nodes: Vec<NodeId>,
|
nodes: Vec<NodeId>,
|
||||||
},
|
},
|
||||||
|
SendClickTargets,
|
||||||
|
EndSendClickTargets,
|
||||||
UnloadWires,
|
UnloadWires,
|
||||||
SendWires,
|
SendWires,
|
||||||
UpdateVisibleNodes,
|
UpdateVisibleNodes,
|
||||||
@@ -386,7 +383,6 @@ impl NodeGraphMessage {
|
|||||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||||
Self::AddNodes { .. }
|
Self::AddNodes { .. }
|
||||||
| Self::CreateNodeFromContextMenu { .. }
|
| Self::CreateNodeFromContextMenu { .. }
|
||||||
| Self::CreateEmptySubgraph { .. }
|
|
||||||
| Self::CreateWire { .. }
|
| Self::CreateWire { .. }
|
||||||
| Self::CreateWires { .. }
|
| Self::CreateWires { .. }
|
||||||
| Self::ConnectUpstreamOutputToInput { .. }
|
| Self::ConnectUpstreamOutputToInput { .. }
|
||||||
@@ -446,6 +442,8 @@ impl NodeGraphMessage {
|
|||||||
| Self::SelectedNodesAdd { .. }
|
| Self::SelectedNodesAdd { .. }
|
||||||
| Self::SelectedNodesRemove { .. }
|
| Self::SelectedNodesRemove { .. }
|
||||||
| Self::SelectedNodesSet { .. }
|
| Self::SelectedNodesSet { .. }
|
||||||
|
| Self::SendClickTargets
|
||||||
|
| Self::EndSendClickTargets
|
||||||
| Self::UnloadWires
|
| Self::UnloadWires
|
||||||
| Self::SendWires
|
| Self::SendWires
|
||||||
| Self::UpdateVisibleNodes
|
| Self::UpdateVisibleNodes
|
||||||
|
|||||||
@@ -5,14 +5,13 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
|||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
||||||
TransactionStatus,
|
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||||
@@ -24,12 +23,14 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
|
|||||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||||
use crate::messages::viewport::Position;
|
use crate::messages::viewport::Position;
|
||||||
use glam::{DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||||
|
use graphene_std::math::math_ext::QuadExt;
|
||||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||||
|
use renderer::Quad;
|
||||||
|
|
||||||
#[derive(Debug, ExtractField)]
|
#[derive(Debug, ExtractField)]
|
||||||
pub struct NodeGraphMessageContext<'a> {
|
pub struct NodeGraphMessageContext<'a> {
|
||||||
@@ -421,23 +422,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
});
|
});
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
responses.add(NodeGraphMessage::SendGraph);
|
||||||
}
|
}
|
||||||
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
|
||||||
let node_id = node_id.unwrap_or_else(NodeId::new);
|
|
||||||
let (x, y) = xy.unwrap_or_else(|| {
|
|
||||||
network_interface
|
|
||||||
.node_graph_ptz(breadcrumb_network_path)
|
|
||||||
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
|
||||||
});
|
|
||||||
|
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
|
||||||
responses.add(NodeGraphMessage::InsertNode {
|
|
||||||
node_id,
|
|
||||||
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
|
||||||
});
|
|
||||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
|
||||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
|
||||||
}
|
|
||||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||||
log::error!("Failed to find upstream node for downstream_input");
|
log::error!("Failed to find upstream node for downstream_input");
|
||||||
@@ -785,19 +769,24 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
||||||
let encapsulating_node_id = NodeId::new();
|
let encapsulating_node_id = NodeId::new();
|
||||||
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
||||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||||
log::error!("Could not get center of selected_nodes");
|
log::error!("Could not get center of selected_nodes");
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||||
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
responses.add(DocumentMessage::AddTransaction);
|
||||||
responses.add(NodeGraphMessage::InsertNode {
|
responses.add(NodeGraphMessage::InsertNode {
|
||||||
node_id: encapsulating_node_id,
|
node_id: encapsulating_node_id,
|
||||||
node_template: Box::new(subgraph_template),
|
node_template: Box::new(default_node_template),
|
||||||
|
});
|
||||||
|
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||||
|
node_id: encapsulating_node_id,
|
||||||
|
network_path: selection_network_path.to_vec(),
|
||||||
|
alias: "Untitled Node".to_string(),
|
||||||
});
|
});
|
||||||
|
|
||||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||||
@@ -2023,6 +2012,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
selected_nodes.set_selected_nodes(nodes);
|
selected_nodes.set_selected_nodes(nodes);
|
||||||
responses.add(EventMessage::SelectionChanged);
|
responses.add(EventMessage::SelectionChanged);
|
||||||
}
|
}
|
||||||
|
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
|
||||||
|
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
|
||||||
|
}),
|
||||||
|
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
|
||||||
NodeGraphMessage::UnloadWires => {
|
NodeGraphMessage::UnloadWires => {
|
||||||
self.frontend_wires.clear();
|
self.frontend_wires.clear();
|
||||||
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
||||||
@@ -2537,13 +2530,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
HashSet::new()
|
HashSet::new()
|
||||||
};
|
};
|
||||||
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
||||||
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
|
|
||||||
for node_id in all_nodes {
|
for node_id in all_nodes {
|
||||||
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
|
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
|
||||||
log::error!("Could not get the body of node {node_id}");
|
log::error!("Could not get transient metadata for node {node_id}");
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if body.overlaps(selection_min, selection_max) {
|
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
|
||||||
|
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
|
||||||
if alt {
|
if alt {
|
||||||
nodes.remove(&node_id);
|
nodes.remove(&node_id);
|
||||||
} else {
|
} else {
|
||||||
@@ -3205,6 +3198,11 @@ impl NodeGraphMessageHandler {
|
|||||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||||
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
||||||
|
|
||||||
|
// Only development builds draw the click targets, so users don't come across the overlay by accident
|
||||||
|
if cfg!(debug_assertions) {
|
||||||
|
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
|
||||||
|
}
|
||||||
|
|
||||||
if self.has_selection {
|
if self.has_selection {
|
||||||
common.extend(actions!(NodeGraphMessageDiscriminant;
|
common.extend(actions!(NodeGraphMessageDiscriminant;
|
||||||
Copy,
|
Copy,
|
||||||
@@ -3428,13 +3426,6 @@ impl NodeGraphMessageHandler {
|
|||||||
})
|
})
|
||||||
.disabled(read_only)
|
.disabled(read_only)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
|
||||||
TextButton::new("New Custom Node")
|
|
||||||
.tooltip_label("New Custom Node")
|
|
||||||
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
|
||||||
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
|
||||||
.disabled(read_only)
|
|
||||||
.widget_instance(),
|
|
||||||
//
|
//
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
|
use super::document_node_definitions::{NODE_OVERRIDES, NodeInspectorContext};
|
||||||
use super::utility_types::FrontendGraphDataType;
|
use super::utility_types::FrontendGraphDataType;
|
||||||
|
use crate::messages::layout::layout_message_handler::unit_suffix;
|
||||||
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
|
use crate::messages::layout::utility_types::math_expression::{MathExpressionTokens, math_expression_error, math_expression_error_ranges, math_expression_tokens};
|
||||||
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
|
use crate::messages::layout::utility_types::tooltip_markdown::{escape_markdown, markdown_code_span};
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
@@ -20,7 +21,6 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
|
|||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||||
use graph_craft::{Type, concrete, item};
|
use graph_craft::{Type, concrete, item};
|
||||||
use graphene_std::WarpStyle;
|
|
||||||
use graphene_std::animation::RealTimeMode;
|
use graphene_std::animation::RealTimeMode;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::raster::{
|
use graphene_std::raster::{
|
||||||
@@ -32,6 +32,7 @@ use graphene_std::text::{Font, TextAlign};
|
|||||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||||
use graphene_std::transfer_curve::TransferCurve;
|
use graphene_std::transfer_curve::TransferCurve;
|
||||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||||
|
use graphene_std::units::{Angle, AngleUnit, Length, LengthUnit, TypedAngle, TypedLength};
|
||||||
use graphene_std::vector::misc::BooleanOperation;
|
use graphene_std::vector::misc::BooleanOperation;
|
||||||
use graphene_std::vector::misc::{
|
use graphene_std::vector::misc::{
|
||||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||||
@@ -41,8 +42,7 @@ use graphene_std::vector::style::{
|
|||||||
build_transform_with_y_preservation,
|
build_transform_with_y_preservation,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
|
||||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
|
||||||
use graphene_std::{NodeParameter, ParameterRef};
|
use graphene_std::{NodeParameter, ParameterRef};
|
||||||
use math_parser::parser::{MessagePart, ParseError};
|
use math_parser::parser::{MessagePart, ParseError};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
@@ -307,7 +307,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
step,
|
step,
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let mut number_input = NumberInput::default();
|
let mut number_input = NumberInput::default().pixels_per_inch(context.network_interface.pixels_per_inch());
|
||||||
if slider {
|
if slider {
|
||||||
number_input = number_input.mode_range();
|
number_input = number_input.mode_range();
|
||||||
}
|
}
|
||||||
@@ -344,7 +344,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
match (number_input.min, number_input.max) {
|
match (number_input.min, number_input.max) {
|
||||||
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
(Some(min), Some(max)) if fixed_extent && min.is_finite() && max.is_finite() && min < max => {
|
||||||
let default = definition_default_number(&default_info);
|
let default = definition_default_number(&default_info);
|
||||||
slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
range_slider_widget(default_info, number_input.mode_increment(), SliderRange { min, max, default }).into()
|
||||||
}
|
}
|
||||||
_ => number_widget(default_info, number_input).into(),
|
_ => number_widget(default_info, number_input).into(),
|
||||||
}
|
}
|
||||||
@@ -389,13 +389,15 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
false => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)),
|
||||||
},
|
},
|
||||||
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
Some(x) if id_is::<i64>(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||||
|
Some(x) if id_is::<Length>(x) => length_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||||
|
Some(x) if id_is::<Angle>(x) => angle_widget(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY)).into(),
|
||||||
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
Some(x) if id_is::<bool>(x) => bool_widget(default_info, CheckboxInput::default()).into(),
|
||||||
Some(x) if id_is::<String>(x) => match multiline {
|
Some(x) if id_is::<String>(x) => match multiline {
|
||||||
true => text_area_widget(default_info).into(),
|
true => text_area_widget(default_info).into(),
|
||||||
false => text_widget(default_info).into(),
|
false => text_widget(default_info).into(),
|
||||||
},
|
},
|
||||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||||
@@ -455,16 +457,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<WarpStyle>(x) => enum_choice::<WarpStyle>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<WaveType>(x) => enum_choice::<WaveType>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<DisplaceMode>(x) => enum_choice::<DisplaceMode>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||||
@@ -795,10 +790,8 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
|||||||
last.clone()
|
last.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
|
||||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||||
let size_unit = size_unit.unwrap_or("x");
|
|
||||||
|
|
||||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
||||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||||
@@ -865,7 +858,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
|||||||
scale_widgets.extend_from_slice(&[
|
scale_widgets.extend_from_slice(&[
|
||||||
NumberInput::new(Some(scale.x))
|
NumberInput::new(Some(scale.x))
|
||||||
.label("W")
|
.label("W")
|
||||||
.unit(size_unit)
|
.unit("x")
|
||||||
.on_update(update_value_at_index(
|
.on_update(update_value_at_index(
|
||||||
move |w: &NumberInput| {
|
move |w: &NumberInput| {
|
||||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
||||||
@@ -879,7 +872,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
|||||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
NumberInput::new(Some(scale.y))
|
NumberInput::new(Some(scale.y))
|
||||||
.label("H")
|
.label("H")
|
||||||
.unit(size_unit)
|
.unit("x")
|
||||||
.on_update(update_value_at_index(
|
.on_update(update_value_at_index(
|
||||||
move |h: &NumberInput| {
|
move |h: &NumberInput| {
|
||||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
||||||
@@ -907,6 +900,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
|||||||
|
|
||||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||||
|
|
||||||
let Some(input) = parameter_widgets_info.input() else {
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
@@ -923,6 +917,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -934,6 +929,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -949,6 +945,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -960,6 +957,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
|||||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||||
.is_integer(is_integer)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
@@ -1223,7 +1221,7 @@ pub fn optional_f64_widget(parameter_widgets_info: ParameterWidgetsInfo, bool_in
|
|||||||
|
|
||||||
let number_props = number_props.disabled(enabled == Some(false));
|
let number_props = number_props.disabled(enabled == Some(false));
|
||||||
let mut widgets = match slider {
|
let mut widgets = match slider {
|
||||||
Some(slider) => slider_widget(parameter_widgets_info, number_props, slider),
|
Some(slider) => range_slider_widget(parameter_widgets_info, number_props, slider),
|
||||||
None => number_widget(parameter_widgets_info, number_props),
|
None => number_widget(parameter_widgets_info, number_props),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1328,6 +1326,92 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props:
|
|||||||
widgets
|
widgets
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Converts a field's bounds from the unit they're given in into the unit its value is shown in.
|
||||||
|
fn bounds_in_unit(number_input: NumberInput, convert: impl Fn(f64) -> f64) -> NumberInput {
|
||||||
|
let convert = |bound: Option<f64>| bound.map(|bound| if bound.is_finite() { convert(bound) } else { bound });
|
||||||
|
NumberInput {
|
||||||
|
min: convert(number_input.min),
|
||||||
|
max: convert(number_input.max),
|
||||||
|
range_min: convert(number_input.range_min),
|
||||||
|
range_max: convert(number_input.range_max),
|
||||||
|
..number_input
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A length's number field, which shows the length in the unit it was typed in and keeps any length unit typed into it, with the
|
||||||
|
/// field's bounds given in pixels.
|
||||||
|
pub fn length_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
let length = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::Length(length)) => length,
|
||||||
|
Some(&TaggedValue::Number(pixels)) => TypedLength::pixels(pixels),
|
||||||
|
_ => return widgets,
|
||||||
|
};
|
||||||
|
|
||||||
|
let pixels_per_inch = parameter_widgets_info.network_interface.pixels_per_inch();
|
||||||
|
let number_props = bounds_in_unit(number_props, |pixels| LengthUnit::Pixel.convert(pixels, length.unit, pixels_per_inch));
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
number_props
|
||||||
|
.value(Some(length.value))
|
||||||
|
.unit(unit_suffix(length.unit.symbol()))
|
||||||
|
.kept_units(LengthUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.pixels_per_inch(pixels_per_inch)
|
||||||
|
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||||
|
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(LengthUnit::from_unit).unwrap_or_default();
|
||||||
|
TaggedValue::Length(TypedLength {
|
||||||
|
value: input.value.unwrap_or_default(),
|
||||||
|
unit,
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
.on_commit(commit_value)
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
widgets
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An angle's number field, which shows the angle in the unit it was typed in and keeps any angle unit typed into it, with the
|
||||||
|
/// field's bounds given in degrees.
|
||||||
|
pub fn angle_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput) -> Vec<WidgetInstance> {
|
||||||
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
|
let Some(input) = parameter_widgets_info.input() else {
|
||||||
|
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||||
|
return vec![];
|
||||||
|
};
|
||||||
|
let angle = match input.as_non_exposed_value() {
|
||||||
|
Some(&TaggedValue::Angle(angle)) => angle,
|
||||||
|
Some(&TaggedValue::Number(degrees)) => TypedAngle::degrees(degrees),
|
||||||
|
_ => return widgets,
|
||||||
|
};
|
||||||
|
|
||||||
|
let number_props = bounds_in_unit(number_props, |degrees| angle.unit.from_angle(Angle::from_degrees(degrees)));
|
||||||
|
widgets.extend_from_slice(&[
|
||||||
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
|
number_props
|
||||||
|
.value(Some(angle.value))
|
||||||
|
.unit(unit_suffix(angle.unit.symbol()))
|
||||||
|
.kept_units(AngleUnit::ALL.iter().map(|unit| unit.symbol().to_string()).collect())
|
||||||
|
.on_update(parameter_widgets_info.update_value(|input: &NumberInput| {
|
||||||
|
let unit = math_parser::units::Unit::named(input.unit.trim()).and_then(AngleUnit::from_unit).unwrap_or_default();
|
||||||
|
TaggedValue::Angle(TypedAngle {
|
||||||
|
value: input.value.unwrap_or_default(),
|
||||||
|
unit,
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
.on_commit(commit_value)
|
||||||
|
.widget_instance(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
widgets
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Auto-generate this enum dropdown menu widget
|
// TODO: Auto-generate this enum dropdown menu widget
|
||||||
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> LayoutGroup {
|
||||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
@@ -1428,6 +1512,7 @@ fn wire_element(ty: &Type) -> Type {
|
|||||||
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
|
||||||
let vocabulary = [
|
let vocabulary = [
|
||||||
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
|
vec![concrete!(bool), concrete!(i64), concrete!(f64)],
|
||||||
|
vec![concrete!(Length), concrete!(Angle)],
|
||||||
vec![concrete!(DVec2)],
|
vec![concrete!(DVec2)],
|
||||||
vec![concrete!(DAffine2)],
|
vec![concrete!(DAffine2)],
|
||||||
vec![concrete!(Artboard)],
|
vec![concrete!(Artboard)],
|
||||||
@@ -1917,8 +2002,6 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
enum MarkerScale {
|
enum MarkerScale {
|
||||||
/// A 0..100 percentage, placed linearly.
|
/// A 0..100 percentage, placed linearly.
|
||||||
Percent,
|
Percent,
|
||||||
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
|
|
||||||
LevelPercent,
|
|
||||||
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
||||||
Gamma,
|
Gamma,
|
||||||
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
||||||
@@ -1928,7 +2011,7 @@ enum MarkerScale {
|
|||||||
impl MarkerScale {
|
impl MarkerScale {
|
||||||
fn position(self, value: f64) -> f64 {
|
fn position(self, value: f64) -> f64 {
|
||||||
match self {
|
match self {
|
||||||
Self::Percent | Self::LevelPercent => value / 100.,
|
Self::Percent => value / 100.,
|
||||||
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
||||||
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
||||||
Self::Degrees => {
|
Self::Degrees => {
|
||||||
@@ -1942,7 +2025,7 @@ impl MarkerScale {
|
|||||||
|
|
||||||
fn value(self, position: f64) -> f64 {
|
fn value(self, position: f64) -> f64 {
|
||||||
match self {
|
match self {
|
||||||
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
|
Self::Percent => (position * 100.).clamp(0., 100.),
|
||||||
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
||||||
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
||||||
Self::Degrees => (position * 360.).clamp(0., 360.),
|
Self::Degrees => (position * 360.).clamp(0., 360.),
|
||||||
@@ -1952,7 +2035,6 @@ impl MarkerScale {
|
|||||||
fn number_input(self) -> NumberInput {
|
fn number_input(self) -> NumberInput {
|
||||||
match self {
|
match self {
|
||||||
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
||||||
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
|
|
||||||
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
||||||
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
||||||
}
|
}
|
||||||
@@ -1977,8 +2059,6 @@ struct SliderSectionParam {
|
|||||||
dash_to_next: bool,
|
dash_to_next: bool,
|
||||||
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
||||||
between_neighbors: bool,
|
between_neighbors: bool,
|
||||||
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
|
|
||||||
overlap_next: MarkerOverlap,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SliderSectionParam {
|
impl SliderSectionParam {
|
||||||
@@ -1991,7 +2071,6 @@ impl SliderSectionParam {
|
|||||||
pair_with_next: false,
|
pair_with_next: false,
|
||||||
dash_to_next: false,
|
dash_to_next: false,
|
||||||
between_neighbors: false,
|
between_neighbors: false,
|
||||||
overlap_next: MarkerOverlap::Never,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2009,52 +2088,11 @@ impl SliderSectionParam {
|
|||||||
self.dash_to_next = true;
|
self.dash_to_next = true;
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
|
||||||
self.overlap_next = overlap;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
|
|
||||||
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
|
|
||||||
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
|
|
||||||
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
|
|
||||||
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
|
|
||||||
let mut lower = 0_f64;
|
|
||||||
let mut upper = 1_f64;
|
|
||||||
|
|
||||||
// A neighbor bounds the marker unless they overlap
|
|
||||||
if overlap(previous) == MarkerOverlap::Never
|
|
||||||
&& let Some(previous) = position(previous)
|
|
||||||
{
|
|
||||||
lower = lower.max(previous);
|
|
||||||
}
|
|
||||||
if overlap(Some(index)) == MarkerOverlap::Never
|
|
||||||
&& let Some(next) = position(next)
|
|
||||||
{
|
|
||||||
upper = upper.min(next);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
|
|
||||||
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
|
|
||||||
if bounds_beyond(overlap(previous), overlap(before_previous))
|
|
||||||
&& let Some(before_previous) = position(before_previous)
|
|
||||||
{
|
|
||||||
lower = lower.max(before_previous);
|
|
||||||
}
|
|
||||||
if bounds_beyond(overlap(Some(index)), overlap(next))
|
|
||||||
&& let Some(after_next) = position(after_next)
|
|
||||||
{
|
|
||||||
upper = upper.min(after_next);
|
|
||||||
}
|
|
||||||
|
|
||||||
(lower, upper)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
||||||
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
||||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
|
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
|
||||||
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
||||||
// Snapshot exposure and values before the mutable-borrow loop
|
// Snapshot exposure and values before the mutable-borrow loop
|
||||||
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
||||||
@@ -2082,7 +2120,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
let mut marker_scales = Vec::new();
|
let mut marker_scales = Vec::new();
|
||||||
let mut marker_positions = Vec::new();
|
let mut marker_positions = Vec::new();
|
||||||
let mut marker_between = Vec::new();
|
let mut marker_between = Vec::new();
|
||||||
let mut marker_overlaps = Vec::new();
|
|
||||||
let mut marker_colors_and_links = Vec::new();
|
let mut marker_colors_and_links = Vec::new();
|
||||||
for (i, param) in params.iter().enumerate() {
|
for (i, param) in params.iter().enumerate() {
|
||||||
let (exposed, value) = exposure_and_value[i];
|
let (exposed, value) = exposure_and_value[i];
|
||||||
@@ -2095,21 +2132,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
marker_default_positions.push(param.scale.position(param.default_value));
|
marker_default_positions.push(param.scale.position(param.default_value));
|
||||||
marker_scales.push(param.scale);
|
marker_scales.push(param.scale);
|
||||||
marker_between.push(param.between_neighbors);
|
marker_between.push(param.between_neighbors);
|
||||||
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
|
|
||||||
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
||||||
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
||||||
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
||||||
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
|
if !cyclic {
|
||||||
if overlapping {
|
|
||||||
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
|
|
||||||
for i in 0..marker_positions.len() {
|
|
||||||
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
|
|
||||||
marker_positions[i] = marker_positions[i].max(lower);
|
|
||||||
}
|
|
||||||
} else if !cyclic {
|
|
||||||
let mut floor = 0.;
|
let mut floor = 0.;
|
||||||
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
||||||
if between {
|
if between {
|
||||||
@@ -2130,8 +2159,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
let slider_markers: Vec<SliderMarker> = marker_positions
|
let slider_markers: Vec<SliderMarker> = marker_positions
|
||||||
.iter()
|
.iter()
|
||||||
.zip(&marker_colors_and_links)
|
.zip(&marker_colors_and_links)
|
||||||
.zip(marker_between.iter().zip(&marker_overlaps))
|
.zip(&marker_between)
|
||||||
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
|
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
|
||||||
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
||||||
if paired {
|
if paired {
|
||||||
marker = marker.pair_with_next();
|
marker = marker.pair_with_next();
|
||||||
@@ -2142,7 +2171,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
if between {
|
if between {
|
||||||
marker = marker.between_neighbors();
|
marker = marker.between_neighbors();
|
||||||
}
|
}
|
||||||
marker = marker.overlap_next(overlap);
|
|
||||||
marker
|
marker
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -2164,7 +2192,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
let marker_scales = marker_scales.clone();
|
let marker_scales = marker_scales.clone();
|
||||||
let marker_positions = marker_positions.clone();
|
let marker_positions = marker_positions.clone();
|
||||||
let marker_between = marker_between.clone();
|
let marker_between = marker_between.clone();
|
||||||
let marker_overlaps = marker_overlaps.clone();
|
|
||||||
move |update: &SliderInputUpdate| {
|
move |update: &SliderInputUpdate| {
|
||||||
let i = match update {
|
let i = match update {
|
||||||
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
||||||
@@ -2179,13 +2206,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
|||||||
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
||||||
// nearest markers that bound it, which a marker placed between its neighbors never does
|
// nearest markers that bound it, which a marker placed between its neighbors never does
|
||||||
let bounding = |j: usize| between || !marker_between[j];
|
let bounding = |j: usize| between || !marker_between[j];
|
||||||
let (left, right) = if overlapping {
|
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||||
overlap_bounds(&marker_positions, &marker_overlaps, i)
|
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||||
} else {
|
|
||||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
|
||||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
|
||||||
(left, right)
|
|
||||||
};
|
|
||||||
|
|
||||||
let scale_position = match update {
|
let scale_position = match update {
|
||||||
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
||||||
@@ -2514,7 +2536,7 @@ fn slider_row(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A slider row running linearly across `slider`'s bounds.
|
/// A slider row running linearly across `slider`'s bounds.
|
||||||
pub(crate) fn slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
pub(crate) fn range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||||
slider_row(
|
slider_row(
|
||||||
parameter_widgets_info,
|
parameter_widgets_info,
|
||||||
number_props,
|
number_props,
|
||||||
@@ -2526,7 +2548,7 @@ pub(crate) fn slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
/// A slider row running linearly across `slider`'s bounds for a periodic number like an angle, which wraps a typed number past either end back into them.
|
||||||
pub(crate) fn wrapping_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
pub(crate) fn wrapping_range_slider_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: NumberInput, slider: SliderRange) -> Vec<WidgetInstance> {
|
||||||
slider_row(
|
slider_row(
|
||||||
parameter_widgets_info,
|
parameter_widgets_info,
|
||||||
number_props,
|
number_props,
|
||||||
@@ -2610,105 +2632,6 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
|||||||
layout
|
layout
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
|
||||||
use graphene_std::blending_nodes::blend_if::blend_if::*;
|
|
||||||
|
|
||||||
let channel = enum_choice::<BlendIfChannel>()
|
|
||||||
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
|
|
||||||
.inspector_row();
|
|
||||||
|
|
||||||
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
|
|
||||||
Some(TaggedValue::BlendIfChannel(channel)) => channel,
|
|
||||||
_ => BlendIfChannel::Gray,
|
|
||||||
};
|
|
||||||
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
|
|
||||||
BlendIfChannel::Gray => (
|
|
||||||
[
|
|
||||||
[
|
|
||||||
ContentFalloffStartInput.into(),
|
|
||||||
ContentRangeStartInput.into(),
|
|
||||||
ContentRangeEndInput.into(),
|
|
||||||
ContentFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
UnderlyingFalloffStartInput.into(),
|
|
||||||
UnderlyingRangeStartInput.into(),
|
|
||||||
UnderlyingRangeEndInput.into(),
|
|
||||||
UnderlyingFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
Color::WHITE,
|
|
||||||
),
|
|
||||||
BlendIfChannel::Red => (
|
|
||||||
[
|
|
||||||
[
|
|
||||||
RedContentFalloffStartInput.into(),
|
|
||||||
RedContentRangeStartInput.into(),
|
|
||||||
RedContentRangeEndInput.into(),
|
|
||||||
RedContentFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
RedUnderlyingFalloffStartInput.into(),
|
|
||||||
RedUnderlyingRangeStartInput.into(),
|
|
||||||
RedUnderlyingRangeEndInput.into(),
|
|
||||||
RedUnderlyingFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
Color::RED,
|
|
||||||
),
|
|
||||||
BlendIfChannel::Green => (
|
|
||||||
[
|
|
||||||
[
|
|
||||||
GreenContentFalloffStartInput.into(),
|
|
||||||
GreenContentRangeStartInput.into(),
|
|
||||||
GreenContentRangeEndInput.into(),
|
|
||||||
GreenContentFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
GreenUnderlyingFalloffStartInput.into(),
|
|
||||||
GreenUnderlyingRangeStartInput.into(),
|
|
||||||
GreenUnderlyingRangeEndInput.into(),
|
|
||||||
GreenUnderlyingFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
Color::GREEN,
|
|
||||||
),
|
|
||||||
BlendIfChannel::Blue => (
|
|
||||||
[
|
|
||||||
[
|
|
||||||
BlueContentFalloffStartInput.into(),
|
|
||||||
BlueContentRangeStartInput.into(),
|
|
||||||
BlueContentRangeEndInput.into(),
|
|
||||||
BlueContentFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
[
|
|
||||||
BlueUnderlyingFalloffStartInput.into(),
|
|
||||||
BlueUnderlyingRangeStartInput.into(),
|
|
||||||
BlueUnderlyingRangeEndInput.into(),
|
|
||||||
BlueUnderlyingFalloffEndInput.into(),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
Color::BLUE,
|
|
||||||
),
|
|
||||||
};
|
|
||||||
|
|
||||||
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
|
|
||||||
let track = Gradient::from(vec![Color::BLACK, track_color]);
|
|
||||||
let mut layout = vec![channel];
|
|
||||||
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
|
|
||||||
let params = [
|
|
||||||
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
|
|
||||||
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
|
|
||||||
.dash_to_next()
|
|
||||||
.overlap_next(MarkerOverlap::Freely),
|
|
||||||
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
|
|
||||||
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
|
|
||||||
];
|
|
||||||
build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout);
|
|
||||||
}
|
|
||||||
layout
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::raster::vibrance::*;
|
use graphene_std::raster::vibrance::*;
|
||||||
|
|
||||||
@@ -2718,8 +2641,8 @@ pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
|||||||
max: 100.,
|
max: 100.,
|
||||||
default: Some(0.),
|
default: Some(0.),
|
||||||
};
|
};
|
||||||
let vibrance = slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
|
let vibrance = range_slider_widget(ParameterWidgetsInfo::new(node_id, VibranceInput, true, context), number_input.clone(), slider);
|
||||||
let saturation = slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
|
let saturation = range_slider_widget(ParameterWidgetsInfo::new(node_id, SaturationInput, true, context), number_input, slider);
|
||||||
|
|
||||||
vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)]
|
vec![LayoutGroup::row(vibrance), LayoutGroup::row(saturation)]
|
||||||
}
|
}
|
||||||
@@ -3079,7 +3002,7 @@ pub(crate) fn sample_polyline_inspector(node_id: NodeId, context: &mut NodeInspe
|
|||||||
pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::raster::exposure::*;
|
use graphene_std::raster::exposure::*;
|
||||||
|
|
||||||
let exposure = slider_widget(
|
let exposure = range_slider_widget(
|
||||||
ParameterWidgetsInfo::new(node_id, ExposureInput, true, context),
|
ParameterWidgetsInfo::new(node_id, ExposureInput, true, context),
|
||||||
NumberInput::default().min(-20.).max(20.),
|
NumberInput::default().min(-20.).max(20.),
|
||||||
SliderRange {
|
SliderRange {
|
||||||
@@ -3088,7 +3011,7 @@ pub(crate) fn exposure_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
|||||||
default: Some(0.),
|
default: Some(0.),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let offset = slider_widget(
|
let offset = range_slider_widget(
|
||||||
ParameterWidgetsInfo::new(node_id, OffsetInput, true, context),
|
ParameterWidgetsInfo::new(node_id, OffsetInput, true, context),
|
||||||
NumberInput::default().min(-0.5).max(0.5),
|
NumberInput::default().min(-0.5).max(0.5),
|
||||||
SliderRange {
|
SliderRange {
|
||||||
@@ -3941,61 +3864,6 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
|||||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
|
||||||
use graphene_std::blending_nodes::filters::sharpen::*;
|
|
||||||
|
|
||||||
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
|
|
||||||
let edges_only = get_document_node(node_id, context)
|
|
||||||
.ok()
|
|
||||||
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
|
|
||||||
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
|
|
||||||
|
|
||||||
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
|
|
||||||
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
|
|
||||||
|
|
||||||
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
|
|
||||||
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
|
|
||||||
|
|
||||||
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
|
|
||||||
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
|
|
||||||
|
|
||||||
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
|
|
||||||
|
|
||||||
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
|
||||||
use graphene_std::blending_nodes::distortions::displace::*;
|
|
||||||
|
|
||||||
// Each mode shows only the maps and distances it reads, and a wired mode shows both sets
|
|
||||||
let mode = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ModeInput)) {
|
|
||||||
Some(TaggedValue::DisplaceMode(mode)) => Some(*mode),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut layout = vec![enum_choice::<DisplaceMode>().for_socket(ParameterWidgetsInfo::new(node_id, ModeInput, true, context)).inspector_row()];
|
|
||||||
if !matches!(mode, Some(DisplaceMode::XAndY)) {
|
|
||||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, DisplacementInput, true, context), ColorInput::default()));
|
|
||||||
|
|
||||||
let number_input = NumberInput::default().mode_range().unit("°").range_min(Some(-180.)).range_max(Some(180.));
|
|
||||||
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, AngleInput, true, context), number_input)));
|
|
||||||
|
|
||||||
let number_input = NumberInput::default().unit(" px");
|
|
||||||
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input)));
|
|
||||||
}
|
|
||||||
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
|
||||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
|
||||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
|
||||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
|
||||||
}
|
|
||||||
|
|
||||||
let edge_mode = enum_choice::<GradientSpread>()
|
|
||||||
.for_socket(ParameterWidgetsInfo::new(node_id, EdgeModeInput, true, context))
|
|
||||||
.inspector_row();
|
|
||||||
layout.push(edge_mode);
|
|
||||||
layout
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct ParameterWidgetsInfo<'a> {
|
pub struct ParameterWidgetsInfo<'a> {
|
||||||
document_id: DocumentId,
|
document_id: DocumentId,
|
||||||
network_interface: &'a NodeNetworkInterface,
|
network_interface: &'a NodeNetworkInterface,
|
||||||
@@ -4284,7 +4152,10 @@ mod tests {
|
|||||||
fn math_expression_errors_quote_the_expression_safely() {
|
fn math_expression_errors_quote_the_expression_safely() {
|
||||||
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
|
// The expression's own text sits in code it can't close, while the message's own code keeps its formatting
|
||||||
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
|
assert_eq!(description("`abc").as_deref(), Some("`` `abc `` is not recognized"));
|
||||||
assert_eq!(description("7 % 3").as_deref(), Some("`%` is reserved for percentages, so the remainder is written `mod(a, b)`"));
|
assert_eq!(
|
||||||
|
description("7 % 3").as_deref(),
|
||||||
|
Some("`%` makes the number before it a percentage, so the remainder is written `mod(a, b)`")
|
||||||
|
);
|
||||||
|
|
||||||
// A quoted token like `*` is a code span, so it can't pair with another into italics
|
// A quoted token like `*` is a code span, so it can't pair with another into italics
|
||||||
let error = description("2 * * 3").unwrap();
|
let error = description("2 * * 3").unwrap();
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ impl FrontendGraphDataType {
|
|||||||
"Color" => Self::Color,
|
"Color" => Self::Color,
|
||||||
"Gradient" => Self::Gradient,
|
"Gradient" => Self::Gradient,
|
||||||
"String" => Self::Typography,
|
"String" => Self::Typography,
|
||||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" | "Length" | "Angle" => Self::Number,
|
||||||
// A generator draws pixels like an image, at whatever resolution is needed
|
// A generator draws pixels like an image, at whatever resolution is needed
|
||||||
"Generator" => Self::Raster,
|
"Generator" => Self::Raster,
|
||||||
raster if raster.starts_with("Raster") => Self::Raster,
|
raster if raster.starts_with("Raster") => Self::Raster,
|
||||||
@@ -212,6 +212,23 @@ pub struct NodeEvaluationError {
|
|||||||
pub message: String,
|
pub message: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct FrontendClickTargets {
|
||||||
|
#[serde(rename = "nodeClickTargets")]
|
||||||
|
pub node_click_targets: Vec<String>,
|
||||||
|
#[serde(rename = "layerClickTargets")]
|
||||||
|
pub layer_click_targets: Vec<String>,
|
||||||
|
#[serde(rename = "connectorClickTargets")]
|
||||||
|
pub connector_click_targets: Vec<String>,
|
||||||
|
#[serde(rename = "iconClickTargets")]
|
||||||
|
pub icon_click_targets: Vec<String>,
|
||||||
|
#[serde(rename = "allNodesBoundingBox")]
|
||||||
|
pub all_nodes_bounding_box: String,
|
||||||
|
#[serde(rename = "importExportNames")]
|
||||||
|
pub import_export_names: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum Direction {
|
pub enum Direction {
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use crate::messages::prelude::*;
|
|||||||
pub struct OverlaysMessageContext<'a> {
|
pub struct OverlaysMessageContext<'a> {
|
||||||
pub visibility_settings: OverlaysVisibilitySettings,
|
pub visibility_settings: OverlaysVisibilitySettings,
|
||||||
pub viewport: &'a ViewportMessageHandler,
|
pub viewport: &'a ViewportMessageHandler,
|
||||||
pub graph_open: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default, ExtractField)]
|
#[derive(Debug, Clone, Default, ExtractField)]
|
||||||
@@ -26,7 +25,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
|||||||
|
|
||||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||||
|
|
||||||
if visibility_settings.all() && !context.graph_open {
|
if visibility_settings.all() {
|
||||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
|
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
|
||||||
|
|
||||||
use super::test_support::open_demo;
|
use super::test_support::open_demo;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
|
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||||
use glam::DVec2;
|
use glam::DVec2;
|
||||||
use graphene_std::uuid::NodeId;
|
use graphene_std::uuid::NodeId;
|
||||||
@@ -20,32 +20,20 @@ const DEMOS: [&str; 8] = [
|
|||||||
const REPETITIONS: u32 = 200;
|
const REPETITIONS: u32 = 200;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
|
fn wire_anchors_match_the_ports_of_every_demo_node() {
|
||||||
for demo in DEMOS {
|
for demo in DEMOS {
|
||||||
let document = open_demo(demo);
|
let document = open_demo(demo);
|
||||||
let interface = &document.network_interface;
|
let interface = &document.network_interface;
|
||||||
|
|
||||||
for node_id in interface.document_network().nodes.keys() {
|
for node_id in interface.document_network().nodes.keys() {
|
||||||
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
|
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
|
||||||
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
|
|
||||||
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
|
|
||||||
let on_port = |wanted: Part, anchor: Option<DVec2>| {
|
|
||||||
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
|
|
||||||
match (port, anchor) {
|
|
||||||
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
|
|
||||||
(Some(port), Some(anchor)) => port.contains(anchor),
|
|
||||||
(None, None) => true,
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
||||||
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
|
let input = InputConnector::node_at_index(*node_id, index);
|
||||||
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
|
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
|
||||||
}
|
}
|
||||||
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
||||||
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
|
let output = OutputConnector::node(*node_id, index);
|
||||||
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
|
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,7 +60,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
|||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
for _ in 0..REPETITIONS {
|
for _ in 0..REPETITIONS {
|
||||||
for node_id in &node_ids {
|
for node_id in &node_ids {
|
||||||
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
|
std::hint::black_box(interface.node_click_targets(node_id, &[]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let all_click_targets = start.elapsed() / REPETITIONS;
|
let all_click_targets = start.elapsed() / REPETITIONS;
|
||||||
|
|||||||
@@ -296,6 +296,29 @@ fn pinned_order_round_trips_through_the_registry() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The document's resolution is shared document state, so it survives a registry round trip, and the default is stored as its absence.
|
||||||
|
#[test]
|
||||||
|
fn pixels_per_inch_round_trips_through_the_registry() {
|
||||||
|
let round_trip = |pixels_per_inch: f64| {
|
||||||
|
let mut document = open_demo("changing-seasons.graphite");
|
||||||
|
document.network_interface.set_pixels_per_inch(pixels_per_inch);
|
||||||
|
|
||||||
|
let network = document.network_interface.document_network().clone();
|
||||||
|
let view = StorageMetadataView::new(&document.network_interface);
|
||||||
|
let conversion = Registry::convert_from_runtime(&network, &view, &Default::default(), PeerId(0)).expect("convert_from_runtime failed");
|
||||||
|
let declarations = conversion.declarations;
|
||||||
|
let (rebuilt_network, node_entries, network_entries) = conversion.registry.to_runtime_with_full_metadata(&declarations, &conversion.blob_bytes).expect("to_runtime failed");
|
||||||
|
let rebuilt = build_interface_from_storage(rebuilt_network, node_entries, network_entries);
|
||||||
|
(
|
||||||
|
rebuilt.pixels_per_inch(),
|
||||||
|
rebuilt.network_metadata(&[]).expect("the rebuilt document network should resolve").persistent_metadata.pixels_per_inch,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(round_trip(300.), (300., Some(300.)));
|
||||||
|
assert_eq!(round_trip(96.), (96., None));
|
||||||
|
}
|
||||||
|
|
||||||
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
/// Per-peer view settings (`ui::doc::*`) survive the `session.json` round-trip: serialize them into
|
||||||
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
/// the view map, then apply it onto a fresh handler and confirm each field matches.
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
|
|||||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||||
node.set_absolute_position(*position);
|
node.set_absolute_position(*position);
|
||||||
}
|
}
|
||||||
|
interface.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,14 +172,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
|
|||||||
interface.finish_drag(&[]);
|
interface.finish_drag(&[]);
|
||||||
|
|
||||||
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
||||||
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
|
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
|
||||||
panic!("the root network is laid out")
|
panic!("the root network is laid out")
|
||||||
};
|
};
|
||||||
let fresh = graph_layout::Layout::new(&graph);
|
let fresh = graph_layout::Layout::new(&graph);
|
||||||
for (other, position) in kept {
|
for (other, position) in kept {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Some(position),
|
Some(position),
|
||||||
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
|
indices.get(&other).map(|index| fresh.node(*index).position),
|
||||||
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,8 +53,6 @@ pub struct DocumentMetadata {
|
|||||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||||
/// The bounding box of the frames that each layer's effects paint anywhere in, in document pixels, for the layers with such effects.
|
|
||||||
pub layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
|
|
||||||
/// Transform from document space to viewport space.
|
/// Transform from document space to viewport space.
|
||||||
pub document_to_viewport: DAffine2,
|
pub document_to_viewport: DAffine2,
|
||||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||||
@@ -366,7 +364,7 @@ impl DocumentMetadata {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||||
/// stroke geometry when the layer is a vector with a stroke style, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a
|
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||||
@@ -374,8 +372,7 @@ impl DocumentMetadata {
|
|||||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||||
});
|
});
|
||||||
let frames = self.layer_effects_frames.get(&layer).copied();
|
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||||
let [min, max] = [stroked, self.bounding_box_document(layer), frames].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
|
||||||
|
|
||||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||||
Some([min - reach, max + reach])
|
Some([min - reach, max + reach])
|
||||||
@@ -754,25 +751,6 @@ mod tests {
|
|||||||
assert_eq!((min.x, max.x), (0., 110.));
|
assert_eq!((min.x, max.x), (0., 110.));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn bounds_with_effects_hold_the_frames_the_effects_paint_in() {
|
|
||||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
|
||||||
let mut square = BezPath::new();
|
|
||||||
square.move_to((-30., -30.));
|
|
||||||
square.line_to((30., -30.));
|
|
||||||
square.line_to((30., 30.));
|
|
||||||
square.line_to((-30., 30.));
|
|
||||||
square.close_path();
|
|
||||||
|
|
||||||
// A layer 30 across each way from its middle, with effects painting anywhere in a frame reaching 40 from it, and 2 past that
|
|
||||||
let mut metadata = DocumentMetadata::default();
|
|
||||||
metadata.click_targets.insert(layer, vec![Arc::new(ClickTarget::new_with_path(square, 0.))]);
|
|
||||||
metadata.layer_effects_frames.insert(layer, [DVec2::splat(-40.), DVec2::splat(40.)]);
|
|
||||||
metadata.layer_effects_reach.insert(layer, 2.);
|
|
||||||
|
|
||||||
assert_eq!(metadata.bounding_box_document_with_stroke_and_effects(layer), Some([DVec2::splat(-42.), DVec2::splat(42.)]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ mod layout;
|
|||||||
mod layout_pass;
|
mod layout_pass;
|
||||||
mod memo_network;
|
mod memo_network;
|
||||||
mod mutations;
|
mod mutations;
|
||||||
mod node_parts;
|
|
||||||
mod queries;
|
mod queries;
|
||||||
mod reconcile;
|
mod reconcile;
|
||||||
mod resolved_types;
|
mod resolved_types;
|
||||||
@@ -37,7 +36,6 @@ mod view;
|
|||||||
|
|
||||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||||
pub use layout_pass::NetworkLayout;
|
pub use layout_pass::NetworkLayout;
|
||||||
pub use node_parts::{Part, PartTarget};
|
|
||||||
pub use reconcile::{ReconcileError, Reconciled};
|
pub use reconcile::{ReconcileError, Reconciled};
|
||||||
use store::Guarded;
|
use store::Guarded;
|
||||||
pub use store::NodeLocator;
|
pub use store::NodeLocator;
|
||||||
@@ -54,7 +52,7 @@ use crate::consts::{
|
|||||||
STACK_VERTICAL_GAP,
|
STACK_VERTICAL_GAP,
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
|
|||||||
EditorDelta::NodeMetadata { network, node_id, change } => {
|
EditorDelta::NodeMetadata { network, node_id, change } => {
|
||||||
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
||||||
match change {
|
match change {
|
||||||
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
|
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
||||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||||
@@ -105,6 +105,7 @@ impl NodeNetworkInterface {
|
|||||||
match change {
|
match change {
|
||||||
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
|
NetworkMetadataChange::Reference(reference) => network.set_reference(reference.clone()),
|
||||||
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
|
NetworkMetadataChange::PinnedOrder(order) => network.set_pinned_order(order.clone()),
|
||||||
|
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => network.set_pixels_per_inch(*pixels_per_inch),
|
||||||
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
|
NetworkMetadataChange::ImportMetadata(import_metadata) => network.set_import_metadata(import_metadata.clone()),
|
||||||
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
|
NetworkMetadataChange::ExportNames(export_names) => network.set_export_names(export_names.clone()),
|
||||||
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
|
NetworkMetadataChange::ExportDescriptions(export_descriptions) => network.set_export_descriptions(export_descriptions.clone()),
|
||||||
|
|||||||
@@ -88,15 +88,34 @@ impl NodeNetworkInterface {
|
|||||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
|
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
|
||||||
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
self.load_import_export_ports(network_path);
|
||||||
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
|
|
||||||
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
|
|
||||||
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
|
|
||||||
cache.unload();
|
|
||||||
}
|
|
||||||
|
|
||||||
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
|
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||||
|
log::error!("Could not get nested network_metadata in import_export_ports");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
|
||||||
|
log::error!("Could not load import export ports in import_export_ports");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
Some(ports)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the import/export ports through &self, loading them first if needed.
|
||||||
|
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
||||||
|
self.network_metadata(network_path)?
|
||||||
|
.transient_metadata
|
||||||
|
.import_export_ports
|
||||||
|
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
||||||
|
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||||
|
log::error!("Could not get nested network_metadata in load_import_export_ports");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
||||||
@@ -107,13 +126,78 @@ impl NodeNetworkInterface {
|
|||||||
transient.import_export_ports.unload();
|
transient.import_export_ports.unload();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The combined bounds of every node in the network, in node graph space.
|
|
||||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||||
self.with_layout(network_path, NetworkLayout::bounds)
|
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||||
|
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
let bounding_box = network_metadata
|
||||||
|
.transient_metadata
|
||||||
|
.all_nodes_bounding_box
|
||||||
|
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
|
||||||
|
if bounding_box.is_none() {
|
||||||
|
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
|
||||||
|
}
|
||||||
|
bounding_box
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The combined bounds of every node in the network, in node graph space.
|
||||||
|
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||||
|
let network_metadata = self.network_metadata(network_path)?;
|
||||||
|
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||||
|
|
||||||
|
Some(
|
||||||
|
nodes
|
||||||
|
.iter()
|
||||||
|
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
|
||||||
|
.reduce(Quad::combine_bounds)
|
||||||
|
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
|
||||||
|
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||||
|
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
transient.all_nodes_bounding_box.unload();
|
||||||
|
transient.import_export_clearance.unload();
|
||||||
|
self.unload_import_export_ports(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||||
self.with_layout(network_path, NetworkLayout::clearance)
|
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||||
|
log::error!("Could not get nested network_metadata in import_export_clearance");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
network_metadata
|
||||||
|
.transient_metadata
|
||||||
|
.import_export_clearance
|
||||||
|
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
|
||||||
|
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||||
|
let network_metadata = self.network_metadata(network_path)?;
|
||||||
|
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||||
|
|
||||||
|
let mut clearance = ImportExportClearance::default();
|
||||||
|
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
||||||
|
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.is_redirect_dot(node_id, network_path) {
|
||||||
|
let center = (top_left.x + bottom_right.x) / 2.;
|
||||||
|
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||||
|
} else {
|
||||||
|
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(clearance)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
||||||
@@ -280,10 +364,6 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
|
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
|
||||||
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
|
|
||||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||||
log::error!("Could not get nested node_metadata in layer_width");
|
log::error!("Could not get nested node_metadata in layer_width");
|
||||||
return None;
|
return None;
|
||||||
@@ -296,7 +376,7 @@ impl NodeNetworkInterface {
|
|||||||
node_metadata
|
node_metadata
|
||||||
.transient_metadata
|
.transient_metadata
|
||||||
.layer_width
|
.layer_width
|
||||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
|
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Unloads layer width if the node is a layer.
|
/// Unloads layer width if the node is a layer.
|
||||||
@@ -395,7 +475,7 @@ impl NodeNetworkInterface {
|
|||||||
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||||
let thick = vertical_end && vertical_start;
|
let thick = vertical_end && vertical_start;
|
||||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||||
|
|
||||||
let path_string = vector_wire.to_svg();
|
let path_string = vector_wire.to_svg();
|
||||||
let center_path_string = center_line.to_svg();
|
let center_path_string = center_line.to_svg();
|
||||||
@@ -443,7 +523,7 @@ impl NodeNetworkInterface {
|
|||||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||||
let thick = vertical_end && vertical_start;
|
let thick = vertical_end && vertical_start;
|
||||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
|
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||||
Some((vector_wire, center_line, thick))
|
Some((vector_wire, center_line, thick))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -469,10 +549,17 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The node's body, ports, and handles, built where it is drawn now.
|
/// The node's body, ports, and handles, built where it is drawn now.
|
||||||
/// The box around the node's body where it sits in its grid cell, in node graph space.
|
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||||
|
self.compute_node_click_targets(node_id, network_path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
|
||||||
|
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||||
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
|
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||||
Some([body.min, body.max])
|
.flatten()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
use super::template::NodeTemplateImplementation;
|
||||||
use super::{InputConnector, OutputConnector, catalog};
|
use super::{InputConnector, OutputConnector, catalog};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
|||||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
||||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||||
|
|
||||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
|||||||
let custom = NodeId::new();
|
let custom = NodeId::new();
|
||||||
let blend = NodeId::new();
|
let blend = NodeId::new();
|
||||||
let interface = &mut editor.active_document_mut().network_interface;
|
let interface = &mut editor.active_document_mut().network_interface;
|
||||||
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
||||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||||
panic!("the Blend should name a table entry")
|
panic!("the Blend should name a table entry")
|
||||||
|
|||||||
+7
-88
@@ -2,7 +2,7 @@ use super::{
|
|||||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||||
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||||
};
|
};
|
||||||
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
||||||
@@ -330,6 +330,7 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
|
|||||||
}
|
}
|
||||||
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
||||||
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
||||||
|
network_interface.invalidate_positions(&[]);
|
||||||
|
|
||||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
||||||
|
|
||||||
@@ -3118,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
|||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||||
let path = [subgraph];
|
let path = [subgraph];
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
|
|
||||||
@@ -3505,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
|||||||
|
|
||||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||||
@@ -4040,30 +4041,18 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_new_subgraph_is_its_own_definition() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
|
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
|
||||||
let network_interface = &editor.active_document().network_interface;
|
|
||||||
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
|
||||||
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
|
||||||
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn cannot_preview_node_without_outputs() {
|
async fn cannot_preview_node_without_outputs() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let subgraph = editor.create_empty_subgraph_at(0, 0).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;
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
|
||||||
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||||
|
|
||||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||||
network_interface.toggle_preview(subgraph, &[]);
|
network_interface.toggle_preview(custom_node, &[]);
|
||||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4227,73 +4216,3 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
|||||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||||
assert_invariants(&editor, "after grouping a group");
|
assert_invariants(&editor, "after grouping a group");
|
||||||
}
|
}
|
||||||
|
|
||||||
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
|
|
||||||
let interface = &editor.active_document().network_interface;
|
|
||||||
let parent = layer.parent(interface.document_metadata())?;
|
|
||||||
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
|
||||||
for x in [0., 50., 100.] {
|
|
||||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
|
||||||
.children(editor.active_document().metadata())
|
|
||||||
.next()
|
|
||||||
.expect("the artboard should be a layer");
|
|
||||||
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
|
|
||||||
group_selected_layers(&mut editor).await;
|
|
||||||
|
|
||||||
let group = artboard
|
|
||||||
.children(editor.active_document().metadata())
|
|
||||||
.next()
|
|
||||||
.expect("the group should be the top layer of the artboard");
|
|
||||||
for insert_index in [0, 2] {
|
|
||||||
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
|
|
||||||
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
|
|
||||||
|
|
||||||
for layer in group.children(editor.active_document().metadata()).chain([group]) {
|
|
||||||
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
|
||||||
for x in [0., 50., 100., 150.] {
|
|
||||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
|
||||||
}
|
|
||||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
|
||||||
.children(editor.active_document().metadata())
|
|
||||||
.next()
|
|
||||||
.expect("the artboard should be a layer");
|
|
||||||
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
|
|
||||||
|
|
||||||
let interface = &mut editor.active_document_mut().network_interface;
|
|
||||||
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
|
|
||||||
for keep_upstream in [false, true] {
|
|
||||||
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
|
|
||||||
let before = interface.positions(layers.iter().copied(), &[]);
|
|
||||||
interface.drag_selected_nodes(offset, keep_upstream, &[]);
|
|
||||||
let dragging = interface.positions(layers.iter().copied(), &[]);
|
|
||||||
interface.finish_drag(&[]);
|
|
||||||
|
|
||||||
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
|
|
||||||
|
|
||||||
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+7
-14
@@ -62,21 +62,11 @@ pub enum NodeMetadataChange {
|
|||||||
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
||||||
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
||||||
NodeType(NodeTypePersistentMetadata),
|
NodeType(NodeTypePersistentMetadata),
|
||||||
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
|
|
||||||
Position(NodeTypePersistentMetadata),
|
|
||||||
DisplayName(String),
|
DisplayName(String),
|
||||||
Locked(bool),
|
Locked(bool),
|
||||||
Pinned(bool),
|
Pinned(bool),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl NodeMetadataChange {
|
|
||||||
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
|
|
||||||
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
|
|
||||||
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
|
|
||||||
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
||||||
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -85,6 +75,7 @@ pub enum NetworkMetadataChange {
|
|||||||
Reference(Option<String>),
|
Reference(Option<String>),
|
||||||
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
|
/// The whole order, since the encoding is one array-valued attribute rather than a slot each.
|
||||||
PinnedOrder(Vec<NodeId>),
|
PinnedOrder(Vec<NodeId>),
|
||||||
|
PixelsPerInch(Option<f64>),
|
||||||
ImportMetadata(Vec<InputMetadata>),
|
ImportMetadata(Vec<InputMetadata>),
|
||||||
ExportNames(Vec<String>),
|
ExportNames(Vec<String>),
|
||||||
ExportDescriptions(Vec<String>),
|
ExportDescriptions(Vec<String>),
|
||||||
@@ -266,6 +257,12 @@ impl EditorDelta {
|
|||||||
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
|
value: (!stored.is_empty()).then(|| serialize_attribute(network_attr::PINNED_ORDER, &stored)).transpose()?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
NetworkMetadataChange::PixelsPerInch(pixels_per_inch) => AttributeDelta {
|
||||||
|
key: network_attr::PIXELS_PER_INCH.to_string(),
|
||||||
|
value: pixels_per_inch
|
||||||
|
.map(|pixels_per_inch| serialize_attribute(network_attr::PIXELS_PER_INCH, &pixels_per_inch))
|
||||||
|
.transpose()?,
|
||||||
|
},
|
||||||
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
|
NetworkMetadataChange::ImportMetadata(import_metadata) => import_metadata_delta(import_metadata)?,
|
||||||
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
|
NetworkMetadataChange::ExportNames(export_names) => export_names_delta(export_names)?,
|
||||||
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
|
NetworkMetadataChange::ExportDescriptions(export_descriptions) => export_descriptions_delta(export_descriptions)?,
|
||||||
@@ -329,10 +326,6 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
|||||||
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
NodeMetadataChange::Position(node_type) => vec![node_attribute(
|
|
||||||
node_attr::ui::POSITION,
|
|
||||||
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
|
|
||||||
)],
|
|
||||||
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
||||||
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
||||||
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
||||||
|
|||||||
+1
-28
@@ -3,7 +3,6 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
|
|||||||
use super::storage_metadata::StorageMetadataView;
|
use super::storage_metadata::StorageMetadataView;
|
||||||
use super::{InputConnector, NodeTemplate};
|
use super::{InputConnector, NodeTemplate};
|
||||||
use crate::test_utils::test_prelude::*;
|
use crate::test_utils::test_prelude::*;
|
||||||
use document_graph_storage::attr::node as node_attr;
|
|
||||||
use document_graph_storage::delta::compute_deltas;
|
use document_graph_storage::delta::compute_deltas;
|
||||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
@@ -185,7 +184,7 @@ async fn per_field_metadata_edits_match_the_diff() {
|
|||||||
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
||||||
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
||||||
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
||||||
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
|
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
|
||||||
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||||
network: None,
|
network: None,
|
||||||
node_id: node,
|
node_id: node,
|
||||||
@@ -284,32 +283,6 @@ async fn unchanged_writes_emit_nothing() {
|
|||||||
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn moving_a_layer_writes_only_its_position() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(0., 0., 40., 40.).await;
|
|
||||||
let layer = LayerNodeIdentifier::ROOT_PARENT
|
|
||||||
.children(editor.active_document().metadata())
|
|
||||||
.next()
|
|
||||||
.expect("the rectangle should be a layer")
|
|
||||||
.to_node();
|
|
||||||
|
|
||||||
let working = convert(&editor);
|
|
||||||
editor.active_document_mut().network_interface.discard_deltas();
|
|
||||||
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
|
|
||||||
|
|
||||||
let emitted = committed_deltas(&mut editor);
|
|
||||||
let written: Vec<String> = construct(&editor, &emitted, &working)
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|op| match op {
|
|
||||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
assert_eq!(written, [node_attr::ui::POSITION]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
||||||
/// without the caller saying anything about it.
|
/// without the caller saying anything about it.
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
+190
-3
@@ -46,6 +46,193 @@ impl NodeNetworkInterface {
|
|||||||
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
|
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
|
||||||
|
let Some(node_position) = self.position(node_id, network_path) else {
|
||||||
|
log::error!("Could not get node position in compute_node_ports for node {node_id}");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let document_node = self.document_node(node_id, network_path)?;
|
||||||
|
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||||
|
let mut ports = Ports::new();
|
||||||
|
|
||||||
|
if self.is_redirect_dot(node_id, network_path) {
|
||||||
|
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
|
||||||
|
} else if !self.is_layer(node_id, network_path) {
|
||||||
|
let mut input_row_count = 0;
|
||||||
|
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
||||||
|
if input.is_exposed() {
|
||||||
|
ports.insert_node_input(input_index, input_row_count, node_top_left);
|
||||||
|
}
|
||||||
|
if input_index == 0 || input.is_exposed() {
|
||||||
|
input_row_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
|
||||||
|
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
|
||||||
|
ports.insert_node_output(output_index, node_top_left);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ports.insert_layer_input(0, node_top_left);
|
||||||
|
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
|
||||||
|
ports.insert_layer_input(1, node_top_left);
|
||||||
|
}
|
||||||
|
ports.insert_layer_output(node_top_left);
|
||||||
|
}
|
||||||
|
|
||||||
|
Some(ports)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
|
||||||
|
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||||
|
let Some(node_position) = self.position(node_id, network_path) else {
|
||||||
|
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let node_metadata = self.node_metadata(node_id, network_path)?;
|
||||||
|
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
|
||||||
|
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||||
|
|
||||||
|
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
|
||||||
|
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
|
||||||
|
if self.is_redirect_dot(node_id, network_path) {
|
||||||
|
const DOT_HALF_WIDTH: f64 = 15.;
|
||||||
|
const DOT_HALF_HEIGHT: f64 = 8.;
|
||||||
|
|
||||||
|
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
|
||||||
|
let path = rounded_rectangle_path(
|
||||||
|
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||||
|
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||||
|
[DOT_HALF_HEIGHT; 4],
|
||||||
|
);
|
||||||
|
|
||||||
|
return Some(DocumentNodeClickTargets {
|
||||||
|
node_click_target: ClickTarget::new_with_path(path, 0.),
|
||||||
|
port_click_targets,
|
||||||
|
node_type_metadata: NodeTypeClickTargets::Node,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||||
|
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
|
||||||
|
let width = 5 * GRID_SIZE;
|
||||||
|
// Offset down by half a grid so the click target sits below the top connector strip.
|
||||||
|
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
|
||||||
|
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
||||||
|
|
||||||
|
let radius = 3.;
|
||||||
|
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||||
|
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||||
|
|
||||||
|
DocumentNodeClickTargets {
|
||||||
|
node_click_target,
|
||||||
|
port_click_targets,
|
||||||
|
node_type_metadata: NodeTypeClickTargets::Node,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
|
||||||
|
log::error!("Could not get layer width in compute_node_click_targets");
|
||||||
|
0
|
||||||
|
});
|
||||||
|
let width = layer_width_cells * GRID_SIZE;
|
||||||
|
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
|
||||||
|
let locked = self.is_locked(node_id, network_path);
|
||||||
|
|
||||||
|
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
|
||||||
|
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
|
||||||
|
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
||||||
|
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
||||||
|
|
||||||
|
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||||
|
let path = rounded_rectangle_path(
|
||||||
|
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||||
|
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
||||||
|
[3.; 4],
|
||||||
|
);
|
||||||
|
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
|
||||||
|
|
||||||
|
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
||||||
|
let lock_click_target = if locked {
|
||||||
|
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
||||||
|
let path = rounded_rectangle_path(
|
||||||
|
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
||||||
|
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
||||||
|
[3.; 4],
|
||||||
|
);
|
||||||
|
Some(ClickTarget::new_with_path(path, 0.))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
|
||||||
|
const GRIP_WIDTH: f64 = 8.;
|
||||||
|
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||||
|
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||||
|
let path = rounded_rectangle_path(
|
||||||
|
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||||
|
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||||
|
[0.; 4],
|
||||||
|
);
|
||||||
|
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
||||||
|
|
||||||
|
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
|
||||||
|
// so the rest of the layer still drills into the subgraph on double-click
|
||||||
|
|
||||||
|
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
||||||
|
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
||||||
|
/// `.thumbnail` (70px) + its 1px side margins (= 72)
|
||||||
|
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
|
||||||
|
/// `.details` margin-left
|
||||||
|
const DETAILS_LEFT_MARGIN: f64 = 8.;
|
||||||
|
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
|
||||||
|
/// Distance from layer's right edge to visibility's left edge (= 12)
|
||||||
|
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
|
||||||
|
const FONT_SIZE: f64 = 14.;
|
||||||
|
|
||||||
|
let display_name = self.display_name(node_id, network_path);
|
||||||
|
let name_click_target = if display_name.is_empty() {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
|
||||||
|
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
|
||||||
|
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
|
||||||
|
let name_width = text_width(&display_name, FONT_SIZE);
|
||||||
|
let name_right = (name_left + name_width).min(name_right_max);
|
||||||
|
if name_right > name_left {
|
||||||
|
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
||||||
|
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
||||||
|
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
||||||
|
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||||
|
Some(ClickTarget::new_with_path(path, 0.))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// The layer click target spans the layer and its chain background
|
||||||
|
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||||
|
|
||||||
|
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||||
|
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
||||||
|
const CORNER_RADIUS: f64 = 10.;
|
||||||
|
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||||
|
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||||
|
|
||||||
|
DocumentNodeClickTargets {
|
||||||
|
node_click_target,
|
||||||
|
port_click_targets,
|
||||||
|
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
|
||||||
|
visibility_click_target,
|
||||||
|
lock_click_target,
|
||||||
|
grip_click_target,
|
||||||
|
name_click_target,
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(document_node_click_targets)
|
||||||
|
}
|
||||||
|
|
||||||
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
|
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
|
||||||
/// Laid out as the frontend draws them, just past the connector.
|
/// Laid out as the frontend draws them, just past the connector.
|
||||||
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
|
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
|
||||||
@@ -152,9 +339,9 @@ impl NodeNetworkInterface {
|
|||||||
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
|
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
|
||||||
/// because measuring the name's text is slow.
|
/// because measuring the name's text is slow.
|
||||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
|
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
|
||||||
const GAP_WIDTH: f64 = 8.;
|
const GAP_WIDTH: f64 = 8.;
|
||||||
const FONT_SIZE: f64 = 14.;
|
const FONT_SIZE: f64 = 14.;
|
||||||
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
||||||
@@ -169,7 +356,7 @@ impl NodeNetworkInterface {
|
|||||||
let icon_overhang_width = GRID_SIZE as f64 / 2.;
|
let icon_overhang_width = GRID_SIZE as f64 / 2.;
|
||||||
|
|
||||||
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
|
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
|
||||||
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
((layer_width_pixels / 24.).ceil() as u32).max(8)
|
||||||
}
|
}
|
||||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||||
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
||||||
|
|||||||
+116
-59
@@ -24,6 +24,81 @@ impl NodeNetworkInterface {
|
|||||||
all_selected_nodes
|
all_selected_nodes
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
|
||||||
|
let mut all_node_click_targets = Vec::new();
|
||||||
|
let mut connector_click_targets = Vec::new();
|
||||||
|
let mut icon_click_targets = Vec::new();
|
||||||
|
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||||
|
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
|
||||||
|
return FrontendClickTargets::default();
|
||||||
|
};
|
||||||
|
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||||
|
self.with_import_export_ports(network_path, |import_export_click_targets| {
|
||||||
|
for port in import_export_click_targets.click_targets() {
|
||||||
|
if let ClickTargetType::Path(path) = port.target_type() {
|
||||||
|
connector_click_targets.push(path.to_svg());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
nodes.into_iter().for_each(|node_id| {
|
||||||
|
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
|
||||||
|
let mut node_path = String::new();
|
||||||
|
|
||||||
|
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
|
||||||
|
node_path.push_str(path.to_svg().as_str())
|
||||||
|
}
|
||||||
|
all_node_click_targets.push((node_id, node_path));
|
||||||
|
for port in node_click_targets.port_click_targets.click_targets() {
|
||||||
|
if let ClickTargetType::Path(path) = port.target_type() {
|
||||||
|
connector_click_targets.push(path.to_svg());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
||||||
|
// Visibility button (eye icon)
|
||||||
|
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
|
||||||
|
icon_click_targets.push(path.to_svg());
|
||||||
|
}
|
||||||
|
// Lock button (padlock icon), only when the layer is locked
|
||||||
|
if let Some(lock_click_target) = &layer_metadata.lock_click_target
|
||||||
|
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
|
||||||
|
{
|
||||||
|
icon_click_targets.push(path.to_svg());
|
||||||
|
}
|
||||||
|
// Drag grip (dotted symbol)
|
||||||
|
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
|
||||||
|
icon_click_targets.push(path.to_svg());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
let mut layer_click_targets = Vec::new();
|
||||||
|
let mut node_click_targets = Vec::new();
|
||||||
|
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
|
||||||
|
if self.is_layer(&node_id, network_path) {
|
||||||
|
layer_click_targets.push(path);
|
||||||
|
} else {
|
||||||
|
node_click_targets.push(path);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
|
||||||
|
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
|
||||||
|
|
||||||
|
let import_export_names = self
|
||||||
|
.import_export_name_bounds(network_path)
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
|
||||||
|
.collect();
|
||||||
|
FrontendClickTargets {
|
||||||
|
node_click_targets,
|
||||||
|
layer_click_targets,
|
||||||
|
connector_click_targets,
|
||||||
|
icon_click_targets,
|
||||||
|
all_nodes_bounding_box,
|
||||||
|
import_export_names,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
||||||
self.document_metadata.document_to_viewport = transform;
|
self.document_metadata.document_to_viewport = transform;
|
||||||
}
|
}
|
||||||
@@ -48,24 +123,6 @@ impl NodeNetworkInterface {
|
|||||||
Some(&mut navigation.node_graph_ptz)
|
Some(&mut navigation.node_graph_ptz)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
|
|
||||||
/// grid cell, and an input by its index rather than the row a node draws it in.
|
|
||||||
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
|
|
||||||
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
|
|
||||||
let inputs = &self.document_node(node_id, network_path)?.inputs;
|
|
||||||
|
|
||||||
self.with_layout(network_path, |layout| {
|
|
||||||
layout.find_part(node_id, |target| {
|
|
||||||
let part = match target.part {
|
|
||||||
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
|
|
||||||
part => part,
|
|
||||||
};
|
|
||||||
find(part, target)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.flatten()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
||||||
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||||
@@ -76,13 +133,16 @@ impl NodeNetworkInterface {
|
|||||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||||
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
||||||
let glide_offsets = self.glide_offsets(network_path);
|
let glide_offsets = self.glide_offsets(network_path);
|
||||||
let reaching = self.nodes_reaching(point, network_path);
|
let clicked_nodes = self
|
||||||
let clicked_nodes = self.with_layout(network_path, |layout| {
|
.nodes_reaching(point, network_path)
|
||||||
reaching
|
.iter()
|
||||||
.into_iter()
|
.filter(|node_id| {
|
||||||
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
|
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||||
.collect::<Vec<_>>()
|
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
||||||
})?;
|
}) == Some(true)
|
||||||
|
})
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||||
let drawing_layer = |node_id: &NodeId| {
|
let drawing_layer = |node_id: &NodeId| {
|
||||||
if self.is_redirect_dot(node_id, network_path) {
|
if self.is_redirect_dot(node_id, network_path) {
|
||||||
@@ -105,18 +165,25 @@ impl NodeNetworkInterface {
|
|||||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||||
let glide_offsets = self.glide_offsets(network_path);
|
let glide_offsets = self.glide_offsets(network_path);
|
||||||
|
|
||||||
let wanted = match click_target_type {
|
self.nodes_reaching(point, network_path)
|
||||||
LayerClickTargetTypes::Visibility => Part::Visibility,
|
.iter()
|
||||||
LayerClickTargetTypes::Lock => Part::Lock,
|
.filter_map(|node_id| {
|
||||||
LayerClickTargetTypes::Grip => Part::Grip,
|
let point = point - glide_offsets.node(node_id);
|
||||||
LayerClickTargetTypes::Name => Part::Name,
|
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||||
};
|
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
|
||||||
|
match click_target_type {
|
||||||
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
|
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||||
let point = point - glide_offsets.node(node_id);
|
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||||
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
|
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||||
.is_some()
|
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||||
})
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
})
|
||||||
|
.next()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
||||||
@@ -202,11 +269,13 @@ impl NodeNetworkInterface {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||||
.filter_map(|node_id| {
|
.filter_map(|node_id| {
|
||||||
let point = point - glide_offsets.node(node_id);
|
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
transient_node_metadata
|
||||||
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
|
.port_click_targets
|
||||||
_ => None,
|
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
||||||
|
.map(|port| InputConnector::node_at_index(*node_id, port))
|
||||||
})
|
})
|
||||||
|
.flatten()
|
||||||
})
|
})
|
||||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
@@ -233,11 +302,13 @@ impl NodeNetworkInterface {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||||
.filter_map(|node_id| {
|
.filter_map(|node_id| {
|
||||||
let point = point - glide_offsets.node(node_id);
|
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
transient_node_metadata
|
||||||
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
|
.port_click_targets
|
||||||
_ => None,
|
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
||||||
|
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
||||||
})
|
})
|
||||||
|
.flatten()
|
||||||
})
|
})
|
||||||
.next()
|
.next()
|
||||||
.or_else(|| {
|
.or_else(|| {
|
||||||
@@ -355,17 +426,3 @@ impl NodeNetworkInterface {
|
|||||||
(layer_widths, chain_widths, has_left_input_wire)
|
(layer_widths, chain_widths, has_left_input_wire)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
|
|
||||||
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
|
|
||||||
let mut current_row = 0;
|
|
||||||
for (index, input) in inputs.iter().enumerate() {
|
|
||||||
if input.is_exposed() && current_row == row {
|
|
||||||
return Some(index);
|
|
||||||
}
|
|
||||||
if index == 0 || input.is_exposed() {
|
|
||||||
current_row += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
@@ -6,6 +6,10 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
impl NodeNetworkInterface {
|
impl NodeNetworkInterface {
|
||||||
|
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
|
}
|
||||||
|
|
||||||
/// Unloads the network's import and export ports.
|
/// Unloads the network's import and export ports.
|
||||||
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
||||||
self.unload_import_export_ports(network_path);
|
self.unload_import_export_ports(network_path);
|
||||||
@@ -13,5 +17,6 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||||
self.try_unload_layer_width(node_id, network_path);
|
self.try_unload_layer_width(node_id, network_path);
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -52,6 +52,7 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
||||||
@@ -144,6 +145,7 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the position of a layer to a stack position
|
/// Sets the position of a layer to a stack position
|
||||||
@@ -157,6 +159,8 @@ impl NodeNetworkInterface {
|
|||||||
} else if node.set_stack_position(y_offset) {
|
} else if node.set_stack_position(y_offset) {
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets the position of a node to a stack position without changing its y offset
|
/// Sets the position of a node to a stack position without changing its y offset
|
||||||
@@ -367,6 +371,7 @@ impl NodeNetworkInterface {
|
|||||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||||
if node.shift_absolute_position(position - current_position) {
|
if node.shift_absolute_position(position - current_position) {
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+36
-158
@@ -1,9 +1,7 @@
|
|||||||
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use glam::UVec2;
|
use glam::UVec2;
|
||||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
|
|
||||||
const REACH_MARGIN: f64 = 16.;
|
const REACH_MARGIN: f64 = 16.;
|
||||||
|
|
||||||
@@ -11,53 +9,13 @@ const REACH_MARGIN: f64 = 16.;
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct NetworkLayout {
|
pub struct NetworkLayout {
|
||||||
revision: u64,
|
revision: u64,
|
||||||
generation: u64,
|
|
||||||
node_ids: Vec<NodeId>,
|
node_ids: Vec<NodeId>,
|
||||||
indices: HashMap<NodeId, NodeIndex>,
|
indices: HashMap<NodeId, NodeIndex>,
|
||||||
graph: Graph,
|
graph: Graph,
|
||||||
shapes: Vec<NodeShape>,
|
|
||||||
layout: Layout,
|
layout: Layout,
|
||||||
bounds: [DVec2; 2],
|
|
||||||
clearance: ImportExportClearance,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
|
|
||||||
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
|
|
||||||
|
|
||||||
impl NetworkLayout {
|
impl NetworkLayout {
|
||||||
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
|
|
||||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
|
||||||
let mut network_layout = Self {
|
|
||||||
revision,
|
|
||||||
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
|
|
||||||
node_ids,
|
|
||||||
indices,
|
|
||||||
graph,
|
|
||||||
shapes,
|
|
||||||
layout,
|
|
||||||
bounds: [DVec2::ZERO; 2],
|
|
||||||
clearance: ImportExportClearance::default(),
|
|
||||||
};
|
|
||||||
network_layout.measure_bounds_and_clearance();
|
|
||||||
network_layout
|
|
||||||
}
|
|
||||||
|
|
||||||
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
|
|
||||||
let Self {
|
|
||||||
node_ids,
|
|
||||||
indices,
|
|
||||||
shapes,
|
|
||||||
graph,
|
|
||||||
layout,
|
|
||||||
..
|
|
||||||
} = self;
|
|
||||||
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn generation(&self) -> u64 {
|
|
||||||
self.generation
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
||||||
Some(self.node(node_id)?.position)
|
Some(self.node(node_id)?.position)
|
||||||
}
|
}
|
||||||
@@ -95,33 +53,6 @@ impl NetworkLayout {
|
|||||||
self.node(layer).map_or(0, |node| node.chain_length)
|
self.node(layer).map_or(0, |node| node.chain_length)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
|
|
||||||
pub fn bounds(&self) -> [DVec2; 2] {
|
|
||||||
self.bounds
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the imports and exports keep their distance from horizontally.
|
|
||||||
pub(crate) fn clearance(&self) -> ImportExportClearance {
|
|
||||||
self.clearance
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node's body where it sits in its grid cell, in node graph space.
|
|
||||||
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
|
|
||||||
Some(self.placed(*self.indices.get(node_id)?).body())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first of the node's parts, its body last, that `find` picks something from.
|
|
||||||
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
|
|
||||||
let placed = self.placed(*self.indices.get(node_id)?);
|
|
||||||
let mut found = None;
|
|
||||||
placed.parts(|target| {
|
|
||||||
if found.is_none() {
|
|
||||||
found = find(&target);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
||||||
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
||||||
let Some(index) = self.indices.get(node_id) else { return false };
|
let Some(index) = self.indices.get(node_id) else { return false };
|
||||||
@@ -131,38 +62,6 @@ impl NetworkLayout {
|
|||||||
point.cmpge(min).all() && point.cmplt(max).all()
|
point.cmpge(min).all() && point.cmplt(max).all()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
|
|
||||||
let node_layout = self.layout.node(index);
|
|
||||||
PlacedNode {
|
|
||||||
node: &self.graph[index],
|
|
||||||
shape: &self.shapes[index.index()],
|
|
||||||
position: node_layout.position,
|
|
||||||
chain_length: node_layout.chain_length,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
|
|
||||||
fn measure_bounds_and_clearance(&mut self) {
|
|
||||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
|
||||||
|
|
||||||
let mut bounds: Option<[DVec2; 2]> = None;
|
|
||||||
let mut clearance = ImportExportClearance::default();
|
|
||||||
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
|
|
||||||
let body = self.placed(index).body();
|
|
||||||
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
|
|
||||||
|
|
||||||
if self.graph[index].kind == NodeKind::Waypoint {
|
|
||||||
let center = (body.min.x + body.max.x) / 2.;
|
|
||||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
|
||||||
} else {
|
|
||||||
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self.bounds = bounds.unwrap_or_default();
|
|
||||||
self.clearance = clearance;
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
||||||
Some(self.layout.node(*self.indices.get(node_id)?))
|
Some(self.layout.node(*self.indices.get(node_id)?))
|
||||||
}
|
}
|
||||||
@@ -187,14 +86,12 @@ struct DragOrigin {
|
|||||||
keep_upstream: bool,
|
keep_upstream: bool,
|
||||||
node_ids: Vec<NodeId>,
|
node_ids: Vec<NodeId>,
|
||||||
indices: HashMap<NodeId, NodeIndex>,
|
indices: HashMap<NodeId, NodeIndex>,
|
||||||
shapes: Vec<NodeShape>,
|
|
||||||
start: Graph,
|
start: Graph,
|
||||||
drag: Drag,
|
drag: Drag,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DragOrigin {
|
impl DragOrigin {
|
||||||
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
|
||||||
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
||||||
Self {
|
Self {
|
||||||
revision,
|
revision,
|
||||||
@@ -202,7 +99,6 @@ impl DragOrigin {
|
|||||||
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
||||||
node_ids,
|
node_ids,
|
||||||
indices,
|
indices,
|
||||||
shapes,
|
|
||||||
start,
|
start,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -258,6 +154,7 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
transient.layout.unload();
|
transient.layout.unload();
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
||||||
@@ -281,14 +178,9 @@ impl NodeNetworkInterface {
|
|||||||
.filter(|((before, after), _)| before.placement != after.placement)
|
.filter(|((before, after), _)| before.placement != after.placement)
|
||||||
.map(|((_, after), node_id)| (*node_id, after.placement))
|
.map(|((_, after), node_id)| (*node_id, after.placement))
|
||||||
.collect();
|
.collect();
|
||||||
let laid_out = LaidOutNodes {
|
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
|
||||||
node_ids: std::mem::take(&mut origin.node_ids),
|
|
||||||
indices: std::mem::take(&mut origin.indices),
|
|
||||||
shapes: std::mem::take(&mut origin.shapes),
|
|
||||||
};
|
|
||||||
(moved_placements, laid_out, moved)
|
|
||||||
});
|
});
|
||||||
let Some((moved_placements, laid_out, graph)) = finished else { return };
|
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
|
||||||
|
|
||||||
let mut stored_all = true;
|
let mut stored_all = true;
|
||||||
for (node_id, placement) in moved_placements {
|
for (node_id, placement) in moved_placements {
|
||||||
@@ -297,7 +189,13 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
||||||
let layout = Layout::new(&graph);
|
let layout = Layout::new(&graph);
|
||||||
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
|
network_metadata.transient_metadata.layout.store(NetworkLayout {
|
||||||
|
revision: store::revision(),
|
||||||
|
layout,
|
||||||
|
graph,
|
||||||
|
node_ids,
|
||||||
|
indices,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,15 +208,16 @@ impl NodeNetworkInterface {
|
|||||||
let transient = self.network_transient_mut(network_path)?;
|
let transient = self.network_transient_mut(network_path)?;
|
||||||
let drag = transient.drag.take()?;
|
let drag = transient.drag.take()?;
|
||||||
transient.layout.unload();
|
transient.layout.unload();
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
Some(drag)
|
Some(drag)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
||||||
let mut origin = drag.origin.borrow_mut();
|
let mut origin = drag.origin.borrow_mut();
|
||||||
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
||||||
let (laid_out, start) = self.layout_graph(network_path)?;
|
let (node_ids, indices, start) = self.layout_graph(network_path)?;
|
||||||
let start_layout = Layout::new(&start);
|
let start_layout = Layout::new(&start);
|
||||||
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||||
}
|
}
|
||||||
origin.as_mut().map(read)
|
origin.as_mut().map(read)
|
||||||
}
|
}
|
||||||
@@ -328,8 +227,8 @@ impl NodeNetworkInterface {
|
|||||||
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
||||||
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
||||||
|
|
||||||
let (laid_out, graph, layout) = cached.into_parts();
|
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
|
||||||
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
|
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
||||||
@@ -347,38 +246,40 @@ impl NodeNetworkInterface {
|
|||||||
};
|
};
|
||||||
if node.set_node_type(node_type) {
|
if node.set_node_type(node_type) {
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
|
self.invalidate_positions(network_path);
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
||||||
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||||
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
||||||
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
||||||
layout.snap_chains(&graph);
|
layout.snap_chains(&graph);
|
||||||
let laid_out = LaidOutNodes {
|
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
|
||||||
node_ids: origin.node_ids.clone(),
|
|
||||||
indices: origin.indices.clone(),
|
|
||||||
shapes: origin.shapes.clone(),
|
|
||||||
};
|
|
||||||
(laid_out, graph, layout)
|
|
||||||
})?,
|
})?,
|
||||||
None => {
|
None => {
|
||||||
let (laid_out, graph) = self.layout_graph(network_path)?;
|
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
|
||||||
let layout = Layout::new(&graph);
|
let layout = Layout::new(&graph);
|
||||||
(laid_out, graph, layout)
|
(node_ids, indices, graph, layout)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Some(NetworkLayout::new(revision, laid_out, graph, layout))
|
Some(NetworkLayout {
|
||||||
|
revision,
|
||||||
|
layout,
|
||||||
|
graph,
|
||||||
|
node_ids,
|
||||||
|
indices,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
|
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
|
||||||
let network = self.nested_network(network_path)?;
|
let network = self.nested_network(network_path)?;
|
||||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||||
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
||||||
|
|
||||||
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
|
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
|
||||||
let wires = node_ids
|
let wires = node_ids
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -396,10 +297,10 @@ impl NodeNetworkInterface {
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
|
Some((node_ids, indices, Graph { nodes, wires }))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
|
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
|
||||||
let metadata = self.node_metadata(node_id, network_path)?;
|
let metadata = self.node_metadata(node_id, network_path)?;
|
||||||
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
||||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||||
@@ -413,40 +314,17 @@ impl NodeNetworkInterface {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
||||||
let (layer_width, name_width) = if is_layer {
|
|
||||||
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
|
|
||||||
} else {
|
|
||||||
(0, 0.)
|
|
||||||
};
|
|
||||||
let (kind, size) = match (is_layer, is_redirect_dot) {
|
let (kind, size) = match (is_layer, is_redirect_dot) {
|
||||||
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
|
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
|
||||||
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
|
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||||
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
|
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||||
};
|
};
|
||||||
|
Some(Node {
|
||||||
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
|
||||||
let node = Node {
|
|
||||||
placement,
|
placement,
|
||||||
kind,
|
kind,
|
||||||
size: size.as_ivec2(),
|
size: size.as_ivec2(),
|
||||||
chainable: !is_redirect_dot && !primary_output_hidden,
|
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
|
||||||
held: false,
|
held: false,
|
||||||
};
|
})
|
||||||
let shape = NodeShape {
|
|
||||||
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
|
|
||||||
outputs: self.number_of_outputs(node_id, network_path) as u32,
|
|
||||||
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
|
|
||||||
primary_output_hidden,
|
|
||||||
name_width,
|
|
||||||
locked: self.is_locked(node_id, network_path),
|
|
||||||
};
|
|
||||||
Some((node, shape))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
|
|
||||||
pub(crate) struct LaidOutNodes {
|
|
||||||
pub(crate) node_ids: Vec<NodeId>,
|
|
||||||
pub(crate) indices: HashMap<NodeId, NodeIndex>,
|
|
||||||
shapes: Vec<NodeShape>,
|
|
||||||
}
|
|
||||||
+30
-6
@@ -94,9 +94,11 @@ impl NodeNetworkInterface {
|
|||||||
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update the outward wires for all nodes in the encapsulating network
|
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
||||||
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
||||||
encapsulating_transient.outward_wires.unload();
|
encapsulating_transient.outward_wires.unload();
|
||||||
|
encapsulating_transient.all_nodes_bounding_box.unload();
|
||||||
|
encapsulating_transient.import_export_clearance.unload();
|
||||||
}
|
}
|
||||||
|
|
||||||
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
||||||
@@ -139,6 +141,7 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
// Update the metadata for the encapsulating node
|
// Update the metadata for the encapsulating node
|
||||||
self.unload_outward_wires(encapsulating_network_path);
|
self.unload_outward_wires(encapsulating_network_path);
|
||||||
|
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||||
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
||||||
}
|
}
|
||||||
if affects_document_structure {
|
if affects_document_structure {
|
||||||
@@ -176,6 +179,7 @@ impl NodeNetworkInterface {
|
|||||||
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
||||||
// Update the metadata for the encapsulating node
|
// Update the metadata for the encapsulating node
|
||||||
self.unload_outward_wires(encapsulating_network_path);
|
self.unload_outward_wires(encapsulating_network_path);
|
||||||
|
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||||
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
||||||
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
||||||
}
|
}
|
||||||
@@ -568,7 +572,8 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
/// Lightweight version of `set_input` for bulk import operations.
|
/// Lightweight version of `set_input` for bulk import operations.
|
||||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||||
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
|
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||||
|
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
|
||||||
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
||||||
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
||||||
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
||||||
@@ -668,6 +673,8 @@ impl NodeNetworkInterface {
|
|||||||
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
||||||
// Exposing or hiding a value input changes the node's port count
|
// Exposing or hiding a value input changes the node's port count
|
||||||
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
|
|
||||||
// A nested network draws its interior ports from the encapsulating node's inputs
|
// A nested network draws its interior ports from the encapsulating node's inputs
|
||||||
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
||||||
let nested_path = [network_path, &[*node_id]].concat();
|
let nested_path = [network_path, &[*node_id]].concat();
|
||||||
@@ -897,6 +904,7 @@ impl NodeNetworkInterface {
|
|||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
}
|
}
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
self.unload_outward_wires(network_path);
|
self.unload_outward_wires(network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -919,6 +927,7 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
|
|
||||||
previous_entry
|
previous_entry
|
||||||
}
|
}
|
||||||
@@ -1083,6 +1092,7 @@ impl NodeNetworkInterface {
|
|||||||
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
||||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||||
return;
|
return;
|
||||||
@@ -1116,10 +1126,10 @@ impl NodeNetworkInterface {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
|
let reconnected_offset = reconnect_to_input
|
||||||
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
|
.as_ref()
|
||||||
Some((reconnected, offset))
|
.and_then(NodeInput::as_node)
|
||||||
});
|
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
|
||||||
|
|
||||||
let mut exports_fed_by_import = Vec::new();
|
let mut exports_fed_by_import = Vec::new();
|
||||||
|
|
||||||
@@ -1244,6 +1254,19 @@ impl NodeNetworkInterface {
|
|||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Sets how many pixels make an inch in the document, stored only where it differs from the default.
|
||||||
|
pub fn set_pixels_per_inch(&mut self, pixels_per_inch: f64) {
|
||||||
|
let stored = (pixels_per_inch != graphene_std::units::DEFAULT_PIXELS_PER_INCH).then_some(pixels_per_inch);
|
||||||
|
|
||||||
|
let Some(mut network) = self.network_mut(&[]) else {
|
||||||
|
log::error!("Could not get the root network in set_pixels_per_inch");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
network.set_pixels_per_inch(stored);
|
||||||
|
|
||||||
|
self.transaction_modified();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
|
pub fn set_visibility(&mut self, node_id: &NodeId, network_path: &[NodeId], is_visible: bool) {
|
||||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||||
log::error!("Could not get node {node_id} in set_visibility");
|
log::error!("Could not get node {node_id} in set_visibility");
|
||||||
@@ -1355,6 +1378,7 @@ impl NodeNetworkInterface {
|
|||||||
transient.layer_width.unload();
|
transient.layer_width.unload();
|
||||||
|
|
||||||
self.transaction_modified();
|
self.transaction_modified();
|
||||||
|
self.unload_all_nodes_bounding_box(network_path);
|
||||||
self.invalidate_import_export(network_path);
|
self.invalidate_import_export(network_path);
|
||||||
self.load_structure();
|
self.load_structure();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,231 +0,0 @@
|
|||||||
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
|
|
||||||
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
|
|
||||||
|
|
||||||
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
|
|
||||||
use glam::{DVec2, IVec2};
|
|
||||||
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
|
|
||||||
|
|
||||||
const GRID: f64 = GRID_SIZE as f64;
|
|
||||||
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
|
|
||||||
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
|
|
||||||
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
|
|
||||||
const SIDE_PORT_INWARD_REACH: f64 = 8.;
|
|
||||||
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
|
|
||||||
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
|
||||||
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
|
|
||||||
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
|
|
||||||
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
|
|
||||||
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
|
|
||||||
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
|
|
||||||
const GRIP_WIDTH: f64 = 8.;
|
|
||||||
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
|
|
||||||
|
|
||||||
/// What a node draws beyond the size the layout gives it.
|
|
||||||
#[derive(Clone, Copy, Debug, Default)]
|
|
||||||
pub struct NodeShape {
|
|
||||||
/// How many inputs have a port, which doesn't count a hidden primary input.
|
|
||||||
pub inputs: u32,
|
|
||||||
pub outputs: u32,
|
|
||||||
/// Whether a node's primary input has no port, though its row is still drawn.
|
|
||||||
pub primary_input_hidden: bool,
|
|
||||||
pub primary_output_hidden: bool,
|
|
||||||
/// The width of a layer's name in pixels.
|
|
||||||
pub name_width: f64,
|
|
||||||
pub locked: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Part {
|
|
||||||
Body,
|
|
||||||
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
|
|
||||||
Input(u32),
|
|
||||||
Output(u32),
|
|
||||||
Visibility,
|
|
||||||
Lock,
|
|
||||||
Grip,
|
|
||||||
Name,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A rounded rectangle of a node that reacts to the pointer.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub struct PartTarget {
|
|
||||||
pub min: DVec2,
|
|
||||||
pub max: DVec2,
|
|
||||||
pub corner_radius: f64,
|
|
||||||
pub part: Part,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartTarget {
|
|
||||||
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
|
|
||||||
Self {
|
|
||||||
min: center - half_size,
|
|
||||||
max: center + half_size,
|
|
||||||
corner_radius,
|
|
||||||
part,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A port on the left side of a node, reaching further out than over the node.
|
|
||||||
fn input_port(center: DVec2, input: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
|
||||||
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
|
||||||
corner_radius: 4.,
|
|
||||||
part: Part::Input(input),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A port on the right side of a node, reaching further out than over the node.
|
|
||||||
fn output_port(center: DVec2, output: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
|
||||||
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
|
||||||
corner_radius: 4.,
|
|
||||||
part: Part::Output(output),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
|
|
||||||
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
|
|
||||||
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let radius = self.clamped_radius();
|
|
||||||
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
|
|
||||||
gap == DVec2::ZERO || gap.length_squared() < radius * radius
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `point` is inside the rounded rectangle.
|
|
||||||
pub fn contains(&self, point: DVec2) -> bool {
|
|
||||||
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let radius = self.clamped_radius();
|
|
||||||
let inner = point.clamp(self.min + radius, self.max - radius);
|
|
||||||
point.distance_squared(inner) <= radius * radius
|
|
||||||
}
|
|
||||||
|
|
||||||
fn clamped_radius(&self) -> f64 {
|
|
||||||
self.corner_radius.min((self.max - self.min).min_element() / 2.)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub struct PlacedNode<'a> {
|
|
||||||
pub node: &'a Node,
|
|
||||||
pub shape: &'a NodeShape,
|
|
||||||
pub position: IVec2,
|
|
||||||
pub chain_length: u32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PlacedNode<'_> {
|
|
||||||
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
|
|
||||||
pub fn body(&self) -> PartTarget {
|
|
||||||
let top_left = self.top_left();
|
|
||||||
let size = self.node.size.as_dvec2() * GRID;
|
|
||||||
|
|
||||||
match self.node.kind {
|
|
||||||
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
|
|
||||||
NodeKind::Layer => PartTarget {
|
|
||||||
min: top_left - DVec2::new(self.chain_width(), 0.),
|
|
||||||
max: top_left + size,
|
|
||||||
corner_radius: 10.,
|
|
||||||
part: Part::Body,
|
|
||||||
},
|
|
||||||
NodeKind::Node => {
|
|
||||||
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
|
|
||||||
PartTarget {
|
|
||||||
min: body_top_left,
|
|
||||||
max: body_top_left + size - DVec2::new(0., GRID),
|
|
||||||
corner_radius: 3.,
|
|
||||||
part: Part::Body,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Calls `visit` with each part, the body last.
|
|
||||||
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
|
|
||||||
match self.node.kind {
|
|
||||||
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
|
|
||||||
NodeKind::Layer => self.layer_parts(&mut visit),
|
|
||||||
NodeKind::Node => self.node_ports(&mut visit),
|
|
||||||
}
|
|
||||||
visit(self.body());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
|
||||||
let center = self.top_left() + DVec2::new(0., GRID);
|
|
||||||
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
|
|
||||||
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
|
|
||||||
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
|
||||||
let top_left = self.top_left();
|
|
||||||
let width = self.node.size.x as f64 * GRID;
|
|
||||||
let row_center = |row: u32| GRID * (row as f64 + 1.);
|
|
||||||
|
|
||||||
let first_input_row = u32::from(self.shape.primary_input_hidden);
|
|
||||||
for row in first_input_row..first_input_row + self.shape.inputs {
|
|
||||||
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
|
|
||||||
}
|
|
||||||
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
|
|
||||||
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
|
|
||||||
let top_left = self.top_left();
|
|
||||||
let size = self.node.size.as_dvec2() * GRID;
|
|
||||||
|
|
||||||
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
|
|
||||||
if self.has_side_input() {
|
|
||||||
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
|
|
||||||
}
|
|
||||||
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
|
|
||||||
|
|
||||||
let icon_half_size = DVec2::splat(HALF_GRID);
|
|
||||||
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
|
|
||||||
if self.shape.locked {
|
|
||||||
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
|
|
||||||
}
|
|
||||||
|
|
||||||
let icons_width = if self.shape.locked { GRID } else { 0. };
|
|
||||||
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
|
|
||||||
let handle_top = top_left.y + HALF_GRID;
|
|
||||||
let handle_bottom = top_left.y + GRID + HALF_GRID;
|
|
||||||
visit(PartTarget {
|
|
||||||
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
|
|
||||||
max: DVec2::new(grip_right, handle_bottom),
|
|
||||||
corner_radius: 0.,
|
|
||||||
part: Part::Grip,
|
|
||||||
});
|
|
||||||
|
|
||||||
let name_left = top_left.x + NAME_LEFT_OFFSET;
|
|
||||||
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
|
|
||||||
if name_right > name_left {
|
|
||||||
visit(PartTarget {
|
|
||||||
min: DVec2::new(name_left, handle_top),
|
|
||||||
max: DVec2::new(name_right, handle_bottom),
|
|
||||||
corner_radius: 3.,
|
|
||||||
part: Part::Name,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn top_left(&self) -> DVec2 {
|
|
||||||
self.position.as_dvec2() * GRID
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_side_input(&self) -> bool {
|
|
||||||
self.shape.inputs > 1
|
|
||||||
}
|
|
||||||
|
|
||||||
fn chain_width(&self) -> f64 {
|
|
||||||
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -128,10 +128,18 @@ impl NodeNetworkInterface {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let mut hasher = std::hash::DefaultHasher::new();
|
let mut hasher = std::hash::DefaultHasher::new();
|
||||||
(self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
|
(self.network.current_hash(), self.previewed_nodes(), layers_hash, self.pixels_per_inch().to_bits()).hash(&mut hasher);
|
||||||
hasher.finish()
|
hasher.finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many pixels make an inch in the document, which sizes the lengths typed in a physical unit.
|
||||||
|
pub fn pixels_per_inch(&self) -> f64 {
|
||||||
|
self.network_metadata(&[])
|
||||||
|
.and_then(|metadata| metadata.persistent_metadata.pixels_per_inch)
|
||||||
|
.filter(|pixels_per_inch| pixels_per_inch.is_finite() && *pixels_per_inch > 0.)
|
||||||
|
.unwrap_or(graphene_std::units::DEFAULT_PIXELS_PER_INCH)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the specified document node in the nested network based on node_id and network_path
|
/// Get the specified document node in the nested network based on node_id and network_path
|
||||||
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
|
pub fn document_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<&DocumentNode> {
|
||||||
self.query(network_path, "document_node", |view| view.node(node_id))
|
self.query(network_path, "document_node", |view| view.node(node_id))
|
||||||
@@ -802,7 +810,7 @@ impl NodeNetworkInterface {
|
|||||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||||
self.reference(node_id, network_path)
|
self.reference(node_id, network_path)
|
||||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||||
@@ -875,16 +883,16 @@ impl NodeNetworkInterface {
|
|||||||
node.set_widget_override(index, widget_override);
|
node.set_widget_override(index, widget_override);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
||||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||||
.unwrap_or_else(|| "Subgraph".to_string())
|
.unwrap_or_else(|| "Custom Node".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||||
.unwrap_or_else(|| "Subgraph".to_string())
|
.unwrap_or_else(|| "Custom Node".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ impl NodeNetworkInterface {
|
|||||||
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
if current_metadata.pinned_node_order != target.metadata.pinned_order {
|
||||||
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
deltas.push(change(NetworkMetadataChange::PinnedOrder(target.metadata.pinned_order.clone())));
|
||||||
}
|
}
|
||||||
|
if current_metadata.pixels_per_inch != target.metadata.pixels_per_inch {
|
||||||
|
deltas.push(change(NetworkMetadataChange::PixelsPerInch(target.metadata.pixels_per_inch)));
|
||||||
|
}
|
||||||
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
|
// An empty list states nothing, since a catalog entry's interface comes from the catalog rather than storage
|
||||||
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
let import_metadata: Vec<_> = target.metadata.import_metadata.iter().cloned().map(input_metadata_entry_to_runtime).collect();
|
||||||
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
if !import_metadata.is_empty() && current_metadata.import_metadata != import_metadata {
|
||||||
@@ -328,10 +331,7 @@ fn field_deltas(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||||
deltas.push(metadata(NodeMetadataChange::placement(
|
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||||
¤t_metadata.node_type_metadata,
|
|
||||||
target_metadata.node_type_metadata.clone(),
|
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
if current_metadata.display_name != target_metadata.display_name {
|
if current_metadata.display_name != target_metadata.display_name {
|
||||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||||
|
|||||||
+5
@@ -111,6 +111,10 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
|
|||||||
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
|
fn pinned_order(&self, network: NetworkLocation) -> Vec<NodeId> {
|
||||||
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
|
self.network_persistent(network).map(|persistent| persistent.pinned_node_order.clone()).unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn pixels_per_inch(&self, network: NetworkLocation) -> Option<f64> {
|
||||||
|
self.network_persistent(network)?.pixels_per_inch
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DocumentSettings<'_> {
|
impl DocumentSettings<'_> {
|
||||||
@@ -307,6 +311,7 @@ fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries:
|
|||||||
network_metadata.persistent_metadata.reference = Some(reference);
|
network_metadata.persistent_metadata.reference = Some(reference);
|
||||||
}
|
}
|
||||||
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
|
network_metadata.persistent_metadata.pinned_node_order = entry.pinned_order;
|
||||||
|
network_metadata.persistent_metadata.pixels_per_inch = entry.pixels_per_inch;
|
||||||
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
|
network_metadata.persistent_metadata.import_metadata = entry.import_metadata.into_iter().map(input_metadata_entry_to_runtime).collect();
|
||||||
network_metadata.persistent_metadata.export_names = entry.export_names;
|
network_metadata.persistent_metadata.export_names = entry.export_names;
|
||||||
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
|
network_metadata.persistent_metadata.export_descriptions = entry.export_descriptions;
|
||||||
|
|||||||
+16
-7
@@ -229,14 +229,13 @@ impl NodeMut<'_> {
|
|||||||
|
|
||||||
/// Whether the node is displayed as a layer or a node, together with its position.
|
/// Whether the node is displayed as a layer or a node, together with its position.
|
||||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||||
if self.metadata.node_type_metadata == node_type {
|
let changed = self.metadata.node_type_metadata != node_type;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
|
|
||||||
self.metadata.node_type_metadata = node_type;
|
self.metadata.node_type_metadata = node_type;
|
||||||
self.deltas.metadata(change);
|
if changed {
|
||||||
true
|
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||||
|
self.deltas.metadata(change);
|
||||||
|
}
|
||||||
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
||||||
@@ -539,6 +538,16 @@ impl NetworkMut<'_> {
|
|||||||
changed
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How many pixels make an inch in the document, or `None` for the default.
|
||||||
|
pub(crate) fn set_pixels_per_inch(&mut self, pixels_per_inch: Option<f64>) -> bool {
|
||||||
|
let changed = self.metadata.pixels_per_inch != pixels_per_inch;
|
||||||
|
self.metadata.pixels_per_inch = pixels_per_inch;
|
||||||
|
if changed {
|
||||||
|
self.emit(NetworkMetadataChange::PixelsPerInch(pixels_per_inch));
|
||||||
|
}
|
||||||
|
changed
|
||||||
|
}
|
||||||
|
|
||||||
/// The display order of pinned nodes in the Inspector.
|
/// The display order of pinned nodes in the Inspector.
|
||||||
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
pub(crate) fn set_pinned_order(&mut self, pinned_node_order: Vec<NodeId>) -> bool {
|
||||||
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
let changed = self.metadata.pinned_node_order != pinned_node_order;
|
||||||
|
|||||||
@@ -511,6 +511,7 @@ impl NodeNetworkInterface {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.chain([
|
.chain([
|
||||||
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
|
NetworkMetadataChange::PinnedOrder(persistent_metadata.pinned_node_order.clone()),
|
||||||
|
NetworkMetadataChange::PixelsPerInch(persistent_metadata.pixels_per_inch),
|
||||||
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
|
NetworkMetadataChange::ImportMetadata(persistent_metadata.import_metadata.clone()),
|
||||||
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
|
NetworkMetadataChange::ExportNames(persistent_metadata.export_names.clone()),
|
||||||
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
|
NetworkMetadataChange::ExportDescriptions(persistent_metadata.export_descriptions.clone()),
|
||||||
|
|||||||
@@ -200,11 +200,10 @@ impl NodeNetworkInterface {
|
|||||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Update how far each layer's effects paint past its content, and the frames they paint anywhere in.
|
/// Update how far each layer's effects paint past its content.
|
||||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) {
|
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||||
self.document_metadata.mark_changed();
|
self.document_metadata.mark_changed();
|
||||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||||
self.document_metadata.layer_effects_frames = new_layer_effects_frames;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,14 +38,6 @@ pub struct NodeTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NodeTemplate {
|
impl NodeTemplate {
|
||||||
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
|
||||||
pub fn empty_subgraph() -> Self {
|
|
||||||
Self {
|
|
||||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||||
self.inputs.get(P::INDEX)
|
self.inputs.get(P::INDEX)
|
||||||
@@ -299,6 +291,7 @@ impl NodeTemplateImplementation {
|
|||||||
reference,
|
reference,
|
||||||
node_metadata,
|
node_metadata,
|
||||||
pinned_node_order,
|
pinned_node_order,
|
||||||
|
pixels_per_inch: None,
|
||||||
previewing,
|
previewing,
|
||||||
navigation_metadata,
|
navigation_metadata,
|
||||||
selection_undo_history: Default::default(),
|
selection_undo_history: Default::default(),
|
||||||
|
|||||||
@@ -3,7 +3,12 @@ use graphene_std::ParameterRef;
|
|||||||
use graphene_std::vector::misc::dvec2_to_point;
|
use graphene_std::vector::misc::dvec2_to_point;
|
||||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||||
|
|
||||||
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
|
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
||||||
|
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||||
|
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||||
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
||||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||||
if radii.iter().all(|radius| *radius == 0.) {
|
if radii.iter().all(|radius| *radius == 0.) {
|
||||||
@@ -14,6 +19,16 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
|
|||||||
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ellipse inscribed in the box spanning the two opposite corners.
|
||||||
|
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||||
|
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||||
|
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
|
||||||
|
|
||||||
|
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
|
||||||
|
path.close_path();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct ChainNodeCopy {
|
pub struct ChainNodeCopy {
|
||||||
@@ -277,6 +292,13 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
|||||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
|
||||||
|
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
|
||||||
|
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||||
|
|
||||||
|
[center - HALF_SIZE, center + HALF_SIZE]
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||||
const CORNER_RADIUS: f64 = 4.;
|
const CORNER_RADIUS: f64 = 4.;
|
||||||
|
|
||||||
@@ -310,6 +332,13 @@ impl Ports {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
|
||||||
|
self.input_ports
|
||||||
|
.iter()
|
||||||
|
.map(|(_, click_target)| click_target)
|
||||||
|
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||||
self.input_ports.iter()
|
self.input_ports.iter()
|
||||||
}
|
}
|
||||||
@@ -319,15 +348,51 @@ impl Ports {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||||
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
|
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
||||||
self.input_anchors.push((input_index, center));
|
self.input_anchors.push((input_index, center));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||||
|
self.input_ports.push((input_index, click_target));
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||||
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
|
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
||||||
self.output_anchors.push((output_index, center));
|
self.output_anchors.push((output_index, center));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||||
|
self.output_ports.push((output_index, click_target));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
|
||||||
|
// The center of the click target is always 24 px down from the top left corner of the node
|
||||||
|
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
|
||||||
|
self.insert_input_port_at_center(input_index, center);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
|
||||||
|
// The center of the click target is always 24 px down from the top left corner of the node
|
||||||
|
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
|
||||||
|
self.insert_output_port_at_center(output_index, center);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
|
||||||
|
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
|
||||||
|
if input_index == 0 {
|
||||||
|
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
|
||||||
|
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
|
||||||
|
} else {
|
||||||
|
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
|
||||||
|
// The center of the click target is 8 px above the layer, over its thumbnail
|
||||||
|
let center = node_top_left + DVec2::new(2. * 24., -8.);
|
||||||
|
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
|
||||||
|
}
|
||||||
|
|
||||||
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
||||||
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||||
}
|
}
|
||||||
@@ -336,12 +401,37 @@ impl Ports {
|
|||||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
|
||||||
|
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
|
||||||
|
const GUTTER_OFFSET: f64 = 10.;
|
||||||
|
const GUTTER_RADIUS: f64 = 5.;
|
||||||
|
|
||||||
|
let gutter = |x_offset: f64| {
|
||||||
|
let gutter_center = center + DVec2::new(x_offset, 0.);
|
||||||
|
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
|
||||||
|
};
|
||||||
|
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
|
||||||
|
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
|
||||||
|
self.input_anchors.push((0, center));
|
||||||
|
self.output_anchors.push((0, center));
|
||||||
|
}
|
||||||
|
|
||||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||||
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||||
|
return Some(*anchor);
|
||||||
|
}
|
||||||
|
self.input_ports
|
||||||
|
.iter()
|
||||||
|
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
||||||
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||||
|
return Some(*anchor);
|
||||||
|
}
|
||||||
|
self.output_ports
|
||||||
|
.iter()
|
||||||
|
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -584,6 +674,9 @@ pub struct NodeNetworkPersistentMetadata {
|
|||||||
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
|
/// The display order of pinned nodes in the Inspector (shown when nothing is selected in this network), keyed by node ID.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub pinned_node_order: Vec<NodeId>,
|
pub pinned_node_order: Vec<NodeId>,
|
||||||
|
/// How many pixels make an inch, which sizes lengths typed in a physical unit, or `None` for the default of 96. Only the root network's applies.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub pixels_per_inch: Option<f64>,
|
||||||
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
|
/// Cached metadata for each node, which is calculated when adding a node to node_metadata
|
||||||
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
|
/// Indicates whether the network is currently rendered with a particular node that is previewed, and if so, which connection should be restored when the preview ends.
|
||||||
pub previewing: Previewing,
|
pub previewing: Previewing,
|
||||||
@@ -657,12 +750,16 @@ impl<T> TransientCache<T> {
|
|||||||
#[derive(Debug, Default, Clone)]
|
#[derive(Debug, Default, Clone)]
|
||||||
pub struct NodeNetworkTransientMetadata {
|
pub struct NodeNetworkTransientMetadata {
|
||||||
pub selected_nodes: SelectedNodes,
|
pub selected_nodes: SelectedNodes,
|
||||||
|
/// Cache for the bounding box around all nodes in node graph space.
|
||||||
|
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
|
||||||
|
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
|
||||||
|
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
|
||||||
/// Cache for all outward wire connections
|
/// Cache for all outward wire connections
|
||||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||||
pub(crate) layout: TransientCache<NetworkLayout>,
|
pub(crate) layout: TransientCache<NetworkLayout>,
|
||||||
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
||||||
/// The import and export connector click targets, with the generation of the layout they were placed by.
|
/// All export connector click targets
|
||||||
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
|
pub(crate) import_export_ports: TransientCache<Ports>,
|
||||||
|
|
||||||
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
||||||
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
||||||
@@ -1079,8 +1176,40 @@ impl From<LegacyNodePosition> for NodePosition {
|
|||||||
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
||||||
#[derive(Debug, Default, Clone)]
|
#[derive(Debug, Default, Clone)]
|
||||||
pub struct DocumentNodeTransientMetadata {
|
pub struct DocumentNodeTransientMetadata {
|
||||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
|
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
|
||||||
pub(crate) layer_width: TransientCache<(u32, f64)>,
|
pub(crate) layer_width: TransientCache<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct DocumentNodeClickTargets {
|
||||||
|
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
|
||||||
|
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
|
||||||
|
pub node_click_target: ClickTarget,
|
||||||
|
/// Stores all port click targets in node graph space.
|
||||||
|
pub port_click_targets: Ports,
|
||||||
|
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
|
||||||
|
pub node_type_metadata: NodeTypeClickTargets,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum NodeTypeClickTargets {
|
||||||
|
Layer(Box<LayerClickTargets>),
|
||||||
|
Node, // No transient click targets are stored exclusively for nodes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct LayerClickTargets {
|
||||||
|
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
|
||||||
|
pub visibility_click_target: ClickTarget,
|
||||||
|
/// Cache for the lock icon button, only present when the layer is locked.
|
||||||
|
pub lock_click_target: Option<ClickTarget>,
|
||||||
|
/// Cache for the grip icon, which is next to the visibility button.
|
||||||
|
pub grip_click_target: ClickTarget,
|
||||||
|
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
|
||||||
|
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
|
||||||
|
/// `None` for layers whose display name is empty.
|
||||||
|
pub name_click_target: Option<ClickTarget>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
|||||||
.ok()
|
.ok()
|
||||||
.flatten()
|
.flatten()
|
||||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||||
.unwrap_or("Subgraph".to_string())
|
.unwrap_or("Custom Node".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||||
|
|||||||
Loaded 100 of 250 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user