mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5faf5e67f2 | ||
|
|
1d3d32c169 | ||
|
|
21d2994059 | ||
|
|
d5f0140f26 | ||
|
|
c4a978009a | ||
|
|
256dd26b99 | ||
|
|
06e2a049de | ||
|
|
79df7cfa87 | ||
|
|
16c7544d96 | ||
|
|
a56746c6bf | ||
|
|
456a7c868d | ||
|
|
1c9c19a697 | ||
|
|
696b625a3e | ||
|
|
4d5dce976e | ||
|
|
629a1f4b4c | ||
|
|
f6def3b911 |
No files matched your search
@@ -1,2 +1,2 @@
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/b83626b10f0f9102503c845354e9e3f161949ce0.tar.gz
|
||||
353e9cba90f420b11863055a32e554937638b47d1539632ef0e8a30f37a353d7
|
||||
https://github.com/Keavon/graphite-branded-assets/archive/0d004aa61e6b48d316e8e5db6d59ccc4788f192d.tar.gz
|
||||
772d64518be43c99977ba56f69e574531c56e83d2df2f42ab066f77f74b0dd1f
|
||||
@@ -1,3 +1,7 @@
|
||||
[build]
|
||||
# Keep `--cfg=web_sys_unstable_apis` here so the wasm wrapper crates build with the same web-sys API signatures (e.g. `put_image_data`/`get_image_data` taking `i32` rather than `f64`) on both native test builds and the wasm target. Cargo applies `[build]` rustflags only when no target-specific rustflags table matches, so the wasm-specific list below must continue to include this cfg.
|
||||
rustflags = ["--cfg=web_sys_unstable_apis"]
|
||||
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = [
|
||||
# Currently disabled because of https://github.com/GraphiteEditor/Graphite/issues/1262
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
},
|
||||
"ghcr.io/devcontainers/features/node:1": {}
|
||||
},
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]00",
|
||||
"onCreateCommand": "cargo install cargo-watch wasm-pack cargo-about && cargo install -f [email protected]21",
|
||||
"customizations": {
|
||||
"vscode": {
|
||||
// NOTE: Keep this in sync with `.vscode/extensions.json`
|
||||
|
||||
@@ -283,7 +283,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
@@ -474,7 +474,7 @@ jobs:
|
||||
pull-requests: write
|
||||
|
||||
env:
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.100"
|
||||
WASM_BINDGEN_CLI_VERSION: "0.2.121"
|
||||
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
|
||||
@@ -57,7 +57,8 @@ jobs:
|
||||
|
||||
- name: 🧪 Run Rust tests
|
||||
env:
|
||||
RUSTFLAGS: -Dwarnings
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||
run: mold -run cargo test --all-features
|
||||
|
||||
# Rust format check on GitHub runner
|
||||
|
||||
@@ -22,27 +22,14 @@ jobs:
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: Install Valgrind
|
||||
run: |
|
||||
sudo apt update
|
||||
sudo apt install -y valgrind
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
|
||||
- name: Cache iai-callgrind binary
|
||||
id: cache-iai
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: ~/.cargo/bin/iai-callgrind-runner
|
||||
key: ${{ runner.os }}-iai-callgrind-runner-0.16.1
|
||||
|
||||
- name: Install iai-callgrind
|
||||
if: steps.cache-iai.outputs.cache-hit != 'true'
|
||||
run: cargo install [email protected]
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@v1
|
||||
|
||||
- name: Checkout master branch
|
||||
run: |
|
||||
@@ -66,21 +53,21 @@ jobs:
|
||||
id: cache-benchmark-baselines
|
||||
uses: actions/cache@v5
|
||||
with:
|
||||
path: target/iai
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
path: target/gungraun
|
||||
key: ${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-${{ steps.master-sha.outputs.sha }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-benchmark-baselines-master-
|
||||
${{ runner.os }}-${{ runner.arch }}-${{ steps.cpu-info.outputs.cpu-hash }}-gungraun-benchmark-baselines-master-
|
||||
|
||||
- name: Run baseline benchmarks
|
||||
if: steps.cache-benchmark-baselines.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_iai -- --save-baseline=master
|
||||
cargo bench --bench compile_demo_art_gungraun -- --save-baseline=master
|
||||
|
||||
# Runtime benchmarks
|
||||
cargo bench --bench update_executor_iai -- --save-baseline=master
|
||||
cargo bench --bench run_once_iai -- --save-baseline=master
|
||||
cargo bench --bench run_cached_iai -- --save-baseline=master
|
||||
cargo bench --bench update_executor_gungraun -- --save-baseline=master
|
||||
cargo bench --bench run_once_gungraun -- --save-baseline=master
|
||||
cargo bench --bench run_cached_gungraun -- --save-baseline=master
|
||||
|
||||
- name: Checkout PR branch
|
||||
run: git checkout ${{ github.event.pull_request.head.sha }}
|
||||
@@ -88,12 +75,12 @@ jobs:
|
||||
- name: Run PR benchmarks
|
||||
run: |
|
||||
# Compile benchmarks
|
||||
cargo bench --bench compile_demo_art_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
cargo bench --bench compile_demo_art_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/compile_output.json
|
||||
|
||||
# Runtime benchmarks
|
||||
cargo bench --bench update_executor_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
|
||||
cargo bench --bench run_once_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
|
||||
cargo bench --bench run_cached_iai -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
cargo bench --bench update_executor_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/update_output.json
|
||||
cargo bench --bench run_once_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_once_output.json
|
||||
cargo bench --bench run_cached_gungraun -- --baseline=master --output-format=json | jq -sc | sed 's/\\"//g' > /tmp/run_cached_output.json
|
||||
|
||||
- name: Make old comments collapsed by default
|
||||
# Only run if we have write permissions (not a fork)
|
||||
|
||||
@@ -12,3 +12,4 @@ flamegraph.svg
|
||||
.idea/
|
||||
.direnv
|
||||
.DS_Store
|
||||
.nvim.lua
|
||||
+1
-1
@@ -29,7 +29,7 @@ pkgs.mkShell (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "147.0.10+gd58e84d+chromium-147.0.7727.118";
|
||||
version = "147.0.14+g76d2442+chromium-147.0.7727.138";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-kaRijMDacPcoeCcS31zmRSNOvgozx+uq2M34mD28bu4=";
|
||||
x86_64-linux = "sha256-CHzPofBDhCniDZEpOxXK4I7p57SYjMAY1HVo3Vna0e8=";
|
||||
aarch64-linux = "sha256-Gy2Xs1NHwmIr+buzoqDso1QJVkKlA/UMXytHjNGqpNk=";
|
||||
x86_64-linux = "sha256-os7wAFJ+mVK65HCikvEjhMeQUj2ty7y+6Ad0OlOcbeA=";
|
||||
};
|
||||
|
||||
selectSystem =
|
||||
|
||||
@@ -83,7 +83,7 @@ deps.crane.lib.buildPackage (
|
||||
pkgs.lld
|
||||
pkgs.nodejs
|
||||
pkgs.binaryen
|
||||
pkgs.wasm-bindgen-cli_0_2_100
|
||||
pkgs.wasm-bindgen-cli_0_2_121
|
||||
pkgs.wasm-pack
|
||||
pkgs.cargo-about
|
||||
pkgs.removeReferencesTo
|
||||
|
||||
Generated
+398
-383
File diff suppressed because it is too large.
Load diff
+14
-11
@@ -120,17 +120,17 @@ quote = "1.0"
|
||||
chrono = "0.4"
|
||||
ron = "0.12"
|
||||
fastnoise-lite = "1.1"
|
||||
wgpu = { version = "28.0", features = [
|
||||
wgpu = { version = "29.0", features = [
|
||||
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
|
||||
"fragile-send-sync-non-atomic-wasm",
|
||||
"spirv",
|
||||
"strict_asserts",
|
||||
] }
|
||||
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
|
||||
wasm-bindgen = "=0.2.100" # NOTICE: ensure this stays in sync with the `wasm-bindgen-cli` version in `website/content/volunteer/guide/project-setup/_index.md`. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen = "=0.2.121" # NOTICE: keep in sync with the `wasm-bindgen-cli` version pinned across CI workflows, devcontainer, Nix, and the `cargo-run` tool. We pin this version because wasm-bindgen upgrades may break various things.
|
||||
wasm-bindgen-futures = "0.4"
|
||||
js-sys = "=0.3.77"
|
||||
web-sys = { version = "=0.3.77", features = [
|
||||
js-sys = "=0.3.98"
|
||||
web-sys = { version = "=0.3.98", features = [
|
||||
"Document",
|
||||
"DomRect",
|
||||
"Element",
|
||||
@@ -154,12 +154,12 @@ url = "2.5"
|
||||
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
|
||||
# Linebender ecosystem (BEGIN)
|
||||
kurbo = { version = "0.13", features = ["serde"] }
|
||||
vello = "0.8"
|
||||
vello_encoding = "0.8"
|
||||
vello = "0.9"
|
||||
vello_encoding = "0.9"
|
||||
resvg = "0.47"
|
||||
usvg = "0.47"
|
||||
parley = "0.6"
|
||||
skrifa = "0.40"
|
||||
parley = { version = "0.9", default-features = false, features = ["std"] }
|
||||
skrifa = "0.42"
|
||||
polycool = "0.4"
|
||||
color = "0.3"
|
||||
# Linebender ecosystem (END)
|
||||
@@ -199,12 +199,12 @@ petgraph = { version = "0.7", default-features = false, features = ["graphmap"]
|
||||
half = { version = "2.4", default-features = false, features = ["bytemuck"] }
|
||||
tinyvec = { version = "1", features = ["std"] }
|
||||
criterion = { version = "0.7", features = ["html_reports"] }
|
||||
iai-callgrind = { version = "0.16" }
|
||||
gungraun = { version = "0.18" }
|
||||
ndarray = "0.16"
|
||||
strum = { version = "0.27", features = ["derive"] }
|
||||
dirs = "6.0"
|
||||
cef = "147"
|
||||
cef-dll-sys = "147"
|
||||
cef = "148"
|
||||
cef-dll-sys = "148"
|
||||
include_dir = "0.7"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tracing = "0.1"
|
||||
@@ -219,6 +219,7 @@ lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "e
|
||||
scraper = "0.25"
|
||||
linesweeper = "0.3"
|
||||
smallvec = "1.13.2"
|
||||
zip = { version = "8", default-features = false }
|
||||
|
||||
[workspace.lints.rust]
|
||||
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
|
||||
@@ -245,3 +246,5 @@ debug = true
|
||||
# Force cargo to use only one version of the dpi crate (vendoring breaks without this)
|
||||
dpi = { git = "https://github.com/rust-windowing/winit.git" }
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
cef = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite" }
|
||||
@@ -42,7 +42,7 @@ ignore = [
|
||||
"RUSTSEC-2024-0388", # Unmaintained `derivative`, used directly by graphite-editor and graphite-desktop
|
||||
"RUSTSEC-2024-0436", # Unmaintained `paste`, pulled in by dependencies `metal` and `wgpu-hal`
|
||||
"RUSTSEC-2025-0134", # Unmaintained `rustls-pemfile`, pulled in by build dependency `download-cef`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `iai-callgrind`
|
||||
"RUSTSEC-2025-0141", # Unmaintained `bincode`, pulled in by dev dependency `gungraun`
|
||||
]
|
||||
# Threshold for security vulnerabilities, any vulnerability with a CVSS score
|
||||
# lower than the range specified will be ignored. Note that ignored advisories
|
||||
|
||||
+8
-6
@@ -249,6 +249,12 @@ impl App {
|
||||
});
|
||||
}
|
||||
DesktopFrontendMessage::WriteFile { path, content } => {
|
||||
if let Some(parent) = path.parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
&& let Err(e) = fs::create_dir_all(parent)
|
||||
{
|
||||
tracing::error!("Failed to create parent directory {}: {}", parent.display(), e);
|
||||
}
|
||||
if let Err(e) = fs::write(&path, content) {
|
||||
tracing::error!("Failed to write file {}: {}", path.display(), e);
|
||||
}
|
||||
@@ -582,14 +588,10 @@ impl ApplicationHandler for App {
|
||||
Err(RenderError::OutdatedUITextureError) => {
|
||||
self.cef_context.notify_view_info_changed();
|
||||
}
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::Lost)) => {
|
||||
Err(RenderError::SurfaceLost) => {
|
||||
tracing::warn!("lost surface");
|
||||
}
|
||||
Err(RenderError::SurfaceError(wgpu::SurfaceError::OutOfMemory)) => {
|
||||
tracing::error!("GPU out of memory");
|
||||
self.exit(None);
|
||||
}
|
||||
Err(RenderError::SurfaceError(e)) => tracing::error!("Render error: {:?}", e),
|
||||
Err(other) => tracing::error!("Render error: {:?}", other),
|
||||
}
|
||||
let _ = self.start_render_sender.try_send(());
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ impl RenderState {
|
||||
|
||||
let render_pipeline_layout = context.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("Render Pipeline Layout"),
|
||||
bind_group_layouts: &[&texture_bind_group_layout],
|
||||
bind_group_layouts: &[Some(&texture_bind_group_layout)],
|
||||
immediate_size: size_of::<Immediates>() as u32,
|
||||
});
|
||||
|
||||
@@ -262,7 +262,17 @@ impl RenderState {
|
||||
self.render_overlays(scene);
|
||||
}
|
||||
|
||||
let output = self.surface.get_current_texture().map_err(RenderError::SurfaceError)?;
|
||||
let (output, suboptimal) = match self.surface.get_current_texture() {
|
||||
wgpu::CurrentSurfaceTexture::Success(t) => (t, false),
|
||||
// wgpu reports the swapchain no longer matches the underlying surface; present this frame and reconfigure after present, since `Surface::configure` panics while an acquired `SurfaceTexture` is still alive
|
||||
wgpu::CurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
||||
// Window is minimized or behind another window: skip the frame silently and try again once it becomes visible
|
||||
wgpu::CurrentSurfaceTexture::Occluded => return Ok(()),
|
||||
wgpu::CurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
||||
wgpu::CurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
|
||||
wgpu::CurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
||||
wgpu::CurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
||||
};
|
||||
|
||||
let view = output.texture.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
|
||||
@@ -308,6 +318,10 @@ impl RenderState {
|
||||
window.pre_present_notify();
|
||||
output.present();
|
||||
|
||||
if suboptimal {
|
||||
self.surface.configure(&self.context.device, &self.config);
|
||||
}
|
||||
|
||||
if ui_scale.is_some() {
|
||||
return Err(RenderError::OutdatedUITextureError);
|
||||
}
|
||||
@@ -349,9 +363,13 @@ impl RenderState {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum RenderError {
|
||||
OutdatedUITextureError,
|
||||
SurfaceError(wgpu::SurfaceError),
|
||||
SurfaceLost,
|
||||
SurfaceOutdated,
|
||||
SurfaceTimeout,
|
||||
SurfaceValidation,
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
|
||||
@@ -31,6 +31,20 @@ pub(super) fn handle_desktop_wrapper_message(dispatcher: &mut DesktopWrapperMess
|
||||
SaveFileDialogContext::File { content } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path, content });
|
||||
}
|
||||
SaveFileDialogContext::MultipleFiles { files, expected_extension } => {
|
||||
// Treat the chosen path as the folder name. Strip only the export's expected extension (e.g. ".png" for a
|
||||
// PNG animation export) so that arbitrary dotted folder names like `v1.0` are preserved as-is, while a user
|
||||
// who typed `MyAnim.png` still gets a `MyAnim/` folder rather than a `MyAnim.png/` folder.
|
||||
// The `WriteFile` handler creates parent directories if they don't exist, so the folder is materialized on first write.
|
||||
let folder = match path.extension().and_then(|e| e.to_str()) {
|
||||
Some(ext) if ext.eq_ignore_ascii_case(&expected_extension) => path.with_extension(""),
|
||||
_ => path,
|
||||
};
|
||||
for (filename, content) in files {
|
||||
let file_path = folder.join(&filename);
|
||||
dispatcher.respond(DesktopFrontendMessage::WriteFile { path: file_path, content });
|
||||
}
|
||||
}
|
||||
},
|
||||
DesktopWrapperMessage::OpenFile { path, content } => {
|
||||
let message = PortfolioMessage::OpenFile { path, content };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use graphite_editor::messages::frontend::utility_types::ExportAnimationFrame;
|
||||
#[cfg(target_os = "macos")]
|
||||
use graphite_editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
use graphite_editor::messages::prelude::FrontendMessage;
|
||||
@@ -59,6 +60,61 @@ pub(super) fn intercept_frontend_message(dispatcher: &mut DesktopWrapperMessageD
|
||||
context: SaveFileDialogContext::File { content },
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerExportAnimation {
|
||||
name,
|
||||
extension,
|
||||
mime,
|
||||
size,
|
||||
folder,
|
||||
frames,
|
||||
} => {
|
||||
// Materialize each frame to bytes; SVG strings are encoded as UTF-8.
|
||||
// Raster-needs-canvas-rasterize frames can't be encoded here without a Rust SVG rasterizer,
|
||||
// so fall through to the frontend zip path in that case.
|
||||
// TODO: This fallback is inconsistent with the desktop folder-save flow for the rest of the animation
|
||||
// export — desktop users will see a .zip download instead of a folder. Once SVG rasterization moves to
|
||||
// Rust (resvg), this fallback can be removed and all frame paths can save into the chosen folder.
|
||||
let mut needs_frontend_rasterization = false;
|
||||
let mut materialized = Vec::with_capacity(frames.len());
|
||||
// Dynamic zero-pad width so files keep sorting in playback order beyond 9,999 frames.
|
||||
let pad_width = frames.len().to_string().len().max(4);
|
||||
let safe_base = graphite_editor::messages::frontend::utility_types::sanitize_filename_component(&name);
|
||||
for (index, frame) in frames.iter().enumerate() {
|
||||
let filename = format!("{safe_base}_{:0pad$}.{extension}", index + 1, pad = pad_width);
|
||||
let bytes = match frame {
|
||||
ExportAnimationFrame::Svg(svg) if extension == "svg" => svg.as_bytes().to_vec(),
|
||||
ExportAnimationFrame::Bytes(bytes) => bytes.to_vec(),
|
||||
ExportAnimationFrame::Svg(_) => {
|
||||
needs_frontend_rasterization = true;
|
||||
break;
|
||||
}
|
||||
};
|
||||
materialized.push((filename, bytes));
|
||||
}
|
||||
|
||||
if needs_frontend_rasterization {
|
||||
return Some(FrontendMessage::TriggerExportAnimation {
|
||||
name,
|
||||
extension,
|
||||
mime,
|
||||
size,
|
||||
folder,
|
||||
frames,
|
||||
});
|
||||
}
|
||||
|
||||
// The dialog name is the folder the frames go into (analogous to the .zip on web).
|
||||
dispatcher.respond(DesktopFrontendMessage::SaveFileDialog {
|
||||
title: "Save Animation Frames Folder As".to_string(),
|
||||
default_filename: safe_base,
|
||||
default_folder: folder,
|
||||
filters: Vec::new(),
|
||||
context: SaveFileDialogContext::MultipleFiles {
|
||||
files: materialized,
|
||||
expected_extension: extension,
|
||||
},
|
||||
});
|
||||
}
|
||||
FrontendMessage::TriggerVisitLink { url } => {
|
||||
dispatcher.respond(DesktopFrontendMessage::OpenUrl(url));
|
||||
}
|
||||
|
||||
@@ -111,8 +111,21 @@ pub enum OpenFileDialogContext {
|
||||
}
|
||||
|
||||
pub enum SaveFileDialogContext {
|
||||
Document { document_id: DocumentId, content: Vec<u8> },
|
||||
File { content: Vec<u8> },
|
||||
Document {
|
||||
document_id: DocumentId,
|
||||
content: Vec<u8>,
|
||||
},
|
||||
File {
|
||||
content: Vec<u8>,
|
||||
},
|
||||
/// Multiple files written into a folder whose path is the user-chosen path with the matching `expected_extension`
|
||||
/// stripped (e.g. for a PNG animation export, picking `MyAnim.png` yields a `MyAnim/` folder, while picking `v1.0`
|
||||
/// is preserved as `v1.0/` because `.0` isn't the expected extension). Each `(filename, content)` entry is written
|
||||
/// inside that folder, which is created if it doesn't exist.
|
||||
MultipleFiles {
|
||||
files: Vec<(String, Vec<u8>)>,
|
||||
expected_extension: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub enum MenuItem {
|
||||
|
||||
@@ -21,7 +21,7 @@ pub enum HsvChannel {
|
||||
#[impl_message(Message, ColorPicker)]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ColorPickerMessage {
|
||||
/// Initialize the picker state from an external color/gradient and announce its options. Called by the frontend when a `<ColorPicker>` opens.
|
||||
/// Initialize the picker state from an external color/gradient and announce its options. Called by the frontend when a `<ColorPicker />` opens.
|
||||
Open { initial_value: FillChoice, allow_none: bool, disabled: bool },
|
||||
/// Clear the picker state. Called by the frontend when the popover closes.
|
||||
Close,
|
||||
|
||||
@@ -2,9 +2,10 @@ use crate::messages::color_picker::color_picker_message::{HsvChannel, RgbChannel
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::layout::utility_types::widgets::input_widgets::{ColorPresetsInputUpdate, SpectrumInputUpdate, SpectrumMarker, VisualColorPickersInputUpdate};
|
||||
use crate::messages::prelude::*;
|
||||
use color::{AlphaColor, Srgb};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::style::{FillChoice, GradientStops};
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::parse_css_color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientStops, GradientStopsUI};
|
||||
|
||||
/// Bounds for a midpoint position (relative to the interval between two adjacent gradient stops).
|
||||
const MIN_MIDPOINT: f64 = 0.01;
|
||||
@@ -65,14 +66,6 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
self.allow_none = allow_none;
|
||||
self.disabled = disabled;
|
||||
|
||||
// Each `<ColorPicker>` Svelte instance maintains its own local layout state, but the Rust `LayoutMessageHandler` keeps a single shared layout per target. When a new picker instance opens after a previous one closed, the new instance's layout starts empty and a diff from the previously-shared state would not apply. Destroying the stored layouts here forces the next `SendLayout` to send the full layout instead of a diff.
|
||||
responses.add(LayoutMessage::DestroyLayout {
|
||||
layout_target: LayoutTarget::ColorPickerPickersAndGradient,
|
||||
});
|
||||
responses.add(LayoutMessage::DestroyLayout {
|
||||
layout_target: LayoutTarget::ColorPickerDetails,
|
||||
});
|
||||
|
||||
match initial_value {
|
||||
FillChoice::None => {
|
||||
self.set_new_hsva(0., 0., 0., 1., true);
|
||||
@@ -99,9 +92,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
ColorPickerMessage::Close => {
|
||||
self.gradient = None;
|
||||
self.active_marker_index = None;
|
||||
self.active_marker_is_midpoint = false;
|
||||
responses.add(DocumentMessage::EndTransaction);
|
||||
}
|
||||
ColorPickerMessage::VisualUpdate { update } => {
|
||||
self.hue = update.hue;
|
||||
@@ -115,10 +106,13 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
ColorPickerMessage::SetChannelRgb { channel, value } => {
|
||||
let Some(strength) = value else { return };
|
||||
let Some(current) = self.current_color() else { return };
|
||||
// The RGB inputs are 0..255 sRGB display values; substitute the new channel into the gamma triple and lift back to linear for storage.
|
||||
let new_gamma_channel = (strength / 255.) as f32;
|
||||
let [cur_r, cur_g, cur_b, cur_a] = current.to_gamma_srgb_channels();
|
||||
let updated = match channel {
|
||||
RgbChannel::Red => Color::from_rgbaf32_unchecked((strength / 255.) as f32, current.g(), current.b(), current.a()),
|
||||
RgbChannel::Green => Color::from_rgbaf32_unchecked(current.r(), (strength / 255.) as f32, current.b(), current.a()),
|
||||
RgbChannel::Blue => Color::from_rgbaf32_unchecked(current.r(), current.g(), (strength / 255.) as f32, current.a()),
|
||||
RgbChannel::Red => Color::from_gamma_srgb_channels(new_gamma_channel, cur_g, cur_b, cur_a),
|
||||
RgbChannel::Green => Color::from_gamma_srgb_channels(cur_r, new_gamma_channel, cur_b, cur_a),
|
||||
RgbChannel::Blue => Color::from_gamma_srgb_channels(cur_r, cur_g, new_gamma_channel, cur_a),
|
||||
};
|
||||
self.adopt_color(updated);
|
||||
self.emit_color(responses);
|
||||
@@ -160,7 +154,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
match preset {
|
||||
FillChoice::None => {
|
||||
self.set_new_hsva(0., 0., 0., 1., true);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::None });
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
|
||||
}
|
||||
FillChoice::Solid(color) => {
|
||||
self.adopt_color(color);
|
||||
@@ -185,7 +179,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
self.set_old_hsva(temp.0, temp.1, temp.2, temp.3, temp.4);
|
||||
|
||||
if self.is_none {
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::None });
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoiceUI::None });
|
||||
} else {
|
||||
self.emit_color(responses);
|
||||
}
|
||||
@@ -207,6 +201,7 @@ impl MessageHandler<ColorPickerMessage, ()> for ColorPickerMessageHandler {
|
||||
}
|
||||
|
||||
impl ColorPickerMessageHandler {
|
||||
// The picker's internal HSV state is HSV of sRGB display values
|
||||
fn current_color(&self) -> Option<Color> {
|
||||
if self.is_none {
|
||||
None
|
||||
@@ -249,7 +244,8 @@ impl ColorPickerMessageHandler {
|
||||
|
||||
/// Set HSV state from a Color, preserving hue and saturation in degenerate cases.
|
||||
fn adopt_color(&mut self, color: Color) {
|
||||
let [target_h, target_s, target_v] = rgb_to_hsv(color.r() as f64, color.g() as f64, color.b() as f64);
|
||||
let [target_h, target_s, target_v, target_a] = color.to_hsva();
|
||||
let (target_h, target_s, target_v, target_a) = (target_h as f64, target_s as f64, target_v as f64, target_a as f64);
|
||||
|
||||
// Preserve hue: avoid jumping from 360° (top) to 0° (bottom) and don't reset hue when the color is desaturated or fully dark.
|
||||
if !(target_h == 0. && self.hue == 1.) && target_s > 0. && target_v > 0. {
|
||||
@@ -260,7 +256,7 @@ impl ColorPickerMessageHandler {
|
||||
self.saturation = target_s;
|
||||
}
|
||||
self.value = target_v;
|
||||
self.alpha = color.a() as f64;
|
||||
self.alpha = target_a;
|
||||
self.is_none = false;
|
||||
}
|
||||
|
||||
@@ -274,9 +270,15 @@ impl ColorPickerMessageHandler {
|
||||
{
|
||||
*stop_color = color;
|
||||
let stops = gradient.clone();
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::Gradient(stops) });
|
||||
let fill_choice = FillChoice::Gradient(stops);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
} else {
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged { value: FillChoice::Solid(color) });
|
||||
let fill_choice = FillChoice::Solid(color);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -374,8 +376,9 @@ impl ColorPickerMessageHandler {
|
||||
}
|
||||
|
||||
self.gradient = Some(gradient.clone());
|
||||
let fill_choice = FillChoice::Gradient(gradient);
|
||||
responses.add(FrontendMessage::ColorPickerColorChanged {
|
||||
value: FillChoice::Gradient(gradient),
|
||||
value: FillChoiceUI::from(&fill_choice),
|
||||
});
|
||||
self.send_layouts(responses);
|
||||
}
|
||||
@@ -402,7 +405,7 @@ impl ColorPickerMessageHandler {
|
||||
// For gradient editing, the markers' handle colors mirror their gradient stop colors
|
||||
let markers = gradient.iter().map(|stop| SpectrumMarker::new(stop.position, stop.midpoint, stop.color)).collect();
|
||||
let mut row_widgets = vec![
|
||||
SpectrumInput::new(gradient.clone())
|
||||
SpectrumInput::new(GradientStopsUI::from(gradient))
|
||||
.markers(markers)
|
||||
.active_marker_index(self.active_marker_index)
|
||||
.active_marker_is_midpoint(self.active_marker_is_midpoint)
|
||||
@@ -463,7 +466,11 @@ impl ColorPickerMessageHandler {
|
||||
let old_color = self.old_color();
|
||||
|
||||
let hex_value = new_color.map(|c| color_to_hex_optional_alpha(&c)).unwrap_or_else(|| "-".to_string());
|
||||
let rgb_255 = new_color.map(|c| (c.r() as f64 * 255., c.g() as f64 * 255., c.b() as f64 * 255.));
|
||||
// RGB readouts display sRGB byte values to the user, so we convert from linear-light to gamma here before quantizing.
|
||||
let rgb_255 = new_color.map(|c| {
|
||||
let [r, g, b, _] = c.to_gamma_srgb_channels();
|
||||
(r as f64 * 255., g as f64 * 255., b as f64 * 255.)
|
||||
});
|
||||
|
||||
// Epsilon comparison since the picker round-trips through HSV
|
||||
let differs = match (new_color, old_color) {
|
||||
@@ -480,7 +487,7 @@ impl ColorPickerMessageHandler {
|
||||
|
||||
// New/old comparison swatch with swap button
|
||||
groups.push(LayoutGroup::row(vec![
|
||||
ColorComparisonInput::new(new_color, old_color)
|
||||
ColorComparisonInput::new(new_color.map(SRGBA8::from), old_color.map(SRGBA8::from))
|
||||
.is_none(self.is_none)
|
||||
.old_is_none(self.old_is_none)
|
||||
.disabled(self.disabled)
|
||||
@@ -576,7 +583,10 @@ impl ColorPickerMessageHandler {
|
||||
.disabled(self.disabled)
|
||||
.show_none_option(self.allow_none && self.gradient.is_none())
|
||||
.on_update(|update: &ColorPresetsInputUpdate| match update {
|
||||
ColorPresetsInputUpdate::Preset(fill_choice) => ColorPickerMessage::PickPreset { preset: fill_choice.clone() }.into(),
|
||||
ColorPresetsInputUpdate::Preset(fill_choice) => ColorPickerMessage::PickPreset {
|
||||
preset: FillChoice::from(fill_choice),
|
||||
}
|
||||
.into(),
|
||||
ColorPresetsInputUpdate::EyedropperColorCode(code) => ColorPickerMessage::EyedropperColorCode { code: code.clone() }.into(),
|
||||
})
|
||||
.widget_instance(),
|
||||
@@ -621,33 +631,10 @@ const SATURATION_DESCRIPTION: &str = "The vividness from grayscale to full color
|
||||
const VALUE_DESCRIPTION: &str = "The brightness from black to full color.";
|
||||
const ALPHA_DESCRIPTION: &str = "The level of translucency, from transparent (0%) to opaque (100%).";
|
||||
|
||||
/// Convert an `rgb(0..1)` triple to `hsv(0..1)`. Mirrors the legacy frontend `colorToHSV`.
|
||||
fn rgb_to_hsv(red: f64, green: f64, blue: f64) -> [f64; 3] {
|
||||
let max = red.max(green).max(blue);
|
||||
let min = red.min(green).min(blue);
|
||||
let delta = max - min;
|
||||
|
||||
let mut hue = if delta == 0. {
|
||||
0.
|
||||
} else if max == red {
|
||||
((green - blue) / delta).rem_euclid(6.)
|
||||
} else if max == green {
|
||||
(blue - red) / delta + 2.
|
||||
} else {
|
||||
(red - green) / delta + 4.
|
||||
};
|
||||
hue = (hue * 60. + 360.).rem_euclid(360.) / 360.;
|
||||
|
||||
let saturation = if max == 0. { 0. } else { delta / max };
|
||||
let value = max;
|
||||
|
||||
[hue, saturation, value]
|
||||
}
|
||||
|
||||
/// The popover's background color (the `--color-2-mildblack` design token, `#222`). Used by the comparison swatch's
|
||||
/// outline computation to brighten the inset border for colors close to this background.
|
||||
const POPOVER_BACKGROUND: Color = Color::from_rgbaf32_unchecked(0x22 as f32 / 255., 0x22 as f32 / 255., 0x22 as f32 / 255., 1.);
|
||||
/// The luminance window (in linear-light) within which a color is considered close enough to the popover background
|
||||
/// The popover's background color as sRGB gamma-encoded channels (the `--color-2-mildblack` design token, `#222`).
|
||||
/// Used by the comparison swatch's outline computation to brighten the inset border for colors close to this background.
|
||||
const POPOVER_BACKGROUND_GAMMA_CHANNELS: [f32; 4] = [0x22 as f32 / 255., 0x22 as f32 / 255., 0x22 as f32 / 255., 1.];
|
||||
/// The luminance window within which a color is considered close enough to the popover background
|
||||
/// to warrant an outline. Mirrors the `proximityRange` argument the legacy frontend passed to `contrastingOutlineFactor`.
|
||||
const OUTLINE_PROXIMITY_RANGE: f64 = 0.01;
|
||||
|
||||
@@ -656,61 +643,22 @@ const OUTLINE_PROXIMITY_RANGE: f64 = 0.01;
|
||||
fn contrasting_outline_factor(color: Option<Color>) -> f64 {
|
||||
let Some(color) = color else { return 0. };
|
||||
|
||||
// WCAG-style relative luminance, with alpha composited over white in gamma space
|
||||
let luminance = |color: Color| {
|
||||
// TODO: Remove the `.to_linear_srgb()` once we move to correctly treating `Color` as linear.
|
||||
Color::WHITE
|
||||
.alpha_blend(Color::from_unassociated_alpha(color.r(), color.g(), color.b(), color.a()))
|
||||
.to_linear_srgb()
|
||||
.luminance_srgb() as f64
|
||||
// WCAG-style relative luminance, with alpha composited over white in sRGB gamma space (matching the perceptual intent of `SRGBA8::contrasting_text_color`).
|
||||
let luminance_from_gamma_channels = |[r, g, b, a]: [f32; 4]| -> f64 {
|
||||
let inv_a = 1. - a;
|
||||
Color::from_gamma_srgb_channels(inv_a + r * a, inv_a + g * a, inv_a + b * a, 1.).luminance_rec_709() as f64
|
||||
};
|
||||
|
||||
let distance = (luminance(POPOVER_BACKGROUND) - luminance(color)).abs().max(0.);
|
||||
let color_gamma_channels = color.to_gamma_srgb_channels();
|
||||
let distance = (luminance_from_gamma_channels(POPOVER_BACKGROUND_GAMMA_CHANNELS) - luminance_from_gamma_channels(color_gamma_channels))
|
||||
.abs()
|
||||
.max(0.);
|
||||
let proximity = 1. - (distance / OUTLINE_PROXIMITY_RANGE).min(1.);
|
||||
let [_, saturation, _] = rgb_to_hsv(color.r() as f64, color.g() as f64, color.b() as f64);
|
||||
proximity * (1. - saturation)
|
||||
let [_, saturation, _, _] = color.to_hsva();
|
||||
proximity * (1. - saturation as f64)
|
||||
}
|
||||
|
||||
/// Format a Color as a `#`-prefixed hex string, including the alpha component only if it's not fully opaque.
|
||||
/// Format a linear `Color` as a `#`-prefixed hex string, including the alpha component only if it's not fully opaque.
|
||||
fn color_to_hex_optional_alpha(color: &Color) -> String {
|
||||
format!(
|
||||
"#{}",
|
||||
if color.a() >= 1. {
|
||||
color.to_rgb_hex_srgb_from_gamma()
|
||||
} else {
|
||||
color.to_rgba_hex_srgb_from_gamma()
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse a CSS color string (named color, hex, `rgb(...)`, etc.) into a `Color` using the `color` crate's CSS Color 4 parser.
|
||||
/// Tries the input as-is first (catches CSS named colors like `red`, `rgb(...)`, and well-formed hex like `#abcdef`), then falls back to treating the input as bare hex with length-based expansion to a CSS-parseable form:
|
||||
/// - 1 char `f` → `#fff` (CSS 3-char shorthand)
|
||||
/// - 2 char `ab` → `#ababab` (repeated to 6 chars)
|
||||
/// - 4 char `abcd` → `#00abcd` (left-padded with `00`)
|
||||
/// - 5 char `abcde` → `#0abcde` (left-padded with `0`)
|
||||
/// - 3, 6, 8 char inputs are passed through with a `#` prefix.
|
||||
fn parse_css_color(input: &str) -> Option<Color> {
|
||||
let trimmed = input.trim();
|
||||
|
||||
let parsed = color::parse_color(trimmed).ok().or_else(|| {
|
||||
let bare = trimmed.strip_prefix('#').unwrap_or(trimmed);
|
||||
if bare.is_empty() || !bare.chars().all(|c| c.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let expanded = match bare.len() {
|
||||
1 => bare.repeat(3),
|
||||
2 => bare.repeat(3),
|
||||
4 => format!("00{bare}"),
|
||||
5 => format!("0{bare}"),
|
||||
_ => bare.to_string(),
|
||||
};
|
||||
let candidate = format!("#{expanded}");
|
||||
// Avoid retrying the exact same string we just failed to parse.
|
||||
(candidate != trimmed).then(|| color::parse_color(&candidate).ok()).flatten()
|
||||
})?;
|
||||
|
||||
let srgb: AlphaColor<Srgb> = parsed.to_alpha_color();
|
||||
let [red, green, blue, alpha] = srgb.components;
|
||||
Color::from_rgbaf32(red, green, blue, alpha)
|
||||
SRGBA8::from(*color).to_css_hex()
|
||||
}
|
||||
@@ -7,6 +7,10 @@ pub enum ExportDialogMessage {
|
||||
FileType { file_type: FileType },
|
||||
ScaleFactor { factor: f64 },
|
||||
ExportBounds { bounds: ExportBounds },
|
||||
Animated { animated: bool },
|
||||
Fps { fps: f64 },
|
||||
StartSeconds { start: f64 },
|
||||
EndSeconds { end: f64 },
|
||||
|
||||
Submit,
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, ExportBounds, FileType};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -16,6 +16,10 @@ pub struct ExportDialogMessageHandler {
|
||||
pub bounds: ExportBounds,
|
||||
pub artboards: HashMap<LayerNodeIdentifier, String>,
|
||||
pub has_selection: bool,
|
||||
pub animated: bool,
|
||||
pub fps: f64,
|
||||
pub start_seconds: f64,
|
||||
pub end_seconds: f64,
|
||||
}
|
||||
|
||||
impl Default for ExportDialogMessageHandler {
|
||||
@@ -26,10 +30,32 @@ impl Default for ExportDialogMessageHandler {
|
||||
bounds: Default::default(),
|
||||
artboards: Default::default(),
|
||||
has_selection: false,
|
||||
animated: false,
|
||||
fps: 30.,
|
||||
start_seconds: 0.,
|
||||
end_seconds: 1.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on how many frames a single animation export will queue. Each frame is rendered then held
|
||||
/// in memory until the whole batch ships to the frontend, so we cap to avoid pathological allocations from
|
||||
/// large time ranges. Tuned for typical animation lengths (10k frames is ~5.5 min at 30 fps, ~2.8 min at 60 fps).
|
||||
pub const ANIMATION_EXPORT_MAX_FRAMES: u32 = 10_000;
|
||||
|
||||
impl ExportDialogMessageHandler {
|
||||
fn total_frames(&self) -> u32 {
|
||||
// Sanitize against non-finite values that could otherwise propagate into `Duration::from_secs_f64` and panic.
|
||||
if !self.fps.is_finite() || self.fps <= 0. || !self.start_seconds.is_finite() || !self.end_seconds.is_finite() {
|
||||
return 1;
|
||||
}
|
||||
let duration = (self.end_seconds - self.start_seconds).max(0.);
|
||||
// `ceil` so a duration slightly longer than a frame multiple still gets the trailing frame.
|
||||
let raw = (duration * self.fps).ceil() as i64;
|
||||
raw.clamp(1, ANIMATION_EXPORT_MAX_FRAMES as i64) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for ExportDialogMessageHandler {
|
||||
fn process_message(&mut self, message: ExportDialogMessage, responses: &mut VecDeque<Message>, context: ExportDialogMessageContext) {
|
||||
@@ -39,6 +65,20 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
ExportDialogMessage::FileType { file_type } => self.file_type = file_type,
|
||||
ExportDialogMessage::ScaleFactor { factor } => self.scale_factor = factor,
|
||||
ExportDialogMessage::ExportBounds { bounds } => self.bounds = bounds,
|
||||
ExportDialogMessage::Animated { animated } => self.animated = animated,
|
||||
ExportDialogMessage::Fps { fps } => {
|
||||
// Reject non-finite/non-positive values so we never feed NaN or infinity into duration math downstream.
|
||||
self.fps = if fps.is_finite() && fps > 0. { fps } else { 0.001 };
|
||||
}
|
||||
ExportDialogMessage::StartSeconds { start } => {
|
||||
self.start_seconds = if start.is_finite() { start.max(0.) } else { 0. };
|
||||
if self.end_seconds < self.start_seconds {
|
||||
self.end_seconds = self.start_seconds;
|
||||
}
|
||||
}
|
||||
ExportDialogMessage::EndSeconds { end } => {
|
||||
self.end_seconds = if end.is_finite() { end.max(self.start_seconds) } else { self.start_seconds };
|
||||
}
|
||||
|
||||
ExportDialogMessage::Submit => {
|
||||
// Fall back to "All Artwork" if "Selection" was chosen but nothing is currently selected
|
||||
@@ -52,6 +92,13 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
ExportBounds::Artboard(layer) => self.artboards.get(&layer).cloned(),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let animation = self.animated.then(|| AnimationExport {
|
||||
fps: self.fps,
|
||||
start_seconds: self.start_seconds,
|
||||
total_frames: self.total_frames(),
|
||||
});
|
||||
|
||||
responses.add_front(PortfolioMessage::SubmitDocumentExport {
|
||||
name: portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default(),
|
||||
file_type: self.file_type,
|
||||
@@ -59,6 +106,7 @@ impl MessageHandler<ExportDialogMessage, ExportDialogMessageContext<'_>> for Exp
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count: self.artboards.len(),
|
||||
animation,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -163,6 +211,74 @@ impl LayoutHolder for ExportDialogMessageHandler {
|
||||
DropdownInput::new(entries).selected_index(Some(index as u32)).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(export_type), LayoutGroup::row(resolution), LayoutGroup::row(export_area)])
|
||||
let animation_checkbox_id = CheckboxId::new();
|
||||
let animation_toggle = vec![
|
||||
TextLabel::new("Animation").table_align(true).min_width(100).for_checkbox(animation_checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
CheckboxInput::new(self.animated)
|
||||
.on_update(|checkbox_input: &CheckboxInput| ExportDialogMessage::Animated { animated: checkbox_input.checked }.into())
|
||||
.for_label(animation_checkbox_id)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let mut layout_groups = vec![
|
||||
LayoutGroup::row(export_type),
|
||||
LayoutGroup::row(resolution),
|
||||
LayoutGroup::row(export_area),
|
||||
LayoutGroup::row(animation_toggle),
|
||||
];
|
||||
|
||||
if self.animated {
|
||||
let fps_row = vec![
|
||||
TextLabel::new("FPS").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.fps))
|
||||
.unit(" fps")
|
||||
.min(0.001)
|
||||
.max(1000.)
|
||||
.increment_step(1.)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::Fps { fps: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let start_row = vec![
|
||||
TextLabel::new("Start").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.start_seconds))
|
||||
.unit(" sec")
|
||||
.min(0.)
|
||||
.increment_step(0.1)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::StartSeconds { start: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let end_row = vec![
|
||||
TextLabel::new("End").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.end_seconds))
|
||||
.unit(" sec")
|
||||
.min(self.start_seconds)
|
||||
.increment_step(0.1)
|
||||
.on_update(|number_input: &NumberInput| ExportDialogMessage::EndSeconds { end: number_input.value.unwrap() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let frame_count = self.total_frames();
|
||||
let frames_row = vec![
|
||||
TextLabel::new("Frames").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new(format!("{frame_count} frame{}", if frame_count == 1 { "" } else { "s" })).widget_instance(),
|
||||
];
|
||||
|
||||
layout_groups.push(LayoutGroup::row(fps_row));
|
||||
layout_groups.push(LayoutGroup::row(start_row));
|
||||
layout_groups.push(LayoutGroup::row(end_row));
|
||||
layout_groups.push(LayoutGroup::row(frames_row));
|
||||
}
|
||||
|
||||
Layout(layout_groups)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, ExportAnimationFrame, EyedropperPreviewImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
@@ -13,10 +13,10 @@ use crate::messages::portfolio::utility_types::WorkspacePanelLayout;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::text::Font;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
@@ -107,6 +107,23 @@ pub enum FrontendMessage {
|
||||
mime: String,
|
||||
size: (f64, f64),
|
||||
},
|
||||
/// Export one or more animation frames as a bundle.
|
||||
/// On web, the frontend zips the frames into an uncompressed `.zip` and triggers a single download.
|
||||
/// On desktop, the wrapper intercepts this and writes each frame as a separate file to a user-chosen folder.
|
||||
TriggerExportAnimation {
|
||||
/// Base name without the index suffix or extension (e.g. "MyDocument" or "MyDocument - Artboard 1").
|
||||
name: String,
|
||||
/// File extension without leading dot ("png", "jpg", "svg").
|
||||
extension: String,
|
||||
/// MIME type matching the extension (e.g. "image/png").
|
||||
mime: String,
|
||||
/// Pixel size of each rasterized frame, used when the frontend needs to canvas-rasterize from SVG.
|
||||
size: (f64, f64),
|
||||
/// Document folder, used as a default location for the desktop save dialog.
|
||||
folder: Option<PathBuf>,
|
||||
/// One entry per frame, in playback order. Each frame is either an SVG string or pre-encoded bytes.
|
||||
frames: Vec<ExportAnimationFrame>,
|
||||
},
|
||||
TriggerFetchAndOpenDocument {
|
||||
name: String,
|
||||
filename: String,
|
||||
@@ -167,16 +184,16 @@ pub enum FrontendMessage {
|
||||
document_id: DocumentId,
|
||||
},
|
||||
UpdateGradientStopColorPickerPosition {
|
||||
color: Color, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
color: SRGBA8, // TODO: Color (without `none`) -> Color (with `none`)
|
||||
position: (f64, f64),
|
||||
},
|
||||
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker>` forwards this as its `colorOrGradient` event.
|
||||
/// The Rust color picker handler picked a new color/gradient. The frontend `<ColorPicker />` forwards this as its `colorOrGradient` event.
|
||||
ColorPickerColorChanged {
|
||||
value: FillChoice,
|
||||
value: FillChoiceUI,
|
||||
},
|
||||
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker>` forwards this as its `startHistoryTransaction` event.
|
||||
/// The Rust color picker handler is starting an undo transaction. The frontend `<ColorPicker />` forwards this as its `startHistoryTransaction` event.
|
||||
ColorPickerStartHistoryTransaction,
|
||||
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker>` forwards this as its `commitHistoryTransaction` event.
|
||||
/// The Rust color picker handler is committing the in-flight undo transaction. The frontend `<ColorPicker />` forwards this as its `commitHistoryTransaction` event.
|
||||
ColorPickerCommitHistoryTransaction,
|
||||
UpdateImportsExports {
|
||||
/// If the primary import is not visible, then it is None.
|
||||
@@ -241,7 +258,7 @@ pub enum FrontendMessage {
|
||||
svg: String,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<(u64, Image<Color>)>,
|
||||
image_data: Vec<(u64, Image<SRGBA8>)>,
|
||||
},
|
||||
UpdateDocumentLayerDetails {
|
||||
data: LayerPanelEntry,
|
||||
|
||||
@@ -14,7 +14,7 @@ pub struct DocumentInfo {
|
||||
pub is_saved: bool,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints, from_wasm_abi))]
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct PersistedState {
|
||||
pub documents: Vec<DocumentInfo>,
|
||||
@@ -59,6 +59,14 @@ impl FileType {
|
||||
FileType::Svg => "image/svg+xml",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_extension(self) -> &'static str {
|
||||
match self {
|
||||
FileType::Png => "png",
|
||||
FileType::Jpg => "jpg",
|
||||
FileType::Svg => "svg",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -70,6 +78,56 @@ pub enum ExportBounds {
|
||||
Artboard(LayerNodeIdentifier),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AnimationExport {
|
||||
pub fps: f64,
|
||||
pub start_seconds: f64,
|
||||
pub total_frames: u32,
|
||||
}
|
||||
|
||||
impl Default for AnimationExport {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fps: 30.,
|
||||
start_seconds: 0.,
|
||||
total_frames: 30,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AnimationExport {
|
||||
pub fn frame_time_seconds(&self, frame_index: u32) -> f64 {
|
||||
self.start_seconds + frame_index as f64 / self.fps
|
||||
}
|
||||
}
|
||||
|
||||
/// One frame of a multi-frame animation export, in playback order.
|
||||
/// `Svg` is text that the frontend can save directly (for SVG export) or rasterize via canvas (for PNG/JPG export).
|
||||
/// `Bytes` is already-encoded image bytes from the GPU export path, ready to write directly.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ExportAnimationFrame {
|
||||
Svg(String),
|
||||
Bytes(serde_bytes::ByteBuf),
|
||||
}
|
||||
|
||||
/// Replace characters that have special meaning in filesystem paths (or are otherwise unsafe in filenames) with `_`.
|
||||
/// Used to neutralize user-controlled strings — document names, artboard names — before they become export filenames,
|
||||
/// so a name like `..\evil` or `foo/bar` can't escape the export folder or create nested zip entries.
|
||||
pub fn sanitize_filename_component(name: &str) -> String {
|
||||
let cleaned: String = name
|
||||
.chars()
|
||||
.map(|c| match c {
|
||||
'/' | '\\' | ':' | '*' | '?' | '<' | '>' | '|' | '"' | '\0' => '_',
|
||||
c if c.is_control() => '_',
|
||||
c => c,
|
||||
})
|
||||
.collect();
|
||||
// Strip leading/trailing dots and whitespace; Windows treats trailing `.` / ` ` as hidden and `..` is the parent dir.
|
||||
let trimmed = cleaned.trim().trim_matches('.').trim();
|
||||
if trimmed.is_empty() { "Untitled".to_string() } else { trimmed.to_string() }
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct EyedropperPreviewImage {
|
||||
|
||||
@@ -26,4 +26,8 @@ pub enum LayoutMessage {
|
||||
widget_id: WidgetId,
|
||||
value: serde_json::Value,
|
||||
},
|
||||
WidgetValueDragDrop {
|
||||
layout_target: LayoutTarget,
|
||||
widget_id: WidgetId,
|
||||
},
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -61,6 +62,19 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
|
||||
LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value } => {
|
||||
self.handle_widget_callback(layout_target, widget_id, value, WidgetValueAction::Update, responses);
|
||||
}
|
||||
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id } => {
|
||||
let Some(layout) = self.layouts.get_mut(layout_target as usize) else {
|
||||
warn!("WidgetValueDragDrop referenced an invalid layout. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
let Some(widget_instance) = layout.iter_mut().find(|widget| widget.widget_id == widget_id) else {
|
||||
warn!("WidgetValueDragDrop referenced an invalid widget ID. `widget_id: {widget_id}`, `layout_target: {layout_target:?}`");
|
||||
return;
|
||||
};
|
||||
if let Widget::IconButton(icon_button) = &mut *widget_instance.widget {
|
||||
responses.add((icon_button.on_drag_drop.callback)(icon_button));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -179,11 +193,11 @@ impl LayoutMessageHandler {
|
||||
let callback_message = match action {
|
||||
WidgetValueAction::Commit => (color_button.on_commit.callback)(&()),
|
||||
WidgetValueAction::Update => {
|
||||
let Ok(fill_choice) = serde_json::from_value::<FillChoice>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoice: {color_button:?}");
|
||||
let Ok(fill_choice_ui) = serde_json::from_value::<FillChoiceUI>(value) else {
|
||||
warn!("ColorInput update was not able to be parsed as FillChoiceUI: {color_button:?}");
|
||||
return;
|
||||
};
|
||||
color_button.value = fill_choice;
|
||||
color_button.value = fill_choice_ui;
|
||||
(color_button.on_update.callback)(color_button)
|
||||
}
|
||||
};
|
||||
@@ -496,25 +510,14 @@ fn populate_computed_display_fields(layout: &mut Layout) {
|
||||
}
|
||||
Widget::SpectrumInput(spectrum_input) => {
|
||||
spectrum_input.track_css = spectrum_input.track.to_css_linear_gradient();
|
||||
spectrum_input.track_start_css = spectrum_input
|
||||
.track
|
||||
.color
|
||||
.first()
|
||||
.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma()))
|
||||
.unwrap_or_else(|| "black".to_string());
|
||||
spectrum_input.track_end_css = spectrum_input
|
||||
.track
|
||||
.color
|
||||
.last()
|
||||
.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma()))
|
||||
.unwrap_or_else(|| "black".to_string());
|
||||
spectrum_input.track_start_css = spectrum_input.track.color.first().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
|
||||
spectrum_input.track_end_css = spectrum_input.track.color.last().map(|color| color.to_css_hex()).unwrap_or_else(|| "black".to_string());
|
||||
}
|
||||
Widget::ColorComparisonInput(comparison) => {
|
||||
use graphene_std::Color;
|
||||
let contrasting = |color: Option<Color>| format!("#{}", color.map_or(Color::BLACK, |color| color.contrasting_text_color_from_gamma()).to_rgba_hex_srgb_from_gamma());
|
||||
comparison.new_color_css = comparison.new_color.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma())).unwrap_or_default();
|
||||
let contrasting = |color: Option<SRGBA8>| color.map_or(SRGBA8::BLACK, |color| color.contrasting_text_color()).to_css_hex();
|
||||
comparison.new_color_css = comparison.new_color.map(|color| color.to_css_hex()).unwrap_or_default();
|
||||
comparison.new_color_contrasting = contrasting(comparison.new_color);
|
||||
comparison.old_color_css = comparison.old_color.map(|color| format!("#{}", color.to_rgba_hex_srgb_from_gamma())).unwrap_or_default();
|
||||
comparison.old_color_css = comparison.old_color.map(|color| color.to_css_hex()).unwrap_or_default();
|
||||
comparison.old_color_contrasting = contrasting(comparison.old_color);
|
||||
}
|
||||
_ => {}
|
||||
|
||||
@@ -22,7 +22,7 @@ impl core::fmt::Display for WidgetId {
|
||||
|
||||
macro_rules! define_layout_target {
|
||||
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[repr(u8)]
|
||||
pub enum LayoutTarget {
|
||||
@@ -668,6 +668,7 @@ impl Diffable for WidgetInstance {
|
||||
&& button1.tooltip_description == button2.tooltip_description
|
||||
&& button1.tooltip_shortcut == button2.tooltip_shortcut
|
||||
&& button1.popover_min_width == button2.popover_min_width
|
||||
&& button1.popover_layout.0.len() == button2.popover_layout.0.len()
|
||||
{
|
||||
// Only the popover layout differs, diff it recursively
|
||||
for (i, (a, b)) in button1.popover_layout.0.iter_mut().zip(button2.popover_layout.0.iter()).enumerate() {
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::WidgetCallback;
|
||||
use derivative::*;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -39,6 +39,9 @@ pub struct IconButton {
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_commit: WidgetCallback<()>,
|
||||
#[serde(skip)]
|
||||
#[derivative(Debug = "ignore", PartialEq = "ignore")]
|
||||
pub on_drag_drop: WidgetCallback<IconButton>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -187,11 +190,10 @@ pub struct ImageButton {
|
||||
#[derivative(Debug, PartialEq, Default)]
|
||||
pub struct ColorInput {
|
||||
// Content
|
||||
/// WARNING: The colors are gamma, not linear!
|
||||
#[widget_builder(constructor)]
|
||||
pub value: FillChoice,
|
||||
pub value: FillChoiceUI,
|
||||
/// CSS `linear-gradient(...)` (or solid-color stand-in) for the swatch's `background-image`. Auto-populated from `value` at layout-send time.
|
||||
/// `None` when `value` is `FillChoice::None`, in which case the frontend uses its "none" fallback styling.
|
||||
/// `None` when `value` is `FillChoiceUI::None`, in which case the frontend uses its "none" fallback styling.
|
||||
#[serde(rename = "chosenGradient")]
|
||||
#[widget_builder(skip)]
|
||||
pub chosen_gradient: Option<String>,
|
||||
@@ -202,6 +204,13 @@ pub struct ColorInput {
|
||||
#[serde(rename = "menuDirection")]
|
||||
pub menu_direction: Option<MenuDirection>,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
|
||||
// Styling
|
||||
pub narrow: bool,
|
||||
|
||||
@@ -4,8 +4,9 @@ use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use derivative::*;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::style::{FillChoice, GradientStops};
|
||||
use graphene_std::vector::style::{FillChoiceUI, GradientStopsUI};
|
||||
use graphite_proc_macros::WidgetBuilder;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -20,6 +21,7 @@ pub struct CheckboxInput {
|
||||
#[serde(rename = "forLabel")]
|
||||
pub for_label: CheckboxId,
|
||||
pub disabled: bool,
|
||||
pub mixed: bool,
|
||||
|
||||
// Tooltips
|
||||
#[serde(rename = "tooltipLabel")]
|
||||
@@ -348,9 +350,9 @@ pub struct RadioEntryData {
|
||||
pub struct WorkingColorsInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
pub primary: Color,
|
||||
pub primary: SRGBA8,
|
||||
#[widget_builder(constructor)]
|
||||
pub secondary: Color,
|
||||
pub secondary: SRGBA8,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -483,10 +485,10 @@ pub struct ColorComparisonInput {
|
||||
// Content
|
||||
#[widget_builder(constructor)]
|
||||
#[serde(rename = "newColor")]
|
||||
pub new_color: Option<Color>,
|
||||
pub new_color: Option<SRGBA8>,
|
||||
#[widget_builder(constructor)]
|
||||
#[serde(rename = "oldColor")]
|
||||
pub old_color: Option<Color>,
|
||||
pub old_color: Option<SRGBA8>,
|
||||
#[serde(rename = "isNone")]
|
||||
pub is_none: bool,
|
||||
#[serde(rename = "oldIsNone")]
|
||||
@@ -543,7 +545,7 @@ pub struct ColorPresetsInput {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ColorPresetsInputUpdate {
|
||||
Preset(FillChoice),
|
||||
Preset(FillChoiceUI),
|
||||
EyedropperColorCode(String),
|
||||
}
|
||||
|
||||
@@ -554,7 +556,7 @@ pub struct SpectrumInput {
|
||||
// Content
|
||||
/// The colored gradient drawn behind the markers (display-only, caller-owned).
|
||||
#[widget_builder(constructor)]
|
||||
pub track: GradientStops,
|
||||
pub track: GradientStopsUI,
|
||||
/// CSS `linear-gradient(...)` string for the track strip's `background-image`. Auto-populated from `track` at layout-send time.
|
||||
#[serde(rename = "trackCSS")]
|
||||
#[widget_builder(skip)]
|
||||
@@ -606,14 +608,14 @@ pub struct SpectrumMarker {
|
||||
position: f64,
|
||||
/// Position (0..1) of the midpoint between this marker and the next, used only if `show_midpoints` is true. The last marker's value is ignored.
|
||||
midpoint: f64,
|
||||
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a [`Color`] (gamma space).
|
||||
/// CSS color string for the marker handle's fill. Set via `SpectrumMarker::new` from a linear [`Color`].
|
||||
#[serde(rename = "handleColorCSS")]
|
||||
handle_color_css: String,
|
||||
}
|
||||
|
||||
impl SpectrumMarker {
|
||||
pub fn new(position: f64, midpoint: f64, handle_color: Color) -> Self {
|
||||
let handle_color_css = format!("#{}", handle_color.to_rgba_hex_srgb_from_gamma());
|
||||
let handle_color_css = SRGBA8::from(handle_color).to_css_hex();
|
||||
Self { position, midpoint, handle_color_css }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,6 +72,8 @@ pub struct TextLabel {
|
||||
// Sizing
|
||||
#[serde(rename = "minWidth")]
|
||||
pub min_width: u32,
|
||||
#[serde(rename = "maxWidth")]
|
||||
pub max_width: u32,
|
||||
#[serde(rename = "minWidthCharacters")]
|
||||
pub min_width_characters: u32,
|
||||
|
||||
|
||||
@@ -514,6 +514,11 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.icon("NodeShape")
|
||||
.on_commit(|_| NodeGraphMessage::AddPathNode.into())
|
||||
.disabled(!make_path_editable_is_allowed),
|
||||
MenuListEntry::new("Expand Fill/Stroke")
|
||||
.label("Expand Fill/Stroke")
|
||||
.icon("ExpandFillStroke")
|
||||
.on_commit(|_| DocumentMessage::ExpandFillStrokeOnSelectedLayers.into())
|
||||
.disabled(no_active_document || !has_selected_layers),
|
||||
],
|
||||
])
|
||||
.widget_instance(),
|
||||
|
||||
@@ -7,12 +7,13 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::gradient::GradientStops;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::vector::style::{Fill, FillChoice, GradientSpreadMethod, GradientType};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
|
||||
use graphene_std::{Artboard, Color, Context, Graphic};
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -385,11 +386,15 @@ impl TableItemLayout for Vector {
|
||||
match self.style.fill.clone() {
|
||||
Fill::None => table_rows.push(vec![
|
||||
TextLabel::new("Fill").narrow(true).widget_instance(),
|
||||
ColorInput::new(FillChoice::None).disabled(true).menu_direction(Some(MenuDirection::Top)).narrow(true).widget_instance(),
|
||||
ColorInput::new(FillChoiceUI::None)
|
||||
.disabled(true)
|
||||
.menu_direction(Some(MenuDirection::Top))
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
Fill::Solid(color) => table_rows.push(vec![
|
||||
TextLabel::new("Fill").narrow(true).widget_instance(),
|
||||
ColorInput::new(FillChoice::Solid(color))
|
||||
ColorInput::new(FillChoiceUI::from(&FillChoice::Solid(color)))
|
||||
.disabled(true)
|
||||
.menu_direction(Some(MenuDirection::Top))
|
||||
.narrow(true)
|
||||
@@ -398,7 +403,7 @@ impl TableItemLayout for Vector {
|
||||
Fill::Gradient(gradient) => {
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Fill").narrow(true).widget_instance(),
|
||||
ColorInput::new(FillChoice::Gradient(gradient.stops))
|
||||
ColorInput::new(FillChoiceUI::from(&FillChoice::Gradient(gradient.stops)))
|
||||
.disabled(true)
|
||||
.menu_direction(Some(MenuDirection::Top))
|
||||
.narrow(true)
|
||||
@@ -423,7 +428,11 @@ impl TableItemLayout for Vector {
|
||||
let color = if let Some(color) = stroke.color { FillChoice::Solid(color) } else { FillChoice::None };
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke").narrow(true).widget_instance(),
|
||||
ColorInput::new(color).disabled(true).menu_direction(Some(MenuDirection::Top)).narrow(true).widget_instance(),
|
||||
ColorInput::new(FillChoiceUI::from(&color))
|
||||
.disabled(true)
|
||||
.menu_direction(Some(MenuDirection::Top))
|
||||
.narrow(true)
|
||||
.widget_instance(),
|
||||
]);
|
||||
table_rows.push(vec![
|
||||
TextLabel::new("Stroke Weight").narrow(true).widget_instance(),
|
||||
@@ -561,10 +570,10 @@ impl TableItemLayout for Color {
|
||||
"Color"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
format!("Color (#{})", self.to_gamma_srgb().to_rgba_hex_srgb())
|
||||
format!("Color (#{})", SRGBA8::from(*self).to_rgba_hex())
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
ColorInput::new(FillChoice::Solid(*self))
|
||||
ColorInput::new(FillChoiceUI::from(&FillChoice::Solid(*self)))
|
||||
.disabled(true)
|
||||
.menu_direction(Some(MenuDirection::Top))
|
||||
.narrow(true)
|
||||
@@ -584,7 +593,7 @@ impl TableItemLayout for GradientStops {
|
||||
format!("Gradient ({} stops)", self.len())
|
||||
}
|
||||
fn value_widget(&self, _target: PathStep, _data: &LayoutData) -> WidgetInstance {
|
||||
ColorInput::new(FillChoice::Gradient(self.clone()))
|
||||
ColorInput::new(FillChoiceUI::from(&FillChoice::Gradient(self.clone())))
|
||||
.menu_direction(Some(MenuDirection::Top))
|
||||
.disabled(true)
|
||||
.narrow(true)
|
||||
|
||||
@@ -86,6 +86,8 @@ pub enum DocumentMessage {
|
||||
},
|
||||
BlendSelectedLayers,
|
||||
MorphSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayers,
|
||||
ExpandFillStrokeOnSelectedLayersNoTransaction,
|
||||
GroupSelectedLayers {
|
||||
group_folder_type: GroupFolderType,
|
||||
},
|
||||
|
||||
@@ -11,7 +11,7 @@ use crate::consts::{
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessageContext, DataPanelMessageHandler};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::{ModifyInputsContext, TransformIn};
|
||||
use crate::messages::portfolio::document::node_graph::NodeGraphMessageContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
@@ -20,7 +20,7 @@ use crate::messages::portfolio::document::overlays::utility_types::{OverlaysType
|
||||
use crate::messages::portfolio::document::properties_panel::properties_panel_message_handler::PropertiesPanelMessageContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate, AlignAxis, FlipAxis, PTZ};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, OutputConnector};
|
||||
use crate::messages::portfolio::utility_types::{CachedData, PanelType};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, get_blend_mode, get_fill, get_opacity};
|
||||
@@ -40,7 +40,7 @@ use graphene_std::subpath::Subpath;
|
||||
use graphene_std::vector::PointId;
|
||||
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::vector::style::{Fill, RenderMode};
|
||||
use kurbo::{Affine, BezPath, Line, PathSeg};
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
@@ -631,6 +631,24 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::MorphSelectedLayers => {
|
||||
self.handle_group_selected_layers(GroupFolderType::Morph, responses);
|
||||
}
|
||||
DocumentMessage::ExpandFillStrokeOnSelectedLayers => {
|
||||
// Snapshot must be taken before the mutations, so the actual work runs as a separate message
|
||||
// queued after AddTransaction (which prepends StartTransaction/CommitTransaction to the queue).
|
||||
// All mutations currently target the root document network, so guard against being invoked from inside a nested network.
|
||||
if !self.selection_network_path.is_empty() {
|
||||
log::error!("Expanding fill/stroke is only supported for the document network");
|
||||
return;
|
||||
}
|
||||
if self.network_interface.selected_nodes().selected_layers(self.metadata()).next().is_none() {
|
||||
return;
|
||||
}
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction);
|
||||
}
|
||||
DocumentMessage::ExpandFillStrokeOnSelectedLayersNoTransaction => {
|
||||
// Mutates the network directly, so it must be queued to run after `AddTransaction` has snapshotted the document
|
||||
self.handle_expand_fill_stroke_on_selected_layers(responses);
|
||||
}
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type } => {
|
||||
self.handle_group_selected_layers(group_folder_type, responses);
|
||||
}
|
||||
@@ -2350,6 +2368,86 @@ impl DocumentMessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/// For each selected layer, splits its fill and stroke into two stacked layers connected
|
||||
/// to a shared `Solidify Stroke` node via two `Index Elements` nodes (indices 0 and 1).
|
||||
/// Layers with only a stroke get just a `Solidify Stroke` added.
|
||||
/// Layers with only a fill, or neither, are left untouched.
|
||||
fn handle_expand_fill_stroke_on_selected_layers(&mut self, responses: &mut VecDeque<Message>) {
|
||||
let selected_layers: Vec<LayerNodeIdentifier> = self.network_interface.selected_nodes().selected_layers(self.metadata()).collect();
|
||||
if selected_layers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let solidify_stroke_definition = document_node_definitions::resolve_proto_node_type(graphene_std::vector::solidify_stroke::IDENTIFIER).expect("Solidify Stroke node should exist");
|
||||
let index_elements_definition = document_node_definitions::resolve_proto_node_type(graphene_std::graphic::index_elements::IDENTIFIER).expect("Index Elements node should exist");
|
||||
|
||||
let mut resulting_layers: Vec<NodeId> = Vec::new();
|
||||
|
||||
for layer in selected_layers {
|
||||
let style = self.network_interface.document_metadata().layer_vector_data.get(&layer).map(|arc| arc.style.clone());
|
||||
let Some(style) = style else {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
};
|
||||
|
||||
let has_fill = !matches!(style.fill, Fill::None);
|
||||
// `style.stroke` is `Some` whenever a `Stroke` node is in the chain, even with weight 0 or a transparent color.
|
||||
// So `is_some()` would treat invisibly-stroked fill-only layers as having a stroke.
|
||||
let has_stroke = style.stroke.as_ref().is_some_and(|s| s.has_renderable_stroke());
|
||||
|
||||
// No stroke means there's nothing to solidify. Fill-only layers are already in the desired form, so skip.
|
||||
if !has_stroke {
|
||||
resulting_layers.push(layer.to_node());
|
||||
continue;
|
||||
}
|
||||
|
||||
let solidify_id = NodeId::new();
|
||||
self.network_interface.insert_node(solidify_id, solidify_stroke_definition.default_node_template(), &[]);
|
||||
self.network_interface.move_node_to_chain_start(&solidify_id, layer, &[], false);
|
||||
|
||||
if has_fill && has_stroke {
|
||||
let (existing_index, new_index) = (0_f64, 1_f64);
|
||||
|
||||
let existing_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(existing_index), false))]);
|
||||
let existing_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(existing_index_id, existing_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&existing_index_id, layer, &[], false);
|
||||
|
||||
let parent = layer.parent(self.metadata()).unwrap_or(LayerNodeIdentifier::ROOT_PARENT);
|
||||
let insert_index = parent.children(self.metadata()).position(|c| c == layer).unwrap_or(0);
|
||||
|
||||
let new_layer_id = NodeId::new();
|
||||
let new_layer = ModifyInputsContext::new(&mut self.network_interface, responses).create_layer(new_layer_id);
|
||||
self.network_interface.move_layer_to_stack(new_layer, parent, insert_index, &[]);
|
||||
|
||||
// Copy the original layer's stored name so the new layer shares it
|
||||
let original_name = self
|
||||
.network_interface
|
||||
.node_metadata(&layer.to_node(), &[])
|
||||
.map(|m| m.persistent_metadata.display_name.clone())
|
||||
.unwrap_or_default();
|
||||
if !original_name.is_empty() {
|
||||
self.network_interface.set_display_name(&new_layer_id, original_name, &[]);
|
||||
}
|
||||
|
||||
let new_index_template = index_elements_definition.node_template_input_override([None, Some(NodeInput::value(TaggedValue::F64(new_index), false))]);
|
||||
let new_index_id = NodeId::new();
|
||||
self.network_interface.insert_node(new_index_id, new_index_template, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&new_index_id, new_layer, &[], false);
|
||||
|
||||
self.network_interface.create_wire(&OutputConnector::node(solidify_id, 0), &InputConnector::node(new_index_id, 0), &[]);
|
||||
|
||||
resulting_layers.push(layer.to_node());
|
||||
resulting_layers.push(new_layer.to_node());
|
||||
} else {
|
||||
resulting_layers.push(layer.to_node());
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: resulting_layers });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Helper method for MoveSelectedLayersTo message.
|
||||
/// Handles moving selected layers to a new parent with proper transform preservation.
|
||||
fn handle_move_selected_layers_to(&mut self, parent: LayerNodeIdentifier, insert_index: usize, responses: &mut VecDeque<Message>) {
|
||||
@@ -3190,17 +3288,23 @@ impl DocumentMessageHandler {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.on_drag_drop(|_| {
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
DocumentMessage::GroupSelectedLayers { group_folder_type }.into()
|
||||
})
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
IconButton::new("NewLayer", 24)
|
||||
.tooltip_label("New Layer")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::CreateEmptyFolder))
|
||||
.on_update(|_| DocumentMessage::CreateEmptyFolder.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DuplicateSelectedLayers.into())
|
||||
.widget_instance(),
|
||||
IconButton::new("Trash", 24)
|
||||
.tooltip_label("Delete Selected")
|
||||
.tooltip_shortcut(action_shortcut!(DocumentMessageDiscriminant::DeleteSelectedLayers))
|
||||
.on_update(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.on_drag_drop(|_| DocumentMessage::DeleteSelectedLayers.into())
|
||||
.disabled(!has_selection)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
+2
-2
@@ -323,7 +323,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
|
||||
let layer = modify_inputs.create_layer(id);
|
||||
modify_inputs.insert_text(text, font, typesetting, layer);
|
||||
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke: Stroke::default() });
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
GraphOperationMessage::ResizeArtboard { layer, location, dimensions } => {
|
||||
@@ -486,7 +485,8 @@ struct ArtboardInfo {
|
||||
}
|
||||
|
||||
fn usvg_color(c: usvg::Color, a: f32) -> Color {
|
||||
Color::from_rgbaf32_unchecked(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
// `usvg::Color` channels are u8 sRGB display values (gamma-encoded); lift to linear-light for the internal `Color`
|
||||
Color::from_gamma_srgb_channels(c.red as f32 / 255., c.green as f32 / 255., c.blue as f32 / 255., a)
|
||||
}
|
||||
|
||||
fn usvg_transform(c: usvg::Transform) -> DAffine2 {
|
||||
|
||||
@@ -267,9 +267,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let transform = resolve_proto_node_type(graphene_std::transform_nodes::transform::IDENTIFIER)
|
||||
.expect("Transform node does not exist")
|
||||
.default_node_template();
|
||||
let stroke = resolve_proto_node_type(graphene_std::vector_nodes::stroke::IDENTIFIER)
|
||||
.expect("Stroke node does not exist")
|
||||
.default_node_template();
|
||||
let fill = resolve_proto_node_type(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
.expect("Fill node does not exist")
|
||||
.default_node_template();
|
||||
@@ -282,10 +279,6 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.insert_node(transform_id, transform, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&transform_id, layer, &[], self.import);
|
||||
|
||||
let stroke_id = NodeId::new();
|
||||
self.network_interface.insert_node(stroke_id, stroke, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&stroke_id, layer, &[], self.import);
|
||||
|
||||
let fill_id = NodeId::new();
|
||||
self.network_interface.insert_node(fill_id, fill, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&fill_id, layer, &[], self.import);
|
||||
|
||||
@@ -355,19 +355,21 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
responses.add(NodeGraphMessage::DeleteSelectedNodes { delete_children: true });
|
||||
}
|
||||
NodeGraphMessage::DeleteNodes { node_ids, delete_children } => {
|
||||
// Detect stroke proto nodes among the doomed nodes before they're gone, so the stroke-using tools'
|
||||
// Weight widgets can re-read the layer (they'll now read 0 px since the stroke node is missing).
|
||||
let any_stroke_deleted = node_ids.iter().any(|node_id| {
|
||||
// Detect stroke/fill proto nodes among the doomed nodes before they're gone so the tool control bars can re-sync
|
||||
let stroke = DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let fill = DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER);
|
||||
let any_fill_or_stroke_deleted = node_ids.iter().any(|node_id| {
|
||||
network_interface
|
||||
.reference(node_id, selection_network_path)
|
||||
.is_some_and(|reference| reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
|
||||
.is_some_and(|reference| reference == stroke || reference == fill)
|
||||
});
|
||||
network_interface.delete_nodes(node_ids, delete_children, selection_network_path);
|
||||
if any_stroke_deleted {
|
||||
if any_fill_or_stroke_deleted {
|
||||
responses.add(PenToolMessage::SelectionChanged);
|
||||
responses.add(FreehandToolMessage::SelectionChanged);
|
||||
responses.add(SplineToolMessage::SelectionChanged);
|
||||
responses.add(ShapeToolMessage::SelectionChanged);
|
||||
responses.add(TextToolMessage::SelectionChanged);
|
||||
}
|
||||
}
|
||||
// Deletes selected_nodes. If `reconnect` is true, then all children nodes (secondary input) of the selected nodes are deleted and the siblings (primary input/output) are reconnected.
|
||||
@@ -1740,21 +1742,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
|
||||
use graphene_std::vector::generator_nodes::*;
|
||||
|
||||
let is_fill = matches!(value, TaggedValue::Fill(_));
|
||||
let reference = network_interface.reference(&node_id, selection_network_path);
|
||||
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
|
||||
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
|
||||
let is_fill_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER));
|
||||
let is_shape_generator_node = reference.as_ref().is_some_and(|r| {
|
||||
[
|
||||
graphene_std::vector::generator_nodes::regular_polygon::IDENTIFIER,
|
||||
graphene_std::vector::generator_nodes::star::IDENTIFIER,
|
||||
graphene_std::vector::generator_nodes::arc::IDENTIFIER,
|
||||
graphene_std::vector::generator_nodes::spiral::IDENTIFIER,
|
||||
graphene_std::vector::generator_nodes::grid::IDENTIFIER,
|
||||
graphene_std::vector::generator_nodes::arrow::IDENTIFIER,
|
||||
]
|
||||
.into_iter()
|
||||
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
|
||||
[regular_polygon::IDENTIFIER, star::IDENTIFIER, arc::IDENTIFIER, spiral::IDENTIFIER, grid::IDENTIFIER, arrow::IDENTIFIER]
|
||||
.into_iter()
|
||||
.any(|id| *r == DefinitionIdentifier::ProtoNode(id))
|
||||
});
|
||||
|
||||
let input = NodeInput::value(value, false);
|
||||
@@ -1766,15 +1764,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
if is_fill {
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
if is_text_node {
|
||||
responses.add(TextToolMessage::SelectionChanged);
|
||||
}
|
||||
if is_stroke_node || is_shape_generator_node {
|
||||
// The dispatcher delivers each only to its tool when active, so this just covers all four stroke-using tools.
|
||||
if is_stroke_node || is_fill_node || is_shape_generator_node || is_text_node {
|
||||
responses.add(PenToolMessage::SelectionChanged);
|
||||
responses.add(FreehandToolMessage::SelectionChanged);
|
||||
responses.add(SplineToolMessage::SelectionChanged);
|
||||
responses.add(ShapeToolMessage::SelectionChanged);
|
||||
responses.add(TextToolMessage::SelectionChanged);
|
||||
}
|
||||
if network_interface.connected_to_output(&node_id, selection_network_path) {
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
|
||||
@@ -30,7 +30,7 @@ use graphene_std::text_nodes::StringCapitalization;
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{ArcType, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, GradientSpreadMethod, GradientStops, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, GradientSpreadMethod, GradientStops, GradientStopsUI, GradientType, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
|
||||
pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
|
||||
@@ -276,7 +276,7 @@ pub(crate) fn property_from_type(
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new("-")
|
||||
.tooltip_label(format!("Data Type: {concrete_type}"))
|
||||
.tooltip_label(concrete_type.to_string())
|
||||
.tooltip_description("This data can only be supplied through the node graph because no widget exists for its type.")
|
||||
.widget_instance(),
|
||||
]);
|
||||
@@ -1164,19 +1164,19 @@ pub fn color_widget(parameter_widgets_info: ParameterWidgetsInfo, color_button:
|
||||
match &**tagged_value {
|
||||
TaggedValue::Color(color) => widgets.push(
|
||||
color_button
|
||||
.value(match color {
|
||||
.value(FillChoiceUI::from(&match color {
|
||||
Some(color) => FillChoice::Solid(*color),
|
||||
None => FillChoice::None,
|
||||
})
|
||||
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid()), node_id, index))
|
||||
}))
|
||||
.on_update(update_value(|input: &ColorInput| TaggedValue::Color(input.value.as_solid().map(Color::from)), node_id, index))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
),
|
||||
TaggedValue::Gradient(stops) => widgets.push(
|
||||
color_button
|
||||
.value(FillChoice::Gradient(stops.clone()))
|
||||
.value(FillChoiceUI::from(&FillChoice::Gradient(stops.clone())))
|
||||
.on_update(update_value(
|
||||
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().cloned().unwrap_or_default()),
|
||||
|input: &ColorInput| TaggedValue::Gradient(input.value.as_gradient().map(GradientStops::from).unwrap_or_default()),
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
@@ -1417,7 +1417,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
|
||||
|
||||
// Build the shared spectrum widget (placed on the first non-exposed row)
|
||||
let spectrum_widget = (!spectrum_markers.is_empty()).then(|| {
|
||||
SpectrumInput::new(bw_track())
|
||||
SpectrumInput::new(GradientStopsUI::from(&bw_track()))
|
||||
.markers(spectrum_markers)
|
||||
.show_midpoints(false)
|
||||
.allow_insert(false)
|
||||
@@ -1591,7 +1591,7 @@ fn spectrum_slider_row(
|
||||
|
||||
let position_to_value = move |position: f64| value_min + position * value_range;
|
||||
row.push(
|
||||
SpectrumInput::new(track)
|
||||
SpectrumInput::new(GradientStopsUI::from(&track))
|
||||
.markers(vec![SpectrumMarker::new(position, 0.5, handle_color)])
|
||||
.show_midpoints(false)
|
||||
.allow_insert(false)
|
||||
@@ -2482,7 +2482,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
widgets_first_row.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets_first_row.push(
|
||||
ColorInput::default()
|
||||
.value(fill.clone().into())
|
||||
.value(FillChoiceUI::from(&FillChoice::from(fill.clone())))
|
||||
.on_update(move |x: &ColorInput| Message::Batched {
|
||||
messages: Box::new([
|
||||
match &fill2 {
|
||||
@@ -2508,7 +2508,7 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: FillInput::<Color>::INDEX,
|
||||
value: TaggedValue::Fill(x.value.to_fill(fill2.as_gradient())),
|
||||
value: TaggedValue::Fill(FillChoice::from(&x.value).to_fill(fill2.as_gradient())),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
|
||||
@@ -3,9 +3,9 @@ use crate::messages::portfolio::document::overlays::utility_types::OverlayContex
|
||||
use crate::messages::portfolio::document::utility_types::misc::{GridSnapping, GridType};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::DVec2;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
|
||||
fn grid_overlay_rectangular(document: &DocumentMessageHandler, overlay_context: &mut OverlayContext, spacing: DVec2) {
|
||||
let origin = document.snapping_state.grid.origin;
|
||||
@@ -231,7 +231,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
widgets.push(LayoutGroup::row(vec![TextLabel::new("Grid").bold(true).widget_instance()]));
|
||||
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Type").table_align(true).widget_instance(),
|
||||
TextLabel::new("Type").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
RadioInput::new(vec![
|
||||
RadioEntryData::new("rectangular").label("Rectangular").on_update(update_val(grid, |grid, _| {
|
||||
@@ -262,7 +262,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
]));
|
||||
|
||||
let mut color_widgets = vec![
|
||||
TextLabel::new("Display").table_align(true).widget_instance(),
|
||||
TextLabel::new("Display").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
];
|
||||
color_widgets.extend([
|
||||
@@ -274,12 +274,12 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
]);
|
||||
color_widgets.push(
|
||||
ColorInput::new(FillChoice::Solid(Color::from_hex_str(&grid.color).unwrap_or(Color::BLACK)))
|
||||
ColorInput::new(FillChoiceUI::Solid(SRGBA8::from_hex_str(&grid.color).unwrap_or(SRGBA8::BLACK)))
|
||||
.tooltip_label("Grid Display Color")
|
||||
.allow_none(false)
|
||||
.on_update(update_val::<ColorInput, _>(grid, |grid, color| {
|
||||
if let Some(color) = color.value.as_solid() {
|
||||
grid.color = format!("#{}", color.to_rgba_hex_srgb_from_gamma());
|
||||
if let Some(srgba) = color.value.as_solid() {
|
||||
grid.color = srgba.to_css_hex();
|
||||
}
|
||||
}))
|
||||
.widget_instance(),
|
||||
@@ -287,7 +287,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
widgets.push(LayoutGroup::row(color_widgets));
|
||||
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Origin").table_align(true).widget_instance(),
|
||||
TextLabel::new("Origin").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(grid.origin.x))
|
||||
.label("X")
|
||||
@@ -306,7 +306,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
|
||||
match grid.grid_type {
|
||||
GridType::Rectangular { spacing } => widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Spacing").table_align(true).widget_instance(),
|
||||
TextLabel::new("Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(spacing.x))
|
||||
.label("X")
|
||||
@@ -326,7 +326,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
])),
|
||||
GridType::Isometric { y_axis_spacing, angle_a, angle_b } => {
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Y Spacing").table_align(true).widget_instance(),
|
||||
TextLabel::new("Y Spacing").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(y_axis_spacing))
|
||||
.unit(" px")
|
||||
@@ -336,7 +336,7 @@ pub fn overlay_options(grid: &GridSnapping) -> Vec<LayoutGroup> {
|
||||
.widget_instance(),
|
||||
]));
|
||||
widgets.push(LayoutGroup::row(vec![
|
||||
TextLabel::new("Angles").table_align(true).widget_instance(),
|
||||
TextLabel::new("Angles").min_width(60).max_width(60).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(angle_a))
|
||||
.unit("°")
|
||||
|
||||
@@ -1040,7 +1040,7 @@ impl OverlayContext {
|
||||
}
|
||||
|
||||
let image_data = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&data), PATTERN_WIDTH as u32, PATTERN_HEIGHT as u32).unwrap();
|
||||
pattern_context.put_image_data(&image_data, 0., 0.).unwrap();
|
||||
pattern_context.put_image_data(&image_data, 0, 0).unwrap();
|
||||
let pattern = self.render_context.create_pattern_with_offscreen_canvas(&pattern_canvas, "repeat").unwrap().unwrap();
|
||||
|
||||
self.push_path(subpaths, transform);
|
||||
|
||||
+6
-6
@@ -94,8 +94,8 @@ impl TypeSource {
|
||||
/// The type to display in the tooltip label.
|
||||
pub fn resolved_type_tooltip_string(&self) -> String {
|
||||
match self {
|
||||
TypeSource::Compiled(compiled_type) => format!("Data Type: {}", compiled_type.nested_type()),
|
||||
TypeSource::TaggedValue(value_type) => format!("Data Type: {}", value_type.nested_type()),
|
||||
TypeSource::Compiled(compiled_type) => compiled_type.nested_type().to_string(),
|
||||
TypeSource::TaggedValue(value_type) => value_type.nested_type().to_string(),
|
||||
TypeSource::Unknown => "Unknown Data Type".to_string(),
|
||||
TypeSource::Invalid => "Invalid Type Combination".to_string(),
|
||||
TypeSource::Error(_) => "Error Getting Data Type".to_string(),
|
||||
@@ -253,8 +253,8 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
let number_of_inputs = self.number_of_inputs(node_id, network_path);
|
||||
implementations
|
||||
.iter()
|
||||
.filter_map(|(node_io, _)| {
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
// Check if this NodeIOTypes implementation is valid for the other inputs
|
||||
let valid_implementation = (0..number_of_inputs).filter(|iterator_index| iterator_index != input_index).all(|iterator_index| {
|
||||
let input_type = self.input_type_not_invalid(&InputConnector::node(*node_id, iterator_index), network_path);
|
||||
@@ -293,8 +293,8 @@ impl NodeNetworkInterface {
|
||||
let valid_output_types = self.valid_output_types(&OutputConnector::node(*node_id, 0), network_path);
|
||||
|
||||
implementations
|
||||
.iter()
|
||||
.filter_map(|(node_io, _)| {
|
||||
.keys()
|
||||
.filter_map(|node_io| {
|
||||
if !valid_output_types.iter().any(|output_type| output_type.nested_type() == node_io.return_value.nested_type()) {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use super::persistent_state::PersistentStateMessage;
|
||||
use super::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::portfolio::document::utility_types::clipboards::Clipboard;
|
||||
use crate::messages::portfolio::utility_types::FontCatalog;
|
||||
use crate::messages::prelude::*;
|
||||
@@ -178,6 +178,7 @@ pub enum PortfolioMessage {
|
||||
bounds: ExportBounds,
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
animation: Option<AnimationExport>,
|
||||
},
|
||||
SubmitActiveGraphRender,
|
||||
SubmitGraphRender {
|
||||
|
||||
@@ -999,13 +999,10 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
|
||||
// Add default fill and stroke to the layer
|
||||
let fill_color = Color::WHITE;
|
||||
let stroke_color = Color::BLACK;
|
||||
|
||||
let fill = graphene_std::vector::style::Fill::solid(fill_color.to_gamma_srgb());
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(stroke_color.to_gamma_srgb()), DEFAULT_STROKE_WIDTH);
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
// Create new point ids and add those into the existing Vector path
|
||||
@@ -1444,6 +1441,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
animation,
|
||||
} => {
|
||||
let document_id = self.active_document_id.expect("Tried to render non-existent document");
|
||||
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
|
||||
@@ -1454,6 +1452,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
bounds,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
animation,
|
||||
..Default::default()
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
|
||||
@@ -34,6 +34,7 @@ impl FontCatalog {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FontCatalogFamily {
|
||||
/// The font family name.
|
||||
@@ -55,6 +56,7 @@ impl FontCatalogFamily {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FontCatalogStyle {
|
||||
pub weight: u32,
|
||||
@@ -88,7 +90,7 @@ impl FontCatalogStyle {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(PartialEq, Eq, Hash, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PanelType {
|
||||
Welcome,
|
||||
@@ -124,7 +126,7 @@ impl PanelType {
|
||||
pub struct PanelGroupId(pub u64);
|
||||
|
||||
/// Which edge of a panel group to split on when docking a dragged panel.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum DockingSplitDirection {
|
||||
Left,
|
||||
|
||||
@@ -1,74 +1,76 @@
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::TransactionStatus;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::utility_types::DocumentToolData;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ToolColorType {
|
||||
Primary,
|
||||
Secondary,
|
||||
Custom,
|
||||
}
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// Color selector widgets seen in [`LayoutTarget::ToolOptions`] bar.
|
||||
pub struct ToolColorOptions {
|
||||
pub custom_color: Option<Color>,
|
||||
pub primary_working_color: Option<Color>,
|
||||
pub secondary_working_color: Option<Color>,
|
||||
pub color_type: ToolColorType,
|
||||
/// The fill/stroke value shown in the swatch. `None` = mixed across selected layers.
|
||||
pub fill_choice: Option<FillChoice>,
|
||||
/// The checkbox state. `None` = mixed across selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// When set, `fill_choice` is a working-color fallback (vs. a layer-derived saved color) and is refreshed live by `WorkingColorChanged`.
|
||||
pub tracks_working_color: bool,
|
||||
}
|
||||
|
||||
impl Default for ToolColorOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Primary,
|
||||
custom_color: Some(Color::BLACK),
|
||||
primary_working_color: Some(Color::BLACK),
|
||||
secondary_working_color: Some(Color::WHITE),
|
||||
fill_choice: Some(FillChoice::Solid(Color::BLACK)),
|
||||
enabled: Some(true),
|
||||
tracks_working_color: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ToolColorOptions {
|
||||
pub fn new_primary() -> Self {
|
||||
pub fn new_enabled() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn new_secondary() -> Self {
|
||||
pub fn new_disabled() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Secondary,
|
||||
..Default::default()
|
||||
fill_choice: Some(FillChoice::None),
|
||||
enabled: Some(false),
|
||||
tracks_working_color: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_none() -> Self {
|
||||
Self {
|
||||
color_type: ToolColorType::Custom,
|
||||
custom_color: None,
|
||||
..Default::default()
|
||||
}
|
||||
/// True when the slot is actively applied, i.e. `enabled` is `Some(true)`.
|
||||
/// `None` (mixed) and `Some(false)` both count as not actively applied.
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.enabled == Some(true)
|
||||
}
|
||||
|
||||
/// The active solid color, suitable for storing in a working color or downstream rendering input.
|
||||
pub fn active_color(&self) -> Option<Color> {
|
||||
match self.color_type {
|
||||
ToolColorType::Custom => self.custom_color,
|
||||
ToolColorType::Primary => self.primary_working_color,
|
||||
ToolColorType::Secondary => self.secondary_working_color,
|
||||
if !self.is_active() {
|
||||
return None;
|
||||
}
|
||||
self.fill_choice.as_ref()?.as_solid()
|
||||
}
|
||||
|
||||
pub fn apply_fill(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if let Some(color) = self.active_color() {
|
||||
let fill = graphene_std::vector::style::Fill::solid(color.to_gamma_srgb());
|
||||
if !self.is_active() {
|
||||
return;
|
||||
}
|
||||
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
|
||||
let fill = graphene_std::vector::style::Fill::Solid(*color);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_stroke(&self, weight: f64, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if let Some(color) = self.active_color() {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(color.to_gamma_srgb()), weight);
|
||||
if !self.is_active() {
|
||||
return;
|
||||
}
|
||||
if let Some(FillChoice::Solid(color)) = &self.fill_choice {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(*color), weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
@@ -76,49 +78,523 @@ impl ToolColorOptions {
|
||||
pub fn create_widgets(
|
||||
&self,
|
||||
label_text: impl Into<String>,
|
||||
color_allow_none: bool,
|
||||
reset_callback: impl Fn(&IconButton) -> Message + 'static + Send + Sync,
|
||||
radio_callback: fn(ToolColorType) -> WidgetCallback<()>,
|
||||
checkbox_callback: impl Fn(&CheckboxInput) -> Message + 'static + Send + Sync,
|
||||
color_callback: impl Fn(&ColorInput) -> Message + 'static + Send + Sync,
|
||||
) -> Vec<WidgetInstance> {
|
||||
let mut widgets = vec![TextLabel::new(label_text).widget_instance()];
|
||||
let checkbox_id = CheckboxId::new();
|
||||
// In the mixed state (`fill_choice` is `None`) the dash overlay covers the swatch, so the underlying widget value just drives the picker's initial position.
|
||||
// `FillChoice::None` gives it a neutral starting point.
|
||||
let mixed_color = self.fill_choice.is_none();
|
||||
// Convert the internal linear-light `FillChoice` to the JS-boundary `FillChoiceUI` (with `SRGBA8` colors) for the widget value.
|
||||
let widget_value = FillChoiceUI::from(self.fill_choice.as_ref().unwrap_or(&FillChoice::None));
|
||||
let mixed_enabled = self.enabled.is_none();
|
||||
// In the mixed-enabled state the underlying `checked` value is hidden behind the indeterminate dash.
|
||||
// The frontend's click handler sends `true` when the user resolves the mixed state by clicking.
|
||||
let checked = self.enabled.unwrap_or(false);
|
||||
|
||||
if !color_allow_none {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
} else {
|
||||
let reset = IconButton::new("CloseX", 12)
|
||||
.disabled(self.custom_color.is_none() && self.color_type == ToolColorType::Custom)
|
||||
.tooltip_label("Clear Color")
|
||||
.on_update(reset_callback);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(reset.widget_instance());
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
};
|
||||
|
||||
let entries = vec![
|
||||
("WorkingColorsPrimary", "Primary Working Color", ToolColorType::Primary),
|
||||
("WorkingColorsSecondary", "Secondary Working Color", ToolColorType::Secondary),
|
||||
("CustomColor", "Custom Color", ToolColorType::Custom),
|
||||
vec![
|
||||
CheckboxInput::new(checked).mixed(mixed_enabled).on_update(checkbox_callback).for_label(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextLabel::new(label_text).for_checkbox(checkbox_id).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
ColorInput::new(widget_value)
|
||||
.mixed(mixed_color)
|
||||
.min_width(48)
|
||||
.max_width(48)
|
||||
.narrow(true)
|
||||
.on_update(color_callback)
|
||||
.widget_instance(),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(icon, label, color_type)| {
|
||||
let mut entry = RadioEntryData::new(format!("{color_type:?}")).tooltip_label(label).icon(icon);
|
||||
entry.on_update = radio_callback(color_type);
|
||||
entry
|
||||
})
|
||||
.collect();
|
||||
let radio = RadioInput::new(entries).selected_index(Some(self.color_type.clone() as u32)).widget_instance();
|
||||
widgets.push(radio);
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
|
||||
let fill_choice = match self.active_color() {
|
||||
Some(color) => FillChoice::Solid(color.to_gamma_srgb()),
|
||||
None => FillChoice::None,
|
||||
};
|
||||
let color_button = ColorInput::new(fill_choice).allow_none(color_allow_none).on_update(color_callback);
|
||||
widgets.push(color_button.widget_instance());
|
||||
|
||||
widgets
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared per-tool state for drawing tools that produce a stroked-and-filled shape (Shape, Pen, Freehand, Spline).
|
||||
pub struct DrawingToolState {
|
||||
/// The current stroke weight. `None` = mixed across selected layers.
|
||||
pub line_weight: Option<f64>,
|
||||
/// Persistent default weight, updated when the user edits the weight while no layer is selected.
|
||||
pub default_line_weight: f64,
|
||||
/// Stroke alignment from the selection. `None` = mixed.
|
||||
pub stroke_align: Option<StrokeAlign>,
|
||||
/// Stroke cap from the selection. `None` = mixed.
|
||||
pub stroke_cap: Option<StrokeCap>,
|
||||
/// Stroke join from the selection. `None` = mixed.
|
||||
pub stroke_join: Option<StrokeJoin>,
|
||||
/// Stroke miter limit from the selection. `None` = mixed.
|
||||
pub miter_limit: Option<f64>,
|
||||
/// Paint order from the selection. `None` = mixed.
|
||||
pub paint_order: Option<PaintOrder>,
|
||||
/// Dash lengths from the selection. `None` = mixed.
|
||||
pub dash_lengths: Option<Vec<f64>>,
|
||||
/// Dash offset from the selection. `None` = mixed.
|
||||
pub dash_offset: Option<f64>,
|
||||
/// Set of layers we last synced from, used to detect real selection changes vs. internal node toggles.
|
||||
pub last_synced_selection: Vec<LayerNodeIdentifier>,
|
||||
/// The fill swatch's color, checkbox, and mixed state.
|
||||
pub fill: ToolColorOptions,
|
||||
/// The stroke swatch's color, checkbox, and mixed state.
|
||||
pub stroke: ToolColorOptions,
|
||||
/// When false (default), fill follows the secondary working color and stroke follows the primary; when true, the routing is reversed.
|
||||
/// Persisted per-tool. The Shape tool additionally persists it for each shape mode via its options.
|
||||
pub colors_swapped: bool,
|
||||
}
|
||||
|
||||
impl DrawingToolState {
|
||||
pub fn new(fill_enabled: bool) -> Self {
|
||||
Self {
|
||||
line_weight: Some(DEFAULT_STROKE_WIDTH),
|
||||
default_line_weight: DEFAULT_STROKE_WIDTH,
|
||||
stroke_align: Some(StrokeAlign::default()),
|
||||
stroke_cap: Some(StrokeCap::default()),
|
||||
stroke_join: Some(StrokeJoin::default()),
|
||||
miter_limit: Some(4.),
|
||||
paint_order: Some(PaintOrder::default()),
|
||||
dash_lengths: Some(Vec::new()),
|
||||
dash_offset: Some(0.),
|
||||
last_synced_selection: Vec::new(),
|
||||
fill: if fill_enabled { ToolColorOptions::new_enabled() } else { ToolColorOptions::new_disabled() },
|
||||
stroke: ToolColorOptions::new_enabled(),
|
||||
colors_swapped: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The line weight to apply, falling back to the persistent default when [`Self::line_weight`] is `None` (mixed).
|
||||
pub fn effective_line_weight(&self) -> f64 {
|
||||
self.line_weight.unwrap_or(self.default_line_weight)
|
||||
}
|
||||
|
||||
/// Dash lengths to apply, falling back to empty when [`Self::dash_lengths`] is `None` (mixed).
|
||||
pub fn effective_dash_lengths(&self) -> Vec<f64> {
|
||||
self.dash_lengths.clone().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Applies a stroke to a freshly created `layer` using the tool's currently selected color, weight, and stroke options (align, cap, join, etc.).
|
||||
/// Used by the drawing tools at shape-creation time so new shapes inherit the popover's options instead of defaulting to the `Stroke` struct's defaults.
|
||||
pub fn apply_stroke_to_new_layer(&self, layer: LayerNodeIdentifier, responses: &mut VecDeque<Message>) {
|
||||
if !self.stroke.is_active() {
|
||||
return;
|
||||
}
|
||||
let Some(FillChoice::Solid(color)) = &self.stroke.fill_choice else { return };
|
||||
let stroke = graphene_std::vector::style::Stroke {
|
||||
color: Some(*color),
|
||||
weight: self.effective_line_weight(),
|
||||
align: self.stroke_align.unwrap_or_default(),
|
||||
cap: self.stroke_cap.unwrap_or_default(),
|
||||
join: self.stroke_join.unwrap_or_default(),
|
||||
join_miter_limit: self.miter_limit.unwrap_or(4.),
|
||||
paint_order: self.paint_order.unwrap_or_default(),
|
||||
dash_lengths: self.effective_dash_lengths(),
|
||||
dash_offset: self.dash_offset.unwrap_or(0.),
|
||||
transform: glam::DAffine2::IDENTITY,
|
||||
};
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `FillChoice::Solid` from a color.
|
||||
pub fn solid(color: Color) -> FillChoice {
|
||||
FillChoice::Solid(color)
|
||||
}
|
||||
|
||||
/// The fill working color (the source for the fill swatch when nothing is selected).
|
||||
/// Defaults to secondary, swapped to primary when the per-tool [`DrawingToolState::colors_swapped`] flag is set.
|
||||
pub fn fill_working_color(global: &DocumentToolData, colors_swapped: bool) -> Color {
|
||||
if colors_swapped { global.primary_color } else { global.secondary_color }
|
||||
}
|
||||
|
||||
/// The stroke working color (the source for the stroke swatch when nothing is selected).
|
||||
/// Defaults to primary, swapped to secondary when the per-tool [`DrawingToolState::colors_swapped`] flag is set.
|
||||
pub fn stroke_working_color(global: &DocumentToolData, colors_swapped: bool) -> Color {
|
||||
if colors_swapped { global.secondary_color } else { global.primary_color }
|
||||
}
|
||||
|
||||
/// Syncs fill and stroke from the selection (or working colors when empty). With `selection_changed = false`, preserves display values
|
||||
/// for inactive states instead of resetting them. Returns `true` if anything changed.
|
||||
pub fn sync_color_options(
|
||||
drawing: &mut DrawingToolState,
|
||||
natural_fill_enabled: bool,
|
||||
natural_stroke_enabled: bool,
|
||||
global: &DocumentToolData,
|
||||
document: &DocumentMessageHandler,
|
||||
selection_changed: bool,
|
||||
) -> bool {
|
||||
let fill_fallback = solid(fill_working_color(global, drawing.colors_swapped));
|
||||
let stroke_fallback = solid(stroke_working_color(global, drawing.colors_swapped));
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
// FILL
|
||||
|
||||
let new_fill = if let Some(state) = graph_modification_utils::selected_fill_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working) = match &state.fill_choice {
|
||||
Some(choice) if active => (Some(choice.clone()), false),
|
||||
Some(_) if selection_changed => (Some(fill_fallback.clone()), true),
|
||||
Some(_) => (drawing.fill.fill_choice.clone(), drawing.fill.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working)
|
||||
} else {
|
||||
// On a real deselect, revert to the working color; otherwise preserve the displayed value.
|
||||
let display_choice = if selection_changed { Some(fill_fallback) } else { drawing.fill.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { drawing.fill.tracks_working_color };
|
||||
(Some(natural_fill_enabled), display_choice, tracks_working)
|
||||
};
|
||||
if drawing.fill.enabled != new_fill.0 || drawing.fill.fill_choice != new_fill.1 || drawing.fill.tracks_working_color != new_fill.2 {
|
||||
drawing.fill.enabled = new_fill.0;
|
||||
drawing.fill.fill_choice = new_fill.1;
|
||||
drawing.fill.tracks_working_color = new_fill.2;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
// STROKE
|
||||
|
||||
let new_stroke = if let Some(state) = graph_modification_utils::selected_stroke_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working) = match state.optional_color {
|
||||
Some(color) if active => (Some(color.map_or(FillChoice::None, FillChoice::Solid)), false),
|
||||
Some(_) if selection_changed => (Some(stroke_fallback.clone()), true),
|
||||
Some(_) => (drawing.stroke.fill_choice.clone(), drawing.stroke.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working)
|
||||
} else {
|
||||
let display_choice = if selection_changed { Some(stroke_fallback) } else { drawing.stroke.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { drawing.stroke.tracks_working_color };
|
||||
(Some(natural_stroke_enabled), display_choice, tracks_working)
|
||||
};
|
||||
if drawing.stroke.enabled != new_stroke.0 || drawing.stroke.fill_choice != new_stroke.1 || drawing.stroke.tracks_working_color != new_stroke.2 {
|
||||
drawing.stroke.enabled = new_stroke.0;
|
||||
drawing.stroke.fill_choice = new_stroke.1;
|
||||
drawing.stroke.tracks_working_color = new_stroke.2;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// Full SelectionChanged update for a drawing tool: syncs fill/stroke colors and the stroke weight. Returns `true` if the layout needs refreshing.
|
||||
pub fn sync_drawing_state(drawing: &mut DrawingToolState, natural_fill_enabled: bool, natural_stroke_enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler) -> bool {
|
||||
let selection_changed = selection_changed_since_last_sync(&mut drawing.last_synced_selection, document);
|
||||
let mut needs_refresh = sync_color_options(drawing, natural_fill_enabled, natural_stroke_enabled, global, document, selection_changed);
|
||||
|
||||
let new_line_weight = match compute_weight_sync(document) {
|
||||
WeightSyncOutcome::Set(weight) => Some(weight),
|
||||
WeightSyncOutcome::Mixed => None,
|
||||
// On a real selection change, revert to the default; otherwise preserve.
|
||||
WeightSyncOutcome::NoStrokes | WeightSyncOutcome::NoSelection => {
|
||||
if selection_changed {
|
||||
Some(drawing.default_line_weight)
|
||||
} else {
|
||||
drawing.line_weight
|
||||
}
|
||||
}
|
||||
};
|
||||
if drawing.line_weight != new_line_weight {
|
||||
drawing.line_weight = new_line_weight;
|
||||
needs_refresh = true;
|
||||
}
|
||||
|
||||
needs_refresh |= sync_stroke_options(drawing, document);
|
||||
|
||||
needs_refresh
|
||||
}
|
||||
|
||||
/// Reads the stroke proto-node inputs (align, cap, join, miter limit, paint order, dash lengths, dash offset) across the selection and updates
|
||||
/// the matching fields on `drawing`. Each field becomes `None` (mixed) when selected strokes disagree. With no selection, fields are left as-is.
|
||||
fn sync_stroke_options(drawing: &mut DrawingToolState, document: &DocumentMessageHandler) -> bool {
|
||||
let strokes: Vec<_> = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.filter_map(|layer| graph_modification_utils::get_stroke_options(layer, &document.network_interface))
|
||||
.collect();
|
||||
if strokes.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
fn unanimous<T: PartialEq + Clone>(values: impl IntoIterator<Item = T>) -> Option<T> {
|
||||
let mut iter = values.into_iter();
|
||||
let first = iter.next()?;
|
||||
iter.all(|v| v == first).then_some(first)
|
||||
}
|
||||
|
||||
let new_align = unanimous(strokes.iter().map(|s| s.align));
|
||||
let new_cap = unanimous(strokes.iter().map(|s| s.cap));
|
||||
let new_join = unanimous(strokes.iter().map(|s| s.join));
|
||||
let new_miter = unanimous(strokes.iter().map(|s| s.miter_limit));
|
||||
let new_paint_order = unanimous(strokes.iter().map(|s| s.paint_order));
|
||||
let new_dash_lengths = unanimous(strokes.iter().map(|s| &s.dash_lengths)).cloned();
|
||||
let new_dash_offset = unanimous(strokes.iter().map(|s| s.dash_offset));
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
if drawing.stroke_align != new_align {
|
||||
drawing.stroke_align = new_align;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.stroke_cap != new_cap {
|
||||
drawing.stroke_cap = new_cap;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.stroke_join != new_join {
|
||||
drawing.stroke_join = new_join;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.miter_limit != new_miter {
|
||||
drawing.miter_limit = new_miter;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.paint_order != new_paint_order {
|
||||
drawing.paint_order = new_paint_order;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.dash_lengths != new_dash_lengths {
|
||||
drawing.dash_lengths = new_dash_lengths;
|
||||
changed = true;
|
||||
}
|
||||
if drawing.dash_offset != new_dash_offset {
|
||||
drawing.dash_offset = new_dash_offset;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// Same as [`sync_color_options`] but for tools that only have a fill option (e.g., text). The fill follows the given working color when nothing is selected.
|
||||
pub fn sync_fill_only(fill: &mut ToolColorOptions, natural_fill_enabled: bool, fill_color: Color, document: &DocumentMessageHandler, selection_changed: bool) -> bool {
|
||||
let fill_fallback = solid(fill_color);
|
||||
|
||||
let new_fill = if let Some(state) = graph_modification_utils::selected_fill_state(document) {
|
||||
let active = state.enabled == Some(true);
|
||||
let (display_choice, tracks_working_color) = match &state.fill_choice {
|
||||
Some(choice) if active => (Some(choice.clone()), false),
|
||||
Some(_) if selection_changed => (Some(fill_fallback.clone()), true),
|
||||
Some(_) => (fill.fill_choice.clone(), fill.tracks_working_color),
|
||||
None => (None, true),
|
||||
};
|
||||
(state.enabled, display_choice, tracks_working_color)
|
||||
} else {
|
||||
let display_choice = if selection_changed { Some(fill_fallback) } else { fill.fill_choice.clone() };
|
||||
let tracks_working = if selection_changed { true } else { fill.tracks_working_color };
|
||||
(Some(natural_fill_enabled), display_choice, tracks_working)
|
||||
};
|
||||
|
||||
if fill.enabled != new_fill.0 || fill.fill_choice != new_fill.1 || fill.tracks_working_color != new_fill.2 {
|
||||
fill.enabled = new_fill.0;
|
||||
fill.fill_choice = new_fill.1;
|
||||
fill.tracks_working_color = new_fill.2;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// True if at least one (non-artboard) layer is currently selected.
|
||||
pub fn has_selection(document: &DocumentMessageHandler) -> bool {
|
||||
document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers_except_artboards(&document.network_interface)
|
||||
.next()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Applies a user-picked fill (gradient or solid). With a selection, writes to the layers; with none, pushes a solid to the swap-routed working color slot.
|
||||
pub fn apply_fill_color_pick(drawing: &mut DrawingToolState, fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
apply_fill_only_color_pick(&mut drawing.fill, fill_choice, drawing.colors_swapped, document, responses);
|
||||
}
|
||||
|
||||
/// Single-slot variant of [`apply_fill_color_pick`] (e.g. for text). `slot_is_primary` says which working color this slot binds to.
|
||||
pub fn apply_fill_only_color_pick(fill: &mut ToolColorOptions, fill_choice: FillChoice, slot_is_primary: bool, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fill.fill_choice = Some(fill_choice.clone());
|
||||
fill.enabled = Some(true);
|
||||
fill.tracks_working_color = false;
|
||||
if has_selection(document) {
|
||||
if document.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
graph_modification_utils::set_fill_for_selected_layers(fill_choice, document, responses);
|
||||
} else if let FillChoice::Solid(color) = fill_choice {
|
||||
responses.add(ToolMessage::SelectWorkingColor { color, primary: slot_is_primary });
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-picked stroke color. With a selection, writes to the layers; with none, pushes to the swap-routed working color slot.
|
||||
pub fn apply_stroke_color_pick(drawing: &mut DrawingToolState, color: Option<Color>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke.fill_choice = Some(color.map_or(FillChoice::None, FillChoice::Solid));
|
||||
drawing.stroke.enabled = Some(true);
|
||||
drawing.stroke.tracks_working_color = false;
|
||||
if has_selection(document) {
|
||||
if document.network_interface.transaction_status() == TransactionStatus::Finished {
|
||||
responses.add(DocumentMessage::StartTransaction);
|
||||
}
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(color, drawing.effective_line_weight(), document, responses);
|
||||
} else if let Some(color) = color {
|
||||
responses.add(ToolMessage::SelectWorkingColor {
|
||||
color,
|
||||
primary: !drawing.colors_swapped,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the fill checkbox: re-applies the preserved color when enabled, removes the fill node when disabled.
|
||||
pub fn apply_fill_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
apply_fill_only_enabled(&mut drawing.fill, enabled, fill_working_color(global, drawing.colors_swapped), document, responses);
|
||||
}
|
||||
|
||||
/// Single-slot variant of [`apply_fill_enabled`]. `working_color` is the fallback used when re-ticking or unticking from a mixed state.
|
||||
pub fn apply_fill_only_enabled(fill: &mut ToolColorOptions, enabled: bool, working_color: Color, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
fill.enabled = Some(enabled);
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
if enabled {
|
||||
// Mixed re-tick has no per-layer color to restore; fall back to the working color and keep tracking it.
|
||||
let fill_choice = fill.fill_choice.clone().unwrap_or_else(|| {
|
||||
fill.tracks_working_color = true;
|
||||
solid(working_color)
|
||||
});
|
||||
fill.fill_choice = Some(fill_choice.clone());
|
||||
graph_modification_utils::set_fill_for_selected_layers(fill_choice, document, responses);
|
||||
} else {
|
||||
// Unticking from mixed: capture the working color as the saved value so the swatch keeps following the link.
|
||||
if fill.fill_choice.is_none() {
|
||||
fill.fill_choice = Some(solid(working_color));
|
||||
fill.tracks_working_color = true;
|
||||
}
|
||||
graph_modification_utils::remove_fill_for_selected_layers(document, responses);
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggles the stroke checkbox: mirrors [`apply_fill_enabled`].
|
||||
pub fn apply_stroke_enabled(drawing: &mut DrawingToolState, enabled: bool, global: &DocumentToolData, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke.enabled = Some(enabled);
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
if enabled {
|
||||
let stroke_choice = drawing.stroke.fill_choice.clone().unwrap_or_else(|| {
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
solid(stroke_working_color(global, drawing.colors_swapped))
|
||||
});
|
||||
drawing.stroke.fill_choice = Some(stroke_choice.clone());
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(stroke_choice.as_solid(), drawing.effective_line_weight(), document, responses);
|
||||
} else {
|
||||
if drawing.stroke.fill_choice.is_none() {
|
||||
drawing.stroke.fill_choice = Some(solid(stroke_working_color(global, drawing.colors_swapped)));
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
}
|
||||
graph_modification_utils::remove_stroke_for_selected_layers(document, responses);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a user-edited stroke weight to the selection, also persisting it as the no-selection default.
|
||||
pub fn apply_line_weight(drawing: &mut DrawingToolState, line_weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.line_weight = Some(line_weight);
|
||||
if !has_selection(document) {
|
||||
drawing.default_line_weight = line_weight;
|
||||
}
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, document, responses);
|
||||
}
|
||||
|
||||
/// Propagates working colors to the tool's swatches. With no selection both slots refresh; with a selection, only slots tracking the working color.
|
||||
pub fn apply_working_colors(drawing: &mut DrawingToolState, global: &DocumentToolData, document: &DocumentMessageHandler) {
|
||||
refresh_slot_working_color(&mut drawing.fill, fill_working_color(global, drawing.colors_swapped), document);
|
||||
refresh_slot_working_color(&mut drawing.stroke, stroke_working_color(global, drawing.colors_swapped), document);
|
||||
}
|
||||
|
||||
/// Refreshes a single swatch from the given working color, subject to the rules in [`apply_working_colors`].
|
||||
pub fn refresh_slot_working_color(slot: &mut ToolColorOptions, working_color: Color, document: &DocumentMessageHandler) {
|
||||
if slot.fill_choice.is_some() && (!has_selection(document) || slot.tracks_working_color) {
|
||||
slot.fill_choice = Some(solid(working_color));
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the tool's swatches to the working colors. Called on tool deactivation and shape-mode changes.
|
||||
pub fn reset_colors_on_deactivation(drawing: &mut DrawingToolState, global: &DocumentToolData) {
|
||||
drawing.fill.fill_choice = Some(solid(fill_working_color(global, drawing.colors_swapped)));
|
||||
drawing.stroke.fill_choice = Some(solid(stroke_working_color(global, drawing.colors_swapped)));
|
||||
drawing.fill.tracks_working_color = true;
|
||||
drawing.stroke.tracks_working_color = true;
|
||||
}
|
||||
|
||||
/// Handles the "Swap Fill/Stroke" button. Stroke can only hold a solid color, so a gradient fill collapses to `None` when moved.
|
||||
pub fn swap_fill_and_stroke(drawing: &mut DrawingToolState, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.colors_swapped = !drawing.colors_swapped;
|
||||
|
||||
if has_selection(document) {
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
}
|
||||
|
||||
// The new fill takes the old stroke's value as-is; the new stroke takes the old fill (with any gradient collapsed to `None`,
|
||||
// since stroke can only hold a solid color). `None` (mixed) on either side propagates as `None` to the other.
|
||||
let new_fill = drawing.stroke.fill_choice.clone();
|
||||
let new_stroke = drawing.fill.fill_choice.as_ref().map(|c| c.as_solid().map_or(FillChoice::None, FillChoice::Solid));
|
||||
let (new_fill_tracks, new_stroke_tracks) = (drawing.stroke.tracks_working_color, drawing.fill.tracks_working_color);
|
||||
|
||||
drawing.fill.fill_choice = new_fill.clone();
|
||||
drawing.stroke.fill_choice = new_stroke.clone();
|
||||
drawing.fill.tracks_working_color = new_fill_tracks;
|
||||
drawing.stroke.tracks_working_color = new_stroke_tracks;
|
||||
|
||||
if has_selection(document) {
|
||||
// Apply to layers only when we have a concrete value (`None` means mixed, no single value to broadcast).
|
||||
if drawing.fill.is_active()
|
||||
&& let Some(choice) = new_fill
|
||||
{
|
||||
graph_modification_utils::set_fill_for_selected_layers(choice, document, responses);
|
||||
}
|
||||
if drawing.stroke.is_active()
|
||||
&& let Some(choice) = new_stroke
|
||||
{
|
||||
graph_modification_utils::set_stroke_color_for_selected_layers(choice.as_solid(), drawing.effective_line_weight(), document, responses);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates the cache and returns `true` if the current selection differs from the last-synced one. Cache stays sorted to keep comparisons cheap.
|
||||
pub fn selection_changed_since_last_sync(last_synced: &mut Vec<LayerNodeIdentifier>, document: &DocumentMessageHandler) -> bool {
|
||||
let mut current: Vec<LayerNodeIdentifier> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
current.sort();
|
||||
|
||||
let changed = current != *last_synced;
|
||||
*last_synced = current;
|
||||
changed
|
||||
}
|
||||
|
||||
/// How the weight widget should update from inspecting selected layers' strokes.
|
||||
pub enum WeightSyncOutcome {
|
||||
/// All strokes share this weight.
|
||||
Set(f64),
|
||||
/// Stroke weights differ (or some layers lack a stroke): show the mixed dash.
|
||||
Mixed,
|
||||
/// Selection has no strokes: reset to the tool's default on a real selection change, otherwise preserve.
|
||||
NoStrokes,
|
||||
/// No selection: preserve the current value.
|
||||
NoSelection,
|
||||
}
|
||||
|
||||
/// Inspects the selection and returns how the weight widget should update.
|
||||
pub fn compute_weight_sync(document: &DocumentMessageHandler) -> WeightSyncOutcome {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
|
||||
if layers.is_empty() {
|
||||
return WeightSyncOutcome::NoSelection;
|
||||
}
|
||||
|
||||
let stroke_weights: Vec<f64> = layers.iter().filter_map(|l| graph_modification_utils::get_stroke_width(*l, &document.network_interface)).collect();
|
||||
|
||||
if stroke_weights.is_empty() {
|
||||
return WeightSyncOutcome::NoStrokes;
|
||||
}
|
||||
|
||||
if stroke_weights.len() != layers.len() {
|
||||
return WeightSyncOutcome::Mixed;
|
||||
}
|
||||
|
||||
let first = stroke_weights[0];
|
||||
let all_same = stroke_weights.iter().all(|&w| (w - first).abs() < f64::EPSILON * 100.);
|
||||
if all_same { WeightSyncOutcome::Set(first) } else { WeightSyncOutcome::Mixed }
|
||||
}
|
||||
@@ -15,7 +15,7 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::text::{Font, TypesettingConfig};
|
||||
use graphene_std::vector::misc::ManipulatorPointId;
|
||||
use graphene_std::vector::style::{Fill, Gradient};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, Gradient, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{GradientStops, PointId, SegmentId, VectorModificationType};
|
||||
use std::collections::VecDeque;
|
||||
|
||||
@@ -329,10 +329,10 @@ pub fn get_fill_color(layer: LayerNodeIdentifier, network_interface: &NodeNetwor
|
||||
let fill_index = 1;
|
||||
|
||||
let inputs = NodeGraphLayer::new(layer, network_interface).find_node_inputs(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER))?;
|
||||
let TaggedValue::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
|
||||
let &TaggedValue::Fill(Fill::Solid(color)) = inputs.get(fill_index)?.as_value()? else {
|
||||
return None;
|
||||
};
|
||||
Some(color.to_linear_srgb())
|
||||
Some(color)
|
||||
}
|
||||
|
||||
/// Get the current blend mode of a layer from the closest upstream "Blend Mode" node.
|
||||
@@ -493,6 +493,66 @@ pub fn get_stroke_width(layer: LayerNodeIdentifier, network_interface: &NodeNetw
|
||||
}
|
||||
}
|
||||
|
||||
/// Subset of Stroke node inputs read for the control bar's stroke options popover.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct StrokeOptionsState {
|
||||
pub align: StrokeAlign,
|
||||
pub cap: StrokeCap,
|
||||
pub join: StrokeJoin,
|
||||
pub miter_limit: f64,
|
||||
pub paint_order: PaintOrder,
|
||||
pub dash_lengths: Vec<f64>,
|
||||
pub dash_offset: f64,
|
||||
}
|
||||
|
||||
/// Reads the non-color stroke option inputs from a layer's Stroke proto node. Returns `None` when the layer has no Stroke node.
|
||||
/// Inputs that aren't a static value (e.g. wired to another node) fall back to per-field defaults so the layer still participates in the sync.
|
||||
pub fn get_stroke_options(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<StrokeOptionsState> {
|
||||
let stroke = &DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER);
|
||||
let layer_view = NodeGraphLayer::new(layer, network_interface);
|
||||
layer_view.upstream_node_id_from_name(stroke)?;
|
||||
let read = |index: usize| layer_view.find_input(stroke, index);
|
||||
|
||||
let align = match read(graphene_std::vector::stroke::AlignInput::INDEX) {
|
||||
Some(TaggedValue::StrokeAlign(value)) => *value,
|
||||
_ => StrokeAlign::default(),
|
||||
};
|
||||
let cap = match read(graphene_std::vector::stroke::CapInput::INDEX) {
|
||||
Some(TaggedValue::StrokeCap(value)) => *value,
|
||||
_ => StrokeCap::default(),
|
||||
};
|
||||
let join = match read(graphene_std::vector::stroke::JoinInput::INDEX) {
|
||||
Some(TaggedValue::StrokeJoin(value)) => *value,
|
||||
_ => StrokeJoin::default(),
|
||||
};
|
||||
let miter_limit = match read(graphene_std::vector::stroke::MiterLimitInput::INDEX) {
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 4.,
|
||||
};
|
||||
let paint_order = match read(graphene_std::vector::stroke::PaintOrderInput::INDEX) {
|
||||
Some(TaggedValue::PaintOrder(value)) => *value,
|
||||
_ => PaintOrder::default(),
|
||||
};
|
||||
let dash_lengths = match read(graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX) {
|
||||
Some(TaggedValue::F64Array(value)) => value.clone(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let dash_offset = match read(graphene_std::vector::stroke::DashOffsetInput::INDEX) {
|
||||
Some(TaggedValue::F64(value)) => *value,
|
||||
_ => 0.,
|
||||
};
|
||||
|
||||
Some(StrokeOptionsState {
|
||||
align,
|
||||
cap,
|
||||
join,
|
||||
miter_limit,
|
||||
paint_order,
|
||||
dash_lengths,
|
||||
dash_offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the node ID of a layer's upstream Stroke proto node, if one exists.
|
||||
pub fn get_stroke_id(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<NodeId> {
|
||||
NodeGraphLayer::new(layer, network_interface).upstream_node_id_from_name(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER))
|
||||
@@ -526,6 +586,176 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the `Fill` value from a layer's upstream Fill node.
|
||||
pub fn get_fill_value(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Fill> {
|
||||
let fill_index = graphene_std::vector::fill::FillInput::<Fill>::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER), fill_index)?;
|
||||
if let TaggedValue::Fill(fill) = tagged { Some(fill.clone()) } else { None }
|
||||
}
|
||||
|
||||
/// Returns the stroke color from a layer's upstream Stroke node.
|
||||
pub fn get_stroke_color(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Option<Color>> {
|
||||
let color_index = graphene_std::vector::stroke::ColorInput::INDEX;
|
||||
let tagged = NodeGraphLayer::new(layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER), color_index)?;
|
||||
if let TaggedValue::Color(color) = tagged { Some(*color) } else { None }
|
||||
}
|
||||
|
||||
/// Aggregated fill state across all selected non-artboard layers.
|
||||
pub struct SelectedFillState {
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub fill_choice: Option<FillChoice>,
|
||||
}
|
||||
|
||||
/// Aggregated stroke state across all selected non-artboard layers.
|
||||
pub struct SelectedStrokeState {
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub enabled: Option<bool>,
|
||||
/// `None` means mixed values between selected layers.
|
||||
pub optional_color: Option<Option<Color>>,
|
||||
}
|
||||
|
||||
/// Reads the fill state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Fill node is attached, even when that fill's value is [`FillChoice::None`].
|
||||
/// Unticked means there is no Fill node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_fill_state(document: &DocumentMessageHandler) -> Option<SelectedFillState> {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
|
||||
if get_fill_id(layer, &document.network_interface).is_none() {
|
||||
return (false, FillChoice::None);
|
||||
}
|
||||
let fill_choice = get_fill_value(layer, &document.network_interface).map_or(FillChoice::None, FillChoice::from);
|
||||
(true, fill_choice)
|
||||
});
|
||||
|
||||
let (initial_enabled, initial_choice) = per_layer.next()?;
|
||||
let mut enabled_mixed = false;
|
||||
let mut color_mixed = false;
|
||||
let mut comparison_enabled = initial_enabled;
|
||||
let mut comparison_choice = initial_choice;
|
||||
for (enabled, fill_choice) in per_layer {
|
||||
if enabled != initial_enabled {
|
||||
enabled_mixed = true;
|
||||
}
|
||||
if enabled {
|
||||
if comparison_enabled {
|
||||
if fill_choice != comparison_choice {
|
||||
color_mixed = true;
|
||||
}
|
||||
} else {
|
||||
comparison_enabled = true;
|
||||
comparison_choice = fill_choice;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(SelectedFillState {
|
||||
enabled: (!enabled_mixed).then_some(initial_enabled),
|
||||
fill_choice: (!color_mixed).then_some(comparison_choice),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads the stroke state across all selected non-artboard layers, including whether their enabled states or colors differ.
|
||||
/// "Enabled" tracks node attachment: a layer counts as enabled whenever a Stroke node is attached, even when that stroke's color is `None`.
|
||||
/// Unticked means there is no Stroke node. Returns `None` only when no layer is selected.
|
||||
pub fn selected_stroke_state(document: &DocumentMessageHandler) -> Option<SelectedStrokeState> {
|
||||
let selected_nodes = document.network_interface.selected_nodes();
|
||||
let mut per_layer = selected_nodes.selected_layers_except_artboards(&document.network_interface).map(|layer| {
|
||||
if get_stroke_id(layer, &document.network_interface).is_none() {
|
||||
return (false, None);
|
||||
}
|
||||
let color = get_stroke_color(layer, &document.network_interface).flatten();
|
||||
(true, color)
|
||||
});
|
||||
|
||||
let (initial_enabled, initial_color) = per_layer.next()?;
|
||||
let mut enabled_mixed = false;
|
||||
let mut color_mixed = false;
|
||||
let mut comparison_enabled = initial_enabled;
|
||||
let mut comparison_color = initial_color;
|
||||
for (enabled, color) in per_layer {
|
||||
if enabled != initial_enabled {
|
||||
enabled_mixed = true;
|
||||
}
|
||||
if enabled {
|
||||
if comparison_enabled {
|
||||
if color != comparison_color {
|
||||
color_mixed = true;
|
||||
}
|
||||
} else {
|
||||
comparison_enabled = true;
|
||||
comparison_color = color;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(SelectedStrokeState {
|
||||
enabled: (!enabled_mixed).then_some(initial_enabled),
|
||||
optional_color: (!color_mixed).then_some(comparison_color),
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the fill on all selected non-artboard layers, preserving gradient transform data when the layer already has a gradient fill.
|
||||
pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
let existing_gradient = get_fill_value(layer, &document.network_interface).and_then(|f| match f {
|
||||
Fill::Gradient(g) => Some(g),
|
||||
_ => None,
|
||||
});
|
||||
let fill = fill_choice.clone().to_fill(existing_gradient.as_ref());
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the stroke color on all selected non-artboard layers. Layers without an existing Stroke node get one created using
|
||||
/// the provided `weight`, so picking any color (including `None`) from an unticked stroke control bar entry both attaches
|
||||
/// the Stroke node and applies the chosen color.
|
||||
pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
let input_index = graphene_std::vector::stroke::ColorInput::INDEX;
|
||||
let value = TaggedValue::Color(color);
|
||||
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
|
||||
} else {
|
||||
let stroke = graphene_std::vector::style::Stroke::new(color, weight);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the Fill node from all selected non-artboard layers.
|
||||
pub fn remove_fill_for_selected_layers(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_fill_id(layer, &document.network_interface) {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![node_id],
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
/// Removes the Stroke node from all selected non-artboard layers.
|
||||
pub fn remove_stroke_for_selected_layers(document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
let layers: Vec<_> = document.network_interface.selected_nodes().selected_layers_except_artboards(&document.network_interface).collect();
|
||||
for layer in layers {
|
||||
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
|
||||
responses.add(NodeGraphMessage::DeleteNodes {
|
||||
node_ids: vec![node_id],
|
||||
delete_children: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
|
||||
/// Reads a specific input from the matching proto node on the first selected non-artboard layer that has one.
|
||||
/// Used by tool control bars to mirror per-shape parameters (sides, arc type, turns, etc.) from the selection
|
||||
/// into the control bar's input widget state without each call site re-implementing the layer iteration.
|
||||
@@ -589,9 +819,10 @@ impl<'a> NodeGraphLayer<'a> {
|
||||
self.network_interface.upstream_flow_back_from_nodes(vec![self.layer_node], &[], FlowType::HorizontalFlow)
|
||||
}
|
||||
|
||||
/// Node id of a node if it exists in the layer's primary flow
|
||||
/// Node id of a node if it exists in this specific layer's primary flow, stopping at the next layer upstream so a group doesn't incorrectly match its children's nodes.
|
||||
pub fn upstream_node_id_from_name(&self, identifier: &DefinitionIdentifier) -> Option<NodeId> {
|
||||
self.horizontal_layer_flow()
|
||||
.take_while(|&node_id| node_id == self.layer_node || !self.network_interface.is_layer(&node_id, &[]))
|
||||
.find(|node_id| self.network_interface.reference(node_id, &[]).is_some_and(|reference| reference == *identifier))
|
||||
}
|
||||
|
||||
|
||||
@@ -10,5 +10,6 @@ pub mod resize;
|
||||
pub mod shape_editor;
|
||||
pub mod shapes;
|
||||
pub mod snapping;
|
||||
pub mod stroke_options;
|
||||
pub mod transformation_cage;
|
||||
pub mod utility_functions;
|
||||
@@ -25,7 +25,7 @@ use std::collections::VecDeque;
|
||||
use std::f64::consts::{PI, TAU};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ShapeType {
|
||||
#[default]
|
||||
Polygon = 0,
|
||||
@@ -41,6 +41,26 @@ pub enum ShapeType {
|
||||
}
|
||||
|
||||
impl ShapeType {
|
||||
/// Every shape mode, in dropdown order. Used to seed per-mode default maps.
|
||||
pub const ALL: &[ShapeType] = &[
|
||||
ShapeType::Polygon,
|
||||
ShapeType::Star,
|
||||
ShapeType::Circle,
|
||||
ShapeType::Arc,
|
||||
ShapeType::Spiral,
|
||||
ShapeType::Grid,
|
||||
ShapeType::Arrow,
|
||||
ShapeType::Line, // KEEP THIS AT THE END
|
||||
ShapeType::Rectangle, // KEEP THIS AT THE END
|
||||
ShapeType::Ellipse, // KEEP THIS AT THE END
|
||||
];
|
||||
|
||||
/// True if this shape mode's fill checkbox is ticked by default when nothing is selected.
|
||||
/// Spiral/Grid/Line are open paths and default to fill-off, the closed shapes default to fill-on.
|
||||
pub fn defaults_to_fill(&self) -> bool {
|
||||
matches!(self, Self::Polygon | Self::Star | Self::Circle | Self::Arc | Self::Rectangle | Self::Ellipse | Self::Arrow)
|
||||
}
|
||||
|
||||
pub fn name(&self) -> String {
|
||||
(match self {
|
||||
Self::Polygon => "Polygon",
|
||||
@@ -50,9 +70,9 @@ impl ShapeType {
|
||||
Self::Spiral => "Spiral",
|
||||
Self::Grid => "Grid",
|
||||
Self::Arrow => "Arrow",
|
||||
Self::Line => "Line",
|
||||
Self::Rectangle => "Rectangle",
|
||||
Self::Ellipse => "Ellipse",
|
||||
Self::Line => "Line", // KEEP THIS AT THE END
|
||||
Self::Rectangle => "Rectangle", // KEEP THIS AT THE END
|
||||
Self::Ellipse => "Ellipse", // KEEP THIS AT THE END
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::color_selector::{DrawingToolState, apply_line_weight};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::NodeInputDecleration;
|
||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::vector::style::{PaintOrder, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
|
||||
/// All non-color stroke-related options surfaced in the control bar popover.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum StrokeOptionsUpdate {
|
||||
LineWeight(f64),
|
||||
Align(StrokeAlign),
|
||||
Cap(StrokeCap),
|
||||
Join(StrokeJoin),
|
||||
MiterLimit(f64),
|
||||
PaintOrder(PaintOrder),
|
||||
DashLengths(Vec<f64>),
|
||||
DashOffset(f64),
|
||||
}
|
||||
|
||||
/// Builds the control-bar popover button that opens the stroke options panel (weight, align, caps, joins, miter limit, paint order, dash).
|
||||
/// `to_message` adapts a [`StrokeOptionsUpdate`] into the calling tool's `UpdateOptions` message.
|
||||
pub fn create_stroke_options_popover_widget<F>(drawing: &DrawingToolState, disabled: bool, to_message: F) -> WidgetInstance
|
||||
where
|
||||
F: Fn(StrokeOptionsUpdate) -> Message + 'static + Send + Sync + Clone,
|
||||
{
|
||||
PopoverButton::new()
|
||||
.popover_layout(Layout(build_popover_rows(drawing, to_message)))
|
||||
.disabled(disabled)
|
||||
.tooltip_label("Stroke Options")
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
/// Dispatches a [`StrokeOptionsUpdate`] to the matching apply helper and updates `drawing` in lockstep.
|
||||
pub fn apply_stroke_option(drawing: &mut DrawingToolState, update: StrokeOptionsUpdate, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
match update {
|
||||
StrokeOptionsUpdate::LineWeight(weight) => apply_line_weight(drawing, weight, document, responses),
|
||||
StrokeOptionsUpdate::Align(align) => apply_stroke_align(drawing, align, document, responses),
|
||||
StrokeOptionsUpdate::Cap(cap) => apply_stroke_cap(drawing, cap, document, responses),
|
||||
StrokeOptionsUpdate::Join(join) => apply_stroke_join(drawing, join, document, responses),
|
||||
StrokeOptionsUpdate::MiterLimit(limit) => apply_miter_limit(drawing, limit, document, responses),
|
||||
StrokeOptionsUpdate::PaintOrder(order) => apply_paint_order(drawing, order, document, responses),
|
||||
StrokeOptionsUpdate::DashLengths(lengths) => apply_dash_lengths(drawing, lengths, document, responses),
|
||||
StrokeOptionsUpdate::DashOffset(offset) => apply_dash_offset(drawing, offset, document, responses),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_popover_rows<F>(drawing: &DrawingToolState, to_message: F) -> Vec<LayoutGroup>
|
||||
where
|
||||
F: Fn(StrokeOptionsUpdate) -> Message + 'static + Send + Sync + Clone,
|
||||
{
|
||||
// Miter limit only matters when the join is `Miter`; mixed (`None`) keeps the row visible so the user can still edit the value.
|
||||
let show_miter_limit = drawing.stroke_join != Some(StrokeJoin::Bevel) && drawing.stroke_join != Some(StrokeJoin::Round);
|
||||
// Mixed dash patterns (`None`) keep the offset row visible so the user can still edit the offset when at least some selected layers have dashes.
|
||||
let has_dash = drawing.dash_lengths.as_deref().is_none_or(|lengths| !lengths.is_empty());
|
||||
|
||||
let mut rows = vec![
|
||||
LayoutGroup::row(vec![TextLabel::new("Stroke").bold(true).widget_instance()]),
|
||||
LayoutGroup::row(weight_row(drawing.line_weight, to_message.clone())),
|
||||
LayoutGroup::row(dash_lengths_row(drawing.dash_lengths.as_deref(), to_message.clone())),
|
||||
];
|
||||
if has_dash {
|
||||
rows.push(LayoutGroup::row(dash_offset_row(drawing.dash_offset, to_message.clone())));
|
||||
}
|
||||
rows.push(LayoutGroup::row(enum_radio_row::<PaintOrder, _>("Order", drawing.paint_order, false, {
|
||||
let to_message = to_message.clone();
|
||||
move |value| to_message(StrokeOptionsUpdate::PaintOrder(value))
|
||||
})));
|
||||
rows.push(LayoutGroup::row(enum_radio_row::<StrokeAlign, _>("Align", drawing.stroke_align, false, {
|
||||
let to_message = to_message.clone();
|
||||
move |value| to_message(StrokeOptionsUpdate::Align(value))
|
||||
})));
|
||||
rows.push(LayoutGroup::row(enum_radio_row::<StrokeCap, _>("Cap", drawing.stroke_cap, false, {
|
||||
let to_message = to_message.clone();
|
||||
move |value| to_message(StrokeOptionsUpdate::Cap(value))
|
||||
})));
|
||||
rows.push(LayoutGroup::row(enum_radio_row::<StrokeJoin, _>("Join", drawing.stroke_join, false, {
|
||||
let to_message = to_message.clone();
|
||||
move |value| to_message(StrokeOptionsUpdate::Join(value))
|
||||
})));
|
||||
if show_miter_limit {
|
||||
rows.push(LayoutGroup::row(miter_limit_row(drawing.miter_limit, to_message)));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn weight_row<F>(weight: Option<f64>, to_message: F) -> Vec<WidgetInstance>
|
||||
where
|
||||
F: Fn(StrokeOptionsUpdate) -> Message + 'static + Send + Sync,
|
||||
{
|
||||
vec![
|
||||
TextLabel::new("Weight").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(weight)
|
||||
.unit(" px")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(move |number: &NumberInput| number.value.map_or(Message::NoOp, |value| to_message(StrokeOptionsUpdate::LineWeight(value))))
|
||||
.on_commit(|_| DocumentMessage::StartTransaction.into())
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
fn miter_limit_row<F>(limit: Option<f64>, to_message: F) -> Vec<WidgetInstance>
|
||||
where
|
||||
F: Fn(StrokeOptionsUpdate) -> Message + 'static + Send + Sync,
|
||||
{
|
||||
vec![
|
||||
TextLabel::new("Limit").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(limit)
|
||||
.min(0.)
|
||||
.on_update(move |number: &NumberInput| number.value.map_or(Message::NoOp, |value| to_message(StrokeOptionsUpdate::MiterLimit(value))))
|
||||
.on_commit(|_| DocumentMessage::StartTransaction.into())
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
fn enum_radio_row<E, F>(label_text: &str, current: Option<E>, disabled: bool, to_message: F) -> Vec<WidgetInstance>
|
||||
where
|
||||
E: ChoiceTypeStatic + 'static,
|
||||
F: Fn(E) -> Message + 'static + Send + Sync + Clone,
|
||||
{
|
||||
let entries = E::list()
|
||||
.iter()
|
||||
.flat_map(|section| section.iter())
|
||||
.map(|(value, meta)| {
|
||||
let to_message = to_message.clone();
|
||||
let value = *value;
|
||||
let entry = RadioEntryData::new(meta.name)
|
||||
.tooltip_label(meta.label)
|
||||
.tooltip_description(meta.description.unwrap_or_default())
|
||||
.on_update(move |_| to_message(value))
|
||||
.on_commit(|_| DocumentMessage::StartTransaction.into());
|
||||
if let Some(icon) = meta.icon { entry.icon(icon) } else { entry.label(meta.label) }
|
||||
})
|
||||
.collect();
|
||||
vec![
|
||||
TextLabel::new(label_text).table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
RadioInput::new(entries).selected_index(current.map(|c| c.as_u32())).disabled(disabled).widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
fn dash_lengths_row<F>(current: Option<&[f64]>, to_message: F) -> Vec<WidgetInstance>
|
||||
where
|
||||
F: Fn(StrokeOptionsUpdate) -> Message + 'static + Send + Sync,
|
||||
{
|
||||
let text = current
|
||||
.map(|values| values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
|
||||
.unwrap_or_else(|| "-".to_string());
|
||||
vec![
|
||||
TextLabel::new("Dash").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(text)
|
||||
.centered(true)
|
||||
.tooltip_label("Dash Pattern")
|
||||
.tooltip_description("Comma-separated dash and gap lengths.")
|
||||
.on_update(move |input: &TextInput| {
|
||||
let parsed = input.value.split(&[',', ' ']).filter(|piece| !piece.is_empty()).map(str::parse::<f64>).collect::<Result<Vec<_>, _>>();
|
||||
parsed.map_or(Message::NoOp, |lengths| to_message(StrokeOptionsUpdate::DashLengths(lengths)))
|
||||
})
|
||||
.on_commit(|_| DocumentMessage::StartTransaction.into())
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
fn dash_offset_row<F>(offset: Option<f64>, to_message: F) -> Vec<WidgetInstance>
|
||||
where
|
||||
F: Fn(StrokeOptionsUpdate) -> Message + 'static + Send + Sync,
|
||||
{
|
||||
vec![
|
||||
TextLabel::new("Offset").table_align(true).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(offset)
|
||||
.unit(" px")
|
||||
.on_update(move |number: &NumberInput| number.value.map_or(Message::NoOp, |value| to_message(StrokeOptionsUpdate::DashOffset(value))))
|
||||
.on_commit(|_| DocumentMessage::StartTransaction.into())
|
||||
.widget_instance(),
|
||||
]
|
||||
}
|
||||
|
||||
// =============
|
||||
// APPLY HELPERS
|
||||
// =============
|
||||
|
||||
pub fn apply_stroke_align(drawing: &mut DrawingToolState, align: StrokeAlign, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke_align = Some(align);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::AlignInput::INDEX, TaggedValue::StrokeAlign(align), responses);
|
||||
}
|
||||
|
||||
pub fn apply_stroke_cap(drawing: &mut DrawingToolState, cap: StrokeCap, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke_cap = Some(cap);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::CapInput::INDEX, TaggedValue::StrokeCap(cap), responses);
|
||||
}
|
||||
|
||||
pub fn apply_stroke_join(drawing: &mut DrawingToolState, join: StrokeJoin, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.stroke_join = Some(join);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::JoinInput::INDEX, TaggedValue::StrokeJoin(join), responses);
|
||||
}
|
||||
|
||||
pub fn apply_miter_limit(drawing: &mut DrawingToolState, limit: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.miter_limit = Some(limit);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::MiterLimitInput::INDEX, TaggedValue::F64(limit), responses);
|
||||
}
|
||||
|
||||
pub fn apply_paint_order(drawing: &mut DrawingToolState, order: PaintOrder, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.paint_order = Some(order);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::PaintOrderInput::INDEX, TaggedValue::PaintOrder(order), responses);
|
||||
}
|
||||
|
||||
pub fn apply_dash_lengths(drawing: &mut DrawingToolState, lengths: Vec<f64>, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_lengths = Some(lengths.clone());
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashLengthsInput::<List<f64>>::INDEX, TaggedValue::F64Array(lengths), responses);
|
||||
}
|
||||
|
||||
pub fn apply_dash_offset(drawing: &mut DrawingToolState, offset: f64, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||
drawing.dash_offset = Some(offset);
|
||||
set_stroke_input_for_selected(document, graphene_std::vector::stroke::DashOffsetInput::INDEX, TaggedValue::F64(offset), responses);
|
||||
}
|
||||
|
||||
fn set_stroke_input_for_selected(document: &DocumentMessageHandler, input_index: usize, value: TaggedValue, responses: &mut VecDeque<Message>) {
|
||||
graph_modification_utils::set_proto_node_input_for_selected_layers(document, graphene_std::vector::stroke::IDENTIFIER, input_index, value, responses);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::transform_layer::transform_layer_message_handler::TransformLayerMessageContext;
|
||||
use crate::messages::tool::utility_types::{HintData, ToolType};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
const ARTBOARD_OVERLAY_PROVIDER: OverlayProvider = |context| DocumentMessage::DrawArtboardOverlays { context }.into();
|
||||
@@ -280,7 +281,7 @@ impl MessageHandler<ToolMessage, ToolMessageContext<'_>> for ToolMessageHandler
|
||||
let r = (random_number >> 16) as u8;
|
||||
let g = (random_number >> 8) as u8;
|
||||
let b = random_number as u8;
|
||||
let random_color = Color::from_rgba8_srgb(r, g, b, 255);
|
||||
let random_color = Color::from(SRGBA8::new(r, g, b, 255));
|
||||
|
||||
if primary {
|
||||
document_data.primary_color = random_color;
|
||||
|
||||
@@ -4,12 +4,13 @@ use crate::messages::portfolio::document::graph_operation::transform_utils::get_
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, solid};
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::brush::brush_stroke::{BrushInputSample, BrushStroke, BrushStyle};
|
||||
use graphene_std::raster::BlendMode;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
|
||||
|
||||
const BRUSH_MAX_SIZE: f64 = 5000.;
|
||||
|
||||
@@ -73,13 +74,12 @@ pub enum BrushToolMessageOptionsUpdate {
|
||||
BlendMode(BlendMode),
|
||||
ChangeDiameter(f64),
|
||||
Color(Option<Color>),
|
||||
ColorType(ToolColorType),
|
||||
Diameter(f64),
|
||||
DrawMode(DrawMode),
|
||||
Flow(f64),
|
||||
Hardness(f64),
|
||||
Spacing(f64),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
WorkingColorsChanged,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -104,6 +104,17 @@ impl ToolMetadata for BrushTool {
|
||||
impl LayoutHolder for BrushTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = vec![
|
||||
ColorInput::new(FillChoiceUI::from(self.options.color.fill_choice.as_ref().unwrap_or(&FillChoice::None)))
|
||||
.mixed(self.options.color.fill_choice.is_none())
|
||||
.narrow(true)
|
||||
.on_update(|color: &ColorInput| {
|
||||
BrushToolMessage::UpdateOptions {
|
||||
options: BrushToolMessageOptionsUpdate::Color(color.value.as_solid().map(Color::from)),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
NumberInput::new(Some(self.options.diameter))
|
||||
.label("Diameter")
|
||||
.min(1.)
|
||||
@@ -170,33 +181,6 @@ impl LayoutHolder for BrushTool {
|
||||
.collect();
|
||||
widgets.push(RadioInput::new(draw_mode_entries).selected_index(Some(self.options.draw_mode as u32)).widget_instance());
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.color.create_widgets(
|
||||
"Color",
|
||||
false,
|
||||
|_| {
|
||||
BrushToolMessage::UpdateOptions {
|
||||
options: BrushToolMessageOptionsUpdate::Color(None),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
BrushToolMessage::UpdateOptions {
|
||||
options: BrushToolMessageOptionsUpdate::ColorType(color_type.clone()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
BrushToolMessage::UpdateOptions {
|
||||
options: BrushToolMessageOptionsUpdate::Color(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
|
||||
let blend_mode_entries: Vec<Vec<_>> = BlendMode::list()
|
||||
@@ -254,13 +238,13 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Brus
|
||||
BrushToolMessageOptionsUpdate::Flow(flow) => self.options.flow = flow,
|
||||
BrushToolMessageOptionsUpdate::Spacing(spacing) => self.options.spacing = spacing,
|
||||
BrushToolMessageOptionsUpdate::Color(color) => {
|
||||
self.options.color.custom_color = color;
|
||||
self.options.color.color_type = ToolColorType::Custom;
|
||||
// User picked a color: push to the global primary working color (no tool-local customization).
|
||||
if let Some(color) = color {
|
||||
responses.add(ToolMessage::SelectWorkingColor { color, primary: true });
|
||||
}
|
||||
}
|
||||
BrushToolMessageOptionsUpdate::ColorType(color_type) => self.options.color.color_type = color_type,
|
||||
BrushToolMessageOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.color.primary_working_color = primary;
|
||||
self.options.color.secondary_working_color = secondary;
|
||||
BrushToolMessageOptionsUpdate::WorkingColorsChanged => {
|
||||
self.options.color.fill_choice = Some(solid(context.global_tool_data.primary_color));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,9 +339,7 @@ impl Fsm for BrushToolFsmState {
|
||||
tool_options: &Self::ToolOptions,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) -> Self {
|
||||
let ToolActionMessageContext {
|
||||
document, global_tool_data, input, ..
|
||||
} = tool_action_data;
|
||||
let ToolActionMessageContext { document, input, .. } = tool_action_data;
|
||||
|
||||
let ToolMessage::Brush(event) = event else { return self };
|
||||
match (self, event) {
|
||||
@@ -450,7 +432,7 @@ impl Fsm for BrushToolFsmState {
|
||||
}
|
||||
(_, BrushToolMessage::WorkingColorChanged) => {
|
||||
responses.add(BrushToolMessage::UpdateOptions {
|
||||
options: BrushToolMessageOptionsUpdate::WorkingColors(Some(global_tool_data.primary_color), Some(global_tool_data.secondary_color)),
|
||||
options: BrushToolMessageOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::messages::frontend::utility_types::EyedropperPreviewImage;
|
||||
use crate::messages::tool::utility_types::DocumentToolData;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
@@ -233,8 +234,8 @@ fn update_cursor_preview_common(
|
||||
responses.add(FrontendMessage::UpdateEyedropperSamplingState {
|
||||
image,
|
||||
mouse_position: Some(input.mouse.position.into()),
|
||||
primary_color: "#".to_string() + global_tool_data.primary_color.to_rgb_hex_srgb().as_str(),
|
||||
secondary_color: "#".to_string() + global_tool_data.secondary_color.to_rgb_hex_srgb().as_str(),
|
||||
primary_color: SRGBA8::from(global_tool_data.primary_color).to_css_hex(),
|
||||
secondary_color: SRGBA8::from(global_tool_data.secondary_color).to_css_hex(),
|
||||
set_color_choice,
|
||||
});
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::tool::common_functionality::color_selector::solid;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use graphene_std::vector::style::Fill;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::{Fill, FillChoiceUI};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
pub struct FillTool {
|
||||
fsm_state: FillToolFsmState,
|
||||
primary_color: Color,
|
||||
}
|
||||
|
||||
#[impl_message(Message, ToolMessage, Fill)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FillToolMessage {
|
||||
// Standard messages
|
||||
Abort,
|
||||
@@ -22,6 +26,7 @@ pub enum FillToolMessage {
|
||||
PointerUp,
|
||||
FillPrimaryColor,
|
||||
FillSecondaryColor,
|
||||
SetColor { color: Option<Color> },
|
||||
}
|
||||
|
||||
impl ToolMetadata for FillTool {
|
||||
@@ -38,13 +43,39 @@ impl ToolMetadata for FillTool {
|
||||
|
||||
impl LayoutHolder for FillTool {
|
||||
fn layout(&self) -> Layout {
|
||||
Layout::default()
|
||||
let widgets = vec![
|
||||
ColorInput::new(FillChoiceUI::from(&solid(self.primary_color)))
|
||||
.narrow(true)
|
||||
.on_update(|color: &ColorInput| {
|
||||
FillToolMessage::SetColor {
|
||||
color: color.value.as_solid().map(Color::from),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
];
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for FillTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
// User picked a color in the control bar: push it to the global primary working color (no tool-local customization)
|
||||
if let ToolMessage::Fill(FillToolMessage::SetColor { color: Some(color) }) = &message {
|
||||
responses.add(ToolMessage::SelectWorkingColor { color: *color, primary: true });
|
||||
return;
|
||||
}
|
||||
|
||||
// Mirror the global primary working color into the control bar's color swatch
|
||||
if matches!(message, ToolMessage::Fill(FillToolMessage::WorkingColorChanged)) {
|
||||
let new_color = context.global_tool_data.primary_color;
|
||||
if self.primary_color != new_color {
|
||||
self.primary_color = new_color;
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
}
|
||||
|
||||
self.fsm_state.process_event(message, &mut (), context, &(), responses, true);
|
||||
}
|
||||
fn actions(&self) -> ActionList {
|
||||
@@ -105,13 +136,13 @@ impl Fsm for FillToolFsmState {
|
||||
let ToolMessage::Fill(event) = event else { return self };
|
||||
match (self, event) {
|
||||
(_, FillToolMessage::Overlays { context: mut overlay_context }) => {
|
||||
// Choose the working color to preview
|
||||
// Choose the color to preview
|
||||
let use_secondary = input.keyboard.get(Key::Shift as usize);
|
||||
let preview_color = if use_secondary { global_tool_data.secondary_color } else { global_tool_data.primary_color };
|
||||
|
||||
// Get the layer the user is hovering over
|
||||
if let Some(layer) = document.click(input, viewport) {
|
||||
let color_hex = format!("#{}", preview_color.to_rgba_hex_srgb());
|
||||
let color_hex = SRGBA8::from(preview_color).to_css_hex();
|
||||
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &color_hex);
|
||||
}
|
||||
|
||||
@@ -131,8 +162,8 @@ impl Fsm for FillToolFsmState {
|
||||
return self;
|
||||
}
|
||||
let fill = match color_event {
|
||||
FillToolMessage::FillPrimaryColor => Fill::Solid(global_tool_data.primary_color.to_gamma_srgb()),
|
||||
FillToolMessage::FillSecondaryColor => Fill::Solid(global_tool_data.secondary_color.to_gamma_srgb()),
|
||||
FillToolMessage::FillPrimaryColor => Fill::Solid(global_tool_data.primary_color),
|
||||
FillToolMessage::FillSecondaryColor => Fill::Solid(global_tool_data.secondary_color),
|
||||
_ => return self,
|
||||
};
|
||||
|
||||
@@ -171,6 +202,7 @@ impl Fsm for FillToolFsmState {
|
||||
#[cfg(test)]
|
||||
mod test_fill {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::fill;
|
||||
use graphene_std::vector::style::Fill;
|
||||
|
||||
@@ -210,7 +242,7 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::empty()).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
assert_eq!(fills[0].as_solid().unwrap().to_rgba8_srgb(), Color::GREEN.to_rgba8_srgb());
|
||||
assert_eq!(SRGBA8::from(fills[0].as_solid().unwrap()), SRGBA8::from(Color::GREEN));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -222,6 +254,6 @@ mod test_fill {
|
||||
editor.click_tool(ToolType::Fill, MouseKeys::LEFT, DVec2::new(2., 2.), ModifierKeys::SHIFT).await;
|
||||
let fills = get_fills(&mut editor).await;
|
||||
assert_eq!(fills.len(), 1);
|
||||
assert_eq!(fills[0].as_solid().unwrap().to_rgba8_srgb(), Color::YELLOW.to_rgba8_srgb());
|
||||
assert_eq!(SRGBA8::from(fills[0].as_solid().unwrap()), SRGBA8::from(Color::YELLOW));
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,21 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, reset_colors_on_deactivation, swap_fill_and_stroke,
|
||||
sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
|
||||
use crate::messages::tool::common_functionality::utility_functions::should_extend;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::VectorModificationType;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::{PointId, SegmentId};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
@@ -22,17 +26,13 @@ pub struct FreehandTool {
|
||||
}
|
||||
|
||||
pub struct FreehandOptions {
|
||||
line_weight: f64,
|
||||
fill: ToolColorOptions,
|
||||
stroke: ToolColorOptions,
|
||||
drawing: DrawingToolState,
|
||||
}
|
||||
|
||||
impl Default for FreehandOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
fill: ToolColorOptions::new_none(),
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
drawing: DrawingToolState::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,12 +57,13 @@ pub enum FreehandToolMessage {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum FreehandOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
LineWeight(f64),
|
||||
FillColor(FillChoice),
|
||||
FillEnabled(bool),
|
||||
StrokeOption(StrokeOptionsUpdate),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
StrokeEnabled(bool),
|
||||
SwapFillAndStroke,
|
||||
WorkingColorsChanged,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -84,76 +85,60 @@ impl ToolMetadata for FreehandTool {
|
||||
}
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetInstance {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(1.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::LineWeight(number_input.value.unwrap()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
impl LayoutHolder for FreehandTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| {
|
||||
let mut widgets = self.options.drawing.fill.create_widgets(
|
||||
"Fill:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::FillColor(None),
|
||||
options: FreehandOptionsUpdate::FillEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::FillColorType(color_type.clone()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: FreehandOptionsUpdate::FillColor(FillChoice::from(&color.value)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::StrokeColor(None),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
widgets.push(
|
||||
IconButton::new("SwapHorizontal", 16)
|
||||
.tooltip_label("Swap Fill/Stroke Colors")
|
||||
.on_update(|_| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::StrokeColorType(color_type.clone()),
|
||||
options: FreehandOptionsUpdate::SwapFillAndStroke,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.drawing.stroke.create_widgets(
|
||||
"Stroke:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::StrokeEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: FreehandOptionsUpdate::StrokeColor(color.value.as_solid().map(Color::from)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
let weight_disabled = self.options.drawing.stroke.enabled == Some(false);
|
||||
widgets.push(create_stroke_options_popover_widget(&self.options.drawing, weight_disabled, |update| {
|
||||
FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::StrokeOption(update),
|
||||
}
|
||||
.into()
|
||||
}));
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
@@ -162,12 +147,18 @@ impl LayoutHolder for FreehandTool {
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for FreehandTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
// On tool deactivation (Abort fires from the dispatcher's tool transition), reset the displayed fill/stroke colors so
|
||||
// the next activation starts fresh from the current working colors. The global swap state persists across tool switches.
|
||||
// Guarded on `Ready` so Esc-mid-drawing (which also fires Abort) doesn't wipe the user's customized fill/stroke options.
|
||||
if matches!(&message, ToolMessage::Freehand(FreehandToolMessage::Abort)) && self.fsm_state == FreehandToolFsmState::Ready {
|
||||
reset_colors_on_deactivation(&mut self.options.drawing, context.global_tool_data);
|
||||
}
|
||||
|
||||
if matches!(&message, ToolMessage::Freehand(FreehandToolMessage::SelectionChanged)) {
|
||||
if self.fsm_state == FreehandToolFsmState::Ready
|
||||
&& let Some(weight) = graph_modification_utils::first_selected_stroke_weight(context.document)
|
||||
&& self.options.line_weight != weight
|
||||
{
|
||||
self.options.line_weight = weight;
|
||||
if self.fsm_state != FreehandToolFsmState::Ready {
|
||||
return;
|
||||
}
|
||||
if sync_drawing_state(&mut self.options.drawing, false, true, context.global_tool_data, context.document) {
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
return;
|
||||
@@ -178,25 +169,26 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Free
|
||||
return;
|
||||
};
|
||||
match options {
|
||||
FreehandOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
FreehandOptionsUpdate::FillColor(fill_choice) => {
|
||||
apply_fill_color_pick(&mut self.options.drawing, fill_choice, context.document, responses);
|
||||
}
|
||||
FreehandOptionsUpdate::FillColorType(color_type) => self.options.fill.color_type = color_type,
|
||||
FreehandOptionsUpdate::LineWeight(line_weight) => {
|
||||
self.options.line_weight = line_weight;
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, context.document, responses);
|
||||
FreehandOptionsUpdate::FillEnabled(enabled) => {
|
||||
apply_fill_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
FreehandOptionsUpdate::StrokeOption(update) => {
|
||||
apply_stroke_option(&mut self.options.drawing, update, context.document, responses);
|
||||
}
|
||||
FreehandOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
apply_stroke_color_pick(&mut self.options.drawing, color, context.document, responses);
|
||||
}
|
||||
FreehandOptionsUpdate::StrokeColorType(color_type) => self.options.stroke.color_type = color_type,
|
||||
FreehandOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
FreehandOptionsUpdate::StrokeEnabled(enabled) => {
|
||||
apply_stroke_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
FreehandOptionsUpdate::SwapFillAndStroke => {
|
||||
swap_fill_and_stroke(&mut self.options.drawing, context.document, responses);
|
||||
}
|
||||
FreehandOptionsUpdate::WorkingColorsChanged => {
|
||||
apply_working_colors(&mut self.options.drawing, context.global_tool_data, context.document);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,7 +226,6 @@ impl ToolTransition for FreehandTool {
|
||||
struct FreehandToolData {
|
||||
end_point: Option<(DVec2, PointId)>,
|
||||
dragged: bool,
|
||||
weight: f64,
|
||||
layer: Option<LayerNodeIdentifier>,
|
||||
/// Viewport-space start position for newly created layers, used to compute local-space
|
||||
/// positions before the deferred TransformSet has been reflected in metadata.
|
||||
@@ -255,7 +246,6 @@ impl Fsm for FreehandToolFsmState {
|
||||
) -> Self {
|
||||
let ToolActionMessageContext {
|
||||
document,
|
||||
global_tool_data,
|
||||
input,
|
||||
shape_editor,
|
||||
viewport,
|
||||
@@ -274,7 +264,6 @@ impl Fsm for FreehandToolFsmState {
|
||||
|
||||
tool_data.dragged = false;
|
||||
tool_data.end_point = None;
|
||||
tool_data.weight = tool_options.line_weight;
|
||||
tool_data.new_layer_viewport_start = None;
|
||||
|
||||
// Extend an endpoint of the selected path
|
||||
@@ -313,8 +302,8 @@ impl Fsm for FreehandToolFsmState {
|
||||
let nodes = vec![(NodeId(0), node)];
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
tool_options.stroke.apply_stroke(tool_data.weight, layer, responses);
|
||||
tool_options.fill.apply_fill(layer, responses);
|
||||
tool_options.drawing.apply_stroke_to_new_layer(layer, responses);
|
||||
tool_options.drawing.fill.apply_fill(layer, responses);
|
||||
tool_data.layer = Some(layer);
|
||||
tool_data.new_layer_viewport_start = Some(input.mouse.position);
|
||||
|
||||
@@ -381,7 +370,7 @@ impl Fsm for FreehandToolFsmState {
|
||||
}
|
||||
(_, FreehandToolMessage::WorkingColorChanged) => {
|
||||
responses.add(FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::WorkingColors(Some(global_tool_data.primary_color), Some(global_tool_data.secondary_color)),
|
||||
options: FreehandOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
self
|
||||
}
|
||||
@@ -443,6 +432,7 @@ mod test_freehand {
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_stroke_width};
|
||||
use crate::messages::tool::common_functionality::stroke_options::StrokeOptionsUpdate;
|
||||
use crate::messages::tool::tool_messages::freehand_tool::FreehandOptionsUpdate;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, DVec2};
|
||||
@@ -767,7 +757,7 @@ mod test_freehand {
|
||||
let custom_line_weight = 5.;
|
||||
editor
|
||||
.handle_message(ToolMessage::Freehand(FreehandToolMessage::UpdateOptions {
|
||||
options: FreehandOptionsUpdate::LineWeight(custom_line_weight),
|
||||
options: FreehandOptionsUpdate::StrokeOption(StrokeOptionsUpdate::LineWeight(custom_line_weight)),
|
||||
}))
|
||||
.await;
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@ use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, NodeGraphLayer, get_gradient_stops};
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::{Fill, FillChoice, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientType};
|
||||
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI, Gradient, GradientSpreadMethod, GradientStop, GradientStops, GradientStopsUI, GradientType};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
pub struct GradientTool {
|
||||
@@ -49,7 +50,7 @@ pub enum GradientToolMessage {
|
||||
CommitTransactionForColorStop,
|
||||
CloseStopColorPicker,
|
||||
UpdateStopColor { color: Color },
|
||||
UpdateStops { stops: GradientStops },
|
||||
UpdateStops { stops: GradientStopsUI },
|
||||
UpdateOptions { options: GradientOptionsUpdate },
|
||||
}
|
||||
|
||||
@@ -120,7 +121,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
}
|
||||
}
|
||||
ToolMessage::Gradient(GradientToolMessage::UpdateStops { stops }) => {
|
||||
apply_stops_update(&mut self.data, context, responses, stops);
|
||||
apply_stops_update(&mut self.data, context, responses, GradientStops::from(&stops));
|
||||
}
|
||||
ToolMessage::Gradient(GradientToolMessage::CloseStopColorPicker) => {
|
||||
if self.data.color_picker_transaction_open {
|
||||
@@ -222,23 +223,30 @@ impl LayoutHolder for GradientTool {
|
||||
.selected_index(Some((self.options.gradient_type == GradientType::Radial) as u32))
|
||||
.widget_instance();
|
||||
|
||||
let stops_value = self.data.current_gradient_stops.clone().map(FillChoice::Gradient).unwrap_or_else(|| {
|
||||
FillChoice::Gradient(GradientStops::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: self.data.primary_color,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: self.data.secondary_color,
|
||||
},
|
||||
]))
|
||||
});
|
||||
let stops_widget = ColorInput::new(stops_value)
|
||||
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
||||
let stops_value = self
|
||||
.data
|
||||
.current_gradient_stops
|
||||
.clone()
|
||||
.or_else(|| self.data.default_gradient_stops.clone())
|
||||
.map(FillChoice::Gradient)
|
||||
.unwrap_or_else(|| {
|
||||
FillChoice::Gradient(GradientStops::new([
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: self.data.primary_color,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: self.data.secondary_color,
|
||||
},
|
||||
]))
|
||||
});
|
||||
let stops_widget = ColorInput::new(FillChoiceUI::from(&stops_value))
|
||||
.allow_none(false)
|
||||
.disabled(!self.data.has_selected_gradient)
|
||||
.narrow(true)
|
||||
.tooltip_label("Gradient Stops")
|
||||
.tooltip_description("Edit the gradient's color stops.")
|
||||
.on_update(|input: &ColorInput| {
|
||||
@@ -786,9 +794,13 @@ struct GradientToolData {
|
||||
auto_pan_shift: DVec2,
|
||||
gradient_angle: f64,
|
||||
has_selected_gradient: bool,
|
||||
/// Cached stops of the currently selected layer's gradient, mirrored into the control-bar widget. Independent of any
|
||||
/// in-progress drag (which uses `selected_gradient`) so it stays current after selection changes too.
|
||||
/// Cached stops of the currently selected layer's gradient, mirrored into the control-bar widget.
|
||||
/// Independent of any in-progress drag (which uses `selected_gradient`) so it stays current after selection changes too.
|
||||
current_gradient_stops: Option<GradientStops>,
|
||||
/// User-customized default gradient stop colors: used when nothing that has a gradient is selected.
|
||||
/// `None` means to follow the working colors.
|
||||
/// Cleared on tool deactivation so each fresh activation starts from the working colors again.
|
||||
default_gradient_stops: Option<GradientStops>,
|
||||
/// Cached viewport-space orientation (true = predominantly rightward) of the selected gradient line.
|
||||
/// Used to refresh the control bar's "Reverse Direction" icon only when the line's apparent direction flips.
|
||||
gradient_orientation_rightward: bool,
|
||||
@@ -845,7 +857,7 @@ impl Fsm for GradientToolFsmState {
|
||||
let (start, end) = (transform.transform_point2(*start), transform.transform_point2(*end));
|
||||
|
||||
fn color_to_hex(color: graphene_std::Color) -> String {
|
||||
format!("#{}", color.to_rgb_hex_srgb_from_gamma())
|
||||
SRGBA8::from(color).to_css_hex()
|
||||
}
|
||||
|
||||
let start_hex = stops.color.first().map(|&c| color_to_hex(c)).unwrap_or(String::from(COLOR_OVERLAY_BLUE));
|
||||
@@ -1013,10 +1025,10 @@ impl Fsm for GradientToolFsmState {
|
||||
let transform = gradient_space_transform(layer, document);
|
||||
let gradient = &selected_gradient.gradient;
|
||||
if stop_index < gradient.stops.position.len() {
|
||||
let color = gradient.stops.color[stop_index].to_gamma_srgb();
|
||||
let color = gradient.stops.color[stop_index];
|
||||
let position = gradient.stops.position[stop_index];
|
||||
let position = transform.transform_point2(gradient.start.lerp(gradient.end, position)).into();
|
||||
responses.add(FrontendMessage::UpdateGradientStopColorPickerPosition { color, position });
|
||||
responses.add(FrontendMessage::UpdateGradientStopColorPickerPosition { color: color.into(), position });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1070,9 +1082,9 @@ impl Fsm for GradientToolFsmState {
|
||||
.transform
|
||||
.transform_point2(selected_gradient.gradient.start.lerp(selected_gradient.gradient.end, stop_pos));
|
||||
let position = viewport_pos.into();
|
||||
let color = selected_gradient.gradient.stops.color[stop_index].to_gamma_srgb();
|
||||
let color = selected_gradient.gradient.stops.color[stop_index];
|
||||
tool_data.color_picker_editing_color_stop = Some(stop_index);
|
||||
responses.add(FrontendMessage::UpdateGradientStopColorPickerPosition { color, position });
|
||||
responses.add(FrontendMessage::UpdateGradientStopColorPickerPosition { color: color.into(), position });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -1545,6 +1557,8 @@ impl Fsm for GradientToolFsmState {
|
||||
}
|
||||
(_, GradientToolMessage::Abort) => {
|
||||
dismiss_color_stop_color_picker(tool_data, responses);
|
||||
// Clear the tool-default gradient override so re-activating the tool starts fresh from the working colors
|
||||
tool_data.default_gradient_stops = None;
|
||||
|
||||
GradientToolFsmState::Ready {
|
||||
hovering: GradientHoverTarget::None,
|
||||
@@ -1785,6 +1799,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
.selected_visible_layers(&context.document.network_interface)
|
||||
.collect();
|
||||
|
||||
let mut updated_any_layer = false;
|
||||
for layer in selected_layers {
|
||||
if NodeGraphLayer::is_raster_layer(layer, &mut context.document.network_interface) {
|
||||
continue;
|
||||
@@ -1792,20 +1807,30 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
|
||||
if get_gradient_stops(layer, &context.document.network_interface).is_some() {
|
||||
responses.add(GraphOperationMessage::GradientStopsSet { layer, stops: stops.clone() });
|
||||
updated_any_layer = true;
|
||||
} else if let Some(mut gradient) = get_gradient(layer, &context.document.network_interface) {
|
||||
gradient.stops = stops.clone();
|
||||
responses.add(GraphOperationMessage::FillSet {
|
||||
layer,
|
||||
fill: Fill::Gradient(gradient),
|
||||
});
|
||||
updated_any_layer = true;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(selected_gradient) = &mut data.selected_gradient {
|
||||
selected_gradient.gradient.stops = stops;
|
||||
selected_gradient.gradient.stops = stops.clone();
|
||||
}
|
||||
|
||||
// When no selected layer had a gradient to update, the user is editing the tool's default gradient instead.
|
||||
// Save those stops so the widget keeps showing them until the tool is deactivated.
|
||||
if !updated_any_layer {
|
||||
data.default_gradient_stops = Some(stops);
|
||||
}
|
||||
|
||||
responses.add(PropertiesPanelMessage::Refresh);
|
||||
// Refresh the tool options so the swatch's `chosen_gradient` (precomputed CSS string) updates live as the user edits stops in the picker.
|
||||
responses.add(ToolMessage::RefreshToolOptions);
|
||||
}
|
||||
|
||||
/// Find the first selected visible layer that has a gradient and return both the layer ID and its resolved gradient.
|
||||
@@ -1886,6 +1911,7 @@ mod test_gradient {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::{Fill, Gradient};
|
||||
use graphene_std::vector::{GradientStop, GradientStops, fill};
|
||||
|
||||
@@ -1998,8 +2024,8 @@ mod test_gradient {
|
||||
let (gradient, transform) = get_gradient(&mut editor).await;
|
||||
|
||||
// Gradient goes from primary color to secondary color
|
||||
let stops = gradient.stops.iter().map(|stop| (stop.position, stop.color.to_rgba8_srgb())).collect::<Vec<_>>();
|
||||
assert_eq!(stops, vec![(0., Color::GREEN.to_rgba8_srgb()), (1., Color::BLUE.to_rgba8_srgb())]);
|
||||
let stops = gradient.stops.iter().map(|stop| (stop.position, SRGBA8::from(stop.color))).collect::<Vec<_>>();
|
||||
assert_eq!(stops, vec![(0., SRGBA8::from(Color::GREEN)), (1., SRGBA8::from(Color::BLUE))]);
|
||||
assert!(transform.transform_point2(gradient.start).abs_diff_eq(DVec2::new(2., 3.), 1e-10));
|
||||
assert!(transform.transform_point2(gradient.end).abs_diff_eq(DVec2::new(24., 4.), 1e-10));
|
||||
}
|
||||
@@ -2191,7 +2217,7 @@ mod test_gradient {
|
||||
let positions: Vec<f64> = stops.iter().map(|stop| stop.position).collect();
|
||||
assert_stops_at_positions(&positions, &[0., 0.25, 1.], 0.1);
|
||||
|
||||
let middle_color = stops.color[1].to_rgba8_srgb();
|
||||
let middle_color = SRGBA8::from(stops.color[1]);
|
||||
|
||||
// Simulate dragging the middle stop to position 0.8
|
||||
let click_position = DVec2::new(25., 0.);
|
||||
@@ -2232,9 +2258,9 @@ mod test_gradient {
|
||||
assert_stops_at_positions(&updated_positions, &[0., 0.8, 1.], 0.1);
|
||||
|
||||
// Colors should maintain their associations with the stop points
|
||||
assert_eq!(updated_stops.color[0].to_rgba8_srgb(), Color::GREEN.to_rgba8_srgb());
|
||||
assert_eq!(updated_stops.color[1].to_rgba8_srgb(), middle_color);
|
||||
assert_eq!(updated_stops.color[2].to_rgba8_srgb(), Color::BLUE.to_rgba8_srgb());
|
||||
assert_eq!(SRGBA8::from(updated_stops.color[0]), SRGBA8::from(Color::GREEN));
|
||||
assert_eq!(SRGBA8::from(updated_stops.color[1]), middle_color);
|
||||
assert_eq!(SRGBA8::from(updated_stops.color[2]), SRGBA8::from(Color::BLUE));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -2471,8 +2497,8 @@ mod test_gradient {
|
||||
|
||||
assert_eq!(updated.stops.len(), 3, "Stop count should be preserved");
|
||||
assert_stops_at_positions(&updated.stops.position, &[0., 0.5, 1.], 1e-10);
|
||||
assert_eq!(updated.stops.color[0].to_rgba8_srgb(), Color::RED.to_rgba8_srgb(), "First stop color should be preserved");
|
||||
assert_eq!(updated.stops.color[1].to_rgba8_srgb(), Color::GREEN.to_rgba8_srgb(), "Middle stop color should be preserved");
|
||||
assert_eq!(updated.stops.color[2].to_rgba8_srgb(), Color::BLUE.to_rgba8_srgb(), "Last stop color should be preserved");
|
||||
assert_eq!(SRGBA8::from(updated.stops.color[0]), SRGBA8::from(Color::RED), "First stop color should be preserved");
|
||||
assert_eq!(SRGBA8::from(updated.stops.color[1]), SRGBA8::from(Color::GREEN), "Middle stop color should be preserved");
|
||||
assert_eq!(SRGBA8::from(updated.stops.color[2]), SRGBA8::from(Color::BLUE), "Last stop color should be preserved");
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,7 @@ impl LayoutHolder for PathTool {
|
||||
let x_location = NumberInput::new(x)
|
||||
.unit(" px")
|
||||
.label("X")
|
||||
.min_width(120)
|
||||
.min_width(80)
|
||||
.disabled(x.is_none())
|
||||
.min(-((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
@@ -230,7 +230,7 @@ impl LayoutHolder for PathTool {
|
||||
let y_location = NumberInput::new(y)
|
||||
.unit(" px")
|
||||
.label("Y")
|
||||
.min_width(120)
|
||||
.min_width(80)
|
||||
.disabled(y.is_none())
|
||||
.min(-((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
@@ -2850,13 +2850,10 @@ impl Fsm for PathToolFsmState {
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
|
||||
// Defaults chosen because the pasted geometry has no inherent associated style
|
||||
let stroke_color = Color::BLACK;
|
||||
let fill_color = Color::WHITE;
|
||||
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(stroke_color.to_gamma_srgb()), DEFAULT_STROKE_WIDTH);
|
||||
let stroke = graphene_std::vector::style::Stroke::new(Some(Color::BLACK), DEFAULT_STROKE_WIDTH);
|
||||
responses.add(GraphOperationMessage::StrokeSet { layer, stroke });
|
||||
|
||||
let fill = graphene_std::vector::style::Fill::solid(fill_color.to_gamma_srgb());
|
||||
let fill = graphene_std::vector::style::Fill::solid(Color::WHITE);
|
||||
responses.add(GraphOperationMessage::FillSet { layer, fill });
|
||||
|
||||
new_layers.push(layer);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, DEFAULT_STROKE_WIDTH, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE, SEGMENT_OVERLAY_SIZE};
|
||||
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, LINE_ROTATE_SNAP_ANGLE, SEGMENT_OVERLAY_SIZE};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
@@ -7,15 +7,20 @@ use crate::messages::portfolio::document::overlays::utility_functions::path_over
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, reset_colors_on_deactivation, swap_fill_and_stroke,
|
||||
sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, merge_layers};
|
||||
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandidatePoint, SnapConstraint, SnapData, SnapManager, SnapTypeConfiguration};
|
||||
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
|
||||
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, closest_point, should_extend};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::subpath::pathseg_points;
|
||||
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::{NoHashBuilder, PointId, SegmentId, StrokeId, Vector, VectorModificationType};
|
||||
use kurbo::{CubicBez, PathSeg};
|
||||
|
||||
@@ -27,18 +32,14 @@ pub struct PenTool {
|
||||
}
|
||||
|
||||
pub struct PenOptions {
|
||||
line_weight: f64,
|
||||
fill: ToolColorOptions,
|
||||
stroke: ToolColorOptions,
|
||||
drawing: DrawingToolState,
|
||||
pen_overlay_mode: PenOverlayMode,
|
||||
}
|
||||
|
||||
impl Default for PenOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
fill: ToolColorOptions::new_secondary(),
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
drawing: DrawingToolState::new(true),
|
||||
pen_overlay_mode: PenOverlayMode::FrontierHandles,
|
||||
}
|
||||
}
|
||||
@@ -119,12 +120,13 @@ pub enum PenOverlayMode {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum PenOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
LineWeight(f64),
|
||||
FillColor(FillChoice),
|
||||
FillEnabled(bool),
|
||||
StrokeOption(StrokeOptionsUpdate),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
StrokeEnabled(bool),
|
||||
SwapFillAndStroke,
|
||||
WorkingColorsChanged,
|
||||
OverlayModeType(PenOverlayMode),
|
||||
}
|
||||
|
||||
@@ -140,80 +142,63 @@ impl ToolMetadata for PenTool {
|
||||
}
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetInstance {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::LineWeight(number_input.value.unwrap()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
impl LayoutHolder for PenTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| {
|
||||
let mut widgets = self.options.drawing.fill.create_widgets(
|
||||
"Fill:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::FillColor(None),
|
||||
options: PenOptionsUpdate::FillEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::FillColorType(color_type.clone()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: PenOptionsUpdate::FillColor(FillChoice::from(&color.value)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::StrokeColor(None),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
widgets.push(
|
||||
IconButton::new("SwapHorizontal", 16)
|
||||
.tooltip_label("Swap Fill/Stroke Colors")
|
||||
.on_update(|_| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::StrokeColorType(color_type.clone()),
|
||||
options: PenOptionsUpdate::SwapFillAndStroke,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.drawing.stroke.create_widgets(
|
||||
"Stroke:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::StrokeEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: PenOptionsUpdate::StrokeColor(color.value.as_solid().map(Color::from)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
let weight_disabled = self.options.drawing.stroke.enabled == Some(false);
|
||||
widgets.push(create_stroke_options_popover_widget(&self.options.drawing, weight_disabled, |update| {
|
||||
PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::StrokeOption(update),
|
||||
}
|
||||
.into()
|
||||
}));
|
||||
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(Separator::new(SeparatorStyle::Section).widget_instance());
|
||||
|
||||
widgets.push(
|
||||
RadioInput::new(vec![
|
||||
@@ -249,12 +234,17 @@ impl LayoutHolder for PenTool {
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for PenTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
// On tool deactivation (Abort fires from the dispatcher's tool transition), reset the displayed fill/stroke colors so
|
||||
// the next activation starts fresh from the current working colors. The global swap state persists across tool switches.
|
||||
// Guarded on `Ready` so Esc-mid-drawing (which also fires Abort) doesn't wipe the user's customized fill/stroke options.
|
||||
if matches!(&message, ToolMessage::Pen(PenToolMessage::Abort)) && self.fsm_state == PenToolFsmState::Ready {
|
||||
reset_colors_on_deactivation(&mut self.options.drawing, context.global_tool_data);
|
||||
}
|
||||
|
||||
if matches!(&message, ToolMessage::Pen(PenToolMessage::SelectionChanged))
|
||||
&& self.fsm_state == PenToolFsmState::Ready
|
||||
&& let Some(weight) = graph_modification_utils::first_selected_stroke_weight(context.document)
|
||||
&& self.options.line_weight != weight
|
||||
&& sync_drawing_state(&mut self.options.drawing, true, true, context.global_tool_data, context.document)
|
||||
{
|
||||
self.options.line_weight = weight;
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
|
||||
@@ -268,25 +258,26 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for PenT
|
||||
self.options.pen_overlay_mode = overlay_mode_type;
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
}
|
||||
PenOptionsUpdate::LineWeight(line_weight) => {
|
||||
self.options.line_weight = line_weight;
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, context.document, responses);
|
||||
PenOptionsUpdate::StrokeOption(update) => {
|
||||
apply_stroke_option(&mut self.options.drawing, update, context.document, responses);
|
||||
}
|
||||
PenOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
PenOptionsUpdate::FillColor(fill_choice) => {
|
||||
apply_fill_color_pick(&mut self.options.drawing, fill_choice, context.document, responses);
|
||||
}
|
||||
PenOptionsUpdate::FillEnabled(enabled) => {
|
||||
apply_fill_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
PenOptionsUpdate::FillColorType(color_type) => self.options.fill.color_type = color_type,
|
||||
PenOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
apply_stroke_color_pick(&mut self.options.drawing, color, context.document, responses);
|
||||
}
|
||||
PenOptionsUpdate::StrokeColorType(color_type) => self.options.stroke.color_type = color_type,
|
||||
PenOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
PenOptionsUpdate::StrokeEnabled(enabled) => {
|
||||
apply_stroke_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
PenOptionsUpdate::SwapFillAndStroke => {
|
||||
swap_fill_and_stroke(&mut self.options.drawing, context.document, responses);
|
||||
}
|
||||
PenOptionsUpdate::WorkingColorsChanged => {
|
||||
apply_working_colors(&mut self.options.drawing, context.global_tool_data, context.document);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1306,8 +1297,8 @@ impl PenToolData {
|
||||
let parent = document.new_layer_bounding_artboard(input, viewport);
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
self.current_layer = Some(layer);
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, responses);
|
||||
tool_options.fill.apply_fill(layer, responses);
|
||||
tool_options.drawing.apply_stroke_to_new_layer(layer, responses);
|
||||
tool_options.drawing.fill.apply_fill(layer, responses);
|
||||
self.prior_segment = None;
|
||||
self.prior_segments = None;
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
||||
@@ -1490,7 +1481,6 @@ impl Fsm for PenToolFsmState {
|
||||
) -> Self {
|
||||
let ToolActionMessageContext {
|
||||
document,
|
||||
global_tool_data,
|
||||
input,
|
||||
shape_editor,
|
||||
viewport,
|
||||
@@ -1839,7 +1829,7 @@ impl Fsm for PenToolFsmState {
|
||||
}
|
||||
(_, PenToolMessage::WorkingColorChanged) => {
|
||||
responses.add(PenToolMessage::UpdateOptions {
|
||||
options: PenOptionsUpdate::WorkingColors(Some(global_tool_data.primary_color), Some(global_tool_data.secondary_color)),
|
||||
options: PenOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
@@ -11,27 +11,44 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Flo
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
use crate::messages::preferences::SelectionMode;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, swap_fill_and_stroke, sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::compass_rose::{Axis, CompassRose};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::measure;
|
||||
use crate::messages::tool::common_functionality::pivot::{PivotGizmo, PivotGizmoType, PivotToolSource, pin_pivot_widget, pivot_gizmo_type_widget, pivot_reference_point_widget};
|
||||
use crate::messages::tool::common_functionality::shape_editor::SelectionShapeType;
|
||||
use crate::messages::tool::common_functionality::snapping::{self, SnapCandidatePoint, SnapData, SnapManager};
|
||||
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
|
||||
use crate::messages::tool::common_functionality::transformation_cage::*;
|
||||
use crate::messages::tool::common_functionality::utility_functions::{resize_bounds, rotate_bounds, skew_bounds, text_bounding_box, transforming_transform_cage};
|
||||
use glam::DMat2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Color;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::renderer::Rect;
|
||||
use graphene_std::subpath::Subpath;
|
||||
use graphene_std::transform::ReferencePoint;
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use std::fmt;
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
#[derive(ExtractField)]
|
||||
pub struct SelectTool {
|
||||
fsm_state: SelectToolFsmState,
|
||||
tool_data: SelectToolData,
|
||||
drawing: DrawingToolState,
|
||||
}
|
||||
|
||||
impl Default for SelectTool {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
fsm_state: SelectToolFsmState::default(),
|
||||
tool_data: SelectToolData::default(),
|
||||
drawing: DrawingToolState::new(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(dead_code)]
|
||||
@@ -41,12 +58,19 @@ pub struct SelectOptions {
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SelectOptionsUpdate {
|
||||
NestedSelectionBehavior(NestedSelectionBehavior),
|
||||
PivotGizmoType(PivotGizmoType),
|
||||
SetPivotGizmoEnabled(bool),
|
||||
TogglePivotPinned,
|
||||
FillColor(FillChoice),
|
||||
FillEnabled(bool),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeEnabled(bool),
|
||||
SwapFillAndStroke,
|
||||
StrokeOption(StrokeOptionsUpdate),
|
||||
WorkingColorsChanged,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
@@ -81,6 +105,8 @@ pub struct SelectToolPointerKeys {
|
||||
pub enum SelectToolMessage {
|
||||
// Standard messages
|
||||
Abort,
|
||||
SelectionChanged,
|
||||
WorkingColorChanged,
|
||||
Overlays {
|
||||
context: OverlayContext,
|
||||
},
|
||||
@@ -190,18 +216,6 @@ impl SelectTool {
|
||||
})
|
||||
}
|
||||
|
||||
fn turn_widgets(&self, disabled: bool) -> impl Iterator<Item = WidgetInstance> + use<> {
|
||||
[(-90., "TurnNegative90", "Turn -90°"), (90., "TurnPositive90", "Turn 90°")]
|
||||
.into_iter()
|
||||
.map(move |(degrees, icon, label)| {
|
||||
IconButton::new(icon, 24)
|
||||
.tooltip_label(label)
|
||||
.on_update(move |_| DocumentMessage::RotateSelectedLayers { degrees }.into())
|
||||
.disabled(disabled)
|
||||
.widget_instance()
|
||||
})
|
||||
}
|
||||
|
||||
fn boolean_widgets(&self, selected_count: usize) -> impl Iterator<Item = WidgetInstance> + use<> {
|
||||
let list = <BooleanOperation as graphene_std::choice_type::ChoiceTypeStatic>::list();
|
||||
list.iter().flat_map(|i| i.iter()).map(move |(operation, info)| {
|
||||
@@ -222,6 +236,65 @@ impl LayoutHolder for SelectTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = Vec::new();
|
||||
|
||||
// Fill/Stroke widget set (only shown when there's a selection to apply edits to)
|
||||
if self.tool_data.selected_layers_count > 0 {
|
||||
widgets.append(&mut self.drawing.fill.create_widgets(
|
||||
"Fill:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::FillEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::FillColor(FillChoice::from(&color.value)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(
|
||||
IconButton::new("SwapHorizontal", 16)
|
||||
.tooltip_label("Swap Fill/Stroke Colors")
|
||||
.on_update(|_| {
|
||||
SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::SwapFillAndStroke,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.drawing.stroke.create_widgets(
|
||||
"Stroke:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::StrokeEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::StrokeColor(color.value.as_solid().map(Color::from)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
|
||||
let weight_disabled = self.drawing.stroke.enabled == Some(false);
|
||||
widgets.push(create_stroke_options_popover_widget(&self.drawing, weight_disabled, |update| {
|
||||
SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::StrokeOption(update),
|
||||
}
|
||||
.into()
|
||||
}));
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Section).widget_instance());
|
||||
}
|
||||
|
||||
// Select mode (Deep/Shallow)
|
||||
widgets.push(self.deep_selection_widget());
|
||||
|
||||
@@ -259,10 +332,6 @@ impl LayoutHolder for SelectTool {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.extend(self.flip_widgets(disabled));
|
||||
|
||||
// Turn
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.extend(self.turn_widgets(disabled));
|
||||
|
||||
// Boolean
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.extend(self.boolean_widgets(self.tool_data.selected_layers_count));
|
||||
@@ -275,16 +344,27 @@ impl LayoutHolder for SelectTool {
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for SelectTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
let mut redraw_reference_pivot = false;
|
||||
let mut drawing_options_changed = false;
|
||||
|
||||
if let ToolMessage::Select(SelectToolMessage::SelectOptions { options: ref option_update }) = message {
|
||||
match *option_update {
|
||||
if matches!(&message, ToolMessage::Select(SelectToolMessage::SelectionChanged)) && sync_drawing_state(&mut self.drawing, true, true, context.global_tool_data, context.document) {
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
|
||||
if matches!(&message, ToolMessage::Select(SelectToolMessage::WorkingColorChanged)) {
|
||||
responses.add(SelectToolMessage::SelectOptions {
|
||||
options: SelectOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
}
|
||||
|
||||
if let ToolMessage::Select(SelectToolMessage::SelectOptions { options: option_update }) = &message {
|
||||
match option_update {
|
||||
SelectOptionsUpdate::NestedSelectionBehavior(nested_selection_behavior) => {
|
||||
self.tool_data.nested_selection_behavior = nested_selection_behavior;
|
||||
self.tool_data.nested_selection_behavior = *nested_selection_behavior;
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
}
|
||||
SelectOptionsUpdate::PivotGizmoType(gizmo_type) => {
|
||||
if self.tool_data.pivot_gizmo.state.enabled {
|
||||
self.tool_data.pivot_gizmo.state.gizmo_type = gizmo_type;
|
||||
self.tool_data.pivot_gizmo.state.gizmo_type = *gizmo_type;
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
let pivot_gizmo = self.tool_data.pivot_gizmo();
|
||||
responses.add(TransformLayerMessage::SetPivotGizmo { pivot_gizmo });
|
||||
@@ -293,24 +373,51 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Sele
|
||||
}
|
||||
}
|
||||
SelectOptionsUpdate::SetPivotGizmoEnabled(enabled) => {
|
||||
self.tool_data.pivot_gizmo.state.enabled = enabled;
|
||||
self.tool_data.pivot_gizmo.state.enabled = *enabled;
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
redraw_reference_pivot = true;
|
||||
}
|
||||
|
||||
SelectOptionsUpdate::TogglePivotPinned => {
|
||||
self.tool_data.pivot_gizmo.pivot.pinned = !self.tool_data.pivot_gizmo.pivot.pinned;
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
redraw_reference_pivot = true;
|
||||
}
|
||||
SelectOptionsUpdate::FillColor(fill_choice) => {
|
||||
apply_fill_color_pick(&mut self.drawing, fill_choice.clone(), context.document, responses);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
SelectOptionsUpdate::FillEnabled(enabled) => {
|
||||
apply_fill_enabled(&mut self.drawing, *enabled, context.global_tool_data, context.document, responses);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
SelectOptionsUpdate::StrokeColor(color) => {
|
||||
apply_stroke_color_pick(&mut self.drawing, *color, context.document, responses);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
SelectOptionsUpdate::StrokeEnabled(enabled) => {
|
||||
apply_stroke_enabled(&mut self.drawing, *enabled, context.global_tool_data, context.document, responses);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
SelectOptionsUpdate::SwapFillAndStroke => {
|
||||
swap_fill_and_stroke(&mut self.drawing, context.document, responses);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
SelectOptionsUpdate::StrokeOption(update) => {
|
||||
apply_stroke_option(&mut self.drawing, update.clone(), context.document, responses);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
SelectOptionsUpdate::WorkingColorsChanged => {
|
||||
apply_working_colors(&mut self.drawing, context.global_tool_data, context.document);
|
||||
drawing_options_changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.fsm_state.process_event(message, &mut self.tool_data, context, &(), responses, false);
|
||||
|
||||
if self.tool_data.pivot_gizmo.pivot.should_refresh_pivot_position() || self.tool_data.selected_layers_changed || redraw_reference_pivot {
|
||||
if self.tool_data.pivot_gizmo.pivot.should_refresh_pivot_position() || self.tool_data.selected_layers_changed || redraw_reference_pivot || drawing_options_changed {
|
||||
// Send the layout containing the updated pivot position (a bit ugly to do it here not in the fsm but that doesn't have SelectTool)
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
self.tool_data.selected_layers_changed = false;
|
||||
@@ -340,6 +447,8 @@ impl ToolTransition for SelectTool {
|
||||
fn event_to_message_map(&self) -> EventToMessageMap {
|
||||
EventToMessageMap {
|
||||
tool_abort: Some(SelectToolMessage::Abort.into()),
|
||||
selection_changed: Some(SelectToolMessage::SelectionChanged.into()),
|
||||
working_color_changed: Some(SelectToolMessage::WorkingColorChanged.into()),
|
||||
overlay_provider: Some(|context| SelectToolMessage::Overlays { context }.into()),
|
||||
..Default::default()
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{BOUNDS_SELECT_THRESHOLD, DEFAULT_STROKE_WIDTH, SNAP_POINT_TOLERANCE};
|
||||
use crate::consts::{BOUNDS_SELECT_THRESHOLD, SNAP_POINT_TOLERANCE};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, has_selection, reset_colors_on_deactivation,
|
||||
swap_fill_and_stroke, sync_color_options, sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::gizmos::gizmo_manager::GizmoManager;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::resize::Resize;
|
||||
@@ -20,12 +23,15 @@ use crate::messages::tool::common_functionality::shapes::spiral_shape::Spiral;
|
||||
use crate::messages::tool::common_functionality::shapes::star_shape::Star;
|
||||
use crate::messages::tool::common_functionality::shapes::{Ellipse, Line, Rectangle};
|
||||
use crate::messages::tool::common_functionality::snapping::{self, SnapCandidatePoint, SnapData, SnapTypeConfiguration};
|
||||
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
|
||||
use crate::messages::tool::common_functionality::transformation_cage::{BoundingBoxManager, EdgeBool};
|
||||
use crate::messages::tool::common_functionality::utility_functions::{closest_point, resize_bounds, rotate_bounds, skew_bounds, transforming_transform_cage};
|
||||
use crate::messages::tool::utility_types::DocumentToolData;
|
||||
use graph_craft::document::NodeId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::vector::misc::{ArcType, GridType, SpiralType};
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::{Color, NodeInputDecleration};
|
||||
use std::vec;
|
||||
|
||||
@@ -37,9 +43,17 @@ pub struct ShapeTool {
|
||||
}
|
||||
|
||||
pub struct ShapeToolOptions {
|
||||
line_weight: f64,
|
||||
fill: ToolColorOptions,
|
||||
stroke: ToolColorOptions,
|
||||
drawing: DrawingToolState,
|
||||
/// Per-shape-mode default for whether the fill checkbox is ticked when no layer is selected. Initialized from
|
||||
/// [`ShapeType::defaults_to_fill`] and updated when the user toggles the fill checkbox while nothing is selected,
|
||||
/// so the preference for each mode persists across mode switches and selection changes.
|
||||
shape_fill_defaults: std::collections::HashMap<ShapeType, bool>,
|
||||
/// Per-shape-mode default for whether the stroke checkbox is ticked when no layer is selected.
|
||||
/// Initialized to `true` for every mode and updated when the user toggles the stroke checkbox while nothing is selected.
|
||||
shape_stroke_defaults: std::collections::HashMap<ShapeType, bool>,
|
||||
/// Per-shape-mode value of the fill/stroke swap flag (mirrors `drawing.colors_swapped` for the current shape mode).
|
||||
/// Updated whenever the user toggles swap; read back when changing shape modes so each alias remembers its own routing.
|
||||
shape_colors_swapped: std::collections::HashMap<ShapeType, bool>,
|
||||
vertices: u32,
|
||||
shape_type: ShapeType,
|
||||
arc_type: ArcType,
|
||||
@@ -53,10 +67,15 @@ pub struct ShapeToolOptions {
|
||||
|
||||
impl Default for ShapeToolOptions {
|
||||
fn default() -> Self {
|
||||
let shape_fill_defaults = ShapeType::ALL.iter().map(|&shape| (shape, shape.defaults_to_fill())).collect();
|
||||
let shape_stroke_defaults = ShapeType::ALL.iter().map(|&shape| (shape, true)).collect();
|
||||
let shape_colors_swapped = ShapeType::ALL.iter().map(|&shape| (shape, false)).collect();
|
||||
|
||||
Self {
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
fill: ToolColorOptions::new_secondary(),
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
drawing: DrawingToolState::new(true),
|
||||
shape_fill_defaults,
|
||||
shape_stroke_defaults,
|
||||
shape_colors_swapped,
|
||||
vertices: 5,
|
||||
shape_type: ShapeType::Polygon,
|
||||
arc_type: ArcType::Open,
|
||||
@@ -73,12 +92,13 @@ impl Default for ShapeToolOptions {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ShapeOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
LineWeight(f64),
|
||||
FillColor(FillChoice),
|
||||
FillEnabled(bool),
|
||||
StrokeOption(StrokeOptionsUpdate),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
StrokeEnabled(bool),
|
||||
SwapFillAndStroke,
|
||||
WorkingColorsChanged,
|
||||
Vertices(u32),
|
||||
ShapeType(ShapeType),
|
||||
ArcType(ArcType),
|
||||
@@ -220,21 +240,6 @@ fn create_arc_type_widget(arc_type: ArcType) -> WidgetInstance {
|
||||
RadioInput::new(entries).selected_index(Some(arc_type as u32)).widget_instance()
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetInstance {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::LineWeight(number_input.value.unwrap()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
fn create_arrow_shaft_width_widget(shaft_width: f64) -> WidgetInstance {
|
||||
NumberInput::new(Some(shaft_width))
|
||||
.unit(" px")
|
||||
@@ -431,102 +436,117 @@ fn sync_shape_options_from_selection(options: &mut ShapeToolOptions, tool_data:
|
||||
changed
|
||||
}
|
||||
|
||||
/// Shared logic for handling a shape-mode change from either the `SetShape` alias (FSM-driven) or the `ShapeType` dropdown.
|
||||
/// Loads the new mode's persistent swap flag, resets the displayed fill/stroke colors back to the (now routed) working colors,
|
||||
/// and re-syncs from the selection using the new mode's natural fill/stroke defaults. The caller is responsible for updating
|
||||
/// `options.shape_type` and `tool_data.current_shape` beforehand if needed.
|
||||
fn handle_shape_mode_change(options: &mut ShapeToolOptions, new_shape: ShapeType, prev_shape: ShapeType, global: &DocumentToolData, document: &DocumentMessageHandler) {
|
||||
if new_shape != prev_shape {
|
||||
options.drawing.colors_swapped = *options.shape_colors_swapped.get(&new_shape).unwrap_or(&false);
|
||||
reset_colors_on_deactivation(&mut options.drawing, global);
|
||||
}
|
||||
let natural_fill_enabled = *options.shape_fill_defaults.get(&new_shape).unwrap_or(&new_shape.defaults_to_fill());
|
||||
let natural_stroke_enabled = *options.shape_stroke_defaults.get(&new_shape).unwrap_or(&true);
|
||||
// Treat the shape change as a real selection change so the new mode's natural defaults apply when nothing matches on the selection.
|
||||
sync_color_options(&mut options.drawing, natural_fill_enabled, natural_stroke_enabled, global, document, true);
|
||||
}
|
||||
|
||||
impl LayoutHolder for ShapeTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = vec![];
|
||||
|
||||
if !self.tool_data.hide_shape_option_widget {
|
||||
widgets.push(create_shape_option_widget(self.options.shape_type));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
if self.options.shape_type == ShapeType::Polygon || self.options.shape_type == ShapeType::Star {
|
||||
widgets.push(create_sides_widget(self.options.vertices));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Arc {
|
||||
widgets.push(create_arc_type_widget(self.options.arc_type));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
}
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Spiral {
|
||||
widgets.push(create_spiral_type_widget(self.options.spiral_type));
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
|
||||
widgets.push(create_turns_widget(self.options.turns));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Grid {
|
||||
widgets.push(create_grid_type_widget(self.options.grid_type));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Arrow {
|
||||
widgets.push(create_arrow_shaft_width_widget(self.options.arrow_shaft_width));
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(create_arrow_head_width_widget(self.options.arrow_head_width));
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(create_arrow_head_length_widget(self.options.arrow_head_length));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
}
|
||||
|
||||
// Fill / Stroke / Weight (Shared across all shape modes. Line shows no Fill)
|
||||
if self.options.shape_type != ShapeType::Line {
|
||||
widgets.append(&mut self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| {
|
||||
widgets.append(&mut self.options.drawing.fill.create_widgets(
|
||||
"Fill:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::FillColor(None),
|
||||
options: ShapeOptionsUpdate::FillEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::FillColorType(color_type.clone()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: ShapeOptionsUpdate::FillColor(FillChoice::from(&color.value)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(
|
||||
IconButton::new("SwapHorizontal", 16)
|
||||
.tooltip_label("Swap Fill/Stroke Colors")
|
||||
.on_update(|_| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::SwapFillAndStroke,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
}
|
||||
|
||||
widgets.append(&mut self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| {
|
||||
widgets.append(&mut self.options.drawing.stroke.create_widgets(
|
||||
"Stroke:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::StrokeColor(None),
|
||||
options: ShapeOptionsUpdate::StrokeEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::StrokeColorType(color_type.clone()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: ShapeOptionsUpdate::StrokeColor(color.value.as_solid().map(Color::from)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
let weight_disabled = self.options.drawing.stroke.enabled == Some(false);
|
||||
widgets.push(create_stroke_options_popover_widget(&self.options.drawing, weight_disabled, |update| {
|
||||
ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::StrokeOption(update),
|
||||
}
|
||||
.into()
|
||||
}));
|
||||
|
||||
// Shape-mode dropdown and per-shape parameters
|
||||
if !self.tool_data.hide_shape_option_widget {
|
||||
widgets.push(Separator::new(SeparatorStyle::Section).widget_instance());
|
||||
widgets.push(create_shape_option_widget(self.options.shape_type));
|
||||
|
||||
if self.options.shape_type == ShapeType::Polygon || self.options.shape_type == ShapeType::Star {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_sides_widget(self.options.vertices));
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Arc {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_arc_type_widget(self.options.arc_type));
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Spiral {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_spiral_type_widget(self.options.spiral_type));
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(create_turns_widget(self.options.turns));
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Grid {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_grid_type_widget(self.options.grid_type));
|
||||
}
|
||||
|
||||
if self.options.shape_type == ShapeType::Arrow {
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_arrow_shaft_width_widget(self.options.arrow_shaft_width));
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(create_arrow_head_width_widget(self.options.arrow_head_width));
|
||||
widgets.push(Separator::new(SeparatorStyle::Related).widget_instance());
|
||||
widgets.push(create_arrow_head_length_widget(self.options.arrow_head_length));
|
||||
}
|
||||
}
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
@@ -537,20 +557,23 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
use graphene_std::vector::generator_nodes::*;
|
||||
|
||||
// On tool deactivation (Abort fires from the dispatcher's tool transition), reset the displayed fill/stroke colors so
|
||||
// the next activation starts fresh from the current working colors. The global swap state persists across tool switches.
|
||||
// Guarded on `Ready(_)` so Esc-mid-drawing (which also fires Abort) doesn't wipe the user's customized fill/stroke options.
|
||||
if matches!(&message, ToolMessage::Shape(ShapeToolMessage::Abort)) && matches!(self.fsm_state, ShapeToolFsmState::Ready(_)) {
|
||||
reset_colors_on_deactivation(&mut self.options.drawing, context.global_tool_data);
|
||||
}
|
||||
|
||||
if matches!(&message, ToolMessage::Shape(ShapeToolMessage::SelectionChanged)) {
|
||||
if !matches!(self.fsm_state, ShapeToolFsmState::Ready(_)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut needs_refresh = false;
|
||||
|
||||
// Stroke weight is shape-agnostic. Sync it regardless of which (if any) shape proto node the layer has.
|
||||
if let Some(weight) = graph_modification_utils::first_selected_stroke_weight(context.document)
|
||||
&& self.options.line_weight != weight
|
||||
{
|
||||
self.options.line_weight = weight;
|
||||
needs_refresh = true;
|
||||
}
|
||||
// The natural fill/stroke defaults depend on the shape type (Spiral/Grid/Line have no fill by default).
|
||||
let current_shape = self.tool_data.current_shape;
|
||||
let natural_fill_enabled = *self.options.shape_fill_defaults.get(¤t_shape).unwrap_or(¤t_shape.defaults_to_fill());
|
||||
let natural_stroke_enabled = *self.options.shape_stroke_defaults.get(¤t_shape).unwrap_or(&true);
|
||||
let mut needs_refresh = sync_drawing_state(&mut self.options.drawing, natural_fill_enabled, natural_stroke_enabled, context.global_tool_data, context.document);
|
||||
|
||||
// Detect which shape the first selected layer is by checking for each generator's proto node, then mirror
|
||||
// the control bar's `shape_type` into that and pull the shape's parameters into the matching control bar fields.
|
||||
@@ -562,38 +585,57 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Shap
|
||||
return;
|
||||
}
|
||||
|
||||
// SetShape changes the active shape mode, which can change the natural fill default (e.g. Line/Spiral/Grid have no fill).
|
||||
// Trigger a re-sync afterward so the controls reflect either the current selection or the new natural default.
|
||||
// Note: the `UpdateOptions { ShapeType(_) }` variant matches the `let else` below and is handled by the `ShapeType` arm,
|
||||
// so it can't reach the `else` block where this flag is read — only `SetShape` (the FSM-routed alias) can.
|
||||
let is_set_shape = matches!(&message, ToolMessage::Shape(ShapeToolMessage::SetShape { .. }));
|
||||
let shape_before = self.tool_data.current_shape;
|
||||
|
||||
let ToolMessage::Shape(ShapeToolMessage::UpdateOptions { options }) = message else {
|
||||
self.fsm_state.process_event(message, &mut self.tool_data, context, &self.options, responses, true);
|
||||
if is_set_shape {
|
||||
handle_shape_mode_change(&mut self.options, self.tool_data.current_shape, shape_before, context.global_tool_data, context.document);
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
return;
|
||||
};
|
||||
match options {
|
||||
ShapeOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
ShapeOptionsUpdate::FillColor(fill_choice) => {
|
||||
apply_fill_color_pick(&mut self.options.drawing, fill_choice, context.document, responses);
|
||||
}
|
||||
ShapeOptionsUpdate::FillColorType(color_type) => {
|
||||
self.options.fill.color_type = color_type;
|
||||
ShapeOptionsUpdate::FillEnabled(enabled) => {
|
||||
// When toggled with no selection, persist the new state as the current shape mode's default
|
||||
if !has_selection(context.document) {
|
||||
self.options.shape_fill_defaults.insert(self.tool_data.current_shape, enabled);
|
||||
}
|
||||
apply_fill_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
ShapeOptionsUpdate::LineWeight(line_weight) => {
|
||||
self.options.line_weight = line_weight;
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, context.document, responses);
|
||||
ShapeOptionsUpdate::StrokeOption(update) => {
|
||||
apply_stroke_option(&mut self.options.drawing, update, context.document, responses);
|
||||
}
|
||||
ShapeOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
apply_stroke_color_pick(&mut self.options.drawing, color, context.document, responses);
|
||||
}
|
||||
ShapeOptionsUpdate::StrokeColorType(color_type) => {
|
||||
self.options.stroke.color_type = color_type;
|
||||
ShapeOptionsUpdate::StrokeEnabled(enabled) => {
|
||||
// When toggled with no selection, persist the new state as the current shape mode's default
|
||||
if !has_selection(context.document) {
|
||||
self.options.shape_stroke_defaults.insert(self.tool_data.current_shape, enabled);
|
||||
}
|
||||
apply_stroke_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
ShapeOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
ShapeOptionsUpdate::SwapFillAndStroke => {
|
||||
swap_fill_and_stroke(&mut self.options.drawing, context.document, responses);
|
||||
// Persist the new swap state as the current shape mode's default
|
||||
self.options.shape_colors_swapped.insert(self.tool_data.current_shape, self.options.drawing.colors_swapped);
|
||||
}
|
||||
ShapeOptionsUpdate::WorkingColorsChanged => {
|
||||
apply_working_colors(&mut self.options.drawing, context.global_tool_data, context.document);
|
||||
}
|
||||
ShapeOptionsUpdate::ShapeType(shape) => {
|
||||
self.options.shape_type = shape;
|
||||
self.tool_data.current_shape = shape;
|
||||
handle_shape_mode_change(&mut self.options, shape, shape_before, context.global_tool_data, context.document);
|
||||
}
|
||||
ShapeOptionsUpdate::Vertices(vertices) => {
|
||||
self.options.vertices = vertices;
|
||||
@@ -806,7 +848,6 @@ impl Fsm for ShapeToolFsmState {
|
||||
tool_data: &mut Self::ToolData,
|
||||
ToolActionMessageContext {
|
||||
document,
|
||||
global_tool_data,
|
||||
input,
|
||||
shape_editor,
|
||||
viewport,
|
||||
@@ -1117,8 +1158,8 @@ impl Fsm for ShapeToolFsmState {
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, defered_responses);
|
||||
tool_options.fill.apply_fill(layer, defered_responses);
|
||||
tool_options.drawing.apply_stroke_to_new_layer(layer, defered_responses);
|
||||
tool_options.drawing.fill.apply_fill(layer, defered_responses);
|
||||
}
|
||||
ShapeType::Arrow => {
|
||||
let viewport_drag_start = tool_data.data.viewport_drag_start(document);
|
||||
@@ -1129,10 +1170,10 @@ impl Fsm for ShapeToolFsmState {
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
tool_data.line_data.weight = tool_options.line_weight;
|
||||
tool_data.line_data.weight = tool_options.drawing.effective_line_weight();
|
||||
tool_data.line_data.editing_layer = Some(layer);
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, defered_responses);
|
||||
tool_options.fill.apply_fill(layer, defered_responses);
|
||||
tool_options.drawing.apply_stroke_to_new_layer(layer, defered_responses);
|
||||
tool_options.drawing.fill.apply_fill(layer, defered_responses);
|
||||
}
|
||||
ShapeType::Line => {
|
||||
let viewport_drag_start = tool_data.data.viewport_drag_start(document);
|
||||
@@ -1143,9 +1184,9 @@ impl Fsm for ShapeToolFsmState {
|
||||
skip_rerender: false,
|
||||
});
|
||||
|
||||
tool_data.line_data.weight = tool_options.line_weight;
|
||||
tool_data.line_data.weight = tool_options.drawing.effective_line_weight();
|
||||
tool_data.line_data.editing_layer = Some(layer);
|
||||
tool_options.stroke.apply_stroke(tool_options.line_weight, layer, defered_responses);
|
||||
tool_options.drawing.apply_stroke_to_new_layer(layer, defered_responses);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1351,7 +1392,7 @@ impl Fsm for ShapeToolFsmState {
|
||||
}
|
||||
(_, ShapeToolMessage::WorkingColorChanged) => {
|
||||
responses.add(ShapeToolMessage::UpdateOptions {
|
||||
options: ShapeOptionsUpdate::WorkingColors(Some(global_tool_data.primary_color), Some(global_tool_data.secondary_color)),
|
||||
options: ShapeOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{DEFAULT_STROKE_WIDTH, DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
|
||||
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
|
||||
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
|
||||
@@ -7,12 +7,17 @@ use crate::messages::portfolio::document::overlays::utility_functions::path_endp
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::color_selector::{
|
||||
DrawingToolState, apply_fill_color_pick, apply_fill_enabled, apply_stroke_color_pick, apply_stroke_enabled, apply_working_colors, reset_colors_on_deactivation, swap_fill_and_stroke,
|
||||
sync_drawing_state,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{self, find_spline, merge_layers, merge_points};
|
||||
use crate::messages::tool::common_functionality::snapping::{SnapCandidatePoint, SnapData, SnapManager, SnapTypeConfiguration, SnappedPoint};
|
||||
use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsUpdate, apply_stroke_option, create_stroke_options_popover_widget};
|
||||
use crate::messages::tool::common_functionality::utility_functions::{closest_point, should_extend};
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::Color;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
@@ -23,17 +28,13 @@ pub struct SplineTool {
|
||||
}
|
||||
|
||||
pub struct SplineOptions {
|
||||
line_weight: f64,
|
||||
fill: ToolColorOptions,
|
||||
stroke: ToolColorOptions,
|
||||
drawing: DrawingToolState,
|
||||
}
|
||||
|
||||
impl Default for SplineOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
line_weight: DEFAULT_STROKE_WIDTH,
|
||||
fill: ToolColorOptions::new_none(),
|
||||
stroke: ToolColorOptions::new_primary(),
|
||||
drawing: DrawingToolState::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,12 +72,13 @@ enum SplineToolFsmState {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SplineOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
LineWeight(f64),
|
||||
FillColor(FillChoice),
|
||||
FillEnabled(bool),
|
||||
StrokeOption(StrokeOptionsUpdate),
|
||||
StrokeColor(Option<Color>),
|
||||
StrokeColorType(ToolColorType),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
StrokeEnabled(bool),
|
||||
SwapFillAndStroke,
|
||||
WorkingColorsChanged,
|
||||
}
|
||||
|
||||
impl ToolMetadata for SplineTool {
|
||||
@@ -91,76 +93,60 @@ impl ToolMetadata for SplineTool {
|
||||
}
|
||||
}
|
||||
|
||||
fn create_weight_widget(line_weight: f64) -> WidgetInstance {
|
||||
NumberInput::new(Some(line_weight))
|
||||
.unit(" px")
|
||||
.label("Weight")
|
||||
.min(0.)
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.on_update(|number_input: &NumberInput| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::LineWeight(number_input.value.unwrap()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance()
|
||||
}
|
||||
|
||||
impl LayoutHolder for SplineTool {
|
||||
fn layout(&self) -> Layout {
|
||||
let mut widgets = self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| {
|
||||
let mut widgets = self.options.drawing.fill.create_widgets(
|
||||
"Fill:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::FillColor(None),
|
||||
options: SplineOptionsUpdate::FillEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::FillColorType(color_type.clone()),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: SplineOptionsUpdate::FillColor(FillChoice::from(&color.value)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.stroke.create_widgets(
|
||||
"Stroke",
|
||||
true,
|
||||
|_| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::StrokeColor(None),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
widgets.push(
|
||||
IconButton::new("SwapHorizontal", 16)
|
||||
.tooltip_label("Swap Fill/Stroke Colors")
|
||||
.on_update(|_| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::StrokeColorType(color_type.clone()),
|
||||
options: SplineOptionsUpdate::SwapFillAndStroke,
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
);
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.drawing.stroke.create_widgets(
|
||||
"Stroke:",
|
||||
|checkbox: &CheckboxInput| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::StrokeEnabled(checkbox.checked),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::StrokeColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
options: SplineOptionsUpdate::StrokeColor(color.value.as_solid().map(Color::from)),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
widgets.push(create_weight_widget(self.options.line_weight));
|
||||
let weight_disabled = self.options.drawing.stroke.enabled == Some(false);
|
||||
widgets.push(create_stroke_options_popover_widget(&self.options.drawing, weight_disabled, |update| {
|
||||
SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::StrokeOption(update),
|
||||
}
|
||||
.into()
|
||||
}));
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
@@ -169,12 +155,18 @@ impl LayoutHolder for SplineTool {
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for SplineTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
// On tool deactivation (Abort fires from the dispatcher's tool transition), reset the displayed fill/stroke colors so
|
||||
// the next activation starts fresh from the current working colors. The global swap state persists across tool switches.
|
||||
// Guarded on `Ready` so Esc-mid-drawing (which also fires Abort) doesn't wipe the user's customized fill/stroke options.
|
||||
if matches!(&message, ToolMessage::Spline(SplineToolMessage::Abort)) && self.fsm_state == SplineToolFsmState::Ready {
|
||||
reset_colors_on_deactivation(&mut self.options.drawing, context.global_tool_data);
|
||||
}
|
||||
|
||||
if matches!(&message, ToolMessage::Spline(SplineToolMessage::SelectionChanged)) {
|
||||
if self.fsm_state == SplineToolFsmState::Ready
|
||||
&& let Some(weight) = graph_modification_utils::first_selected_stroke_weight(context.document)
|
||||
&& self.options.line_weight != weight
|
||||
{
|
||||
self.options.line_weight = weight;
|
||||
if self.fsm_state != SplineToolFsmState::Ready {
|
||||
return;
|
||||
}
|
||||
if sync_drawing_state(&mut self.options.drawing, false, true, context.global_tool_data, context.document) {
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions);
|
||||
}
|
||||
return;
|
||||
@@ -185,25 +177,26 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Spli
|
||||
return;
|
||||
};
|
||||
match options {
|
||||
SplineOptionsUpdate::LineWeight(line_weight) => {
|
||||
self.options.line_weight = line_weight;
|
||||
graph_modification_utils::set_stroke_weight_for_selected_layers(line_weight, context.document, responses);
|
||||
SplineOptionsUpdate::StrokeOption(update) => {
|
||||
apply_stroke_option(&mut self.options.drawing, update, context.document, responses);
|
||||
}
|
||||
SplineOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
SplineOptionsUpdate::FillColor(fill_choice) => {
|
||||
apply_fill_color_pick(&mut self.options.drawing, fill_choice, context.document, responses);
|
||||
}
|
||||
SplineOptionsUpdate::FillEnabled(enabled) => {
|
||||
apply_fill_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
SplineOptionsUpdate::FillColorType(color_type) => self.options.fill.color_type = color_type,
|
||||
SplineOptionsUpdate::StrokeColor(color) => {
|
||||
self.options.stroke.custom_color = color;
|
||||
self.options.stroke.color_type = ToolColorType::Custom;
|
||||
apply_stroke_color_pick(&mut self.options.drawing, color, context.document, responses);
|
||||
}
|
||||
SplineOptionsUpdate::StrokeColorType(color_type) => self.options.stroke.color_type = color_type,
|
||||
SplineOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.stroke.primary_working_color = primary;
|
||||
self.options.stroke.secondary_working_color = secondary;
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
SplineOptionsUpdate::StrokeEnabled(enabled) => {
|
||||
apply_stroke_enabled(&mut self.options.drawing, enabled, context.global_tool_data, context.document, responses);
|
||||
}
|
||||
SplineOptionsUpdate::SwapFillAndStroke => {
|
||||
swap_fill_and_stroke(&mut self.options.drawing, context.document, responses);
|
||||
}
|
||||
SplineOptionsUpdate::WorkingColorsChanged => {
|
||||
apply_working_colors(&mut self.options.drawing, context.global_tool_data, context.document);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,7 +304,6 @@ impl Fsm for SplineToolFsmState {
|
||||
) -> Self {
|
||||
let ToolActionMessageContext {
|
||||
document,
|
||||
global_tool_data,
|
||||
input,
|
||||
shape_editor,
|
||||
viewport,
|
||||
@@ -359,7 +351,7 @@ impl Fsm for SplineToolFsmState {
|
||||
|
||||
tool_data.snap_manager.cleanup(responses);
|
||||
tool_data.cleanup();
|
||||
tool_data.weight = tool_options.line_weight;
|
||||
tool_data.weight = tool_options.drawing.effective_line_weight();
|
||||
|
||||
let point = SnapCandidatePoint::handle(document.metadata().document_to_viewport.inverse().transform_point2(input.mouse.position));
|
||||
let snapped = tool_data.snap_manager.free_snap(&SnapData::new(document, input, viewport), &point, SnapTypeConfiguration::default());
|
||||
@@ -415,8 +407,8 @@ impl Fsm for SplineToolFsmState {
|
||||
let nodes = vec![(NodeId(1), path_node), (NodeId(0), spline_node)];
|
||||
|
||||
let layer = graph_modification_utils::new_custom(NodeId::new(), nodes, parent, responses);
|
||||
tool_options.stroke.apply_stroke(tool_data.weight, layer, responses);
|
||||
tool_options.fill.apply_fill(layer, responses);
|
||||
tool_options.drawing.apply_stroke_to_new_layer(layer, responses);
|
||||
tool_options.drawing.fill.apply_fill(layer, responses);
|
||||
tool_data.current_layer = Some(layer);
|
||||
tool_data.new_layer_viewport_start = Some(viewport_vec);
|
||||
|
||||
@@ -545,7 +537,7 @@ impl Fsm for SplineToolFsmState {
|
||||
}
|
||||
(_, SplineToolMessage::WorkingColorChanged) => {
|
||||
responses.add(SplineToolMessage::UpdateOptions {
|
||||
options: SplineOptionsUpdate::WorkingColors(Some(global_tool_data.primary_color), Some(global_tool_data.secondary_color)),
|
||||
options: SplineOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
@@ -8,7 +8,9 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::portfolio::utility_types::{CachedData, FontCatalog, FontCatalogStyle};
|
||||
use crate::messages::tool::common_functionality::auto_panning::AutoPanning;
|
||||
use crate::messages::tool::common_functionality::color_selector::{ToolColorOptions, ToolColorType};
|
||||
use crate::messages::tool::common_functionality::color_selector::{
|
||||
ToolColorOptions, apply_fill_only_color_pick, apply_fill_only_enabled, refresh_slot_working_color, selection_changed_since_last_sync, solid, sync_fill_only,
|
||||
};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::common_functionality::resize::Resize;
|
||||
use crate::messages::tool::common_functionality::snapping::{self, SnapCandidatePoint, SnapData};
|
||||
@@ -18,9 +20,10 @@ use crate::messages::tool::utility_types::ToolRefreshOptions;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::choice_type::ChoiceTypeStatic;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::renderer::Quad;
|
||||
use graphene_std::text::{Font, FontCache, TextAlign, TypesettingConfig, lines_clipping};
|
||||
use graphene_std::vector::style::Fill;
|
||||
use graphene_std::vector::style::{Fill, FillChoice, FillChoiceUI};
|
||||
use graphene_std::{Color, NodeInputDecleration};
|
||||
|
||||
#[derive(Default, ExtractField)]
|
||||
@@ -37,6 +40,8 @@ pub struct TextOptions {
|
||||
fill: ToolColorOptions,
|
||||
tilt: f64,
|
||||
align: TextAlign,
|
||||
/// Set of layers we last synced from, used to detect real selection changes vs. internal node toggles.
|
||||
last_synced_selection: Vec<LayerNodeIdentifier>,
|
||||
}
|
||||
|
||||
impl Default for TextOptions {
|
||||
@@ -45,9 +50,10 @@ impl Default for TextOptions {
|
||||
font_size: 24.,
|
||||
character_spacing: 0.,
|
||||
font: Font::new(graphene_std::consts::DEFAULT_FONT_FAMILY.into(), graphene_std::consts::DEFAULT_FONT_STYLE.into()),
|
||||
fill: ToolColorOptions::new_primary(),
|
||||
fill: ToolColorOptions::new_enabled(),
|
||||
tilt: 0.,
|
||||
align: TextAlign::default(),
|
||||
last_synced_selection: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,12 +84,12 @@ pub enum TextToolMessage {
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum TextOptionsUpdate {
|
||||
FillColor(Option<Color>),
|
||||
FillColorType(ToolColorType),
|
||||
FillColor(FillChoice),
|
||||
FillEnabled(bool),
|
||||
Font { font: Font },
|
||||
FontSize(f64),
|
||||
Align(TextAlign),
|
||||
WorkingColors(Option<Color>, Option<Color>),
|
||||
WorkingColorsChanged,
|
||||
}
|
||||
|
||||
impl ToolMetadata for TextTool {
|
||||
@@ -263,34 +269,21 @@ impl TextTool {
|
||||
}
|
||||
|
||||
fn layout(&self, font_catalog: &FontCatalog, document: &DocumentMessageHandler) -> Layout {
|
||||
let mut widgets = create_text_widgets(self, font_catalog, document);
|
||||
|
||||
widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
widgets.append(&mut self.options.fill.create_widgets(
|
||||
"Fill",
|
||||
true,
|
||||
|_| {
|
||||
TextToolMessage::UpdateOptions {
|
||||
options: TextOptionsUpdate::FillColor(None),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
|color_type: ToolColorType| {
|
||||
WidgetCallback::new(move |_| {
|
||||
let mut widgets = vec![
|
||||
ColorInput::new(FillChoiceUI::from(self.options.fill.fill_choice.as_ref().unwrap_or(&FillChoice::None)))
|
||||
.mixed(self.options.fill.fill_choice.is_none())
|
||||
.narrow(true)
|
||||
.on_update(|color: &ColorInput| {
|
||||
TextToolMessage::UpdateOptions {
|
||||
options: TextOptionsUpdate::FillColorType(color_type.clone()),
|
||||
options: TextOptionsUpdate::FillColor(FillChoice::from(&color.value)),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
},
|
||||
|color: &ColorInput| {
|
||||
TextToolMessage::UpdateOptions {
|
||||
options: TextOptionsUpdate::FillColor(color.value.as_solid().map(|color| color.to_linear_srgb())),
|
||||
}
|
||||
.into()
|
||||
},
|
||||
));
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
];
|
||||
|
||||
widgets.extend(create_text_widgets(self, font_catalog, document));
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
@@ -299,6 +292,13 @@ impl TextTool {
|
||||
#[message_handler_data]
|
||||
impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for TextTool {
|
||||
fn process_message(&mut self, message: ToolMessage, responses: &mut VecDeque<Message>, context: &mut ToolActionMessageContext<'a>) {
|
||||
// On tool deactivation (Abort fires from the dispatcher's tool transition),
|
||||
// reset the displayed fill color so the next activation starts fresh from the current working color.
|
||||
// Guarded on `Ready` so Esc-mid-editing (which also fires Abort) doesn't wipe the user's customized fill option.
|
||||
if matches!(&message, ToolMessage::Text(TextToolMessage::Abort)) && self.fsm_state == TextToolFsmState::Ready {
|
||||
self.options.fill.fill_choice = Some(solid(context.global_tool_data.primary_color));
|
||||
}
|
||||
|
||||
let options = match message {
|
||||
ToolMessage::Text(TextToolMessage::UpdateOptions { options }) => options,
|
||||
ToolMessage::Text(TextToolMessage::SelectionChanged) => {
|
||||
@@ -314,6 +314,18 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
editing_text.font = font.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Only sync from a text selection; reading a non-text layer's fill would pollute the swatch
|
||||
let selection_changed = selection_changed_since_last_sync(&mut self.options.last_synced_selection, context.document);
|
||||
if can_edit_selected(context.document).is_some() {
|
||||
sync_fill_only(&mut self.options.fill, true, context.global_tool_data.primary_color, context.document, selection_changed);
|
||||
} else if selection_changed {
|
||||
self.options.fill.fill_choice = Some(solid(context.global_tool_data.primary_color));
|
||||
self.options.fill.tracks_working_color = true;
|
||||
}
|
||||
// Text tool has no fill checkbox; keep enabled so new text never starts with `None`
|
||||
self.options.fill.enabled = Some(true);
|
||||
|
||||
self.send_layout(responses, LayoutTarget::ToolOptions, &context.cached_data.font_catalog, context.document);
|
||||
return;
|
||||
}
|
||||
@@ -361,14 +373,15 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
|
||||
});
|
||||
}
|
||||
}
|
||||
TextOptionsUpdate::FillColor(color) => {
|
||||
self.options.fill.custom_color = color;
|
||||
self.options.fill.color_type = ToolColorType::Custom;
|
||||
TextOptionsUpdate::FillColor(fill_choice) => {
|
||||
// Text fill is bound to the primary working color (no swap concept).
|
||||
apply_fill_only_color_pick(&mut self.options.fill, fill_choice, true, context.document, responses);
|
||||
}
|
||||
TextOptionsUpdate::FillColorType(color_type) => self.options.fill.color_type = color_type,
|
||||
TextOptionsUpdate::WorkingColors(primary, secondary) => {
|
||||
self.options.fill.primary_working_color = primary;
|
||||
self.options.fill.secondary_working_color = secondary;
|
||||
TextOptionsUpdate::FillEnabled(enabled) => {
|
||||
apply_fill_only_enabled(&mut self.options.fill, enabled, context.global_tool_data.primary_color, context.document, responses);
|
||||
}
|
||||
TextOptionsUpdate::WorkingColorsChanged => {
|
||||
refresh_slot_working_color(&mut self.options.fill, context.global_tool_data.primary_color, context.document);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -485,7 +498,7 @@ impl TextToolData {
|
||||
text: editing_text.text.clone(),
|
||||
line_height_ratio: editing_text.typesetting.line_height_ratio,
|
||||
font_size: editing_text.typesetting.font_size,
|
||||
color: editing_text.color.map_or("#000000".to_string(), |color| format!("#{}", color.to_rgba_hex_srgb())),
|
||||
color: editing_text.color.map_or("#000000".to_string(), |color| SRGBA8::from(color).to_css_hex()),
|
||||
font_data: font_cache.get(&editing_text.font).map(|(data, _)| data.clone()).unwrap_or_default().into(),
|
||||
transform: editing_text.transform.to_cols_array(),
|
||||
max_width: editing_text.typesetting.max_width,
|
||||
@@ -562,7 +575,7 @@ impl TextToolData {
|
||||
});
|
||||
responses.add(GraphOperationMessage::FillSet {
|
||||
layer: self.layer,
|
||||
fill: if let Some(color) = editing_text.color { Fill::Solid(color.to_gamma_srgb()) } else { Fill::None },
|
||||
fill: if let Some(color) = editing_text.color { Fill::Solid(color) } else { Fill::None },
|
||||
});
|
||||
let transform = editing_text.transform;
|
||||
self.editing_text = Some(editing_text);
|
||||
@@ -618,9 +631,10 @@ fn can_edit_selected(document: &DocumentMessageHandler) -> Option<LayerNodeIdent
|
||||
return None;
|
||||
}
|
||||
|
||||
if !document.metadata().is_text_layer(layer) {
|
||||
return None;
|
||||
}
|
||||
// Detect text layers by the presence of a Text proto node in the chain, not via `metadata().is_text_layer()` which is
|
||||
// populated lazily by the renderer after `RunDocumentGraph`. A freshly created text layer's `text_frames` entry isn't
|
||||
// available yet when SelectionChanged fires, so the metadata check would incorrectly classify it as non-text.
|
||||
graph_modification_utils::get_text_id(layer, &document.network_interface)?;
|
||||
|
||||
Some(layer)
|
||||
}
|
||||
@@ -639,7 +653,6 @@ impl Fsm for TextToolFsmState {
|
||||
) -> Self {
|
||||
let ToolActionMessageContext {
|
||||
document,
|
||||
global_tool_data,
|
||||
input,
|
||||
cached_data,
|
||||
viewport,
|
||||
@@ -1036,7 +1049,7 @@ impl Fsm for TextToolFsmState {
|
||||
}
|
||||
(_, TextToolMessage::WorkingColorChanged) => {
|
||||
responses.add(TextToolMessage::UpdateOptions {
|
||||
options: TextOptionsUpdate::WorkingColors(Some(global_tool_data.primary_color), Some(global_tool_data.secondary_color)),
|
||||
options: TextOptionsUpdate::WorkingColorsChanged,
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use crate::messages::preferences::PreferencesMessageHandler;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::ShapeType;
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::color::Color;
|
||||
use std::borrow::Cow;
|
||||
use std::fmt::{self, Debug};
|
||||
@@ -128,9 +129,7 @@ pub struct DocumentToolData {
|
||||
impl DocumentToolData {
|
||||
pub fn update_working_colors(&self, responses: &mut VecDeque<Message>) {
|
||||
let layout = Layout(vec![
|
||||
LayoutGroup::row(vec![
|
||||
WorkingColorsInput::new(self.primary_color.to_gamma_srgb(), self.secondary_color.to_gamma_srgb()).widget_instance(),
|
||||
]),
|
||||
LayoutGroup::row(vec![WorkingColorsInput::new(SRGBA8::from(self.primary_color), SRGBA8::from(self.secondary_color)).widget_instance()]),
|
||||
LayoutGroup::row(vec![
|
||||
IconButton::new("SwapVertical", 16)
|
||||
.tooltip_label("Swap Working Colors")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{ExportAnimationFrame, ExportBounds, FileType};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::EditorPreferences;
|
||||
@@ -6,12 +6,15 @@ use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{NodeGraphUpdateMessage, RenderConfig, TimingInformation};
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::RenderMetadata;
|
||||
use graphene_std::text::FontCache;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
mod runtime_io;
|
||||
pub use runtime_io::NodeRuntimeIO;
|
||||
@@ -58,6 +61,23 @@ pub struct NodeGraphExecutor {
|
||||
/// so the runtime can splice its monitor node alongside the target rather than only at the top level.
|
||||
/// Tracking the previously-sent value lets `update_node_graph` re-send the network when the inspection target changes.
|
||||
previous_node_to_inspect: Vec<NodeId>,
|
||||
/// Per-export accumulator for in-progress animation exports. Each frame execution pushes its rendered output here into the matching u64 export ID slot.
|
||||
/// Once `frames_received == total_frames`, the accumulator is drained into a single `TriggerExportAnimation` message.
|
||||
pending_animation_exports: HashMap<u64, AnimationExportAccumulator>,
|
||||
next_animation_export_id: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AnimationExportAccumulator {
|
||||
name: String,
|
||||
file_type: FileType,
|
||||
size: UVec2,
|
||||
folder: Option<PathBuf>,
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
frames: Vec<Option<ExportAnimationFrame>>,
|
||||
frames_received: u32,
|
||||
total_frames: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -80,6 +100,8 @@ impl NodeGraphExecutor {
|
||||
node_graph_hash: 0,
|
||||
current_execution_id: 0,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
pending_animation_exports: HashMap::new(),
|
||||
next_animation_export_id: 0,
|
||||
};
|
||||
(node_runtime, node_executor)
|
||||
}
|
||||
@@ -263,7 +285,7 @@ impl NodeGraphExecutor {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let render_config = RenderConfig {
|
||||
let base_render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: export_config.scale_factor,
|
||||
time: Default::default(),
|
||||
@@ -275,18 +297,78 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
export_config.size = resolution;
|
||||
|
||||
// Execute the node graph
|
||||
// Send the network update once; the runtime keeps it for all subsequent executions.
|
||||
self.runtime_io
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, node_to_inspect: Vec::new() }))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
},
|
||||
));
|
||||
|
||||
if let Some(animation) = export_config.animation {
|
||||
// Defense-in-depth: the dialog already validates these, but reject non-finite/non-positive values here
|
||||
// too so a corrupt message can't reach `Duration::from_secs_f64` (which panics on NaN/negative/huge).
|
||||
if !animation.fps.is_finite() || animation.fps <= 0. || !animation.start_seconds.is_finite() {
|
||||
return Err("Animation export rejected: fps and start time must be finite, with fps > 0".to_string());
|
||||
}
|
||||
|
||||
// Allocate an export ID and accumulator, then queue one execution per frame.
|
||||
// TODO: All encoded frames are held in `pending_animation_exports` until the last frame arrives, so peak
|
||||
// memory grows with `total_frames * encoded_frame_size`. For long/high-resolution animations, this could
|
||||
// exhaust memory. A bounded cap is enforced upstream in the export dialog (ANIMATION_EXPORT_MAX_FRAMES),
|
||||
// but a true fix would stream frames out incrementally instead of accumulating.
|
||||
let export_id = self.next_animation_export_id;
|
||||
self.next_animation_export_id = self.next_animation_export_id.wrapping_add(1);
|
||||
|
||||
let folder = document.path.as_ref().and_then(|path| path.parent()).map(|parent| parent.to_path_buf());
|
||||
self.pending_animation_exports.insert(
|
||||
export_id,
|
||||
AnimationExportAccumulator {
|
||||
name: export_config.name.clone(),
|
||||
file_type: export_config.file_type,
|
||||
size: resolution,
|
||||
folder,
|
||||
artboard_name: export_config.artboard_name.clone(),
|
||||
artboard_count: export_config.artboard_count,
|
||||
frames: (0..animation.total_frames).map(|_| None).collect(),
|
||||
frames_received: 0,
|
||||
total_frames: animation.total_frames,
|
||||
},
|
||||
);
|
||||
|
||||
for frame_index in 0..animation.total_frames {
|
||||
let frame_seconds = animation.frame_time_seconds(frame_index);
|
||||
// `Duration::from_secs_f64` panics on negative/NaN/huge values; clamp defensively (we've already
|
||||
// validated `fps`/`start_seconds` above, but a far-future `start_seconds` could still overflow).
|
||||
let safe_seconds = if frame_seconds.is_finite() { frame_seconds.clamp(0., 1e9) } else { 0. };
|
||||
let animation_time = Duration::from_secs_f64(safe_seconds);
|
||||
let timing = TimingInformation { time: frame_seconds, animation_time };
|
||||
|
||||
let frame_render_config = RenderConfig { time: timing, ..base_render_config };
|
||||
|
||||
let mut frame_export_config = export_config.clone();
|
||||
frame_export_config.animation_frame = Some(AnimationExportFrame {
|
||||
export_id,
|
||||
frame_index,
|
||||
total_frames: animation.total_frames,
|
||||
});
|
||||
|
||||
let execution_id = self.queue_execution(frame_render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(frame_export_config),
|
||||
document_id,
|
||||
},
|
||||
));
|
||||
}
|
||||
} else {
|
||||
let execution_id = self.queue_execution(base_render_config);
|
||||
self.futures.push_back((
|
||||
execution_id,
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -313,6 +395,24 @@ impl NodeGraphExecutor {
|
||||
document.network_interface.update_click_targets(HashMap::new());
|
||||
document.network_interface.update_outlines(HashMap::new());
|
||||
document.network_interface.update_vector_modify(HashMap::new());
|
||||
|
||||
// If this failure belongs to an animation export, drop its accumulator so the partially
|
||||
// rendered frames don't stay pinned in memory. Subsequent failed frames for the same
|
||||
// export are then silently ignored by `process_animation_frame`.
|
||||
// TODO: An export can also leak if it's interrupted by something *outside* this error
|
||||
// path — e.g. the document is closed mid-export. A proper fix would route a
|
||||
// cancellation through `pending_animation_exports`. Tracked separately.
|
||||
let leaked_export_id = self
|
||||
.futures
|
||||
.iter()
|
||||
.find(|(fid, _)| *fid == execution_id)
|
||||
.and_then(|(_, ctx)| ctx.export_config.as_ref())
|
||||
.and_then(|cfg| cfg.animation_frame)
|
||||
.map(|af| af.export_id);
|
||||
if let Some(export_id) = leaked_export_id {
|
||||
self.pending_animation_exports.remove(&export_id);
|
||||
}
|
||||
|
||||
return Err(format!("Node graph evaluation failed:\n{e}"));
|
||||
}
|
||||
};
|
||||
@@ -398,7 +498,21 @@ impl NodeGraphExecutor {
|
||||
|
||||
match render_output.data {
|
||||
RenderOutputType::Svg { svg, image_data } => {
|
||||
// Send to frontend
|
||||
// Convert each linear-light `Image<Color>` into the JS-boundary `Image<SRGBA8>` form (gamma byte channels) before dispatching.
|
||||
let image_data = image_data
|
||||
.into_iter()
|
||||
.map(|(id, image)| {
|
||||
(
|
||||
id,
|
||||
graphene_std::raster::Image {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(),
|
||||
base64_string: image.base64_string,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
responses.add(FrontendMessage::UpdateImageData { image_data });
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
@@ -444,7 +558,12 @@ impl NodeGraphExecutor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
fn process_export(&mut self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) -> Result<(), String> {
|
||||
// Route animation frames into the per-export accumulator. The final message is emitted when all frames arrive.
|
||||
if let Some(animation_frame) = export_config.animation_frame {
|
||||
return self.process_animation_frame(node_graph_output, &export_config, animation_frame, responses);
|
||||
}
|
||||
|
||||
let ExportConfig {
|
||||
file_type,
|
||||
name,
|
||||
@@ -488,43 +607,7 @@ impl NodeGraphExecutor {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => {
|
||||
use image::buffer::ConvertBuffer;
|
||||
use image::{ImageFormat, RgbImage, RgbaImage};
|
||||
|
||||
let Some(mut image) = RgbaImage::from_raw(width, height, data) else {
|
||||
return Err("Failed to create image buffer for export".to_string());
|
||||
};
|
||||
|
||||
let mut encoded = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(&mut encoded);
|
||||
|
||||
match file_type {
|
||||
FileType::Png => {
|
||||
let result = image.write_to(&mut cursor, ImageFormat::Png);
|
||||
if let Err(err) = result {
|
||||
return Err(format!("Failed to encode PNG: {err}"));
|
||||
}
|
||||
}
|
||||
FileType::Jpg => {
|
||||
// Composite onto a white background since JPG doesn't support transparency
|
||||
for pixel in image.pixels_mut() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
let alpha = a as f32 / 255.;
|
||||
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
|
||||
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
|
||||
}
|
||||
|
||||
let image: RgbImage = image.convert();
|
||||
let result = image.write_to(&mut cursor, ImageFormat::Jpeg);
|
||||
if let Err(err) = result {
|
||||
return Err(format!("Failed to encode JPG: {err}"));
|
||||
}
|
||||
}
|
||||
FileType::Svg => {
|
||||
return Err("SVG cannot be exported from an image buffer".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let encoded = encode_raster_buffer(file_type, data, width, height)?;
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name,
|
||||
folder,
|
||||
@@ -538,6 +621,115 @@ impl NodeGraphExecutor {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn process_animation_frame(
|
||||
&mut self,
|
||||
node_graph_output: TaggedValue,
|
||||
export_config: &ExportConfig,
|
||||
animation_frame: AnimationExportFrame,
|
||||
responses: &mut VecDeque<Message>,
|
||||
) -> Result<(), String> {
|
||||
let file_type = export_config.file_type;
|
||||
|
||||
let frame_data = match node_graph_output {
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => ExportAnimationFrame::Svg(svg),
|
||||
#[cfg(feature = "gpu")]
|
||||
TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Buffer { data, width, height },
|
||||
..
|
||||
}) if file_type != FileType::Svg => match encode_raster_buffer(file_type, data, width, height) {
|
||||
Ok(encoded) => ExportAnimationFrame::Bytes(serde_bytes::ByteBuf::from(encoded)),
|
||||
Err(err) => {
|
||||
// Drop the partial accumulator so its already-received frames don't leak.
|
||||
self.pending_animation_exports.remove(&animation_frame.export_id);
|
||||
return Err(err);
|
||||
}
|
||||
},
|
||||
other => {
|
||||
// Drop the partial accumulator so its already-received frames don't leak.
|
||||
self.pending_animation_exports.remove(&animation_frame.export_id);
|
||||
return Err(format!("Incorrect render type for animation frame ({file_type:?}, {other})"));
|
||||
}
|
||||
};
|
||||
|
||||
let Some(accumulator) = self.pending_animation_exports.get_mut(&animation_frame.export_id) else {
|
||||
// Export was cancelled or already finalized, drop it quietly
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let index = animation_frame.frame_index as usize;
|
||||
if let Some(slot) = accumulator.frames.get_mut(index)
|
||||
&& slot.is_none()
|
||||
{
|
||||
*slot = Some(frame_data);
|
||||
accumulator.frames_received += 1;
|
||||
}
|
||||
|
||||
if accumulator.frames_received < accumulator.total_frames {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// All frames received: drain the accumulator and emit a single message
|
||||
let accumulator = self.pending_animation_exports.remove(&animation_frame.export_id).expect("Accumulator was present");
|
||||
// Sanitize before the name reaches filesystem joins or zip entry names downstream.
|
||||
let safe_doc_name = crate::messages::frontend::utility_types::sanitize_filename_component(&accumulator.name);
|
||||
let base_name = match (accumulator.artboard_name.as_deref(), accumulator.artboard_count) {
|
||||
(Some(artboard_name), count) if count > 1 => format!("{safe_doc_name} - {}", crate::messages::frontend::utility_types::sanitize_filename_component(artboard_name)),
|
||||
_ => safe_doc_name,
|
||||
};
|
||||
let frames: Vec<_> = accumulator
|
||||
.frames
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| f.ok_or_else(|| format!("Missing animation frame {i}")))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
responses.add(FrontendMessage::TriggerExportAnimation {
|
||||
name: base_name,
|
||||
extension: accumulator.file_type.to_extension().to_string(),
|
||||
mime: accumulator.file_type.to_mime().to_string(),
|
||||
size: accumulator.size.as_dvec2().into(),
|
||||
folder: accumulator.folder,
|
||||
frames,
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "gpu")]
|
||||
fn encode_raster_buffer(file_type: FileType, data: Vec<u8>, width: u32, height: u32) -> Result<Vec<u8>, String> {
|
||||
use image::buffer::ConvertBuffer;
|
||||
use image::{ImageFormat, RgbImage, RgbaImage};
|
||||
|
||||
let Some(mut image) = RgbaImage::from_raw(width, height, data) else {
|
||||
return Err("Failed to create image buffer for export".to_string());
|
||||
};
|
||||
|
||||
let mut encoded = Vec::new();
|
||||
let mut cursor = std::io::Cursor::new(&mut encoded);
|
||||
|
||||
match file_type {
|
||||
FileType::Png => image.write_to(&mut cursor, ImageFormat::Png).map_err(|err| format!("Failed to encode PNG: {err}"))?,
|
||||
FileType::Jpg => {
|
||||
// Composite onto a white background since JPG doesn't support transparency
|
||||
for pixel in image.pixels_mut() {
|
||||
let [r, g, b, a] = pixel.0;
|
||||
let alpha = a as f32 / 255.;
|
||||
let blend = |channel: u8| (channel as f32 * alpha + 255. * (1. - alpha)).round() as u8;
|
||||
*pixel = image::Rgba([blend(r), blend(g), blend(b), 255]);
|
||||
}
|
||||
|
||||
let image: RgbImage = image.convert();
|
||||
image.write_to(&mut cursor, ImageFormat::Jpeg).map_err(|err| format!("Failed to encode JPG: {err}"))?;
|
||||
}
|
||||
FileType::Svg => return Err("SVG cannot be exported from an image buffer".to_string()),
|
||||
}
|
||||
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{AnimationExport, ExportBounds, FileType};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
@@ -91,6 +91,17 @@ pub struct ExportConfig {
|
||||
pub size: UVec2,
|
||||
pub artboard_name: Option<String>,
|
||||
pub artboard_count: usize,
|
||||
/// Set when this export is part of a multi-frame animation export. `None` means a normal single-frame export.
|
||||
pub animation: Option<AnimationExport>,
|
||||
/// Set on each per-frame `ExportConfig` to identify which animation export it belongs to and which frame index it represents.
|
||||
pub animation_frame: Option<AnimationExportFrame>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AnimationExportFrame {
|
||||
pub export_id: u64,
|
||||
pub frame_index: u32,
|
||||
pub total_frames: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
Generated
+9
-9
@@ -2,11 +2,11 @@
|
||||
"nodes": {
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1776635034,
|
||||
"narHash": "sha256-OEOJrT3ZfwbChzODfIH4GzlNTtOFuZFWPtW7jIeR8xU=",
|
||||
"lastModified": 1778106249,
|
||||
"narHash": "sha256-cM/AuKy5tMhwOOQIbha8ZRRMHVfNf7cv2aljIw+qoCg=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "dc7496d8ea6e526b1254b55d09b966e94673750f",
|
||||
"rev": "6d015ea29630b7ad2402841386da2cb617a470a7",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -17,11 +17,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1776548001,
|
||||
"narHash": "sha256-ZSK0NL4a1BwVbbTBoSnWgbJy9HeZFXLYQizjb2DPF24=",
|
||||
"lastModified": 1778869304,
|
||||
"narHash": "sha256-30sZNZoA1cqF5JNO9fVX+wgiQYjB7HJqqJ4ztCDeBZE=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "b12141ef619e0a9c1c84dc8c684040326f27cdcc",
|
||||
"rev": "d233902339c02a9c334e7e593de68855ad26c4cb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -45,11 +45,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1776741231,
|
||||
"narHash": "sha256-k9G98qzn+7npROUaks8VqCFm7cFtEG8ulQLBBo5lItg=",
|
||||
"lastModified": 1778987862,
|
||||
"narHash": "sha256-V3qGt9P1eJP/r/1ONablphfGiH0RP4agQhrRANpDYx8=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "02061303f7c4c964f7b4584dabd9e985b4cd442b",
|
||||
"rev": "6f44d8874ac29806c8d5cae42bf8e19ebb5ce0d3",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -328,7 +328,7 @@
|
||||
.icon-button,
|
||||
.text-button,
|
||||
.popover-button,
|
||||
.color-button > button,
|
||||
.color-input > button,
|
||||
.color-picker .preset-color,
|
||||
.working-colors-input .swatch > button,
|
||||
.radio-input button,
|
||||
|
||||
@@ -4,15 +4,15 @@
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import type { ColorPickerStore } from "/src/stores/color-picker";
|
||||
import type { EditorWrapper, FillChoice, MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { ColorPickerCallbacks, ColorPickerStore } from "/src/stores/color-picker";
|
||||
import type { EditorWrapper, FillChoiceUI, MenuDirection } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const dispatch = createEventDispatcher<{ colorOrGradient: FillChoice; startHistoryTransaction: undefined; commitHistoryTransaction: undefined }>();
|
||||
const dispatch = createEventDispatcher<{ colorOrGradient: FillChoiceUI; startHistoryTransaction: undefined; commitHistoryTransaction: undefined }>();
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
const colorPickerStore = getContext<ColorPickerStore>("colorPicker");
|
||||
|
||||
export let colorOrGradient: FillChoice;
|
||||
export let colorOrGradient: FillChoiceUI;
|
||||
export let allowNone = false;
|
||||
// export let allowTransparency = false; // TODO: Implement
|
||||
export let disabled = false;
|
||||
@@ -27,15 +27,18 @@
|
||||
// Open/close lifecycle: when `open` flips, register/clear the global callbacks (so events route to *this* instance)
|
||||
// and tell the Rust handler to (re)initialize its state from the current `colorOrGradient`.
|
||||
let lastOpen = false;
|
||||
// Identity used by `clearCallbacks` to skip stale clears when another picker has already taken over the store's callbacks
|
||||
let installedCallbacks: ColorPickerCallbacks | undefined;
|
||||
$: handleOpenChange(open);
|
||||
|
||||
function handleOpenChange(isOpen: boolean) {
|
||||
if (isOpen && !lastOpen) {
|
||||
colorPickerStore.setCallbacks({
|
||||
installedCallbacks = {
|
||||
onColorChanged: (value) => dispatch("colorOrGradient", value),
|
||||
onStartTransaction: () => dispatch("startHistoryTransaction"),
|
||||
onCommitTransaction: () => dispatch("commitHistoryTransaction"),
|
||||
});
|
||||
};
|
||||
colorPickerStore.setCallbacks(installedCallbacks);
|
||||
editor.openColorPicker(colorOrGradient, allowNone, disabled);
|
||||
// Auto-select the hex color code text input. Deferred so the layout has time to render after the picker opens.
|
||||
setTimeout(() => {
|
||||
@@ -43,7 +46,8 @@
|
||||
if (hexInput instanceof HTMLInputElement) hexInput.select();
|
||||
}, 0);
|
||||
} else if (!isOpen && lastOpen) {
|
||||
colorPickerStore.clearCallbacks();
|
||||
if (installedCallbacks) colorPickerStore.clearCallbacks(installedCallbacks);
|
||||
installedCallbacks = undefined;
|
||||
editor.closeColorPicker();
|
||||
}
|
||||
lastOpen = isOpen;
|
||||
@@ -55,7 +59,8 @@
|
||||
|
||||
onDestroy(() => {
|
||||
if (!lastOpen) return;
|
||||
colorPickerStore.clearCallbacks();
|
||||
if (installedCallbacks) colorPickerStore.clearCallbacks(installedCallbacks);
|
||||
installedCallbacks = undefined;
|
||||
editor.closeColorPicker();
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -336,7 +336,7 @@
|
||||
|
||||
// HOVER TRANSFER
|
||||
// Transfer from this open floating menu to a sibling floating menu if the pointer hovers to a valid neighboring floating menu spawner
|
||||
hoverTransfer(self, ownSpawner, targetSpawner);
|
||||
if (strayCloses) hoverTransfer(self, ownSpawner, targetSpawner);
|
||||
|
||||
// POINTER STRAY
|
||||
// Close the floating menu if the pointer has strayed far enough from its bounds (and it's not hovering over its own spawner)
|
||||
|
||||
@@ -12,12 +12,12 @@
|
||||
import type { DocumentStore } from "/src/stores/document";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageBody } from "/src/subscriptions-router";
|
||||
import { fillChoiceColor, createColor } from "/src/utility-functions/colors";
|
||||
import { fillChoiceUIColor, createSRgba8 } from "/src/utility-functions/colors";
|
||||
import { pasteFile } from "/src/utility-functions/files";
|
||||
import { textInputCleanup } from "/src/utility-functions/keyboard-entry";
|
||||
import { rasterizeSVGCanvas } from "/src/utility-functions/rasterization";
|
||||
import { setupViewportResizeObserver } from "/src/utility-functions/viewports";
|
||||
import type { Color, EditorWrapper, MenuDirection, MouseCursorIcon } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { EditorWrapper, MenuDirection, MouseCursorIcon, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
let rulerHorizontal: RulerInput | undefined;
|
||||
let rulerVertical: RulerInput | undefined;
|
||||
@@ -70,7 +70,7 @@
|
||||
let cursorEyedropperPreviewColorSecondary = "";
|
||||
|
||||
// Gradient stop color picker
|
||||
let gradientStopPickerColor: Color | undefined = undefined;
|
||||
let gradientStopPickerColor: SRGBA8 | undefined = undefined;
|
||||
let gradientStopPickerPosition: { x: number; y: number } | undefined = undefined;
|
||||
|
||||
// Canvas dimensions
|
||||
@@ -223,7 +223,7 @@
|
||||
mousePosition: [number, number] | undefined,
|
||||
colorPrimary: string,
|
||||
colorSecondary: string,
|
||||
): Promise<[number, number, number] | undefined> {
|
||||
): Promise<SRGBA8 | undefined> {
|
||||
if (mousePosition === undefined) {
|
||||
cursorEyedropper = false;
|
||||
return undefined;
|
||||
@@ -275,14 +275,14 @@
|
||||
};
|
||||
})();
|
||||
const hex = [centerPixel.r, centerPixel.g, centerPixel.b].map((x) => x.toString(16).padStart(2, "0")).join("");
|
||||
const rgb: [number, number, number] = [centerPixel.r / 255, centerPixel.g / 255, centerPixel.b / 255];
|
||||
const sRgba8: SRGBA8 = { red: centerPixel.r, green: centerPixel.g, blue: centerPixel.b, alpha: 255 };
|
||||
|
||||
cursorEyedropperPreviewColorChoice = "#" + hex;
|
||||
cursorEyedropperPreviewColorPrimary = colorPrimary;
|
||||
cursorEyedropperPreviewColorSecondary = colorSecondary;
|
||||
cursorEyedropperPreviewImageData = preview;
|
||||
|
||||
return rgb;
|
||||
return sRgba8;
|
||||
}
|
||||
|
||||
// Update scrollbars and rulers
|
||||
@@ -477,11 +477,11 @@
|
||||
|
||||
const { image, mousePosition, primaryColor, secondaryColor, setColorChoice } = data;
|
||||
const imageData = image !== undefined ? new ImageData(new Uint8ClampedArray(image.data), image.width, image.height) : undefined;
|
||||
const rgb = await updateEyedropperSamplingState(imageData, mousePosition, primaryColor, secondaryColor);
|
||||
const sRgba8 = await updateEyedropperSamplingState(imageData, mousePosition, primaryColor, secondaryColor);
|
||||
|
||||
if (setColorChoice && rgb) {
|
||||
if (setColorChoice === "Primary") editor.updatePrimaryColor(...rgb, 1);
|
||||
if (setColorChoice === "Secondary") editor.updateSecondaryColor(...rgb, 1);
|
||||
if (setColorChoice && sRgba8) {
|
||||
if (setColorChoice === "Primary") editor.updatePrimaryColor(sRgba8);
|
||||
if (setColorChoice === "Secondary") editor.updateSecondaryColor(sRgba8);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -668,10 +668,10 @@
|
||||
gradientStopPickerColor = undefined;
|
||||
}
|
||||
}}
|
||||
colorOrGradient={{ Solid: gradientStopPickerColor || createColor(0, 0, 0, 1) }}
|
||||
colorOrGradient={{ Solid: gradientStopPickerColor || createSRgba8(0, 0, 0, 255) }}
|
||||
on:colorOrGradient={({ detail }) => {
|
||||
const color = fillChoiceColor(detail);
|
||||
if (color) editor.updateGradientStopColor(color.red, color.green, color.blue, color.alpha);
|
||||
const color = fillChoiceUIColor(detail);
|
||||
if (color) editor.updateGradientStopColor(color);
|
||||
}}
|
||||
on:startHistoryTransaction={() => editor.startGradientStopColorTransaction()}
|
||||
on:commitHistoryTransaction={() => editor.commitGradientStopColorTransaction()}
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import Separator from "/src/components/widgets/labels/Separator.svelte";
|
||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
|
||||
import type { NodeGraphStore } from "/src/stores/node-graph";
|
||||
import { layersPanelControlBarLeftLayout, layersPanelControlBarRightLayout, layersPanelBottomBarLayout } from "/src/stores/portfolio";
|
||||
import type { PortfolioStore } from "/src/stores/portfolio";
|
||||
@@ -63,14 +64,20 @@
|
||||
let fakeHighlightOfNotYetSelectedLayerBeingDragged: undefined | bigint = undefined;
|
||||
let justFinishedDrag = false; // Used to prevent click events after a drag
|
||||
let dragInPanel = false;
|
||||
let dragDropTarget: HTMLElement | undefined = undefined;
|
||||
|
||||
// Interactive clipping
|
||||
let layerToClipUponClick: LayerListingInfo | undefined = undefined;
|
||||
let layerToClipAltKeyPressed = false;
|
||||
|
||||
// Drag-toggle: tracked here so the template can render the invisible lock placeholder during a `layer-lock` gesture
|
||||
let activeDragToggleGroup: string | undefined = undefined;
|
||||
|
||||
$: rebuildLayerHierarchy($portfolio.layerStructure, $portfolio.layerCache);
|
||||
|
||||
onMount(() => {
|
||||
createDragToggleManager(dragToggleListener);
|
||||
|
||||
addEventListener("pointerup", draggingPointerUp);
|
||||
addEventListener("pointermove", draggingPointerMove);
|
||||
addEventListener("mousedown", draggingMouseDown);
|
||||
@@ -83,6 +90,8 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
destroyDragToggleManager(dragToggleListener);
|
||||
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("mousedown", draggingMouseDown);
|
||||
@@ -94,6 +103,10 @@
|
||||
removeEventListener("keyup", clippingKeyPress);
|
||||
});
|
||||
|
||||
function dragToggleListener(group: string | undefined) {
|
||||
activeDragToggleGroup = group;
|
||||
}
|
||||
|
||||
function toggleNodeVisibilityLayerPanel(id: bigint) {
|
||||
editor.toggleNodeVisibilityLayerPanel(id);
|
||||
}
|
||||
@@ -246,7 +259,7 @@
|
||||
|
||||
let markerHeight = 0;
|
||||
const layerPanel = document.querySelector("[data-layer-panel]"); // Selects the element with the data-layer-panel attribute
|
||||
if (layerPanel !== null && treeChildren !== undefined && treeOffset !== undefined) {
|
||||
if (layerPanel && treeChildren && treeOffset !== undefined) {
|
||||
let layerPanelTop = layerPanel.getBoundingClientRect().top;
|
||||
Array.from(treeChildren).forEach((treeChild) => {
|
||||
const indexAttribute = treeChild.getAttribute("data-index");
|
||||
@@ -346,6 +359,18 @@
|
||||
|
||||
// Perform drag calculations if a drag is occurring
|
||||
if (internalDragState.active) {
|
||||
// Check if the cursor is over any element flagged as a drag drop target
|
||||
// (e.g. a bottom-bar action button whose backend widget has an `on_drag_drop` callback set)
|
||||
const droppable = (e.target instanceof Element && e.target.closest("[data-drag-droppable]")) || undefined;
|
||||
dragDropTarget = droppable instanceof HTMLElement ? droppable : undefined;
|
||||
|
||||
// Hide the move-in-tree insert indicator whenever the cursor enters the bottom bar
|
||||
const overBottomBar = ((e.target instanceof Element && e.target.closest("[data-layer-bottom-bar]")) || undefined) !== undefined;
|
||||
if (dragDropTarget || overBottomBar) {
|
||||
draggingData = undefined;
|
||||
return;
|
||||
}
|
||||
|
||||
const select = () => {
|
||||
if (internalDragState && !$nodeGraph.selected.includes(internalDragState.layerId)) {
|
||||
selectLayer(internalDragState.listing, false, false);
|
||||
@@ -357,7 +382,15 @@
|
||||
}
|
||||
|
||||
function draggingPointerUp() {
|
||||
if (internalDragState?.active && draggingData) {
|
||||
if (internalDragState?.active && dragDropTarget) {
|
||||
// Ensure the dragged layer is part of the selection, matching the move-in-tree behavior
|
||||
if (!$nodeGraph.selected.includes(internalDragState.layerId)) selectLayer(internalDragState.listing, false, false);
|
||||
|
||||
// Hand off to the button's backend `on_drag_drop` callback via the custom event
|
||||
dragDropTarget.dispatchEvent(new CustomEvent("dragdrop"));
|
||||
|
||||
justFinishedDrag = true;
|
||||
} else if (internalDragState?.active && draggingData) {
|
||||
const { select, insertParentId, insertIndex } = draggingData;
|
||||
|
||||
// Commit the move
|
||||
@@ -382,6 +415,7 @@
|
||||
draggingData = undefined;
|
||||
fakeHighlightOfNotYetSelectedLayerBeingDragged = undefined;
|
||||
dragInPanel = false;
|
||||
dragDropTarget = undefined;
|
||||
}
|
||||
|
||||
function draggingMouseDown(e: MouseEvent) {
|
||||
@@ -614,6 +648,17 @@
|
||||
hoverIcon={listing.entry.unlocked ? "PadlockLocked" : "PadlockUnlocked"}
|
||||
tooltipLabel={listing.entry.unlocked ? "Lock" : "Unlock"}
|
||||
tooltipDescription={!listing.parentsUnlocked ? "A parent of this layer is locked and that status is being inherited." : ""}
|
||||
data-drag-toggle-group="layer-lock"
|
||||
data-drag-toggle-state={listing.entry.unlocked ? "unlocked" : "locked"}
|
||||
/>
|
||||
{:else if activeDragToggleGroup === "layer-lock"}
|
||||
<IconButton
|
||||
class="status-toggle drag-toggle-placeholder"
|
||||
action={(e) => (toggleLayerLock(listing.entry.id), e?.stopPropagation())}
|
||||
size={24}
|
||||
icon="PadlockUnlocked"
|
||||
data-drag-toggle-group="layer-lock"
|
||||
data-drag-toggle-state="unlocked"
|
||||
/>
|
||||
{/if}
|
||||
<IconButton
|
||||
@@ -625,6 +670,8 @@
|
||||
hoverIcon={listing.entry.visible ? "EyeHide" : "EyeShow"}
|
||||
tooltipLabel={listing.entry.visible ? "Hide" : "Show"}
|
||||
tooltipDescription={!listing.parentsVisible ? "A parent of this layer is hidden and that status is being inherited." : ""}
|
||||
data-drag-toggle-group="layer-visibility"
|
||||
data-drag-toggle-state={listing.entry.visible ? "visible" : "hidden"}
|
||||
/>
|
||||
</LayoutRow>
|
||||
{/each}
|
||||
@@ -633,7 +680,7 @@
|
||||
<div class="insert-mark" style:left={`${4 + draggingData.insertDepth * 16}px`} style:top={`${draggingData.markerHeight}px`}></div>
|
||||
{/if}
|
||||
</LayoutRow>
|
||||
<LayoutRow class="bottom-bar" scrollableX={true}>
|
||||
<LayoutRow class="bottom-bar" classes={{ "layer-drag-active": Boolean(internalDragState?.active) }} scrollableX={true} data-layer-bottom-bar>
|
||||
<WidgetLayout layout={$layersPanelBottomBarLayout} layoutTarget="LayersPanelBottomBar" />
|
||||
</LayoutRow>
|
||||
</LayoutCol>
|
||||
@@ -673,6 +720,26 @@
|
||||
&:not(:has(*)) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
&.layer-drag-active .icon-button,
|
||||
&.layer-drag-active .popover-button {
|
||||
&.drag-droppable:hover {
|
||||
background: var(--color-e-nearwhite);
|
||||
|
||||
svg {
|
||||
fill: var(--color-2-mildblack);
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.drag-droppable) {
|
||||
pointer-events: none;
|
||||
background: none;
|
||||
|
||||
svg {
|
||||
fill: var(--color-8-uppergray);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Layer hierarchy
|
||||
@@ -844,6 +911,17 @@
|
||||
background-image: var(--inheritance-stripes-background);
|
||||
}
|
||||
|
||||
// Invisible placeholder rendered only during a lock drag-toggle gesture, so the drag can still land on rows whose lock icon is normally omitted.
|
||||
// Overlaid with absolute positioning so it doesn't shift the layer name's width.
|
||||
&.drag-toggle-placeholder {
|
||||
position: absolute;
|
||||
width: 24px;
|
||||
right: 24px;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
opacity: 0; // Not `visibility: hidden`, which would exclude it from hit-testing
|
||||
}
|
||||
|
||||
.icon-button {
|
||||
height: 100%;
|
||||
width: calc(24px + 2 * 4px);
|
||||
|
||||
@@ -188,10 +188,6 @@
|
||||
return `M-2,-2 L${nodeWidth + 2},-2 L${nodeWidth + 2},${nodeHeight + 2} L-2,${nodeHeight + 2}z ${rectangles.join(" ")}`;
|
||||
}
|
||||
|
||||
function dataTypeTooltipLabel(value: FrontendGraphInput | FrontendGraphOutput): string {
|
||||
return `Data Type: ${value.resolvedType}`;
|
||||
}
|
||||
|
||||
function nodeNameTooltipLabel(node: FrontendNode): string {
|
||||
return node.displayName === node.implementationName ? node.displayName : `${node.displayName} (${node.implementationName})`;
|
||||
}
|
||||
@@ -349,7 +345,7 @@
|
||||
viewBox="0 0 8 8"
|
||||
class="connector"
|
||||
data-connector="output"
|
||||
data-tooltip-label={dataTypeTooltipLabel(frontendOutput)}
|
||||
data-tooltip-label={frontendOutput.resolvedType}
|
||||
data-tooltip-description={outputConnectedToText(frontendOutput)}
|
||||
data-datatype={frontendOutput.dataType}
|
||||
style:--data-color={`var(--color-data-${frontendOutput.dataType.toLowerCase()})`}
|
||||
@@ -418,7 +414,7 @@
|
||||
viewBox="0 0 8 8"
|
||||
class="connector"
|
||||
data-connector="input"
|
||||
data-tooltip-label={dataTypeTooltipLabel(frontendInput)}
|
||||
data-tooltip-label={frontendInput.resolvedType}
|
||||
data-tooltip-description={inputConnectedToText(frontendInput)}
|
||||
data-datatype={frontendInput.dataType}
|
||||
style:--data-color={`var(--color-data-${frontendInput.dataType.toLowerCase()})`}
|
||||
@@ -556,7 +552,7 @@
|
||||
viewBox="0 0 8 12"
|
||||
class="connector top"
|
||||
data-connector="output"
|
||||
data-tooltip-label={dataTypeTooltipLabel(node.primaryOutput)}
|
||||
data-tooltip-label={node.primaryOutput.resolvedType}
|
||||
data-tooltip-description={outputConnectedToText(node.primaryOutput)}
|
||||
data-datatype={node.primaryOutput.dataType}
|
||||
style:--data-color={`var(--color-data-${node.primaryOutput.dataType.toLowerCase()})`}
|
||||
@@ -578,7 +574,7 @@
|
||||
viewBox="0 0 8 12"
|
||||
class="connector bottom"
|
||||
data-connector="input"
|
||||
data-tooltip-label={node.primaryInput ? dataTypeTooltipLabel(node.primaryInput) : ""}
|
||||
data-tooltip-label={node.primaryInput ? node.primaryInput.resolvedType : ""}
|
||||
data-tooltip-description={node.primaryInput ? `${validTypesText(node.primaryInput).trim()}\n\n${inputConnectedToText(node.primaryInput)}` : ""}
|
||||
data-datatype={node.primaryInput?.dataType}
|
||||
style:--data-color={`var(--color-data-${(node.primaryInput?.dataType || "General").toLowerCase()})`}
|
||||
@@ -601,7 +597,7 @@
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
viewBox="0 0 8 8"
|
||||
class="connector"
|
||||
data-tooltip-label={dataTypeTooltipLabel(stackDataInput)}
|
||||
data-tooltip-label={stackDataInput.resolvedType}
|
||||
data-tooltip-description={`${validTypesText(stackDataInput).trim()}\n\n${inputConnectedToText(stackDataInput)}`}
|
||||
data-connector="input"
|
||||
data-datatype={stackDataInput.dataType}
|
||||
@@ -755,7 +751,7 @@
|
||||
viewBox="0 0 8 8"
|
||||
class="connector primary-connector"
|
||||
data-connector="input"
|
||||
data-tooltip-label={dataTypeTooltipLabel(node.primaryInput)}
|
||||
data-tooltip-label={node.primaryInput.resolvedType}
|
||||
data-tooltip-description={`${validTypesText(node.primaryInput).trim()}\n\n${inputConnectedToText(node.primaryInput)}`}
|
||||
data-datatype={node.primaryInput?.dataType}
|
||||
style:--data-color={`var(--color-data-${node.primaryInput.dataType.toLowerCase()})`}
|
||||
@@ -775,7 +771,7 @@
|
||||
viewBox="0 0 8 8"
|
||||
class="connector"
|
||||
data-connector="input"
|
||||
data-tooltip-label={dataTypeTooltipLabel(secondary)}
|
||||
data-tooltip-label={secondary.resolvedType}
|
||||
data-tooltip-description={`${validTypesText(secondary).trim()}\n\n${inputConnectedToText(secondary)}`}
|
||||
data-datatype={secondary.dataType}
|
||||
style:--data-color={`var(--color-data-${secondary.dataType.toLowerCase()})`}
|
||||
@@ -798,7 +794,7 @@
|
||||
viewBox="0 0 8 8"
|
||||
class="connector primary-connector"
|
||||
data-connector="output"
|
||||
data-tooltip-label={dataTypeTooltipLabel(node.primaryOutput)}
|
||||
data-tooltip-label={node.primaryOutput.resolvedType}
|
||||
data-tooltip-description={`${outputConnectedToText(node.primaryOutput)}`}
|
||||
data-datatype={node.primaryOutput.dataType}
|
||||
style:--data-color={`var(--color-data-${node.primaryOutput.dataType.toLowerCase()})`}
|
||||
@@ -817,7 +813,7 @@
|
||||
viewBox="0 0 8 8"
|
||||
class="connector"
|
||||
data-connector="output"
|
||||
data-tooltip-label={dataTypeTooltipLabel(secondary)}
|
||||
data-tooltip-label={secondary.resolvedType}
|
||||
data-tooltip-description={`${outputConnectedToText(secondary)}`}
|
||||
data-datatype={secondary.dataType}
|
||||
style:--data-color={`var(--color-data-${secondary.dataType.toLowerCase()})`}
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
import ShortcutLabel from "/src/components/widgets/labels/ShortcutLabel.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import type { ColorPickerStore } from "/src/stores/color-picker";
|
||||
import { parseFillChoice } from "/src/utility-functions/colors";
|
||||
import { parseFillChoiceUI } from "/src/utility-functions/colors";
|
||||
import type { EditorWrapper, LayoutTarget, Widget, WidgetInstance } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// Extract the discriminant key names from the Widget tagged enum union (e.g. "TextButton" | "CheckboxInput" | ...)
|
||||
@@ -65,6 +65,10 @@
|
||||
editor.widgetValueCommitAndUpdate(layoutTarget, widgets[widgetIndex].widgetId, value, resendWidget);
|
||||
}
|
||||
|
||||
function widgetValueDragDrop(widgetIndex: number) {
|
||||
editor.widgetValueDragDrop(layoutTarget, widgets[widgetIndex].widgetId);
|
||||
}
|
||||
|
||||
// Extracts the kind and props from a Widget tagged enum, validated against the widget registry.
|
||||
// The overload declares the precise correlated return type while the implementation uses broader types.
|
||||
function unwrapWidget(widgetInstance: WidgetInstance): UnwrappedWidget | undefined;
|
||||
@@ -134,7 +138,7 @@
|
||||
component: ColorInput,
|
||||
getProps: (props, index) => ({
|
||||
...props,
|
||||
value: parseFillChoice(props.value),
|
||||
value: parseFillChoiceUI(props.value),
|
||||
$$events: {
|
||||
value: (e: CustomEvent) => widgetValueUpdate(index, e.detail, false),
|
||||
startHistoryTransaction: () => widgetValueCommit(index, props.value),
|
||||
@@ -146,7 +150,7 @@
|
||||
getProps: (props, index) => ({
|
||||
...props,
|
||||
$$events: {
|
||||
// The widget dispatches `"None"` or a bare `Color`, wrap the color in `{ Solid: ... }` so the payload matches Rust's `FillChoice` shape (which the `Preset` variant expects).
|
||||
// The widget dispatches `"None"` or a bare `SRGBA8`, wrap the color in `{ Solid: ... }` so the payload matches Rust's `FillChoiceUI` shape (which the `Preset` variant expects).
|
||||
preset: (e: CustomEvent) => widgetValueCommitAndUpdate(index, { Preset: e.detail === "None" ? "None" : { Solid: e.detail } }, true),
|
||||
eyedropperColorCode: (e: CustomEvent) => widgetValueCommitAndUpdate(index, { EyedropperColorCode: e.detail }, true),
|
||||
},
|
||||
@@ -175,6 +179,7 @@
|
||||
getProps: (props, index) => ({
|
||||
...props,
|
||||
action: () => widgetValueCommitAndUpdate(index, undefined, true),
|
||||
actionDragDrop: () => widgetValueDragDrop(index),
|
||||
}),
|
||||
},
|
||||
IconLabel: {
|
||||
@@ -215,6 +220,7 @@
|
||||
$$events: {
|
||||
value: (e: CustomEvent) => widgetValueUpdate(index, e.detail, true),
|
||||
startHistoryTransaction: () => widgetValueCommit(index, props.value),
|
||||
commitHistoryTransaction: () => editor.endTransaction(),
|
||||
},
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onMount, onDestroy } from "svelte";
|
||||
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
|
||||
import type { IconName, IconSize } from "/src/icons";
|
||||
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -16,6 +17,9 @@
|
||||
export let tooltipShortcut: ActionShortcut | undefined = undefined;
|
||||
// Callbacks
|
||||
export let action: (e?: MouseEvent) => void;
|
||||
// Fired when a draggable item is dropped onto this button. Setting this also flags the button as a valid drop target
|
||||
// (the consumer of the drag interaction looks for `[data-drag-droppable]` and dispatches a `dragdrop` event on it).
|
||||
export let actionDragDrop: (() => void) | undefined = undefined;
|
||||
|
||||
let className = "";
|
||||
export { className as class };
|
||||
@@ -24,6 +28,14 @@
|
||||
$: extraClasses = Object.entries(classes)
|
||||
.flatMap(([className, stateName]) => (stateName ? [className] : []))
|
||||
.join(" ");
|
||||
|
||||
// Element-level listener for the `dragdrop` custom event that consumers dispatch when something is dropped on this button
|
||||
let buttonElement: HTMLButtonElement | undefined;
|
||||
function handleDragDrop() {
|
||||
actionDragDrop?.();
|
||||
}
|
||||
onMount(() => buttonElement?.addEventListener("dragdrop", handleDragDrop));
|
||||
onDestroy(() => buttonElement?.removeEventListener("dragdrop", handleDragDrop));
|
||||
</script>
|
||||
|
||||
<button
|
||||
@@ -31,11 +43,14 @@
|
||||
class:hover-icon={hoverIcon && !disabled}
|
||||
class:disabled
|
||||
class:emphasized
|
||||
class:drag-droppable={Boolean(actionDragDrop)}
|
||||
bind:this={buttonElement}
|
||||
on:click={action}
|
||||
{disabled}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
data-tooltip-description={tooltipDescription}
|
||||
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
|
||||
data-drag-droppable={actionDragDrop ? "" : undefined}
|
||||
tabindex={emphasized ? -1 : 0}
|
||||
{...$$restProps}
|
||||
>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
export let icon: IconName | undefined = undefined;
|
||||
export let forLabel: bigint | undefined = undefined;
|
||||
export let disabled = false;
|
||||
export let mixed = false;
|
||||
// Tooltips
|
||||
export let tooltipLabel: string | undefined = undefined;
|
||||
export let tooltipDescription: string | undefined = undefined;
|
||||
@@ -22,6 +23,7 @@
|
||||
|
||||
$: id = forLabel !== undefined ? String(forLabel) : backupId;
|
||||
$: displayIcon = !checked && (!icon || icon === "Checkmark") ? "Empty12px" : icon || "Checkmark";
|
||||
$: if (inputElement) inputElement.indeterminate = mixed;
|
||||
|
||||
export function isChecked() {
|
||||
return checked;
|
||||
@@ -43,7 +45,14 @@
|
||||
type="checkbox"
|
||||
id={`checkbox-input-${id}`}
|
||||
bind:checked
|
||||
on:change={(_) => dispatch("checked", inputElement?.checked || false)}
|
||||
on:change={(_) => {
|
||||
// Clicking a mixed-state checkbox always transitions to ticked rather than following HTML's default toggle from the previous `checked` value
|
||||
if (mixed && inputElement && !inputElement.checked) {
|
||||
inputElement.checked = true;
|
||||
checked = true;
|
||||
}
|
||||
dispatch("checked", inputElement?.checked || false);
|
||||
}}
|
||||
{disabled}
|
||||
tabindex={disabled ? -1 : 0}
|
||||
bind:this={inputElement}
|
||||
@@ -51,6 +60,7 @@
|
||||
<label
|
||||
class:disabled
|
||||
class:checked
|
||||
class:mixed
|
||||
for={`checkbox-input-${id}`}
|
||||
on:keydown={(e) => e.key === "Enter" && toggleCheckboxFromLabel(e)}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
@@ -130,6 +140,29 @@
|
||||
}
|
||||
}
|
||||
|
||||
// Mixed (takes priority over both checked and unchecked appearances)
|
||||
label.mixed .checkbox-box,
|
||||
input:checked + label.mixed .checkbox-box {
|
||||
position: relative;
|
||||
background: var(--color-5-dullgray);
|
||||
|
||||
.icon-label {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 8px;
|
||||
height: 2px;
|
||||
transform: translate(-50%, -50%);
|
||||
background: var(--color-8-uppergray);
|
||||
border-radius: 1px;
|
||||
}
|
||||
}
|
||||
|
||||
+ .text-label.text-label {
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import type { Color } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const dispatch = createEventDispatcher<{ swap: undefined }>();
|
||||
|
||||
export let newColor: Color | undefined;
|
||||
export let oldColor: Color | undefined;
|
||||
export let newColor: SRGBA8 | undefined;
|
||||
export let oldColor: SRGBA8 | undefined;
|
||||
export let newColorCSS: string;
|
||||
export let newColorContrasting: string;
|
||||
export let oldColorCSS: string;
|
||||
@@ -21,7 +21,7 @@
|
||||
export let outlineAmount: number;
|
||||
|
||||
$: outlined = outlineAmount > 0.0001;
|
||||
$: transparency = (newColor?.alpha ?? 1) < 1 || (oldColor?.alpha ?? 1) < 1;
|
||||
$: transparency = (newColor?.alpha ?? 255) < 255 || (oldColor?.alpha ?? 255) < 255;
|
||||
</script>
|
||||
|
||||
<LayoutRow
|
||||
|
||||
@@ -2,20 +2,24 @@
|
||||
import { createEventDispatcher } from "svelte";
|
||||
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import { contrastingOutlineFactor, fillChoiceColor, fillChoiceGradientStops } from "/src/utility-functions/colors";
|
||||
import type { FillChoice, MenuDirection, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import { contrastingOutlineFactor, fillChoiceUIColor, fillChoiceUIGradientStops } from "/src/utility-functions/colors";
|
||||
import type { FillChoiceUI, MenuDirection, ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const dispatch = createEventDispatcher<{ value: FillChoice; startHistoryTransaction: undefined }>();
|
||||
const dispatch = createEventDispatcher<{ value: FillChoiceUI; startHistoryTransaction: undefined }>();
|
||||
|
||||
// Content
|
||||
export let value: FillChoice;
|
||||
export let value: FillChoiceUI;
|
||||
export let chosenGradient: string | undefined = undefined;
|
||||
export let allowNone = false;
|
||||
// export let allowTransparency = false; // TODO: Implement
|
||||
export let menuDirection: MenuDirection = "Bottom";
|
||||
export let disabled = false;
|
||||
export let mixed = false;
|
||||
// Styling
|
||||
export let narrow = false;
|
||||
// Sizing
|
||||
export let minWidth = 0;
|
||||
export let maxWidth = 0;
|
||||
// Tooltips
|
||||
export let tooltipLabel: string | undefined = undefined;
|
||||
export let tooltipDescription: string | undefined = undefined;
|
||||
@@ -23,15 +27,25 @@
|
||||
|
||||
let open = false;
|
||||
|
||||
$: outlineFactor = contrastingOutlineFactor(value, ["--color-1-nearblack", "--color-3-darkgray"], 0.01);
|
||||
$: outlineFactor = contrastingOutlineFactor(value, "--color-3-darkgray", 0.01);
|
||||
$: outlined = outlineFactor > 0.0001;
|
||||
$: gradientStops = fillChoiceGradientStops(value);
|
||||
$: solidColor = fillChoiceColor(value);
|
||||
$: gradientStops = fillChoiceUIGradientStops(value);
|
||||
$: solidColor = fillChoiceUIColor(value);
|
||||
$: none = value === "None";
|
||||
$: transparency = gradientStops ? gradientStops.color.some((color) => color.alpha < 1) : solidColor ? solidColor.alpha < 1 : false;
|
||||
$: transparency = gradientStops ? gradientStops.color.some((color) => color.alpha < 255) : solidColor ? solidColor.alpha < 255 : false;
|
||||
</script>
|
||||
|
||||
<LayoutCol class="color-button" classes={{ open, disabled, narrow, none, transparency, outlined, "direction-top": menuDirection === "Top" }} {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
|
||||
<LayoutCol
|
||||
class="color-input"
|
||||
classes={{ open, disabled, narrow, none, transparency, outlined, mixed, "direction-top": menuDirection === "Top" }}
|
||||
styles={{
|
||||
...(minWidth > 0 ? { "min-width": `${minWidth}px` } : {}),
|
||||
...(maxWidth > 0 ? { "max-width": `${maxWidth}px` } : {}),
|
||||
}}
|
||||
{tooltipLabel}
|
||||
{tooltipDescription}
|
||||
{tooltipShortcut}
|
||||
>
|
||||
<button style:--chosen-gradient={chosenGradient} style:--outline-amount={outlineFactor} on:click={() => (open = true)} tabindex="0" data-floating-menu-spawner></button>
|
||||
<ColorPicker
|
||||
{open}
|
||||
@@ -53,7 +67,7 @@
|
||||
</LayoutCol>
|
||||
|
||||
<style lang="scss">
|
||||
.color-button {
|
||||
.color-input {
|
||||
position: relative;
|
||||
min-width: 80px;
|
||||
|
||||
@@ -131,6 +145,28 @@
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
&.mixed > button {
|
||||
position: relative;
|
||||
background: var(--color-e-nearwhite);
|
||||
background-image: none;
|
||||
|
||||
&::before {
|
||||
background: var(--color-e-nearwhite);
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 8px;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
transform: translate(-50%, -50%);
|
||||
background: var(--color-8-uppergray);
|
||||
}
|
||||
}
|
||||
|
||||
&:not(.disabled):hover > button .text-label,
|
||||
&:not(.disabled).open > button .text-label {
|
||||
background: var(--color-6-lowergray);
|
||||
|
||||
@@ -3,20 +3,20 @@
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
|
||||
import Separator from "/src/components/widgets/labels/Separator.svelte";
|
||||
import { createColor } from "/src/utility-functions/colors";
|
||||
import type { Color } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import { createSRgba8 } from "/src/utility-functions/colors";
|
||||
import type { SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
type PresetColor = "Black" | "White" | "Red" | "Yellow" | "Green" | "Cyan" | "Blue" | "Magenta";
|
||||
|
||||
const PURE_COLORS: Record<PresetColor, [number, number, number]> = {
|
||||
Black: [0, 0, 0],
|
||||
White: [1, 1, 1],
|
||||
Red: [1, 0, 0],
|
||||
Yellow: [1, 1, 0],
|
||||
Green: [0, 1, 0],
|
||||
Cyan: [0, 1, 1],
|
||||
Blue: [0, 0, 1],
|
||||
Magenta: [1, 0, 1],
|
||||
White: [255, 255, 255],
|
||||
Red: [255, 0, 0],
|
||||
Yellow: [255, 255, 0],
|
||||
Green: [0, 255, 0],
|
||||
Cyan: [0, 255, 255],
|
||||
Blue: [0, 0, 255],
|
||||
Magenta: [255, 0, 255],
|
||||
};
|
||||
const PURE_COLORS_GRAYABLE: [PresetColor, string, string][] = [
|
||||
["Red", "#ff0000", "#4c4c4c"],
|
||||
@@ -28,7 +28,7 @@
|
||||
];
|
||||
|
||||
const dispatch = createEventDispatcher<{
|
||||
preset: Color | "None";
|
||||
preset: SRGBA8 | "None";
|
||||
eyedropperColorCode: string;
|
||||
}>();
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
function pickPreset(preset: PresetColor | "None") {
|
||||
if (disabled) return;
|
||||
dispatch("preset", preset === "None" ? "None" : createColor(...PURE_COLORS[preset], 1));
|
||||
dispatch("preset", preset === "None" ? "None" : createSRgba8(...PURE_COLORS[preset], 255));
|
||||
}
|
||||
|
||||
// TODO: Replace this temporary usage of the browser eyedropper API, that only works in Chromium-based browsers, with the custom color sampler system used by the Eyedropper tool
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
const BUTTON_LEFT = 0;
|
||||
const BUTTON_RIGHT = 2;
|
||||
|
||||
const dispatch = createEventDispatcher<{ value: number | undefined; startHistoryTransaction: undefined }>();
|
||||
const dispatch = createEventDispatcher<{ value: number | undefined; startHistoryTransaction: undefined; commitHistoryTransaction: undefined }>();
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
|
||||
@@ -84,6 +84,9 @@
|
||||
let shiftKeyDown = false;
|
||||
// Track whether the Ctrl key is currently held down.
|
||||
let ctrlKeyDown = false;
|
||||
// True between dispatching `startHistoryTransaction` and the matching `commitHistoryTransaction`, so we only commit
|
||||
// when this widget actually opened a transaction (skipping clicks-without-drag and aborts-before-drag-started).
|
||||
let transactionInProgress = false;
|
||||
// Cleanup function for active drag interactions, called on destroy to prevent leaked listeners
|
||||
let activeDragCleanup: (() => void) | undefined;
|
||||
// Track the slider abort state for cleanup on destroy
|
||||
@@ -135,8 +138,17 @@
|
||||
removeEventListener("keydown", sliderAbortFromDragging);
|
||||
removeEventListener("keydown", incrementPressAbort);
|
||||
if (sliderResetAbortHandler) removeEventListener("pointerup", sliderResetAbortHandler);
|
||||
|
||||
commitTransactionIfInProgress();
|
||||
});
|
||||
|
||||
function commitTransactionIfInProgress() {
|
||||
if (transactionInProgress) {
|
||||
dispatch("commitHistoryTransaction");
|
||||
transactionInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ===============================
|
||||
// TRACKING AND UPDATING THE VALUE
|
||||
// ===============================
|
||||
@@ -203,9 +215,9 @@
|
||||
return `${unitlessDisplayValue}${unPluralize(unit, displayValue)}`;
|
||||
}
|
||||
|
||||
// Removes the trailing "s" from a unit if the quantity is 1.
|
||||
// Removes the "s" suffix from a unit if the quantity is 1.
|
||||
function unPluralize(unit: string, quantity: number): string {
|
||||
if (quantity !== 1 || !unit.endsWith("s")) return unit;
|
||||
if (quantity !== 1 || !unit.endsWith("s") || unit.trim().length < 2) return unit;
|
||||
return unit.slice(0, -1);
|
||||
}
|
||||
|
||||
@@ -243,9 +255,13 @@
|
||||
|
||||
if (newValue !== undefined) {
|
||||
const oldValue = value !== undefined && isInteger ? Math.round(value) : value;
|
||||
if (newValue !== oldValue) dispatch("startHistoryTransaction");
|
||||
if (newValue !== oldValue) {
|
||||
dispatch("startHistoryTransaction");
|
||||
transactionInProgress = true;
|
||||
}
|
||||
}
|
||||
updateValue(newValue);
|
||||
commitTransactionIfInProgress();
|
||||
|
||||
editing = false;
|
||||
self?.unFocus();
|
||||
@@ -477,6 +493,9 @@
|
||||
|
||||
// Clean up the event listeners.
|
||||
activeDragCleanup?.();
|
||||
|
||||
// Close out the transaction `startDragging` opened so the many emits collapse into one history step (covers both confirmed and aborted drags).
|
||||
commitTransactionIfInProgress();
|
||||
};
|
||||
|
||||
addEventListener("pointerup", pointerUp);
|
||||
@@ -626,12 +645,17 @@
|
||||
removeEventListener("keydown", sliderAbortFromMousedown);
|
||||
removeEventListener("pointermove", sliderAbortFromDragging);
|
||||
removeEventListener("keydown", sliderAbortFromDragging);
|
||||
|
||||
// Close out the transaction `startDragging` opened, so the drag's many emits collapse into one history step.
|
||||
// Covers the abort path too (sliderAbort already restored the original value, so the committed step is a no-op).
|
||||
commitTransactionIfInProgress();
|
||||
}
|
||||
|
||||
function startDragging() {
|
||||
// This event is sent to the backend so it knows to start a transaction for the history system. See discussion for some explanation:
|
||||
// <https://github.com/GraphiteEditor/Graphite/pull/1584#discussion_r1477592483>
|
||||
dispatch("startHistoryTransaction");
|
||||
transactionInProgress = true;
|
||||
}
|
||||
|
||||
// We want to let the user abort while dragging the slider by right clicking or pressing Escape.
|
||||
@@ -663,6 +687,8 @@
|
||||
// dragging the slider, now that we're no longer dragging it due to the loss of window focus.
|
||||
removeEventListener("pointermove", sliderAbortFromDragging);
|
||||
removeEventListener("keydown", sliderAbortFromDragging);
|
||||
|
||||
commitTransactionIfInProgress();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,10 +40,16 @@
|
||||
// The `unFocus()` call in `onTextChangeCanceled()` causes itself to be run again, so this if statement skips a second run
|
||||
if (!editing) return;
|
||||
|
||||
// Capture before `onTextChangeCanceled` blurs the input
|
||||
const currentValue = self?.getValue();
|
||||
|
||||
onTextChangeCanceled();
|
||||
|
||||
// TODO: Find a less hacky way to do this
|
||||
if (self) dispatch("commitText", self.getValue());
|
||||
// Only commit on a real edit, so a blur fired when the focused input is removed from the DOM (e.g., from a picker closing
|
||||
// during hover transfer) doesn't round-trip the original value back to the backend and overwrite concurrent state.
|
||||
if (self && currentValue !== undefined && currentValue !== value) {
|
||||
dispatch("commitText", currentValue);
|
||||
}
|
||||
|
||||
// Required if value is not changed by the parent component upon update:value event
|
||||
self?.setInputElementValue(self.getValue());
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import type { TooltipStore } from "/src/stores/tooltip";
|
||||
import { colorContrastingColor, colorOpaque, colorToHexNoAlpha, colorToRgbCSS, createColor, createColorFromHSVA } from "/src/utility-functions/colors";
|
||||
import { sRgba8ContrastingColor, sRgba8Opaque, sRgba8ToHexNoAlpha, sRgba8ToRgbCSS, createSRgba8, createSRgba8FromHsva } from "/src/utility-functions/colors";
|
||||
|
||||
const dispatch = createEventDispatcher<{
|
||||
update: { hue: number; saturation: number; value: number; alpha: number };
|
||||
@@ -184,20 +184,20 @@
|
||||
removeEvents();
|
||||
});
|
||||
|
||||
$: newColor = isNone ? undefined : createColorFromHSVA(hue, saturation, value, alpha);
|
||||
$: opaqueHueColor = createColorFromHSVA(hue, 1, 1, 1);
|
||||
$: opaqueColorOnly = newColor ? colorOpaque(newColor) : createColor(0, 0, 0, 1);
|
||||
$: newColor = isNone ? undefined : createSRgba8FromHsva(hue, saturation, value, alpha);
|
||||
$: opaqueHueColor = createSRgba8FromHsva(hue, 1, 1, 1);
|
||||
$: opaqueColorOnly = newColor ? sRgba8Opaque(newColor) : createSRgba8(0, 0, 0, 255);
|
||||
</script>
|
||||
|
||||
<LayoutRow
|
||||
class="visual-color-pickers-input"
|
||||
classes={{ disabled }}
|
||||
styles={{
|
||||
"--hue-color": colorToRgbCSS(opaqueHueColor),
|
||||
"--hue-color-contrasting": colorContrastingColor(opaqueHueColor),
|
||||
"--opaque-color": colorToHexNoAlpha(opaqueColorOnly),
|
||||
"--opaque-color-contrasting": colorContrastingColor(opaqueColorOnly),
|
||||
"--new-color-contrasting": colorContrastingColor(newColor),
|
||||
"--hue-color": sRgba8ToRgbCSS(opaqueHueColor),
|
||||
"--hue-color-contrasting": sRgba8ContrastingColor(opaqueHueColor),
|
||||
"--opaque-color": sRgba8ToHexNoAlpha(opaqueColorOnly),
|
||||
"--opaque-color-contrasting": sRgba8ContrastingColor(opaqueColorOnly),
|
||||
"--new-color-contrasting": sRgba8ContrastingColor(newColor),
|
||||
}}
|
||||
>
|
||||
{@const hueDescription = "The shade along the spectrum of the rainbow."}
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import ColorPicker from "/src/components/floating-menus/ColorPicker.svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import { fillChoiceColor, colorToRgbaCSS } from "/src/utility-functions/colors";
|
||||
import type { Color, EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import { fillChoiceUIColor, sRgba8ToRgbaCSS } from "/src/utility-functions/colors";
|
||||
import type { SRGBA8, EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const editor = getContext<EditorWrapper>("editor");
|
||||
|
||||
// Content
|
||||
export let primary: Color;
|
||||
export let secondary: Color;
|
||||
export let primary: SRGBA8;
|
||||
export let secondary: SRGBA8;
|
||||
|
||||
let primaryOpen = false;
|
||||
let secondaryOpen = false;
|
||||
@@ -25,37 +25,37 @@
|
||||
secondaryOpen = true;
|
||||
}
|
||||
|
||||
function primaryColorChanged(color: Color) {
|
||||
editor.updatePrimaryColor(color.red, color.green, color.blue, color.alpha);
|
||||
function primaryColorChanged(color: SRGBA8) {
|
||||
editor.updatePrimaryColor(color);
|
||||
}
|
||||
|
||||
function secondaryColorChanged(color: Color) {
|
||||
editor.updateSecondaryColor(color.red, color.green, color.blue, color.alpha);
|
||||
function secondaryColorChanged(color: SRGBA8) {
|
||||
editor.updateSecondaryColor(color);
|
||||
}
|
||||
</script>
|
||||
|
||||
<LayoutCol class="working-colors-button">
|
||||
<LayoutRow class="primary swatch">
|
||||
<button on:click={clickPrimarySwatch} class:open={primaryOpen} style:--swatch-color={colorToRgbaCSS(primary)} data-floating-menu-spawner data-block-hover-transfer tabindex="0"></button>
|
||||
<button on:click={clickPrimarySwatch} class:open={primaryOpen} style:--swatch-color={sRgba8ToRgbaCSS(primary)} data-floating-menu-spawner data-block-hover-transfer tabindex="0"></button>
|
||||
<ColorPicker
|
||||
open={primaryOpen}
|
||||
on:open={({ detail }) => (primaryOpen = detail)}
|
||||
colorOrGradient={{ Solid: primary }}
|
||||
on:colorOrGradient={({ detail }) => {
|
||||
const color = fillChoiceColor(detail);
|
||||
const color = fillChoiceUIColor(detail);
|
||||
if (color) primaryColorChanged(color);
|
||||
}}
|
||||
direction="Right"
|
||||
/>
|
||||
</LayoutRow>
|
||||
<LayoutRow class="secondary swatch">
|
||||
<button on:click={clickSecondarySwatch} class:open={secondaryOpen} style:--swatch-color={colorToRgbaCSS(secondary)} data-floating-menu-spawner data-block-hover-transfer tabindex="0"></button>
|
||||
<button on:click={clickSecondarySwatch} class:open={secondaryOpen} style:--swatch-color={sRgba8ToRgbaCSS(secondary)} data-floating-menu-spawner data-block-hover-transfer tabindex="0"></button>
|
||||
<ColorPicker
|
||||
open={secondaryOpen}
|
||||
on:open={({ detail }) => (secondaryOpen = detail)}
|
||||
colorOrGradient={{ Solid: secondary }}
|
||||
on:colorOrGradient={({ detail }) => {
|
||||
const color = fillChoiceColor(detail);
|
||||
const color = fillChoiceUIColor(detail);
|
||||
if (color) secondaryColorChanged(color);
|
||||
}}
|
||||
direction="Right"
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
export let tableAlign = false;
|
||||
// Sizing
|
||||
export let minWidth = 0;
|
||||
export let maxWidth = 0;
|
||||
export let minWidthCharacters = 0;
|
||||
// Tooltips
|
||||
export let tooltipLabel: string | undefined = undefined;
|
||||
@@ -77,7 +78,8 @@
|
||||
class:multiline
|
||||
class:center-align={centerAlign}
|
||||
class:table-align={tableAlign}
|
||||
style:min-width={minWidthCharacters ? `${minWidthCharacters}ch` : minWidth || undefined}
|
||||
style:min-width={minWidthCharacters ? `${minWidthCharacters}ch` : minWidth > 0 ? `${minWidth}px` : undefined}
|
||||
style:max-width={maxWidth > 0 ? `${maxWidth}px` : undefined}
|
||||
style={`${styleName} ${extraStyles}`.trim() || undefined}
|
||||
data-tooltip-label={tooltipLabel}
|
||||
data-tooltip-description={tooltipDescription}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
|
||||
import { panelDrag, startCrossPanelDrag, endCrossPanelDrag, updateCrossPanelHover, updateDockingHover } from "/src/stores/panel-drag";
|
||||
import type { DockingEdge } from "/src/stores/panel-drag";
|
||||
import type { EditorWrapper, PanelType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { DockingSplitDirection, EditorWrapper, PanelType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const PANEL_COMPONENTS = {
|
||||
Welcome,
|
||||
@@ -40,7 +40,7 @@
|
||||
export let emptySpaceAction: (() => void) | undefined = undefined;
|
||||
export let crossPanelDropAction: ((sourcePanelId: string, targetPanelId: string, insertIndex: number) => void) | undefined = undefined;
|
||||
export let groupDropAction: ((sourcePanelId: string, targetPanelId: string, insertIndex: number) => void) | undefined = undefined;
|
||||
export let splitDropAction: ((targetPanelId: string, direction: DockingEdge, tabs: PanelType[], activeTabIndex: number) => void) | undefined = undefined;
|
||||
export let splitDropAction: ((targetPanelId: string, direction: DockingSplitDirection, tabs: PanelType[], activeTabIndex: number) => void) | undefined = undefined;
|
||||
|
||||
let className = "";
|
||||
export { className as class };
|
||||
@@ -222,7 +222,7 @@
|
||||
dropAction?.(panelId, crossPanelState.hoverDockingPanelId, Number.MAX_SAFE_INTEGER);
|
||||
}
|
||||
// Edge docking drop: create a new split adjacent to the target panel
|
||||
else if (crossPanelState.active && crossPanelState.hoverDockingPanelId && crossPanelState.hoverDockingEdge) {
|
||||
else if (crossPanelState.active && crossPanelState.hoverDockingPanelId && crossPanelState.hoverDockingEdge && crossPanelState.hoverDockingEdge !== "Center") {
|
||||
splitDropAction?.(
|
||||
crossPanelState.hoverDockingPanelId,
|
||||
crossPanelState.hoverDockingEdge,
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
|
||||
import Panel from "/src/components/window/Panel.svelte";
|
||||
import type { PortfolioStore } from "/src/stores/portfolio";
|
||||
import type { DocumentInfo, EditorWrapper, PanelGroupState, PanelLayoutSubdivision } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { DockingSplitDirection, DocumentInfo, EditorWrapper, PanelGroupState, PanelLayoutSubdivision, PanelType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const MIN_PANEL_SIZE = 100;
|
||||
const DOUBLE_CLICK_MILLISECONDS = 500;
|
||||
@@ -85,7 +85,7 @@
|
||||
sizeOverrides = sizeOverrides;
|
||||
|
||||
const allSizes = children.map((child, i) => sizeOverrides[i] ?? child.size);
|
||||
editor.setPanelGroupSizes(splitPath, allSizes);
|
||||
editor.setPanelGroupSizes(new Uint32Array(splitPath), new Float64Array(allSizes));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@
|
||||
// Persist the resized sizes to the backend
|
||||
if ("Split" in subdivision) {
|
||||
const allSizes = subdivision.Split.children.map((child, i) => sizeOverrides[i] ?? child.size);
|
||||
editor.setPanelGroupSizes(splitPath, allSizes);
|
||||
editor.setPanelGroupSizes(new Uint32Array(splitPath), new Float64Array(allSizes));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -179,7 +179,7 @@
|
||||
editor.moveAllPanelTabs(BigInt(sourcePanelId), BigInt(targetPanelId), insertIndex);
|
||||
}
|
||||
|
||||
function splitDrop(targetPanelId: string, direction: string, tabs: string[], activeTabIndex: number) {
|
||||
function splitDrop(targetPanelId: string, direction: DockingSplitDirection, tabs: PanelType[], activeTabIndex: number) {
|
||||
editor.splitPanelGroup(BigInt(targetPanelId), direction, tabs, activeTabIndex);
|
||||
}
|
||||
|
||||
|
||||
@@ -129,6 +129,7 @@ import Cut from "/../branding/assets/icon-16px-solid/cut.svg";
|
||||
import DeselectAll from "/../branding/assets/icon-16px-solid/deselect-all.svg";
|
||||
import Edit from "/../branding/assets/icon-16px-solid/edit.svg";
|
||||
import Empty from "/../branding/assets/icon-16px-solid/empty.svg";
|
||||
import ExpandFillStroke from "/../branding/assets/icon-16px-solid/expand-fill-stroke.svg";
|
||||
import EyeHidden from "/../branding/assets/icon-16px-solid/eye-hidden.svg";
|
||||
import EyeHide from "/../branding/assets/icon-16px-solid/eye-hide.svg";
|
||||
import EyeShow from "/../branding/assets/icon-16px-solid/eye-show.svg";
|
||||
@@ -199,6 +200,17 @@ import StackLower from "/../branding/assets/icon-16px-solid/stack-lower.svg";
|
||||
import StackRaise from "/../branding/assets/icon-16px-solid/stack-raise.svg";
|
||||
import StackReverse from "/../branding/assets/icon-16px-solid/stack-reverse.svg";
|
||||
import Stack from "/../branding/assets/icon-16px-solid/stack.svg";
|
||||
import StrokeAlignCenter from "/../branding/assets/icon-16px-solid/stroke-align-center.svg";
|
||||
import StrokeAlignInside from "/../branding/assets/icon-16px-solid/stroke-align-inside.svg";
|
||||
import StrokeAlignOutside from "/../branding/assets/icon-16px-solid/stroke-align-outside.svg";
|
||||
import StrokeCapButt from "/../branding/assets/icon-16px-solid/stroke-cap-butt.svg";
|
||||
import StrokeCapRound from "/../branding/assets/icon-16px-solid/stroke-cap-round.svg";
|
||||
import StrokeCapSquare from "/../branding/assets/icon-16px-solid/stroke-cap-square.svg";
|
||||
import StrokeJoinBevel from "/../branding/assets/icon-16px-solid/stroke-join-bevel.svg";
|
||||
import StrokeJoinMiter from "/../branding/assets/icon-16px-solid/stroke-join-miter.svg";
|
||||
import StrokeJoinRound from "/../branding/assets/icon-16px-solid/stroke-join-round.svg";
|
||||
import StrokeOrderAbove from "/../branding/assets/icon-16px-solid/stroke-order-above.svg";
|
||||
import StrokeOrderBelow from "/../branding/assets/icon-16px-solid/stroke-order-below.svg";
|
||||
import TextAlignCenter from "/../branding/assets/icon-16px-solid/text-align-center.svg";
|
||||
import TextAlignLeft from "/../branding/assets/icon-16px-solid/text-align-left.svg";
|
||||
import TextAlignRight from "/../branding/assets/icon-16px-solid/text-align-right.svg";
|
||||
@@ -257,6 +269,7 @@ const SOLID_16PX = {
|
||||
DeselectAll: { svg: DeselectAll, size: 16 },
|
||||
Edit: { svg: Edit, size: 16 },
|
||||
Empty: { svg: Empty, size: 16 },
|
||||
ExpandFillStroke: { svg: ExpandFillStroke, size: 16 },
|
||||
Eyedropper: { svg: Eyedropper, size: 16 },
|
||||
EyeHidden: { svg: EyeHidden, size: 16 },
|
||||
EyeHide: { svg: EyeHide, size: 16 },
|
||||
@@ -327,6 +340,17 @@ const SOLID_16PX = {
|
||||
StackLower: { svg: StackLower, size: 16 },
|
||||
StackRaise: { svg: StackRaise, size: 16 },
|
||||
StackReverse: { svg: StackReverse, size: 16 },
|
||||
StrokeAlignCenter: { svg: StrokeAlignCenter, size: 16 },
|
||||
StrokeAlignInside: { svg: StrokeAlignInside, size: 16 },
|
||||
StrokeAlignOutside: { svg: StrokeAlignOutside, size: 16 },
|
||||
StrokeCapButt: { svg: StrokeCapButt, size: 16 },
|
||||
StrokeCapRound: { svg: StrokeCapRound, size: 16 },
|
||||
StrokeCapSquare: { svg: StrokeCapSquare, size: 16 },
|
||||
StrokeJoinBevel: { svg: StrokeJoinBevel, size: 16 },
|
||||
StrokeJoinMiter: { svg: StrokeJoinMiter, size: 16 },
|
||||
StrokeJoinRound: { svg: StrokeJoinRound, size: 16 },
|
||||
StrokeOrderAbove: { svg: StrokeOrderAbove, size: 16 },
|
||||
StrokeOrderBelow: { svg: StrokeOrderBelow, size: 16 },
|
||||
TextAlignCenter: { svg: TextAlignCenter, size: 16 },
|
||||
TextAlignLeft: { svg: TextAlignLeft, size: 16 },
|
||||
TextAlignRight: { svg: TextAlignRight, size: 16 },
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// Drag-toggle: the user presses one toggleable button and drags across its siblings to flip them all
|
||||
// to the opposite of the source's starting state.
|
||||
//
|
||||
// Peers declare themselves with two data attributes on the clickable element:
|
||||
// - data-drag-toggle-group="<group-name>": siblings share this name to form a drag-toggle group
|
||||
// - data-drag-toggle-state="<current-state>": the current toggle state (e.g. "visible" / "hidden")
|
||||
//
|
||||
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
|
||||
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
|
||||
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
|
||||
|
||||
type ActiveGroupListener = (activeGroup: string | undefined) => void;
|
||||
|
||||
const listeners = new Set<ActiveGroupListener>();
|
||||
let activeGroup: string | undefined = undefined;
|
||||
let source: HTMLElement | undefined = undefined;
|
||||
let startingState: string | undefined = undefined;
|
||||
let visited = new WeakSet<Element>();
|
||||
let engaged = false;
|
||||
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
||||
|
||||
export function createDragToggleManager(activeGroupListener?: ActiveGroupListener) {
|
||||
if (activeGroupListener) listeners.add(activeGroupListener);
|
||||
|
||||
// Install the window event listeners only when the first consumer subscribes
|
||||
if (listeners.size === 1) {
|
||||
// Capture phase on pointerdown preempts sibling drag handlers on ancestors so they don't also engage
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
window.addEventListener("pointermove", onPointerMove);
|
||||
window.addEventListener("pointerup", onPointerUp);
|
||||
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
||||
window.addEventListener("click", onClickCapture, true);
|
||||
}
|
||||
}
|
||||
|
||||
export function destroyDragToggleManager(activeGroupListener?: ActiveGroupListener) {
|
||||
if (activeGroupListener) listeners.delete(activeGroupListener);
|
||||
|
||||
// Uninstall the window event listeners only once the last consumer leaves
|
||||
if (listeners.size === 0) {
|
||||
window.removeEventListener("pointerdown", onPointerDown, true);
|
||||
window.removeEventListener("pointermove", onPointerMove);
|
||||
window.removeEventListener("pointerup", onPointerUp);
|
||||
window.removeEventListener("click", onClickCapture, true);
|
||||
|
||||
activeGroup = undefined;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
suppressNextClickFromSource = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
activeGroup = group;
|
||||
listeners.forEach((listener) => listener(group));
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
|
||||
if (!(target instanceof Element)) return undefined;
|
||||
const found = target.closest("[data-drag-toggle-group]");
|
||||
return found instanceof HTMLElement ? found : undefined;
|
||||
}
|
||||
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (e.button !== 0) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
|
||||
const found = findMember(e.target || undefined);
|
||||
if (!found) return;
|
||||
|
||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||
e.stopPropagation();
|
||||
|
||||
source = found;
|
||||
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
const member = findMember(e.target || undefined);
|
||||
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
|
||||
|
||||
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
|
||||
if (member === source || visited.has(member)) return;
|
||||
|
||||
// First crossing engages the drag and toggles the source as part of the operation
|
||||
if (!engaged) {
|
||||
engaged = true;
|
||||
visited.add(source);
|
||||
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
|
||||
}
|
||||
|
||||
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
||||
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||
|
||||
visited.add(member);
|
||||
member.click();
|
||||
}
|
||||
|
||||
function onPointerUp() {
|
||||
if (!activeGroup) return;
|
||||
|
||||
// If a drag engaged, the source was already clicked programmatically; suppress its natural click so it isn't re-toggled
|
||||
if (engaged && source) suppressNextClickFromSource = source;
|
||||
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(undefined);
|
||||
}
|
||||
|
||||
function onClickCapture(e: Event) {
|
||||
if (suppressNextClickFromSource && e.target instanceof Node && suppressNextClickFromSource.contains(e.target)) {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
suppressNextClickFromSource = undefined;
|
||||
}
|
||||
|
||||
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
|
||||
import.meta.hot?.accept((newModule) => {
|
||||
const carried = Array.from(listeners);
|
||||
carried.forEach((listener) => destroyDragToggleManager(listener));
|
||||
carried.forEach((listener) => newModule?.createDragToggleManager(listener));
|
||||
});
|
||||
@@ -2,10 +2,10 @@ import { writable } from "svelte/store";
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { patchLayout } from "/src/utility-functions/widgets";
|
||||
import type { FillChoice, Layout } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { FillChoiceUI, Layout } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type ColorPickerCallbacks = {
|
||||
onColorChanged?: (value: FillChoice) => void;
|
||||
onColorChanged?: (value: FillChoiceUI) => void;
|
||||
onStartTransaction?: () => void;
|
||||
onCommitTransaction?: () => void;
|
||||
};
|
||||
@@ -35,13 +35,14 @@ const { subscribe, update } = store;
|
||||
export type ColorPickerStore = {
|
||||
subscribe: typeof subscribe;
|
||||
setCallbacks: (callbacks: ColorPickerCallbacks) => void;
|
||||
clearCallbacks: () => void;
|
||||
// Identity-checked so a hover-transfer race where another picker's `setCallbacks` already replaced these doesn't clobber the new picker's callbacks
|
||||
clearCallbacks: (expected: ColorPickerCallbacks) => void;
|
||||
setDragging: (dragging: boolean) => void;
|
||||
};
|
||||
|
||||
// The Rust handler keeps a single shared layout per target, but multiple `<ColorPicker>` Svelte instances may be mounted across
|
||||
// The Rust handler keeps a single shared layout per target, but multiple `<ColorPicker />` Svelte instances may be mounted across
|
||||
// the app (one per `ColorInput`/`WorkingColorsInput`/etc.). Subscribing to the layout target from each instance is destructive,
|
||||
// only the last-registered callback wins. So we maintain a single global subscription here and let each `<ColorPicker>` instance
|
||||
// only the last-registered callback wins. So we maintain a single global subscription here and let each `<ColorPicker />` instance
|
||||
// read from the resulting store and register its own per-open callbacks for color/transaction events.
|
||||
export function createColorPickerStore(subscriptions: SubscriptionsRouter): ColorPickerStore {
|
||||
destroyColorPickerStore();
|
||||
@@ -88,10 +89,12 @@ export function createColorPickerStore(subscriptions: SubscriptionsRouter): Colo
|
||||
return state;
|
||||
});
|
||||
},
|
||||
clearCallbacks: () => {
|
||||
clearCallbacks: (expected: ColorPickerCallbacks) => {
|
||||
update((state) => {
|
||||
state.callbacks = {};
|
||||
state.isDragging = false;
|
||||
if (state.callbacks === expected) {
|
||||
state.callbacks = {};
|
||||
}
|
||||
return state;
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { writable } from "svelte/store";
|
||||
import type { Writable } from "svelte/store";
|
||||
import type { PanelType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { DockingSplitDirection, PanelType } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type DockingEdge = "Left" | "Right" | "Top" | "Bottom" | "Center";
|
||||
export type DockingEdge = DockingSplitDirection | "Center";
|
||||
|
||||
export type PanelDragState = {
|
||||
active: boolean;
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import { downloadFile, downloadFileBlob, upload } from "/src/utility-functions/files";
|
||||
import { rasterizeSVG } from "/src/utility-functions/rasterization";
|
||||
import { patchLayout } from "/src/utility-functions/widgets";
|
||||
import { createZipFromFiles } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { EditorWrapper, DocumentInfo, LayerPanelEntry, LayerStructureEntry, Layout, WorkspacePanelLayout } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type PortfolioStore = ReturnType<typeof createPortfolioStore>;
|
||||
@@ -129,6 +130,48 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
}
|
||||
});
|
||||
|
||||
// TODO: This handler orchestrates rasterization + zipping in JS because PNG/JPG frames arrive as SVG strings
|
||||
// TODO: that need the frontend's canvas-based `rasterizeSVG()` to encode. Once SVG rasterization moves to
|
||||
// TODO: always occur in Rust, the executor can build the .zip itself and emit a single `TriggerSaveFile`,
|
||||
// TODO: matching how PNG/JPG/SVG/.graphite single-file exports work today.
|
||||
subscriptions.subscribeFrontendMessage("TriggerExportAnimation", async (data) => {
|
||||
const { name, extension, mime, size, frames } = data;
|
||||
const isRaster = extension === "png" || extension === "jpg";
|
||||
const backgroundColor = mime.endsWith("jpeg") ? "white" : undefined;
|
||||
const padWidth = Math.max(4, String(frames.length).length);
|
||||
|
||||
// Materialize each frame to bytes, rasterizing SVG via canvas when the destination format is raster.
|
||||
// Any per-frame failure aborts the export rather than silently dropping frames, so the user never gets
|
||||
// a zip with mismatched indices vs. the requested playback range.
|
||||
const entries: [string, Uint8Array][] = [];
|
||||
try {
|
||||
for (let i = 0; i < frames.length; i++) {
|
||||
const frame = frames[i];
|
||||
const filename = `${name}_${String(i + 1).padStart(padWidth, "0")}.${extension}`;
|
||||
|
||||
let bytes: Uint8Array;
|
||||
if ("Bytes" in frame) {
|
||||
bytes = frame.Bytes;
|
||||
} else if (isRaster) {
|
||||
const blob = await rasterizeSVG(frame.Svg, size[0], size[1], mime, backgroundColor);
|
||||
bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
} else {
|
||||
bytes = new TextEncoder().encode(frame.Svg);
|
||||
}
|
||||
entries.push([filename, bytes]);
|
||||
}
|
||||
} catch (error) {
|
||||
editor.errorDialog("Animation export failed", error instanceof Error ? error.message : String(error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (entries.length === 0) return;
|
||||
|
||||
// Build the .zip in Rust (uncompressed store mode); web APIs can only deliver a single download, so the user gets one .zip
|
||||
const zipBytes = createZipFromFiles(entries);
|
||||
downloadFileBlob(`${name}.zip`, new Blob([new Uint8Array(zipBytes)], { type: "application/zip" }));
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateWorkspacePanelLayout", (data) => {
|
||||
update((state) => {
|
||||
state.panelLayout = data.panelLayout;
|
||||
@@ -196,6 +239,7 @@ export function destroyPortfolioStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSaveDocument");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSaveFile");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerExportImage");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerExportAnimation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateWorkspacePanelLayout");
|
||||
subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons");
|
||||
subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Color, FillChoice, GradientStops } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { FillChoiceUI, GradientStopsUI, SRGBA8 } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
// Channels can have any range (0-1, 0-255, 0-100, 0-360) in the context they are being used in, these are just containers for the numbers
|
||||
export type HSV = { h: number; s: number; v: number };
|
||||
@@ -6,26 +6,33 @@ export type RGB = { r: number; g: number; b: number };
|
||||
|
||||
// COLOR FACTORY FUNCTIONS
|
||||
|
||||
export function createColor(red: number, green: number, blue: number, alpha: number): Color {
|
||||
export function createSRgba8(red: number, green: number, blue: number, alpha: number): SRGBA8 {
|
||||
return { red, green, blue, alpha };
|
||||
}
|
||||
|
||||
export function createColorFromHSVA(h: number, s: number, v: number, a: number): Color {
|
||||
// Build an `SRGBA8` from HSVA components on the 0..1 range.
|
||||
export function createSRgba8FromHsva(h: number, s: number, v: number, a: number): SRGBA8 {
|
||||
const convert = (n: number): number => {
|
||||
const k = (n + h * 6) % 6;
|
||||
return v - v * s * Math.max(Math.min(...[k, 4 - k, 1]), 0);
|
||||
};
|
||||
|
||||
return { red: convert(5), green: convert(3), blue: convert(1), alpha: a };
|
||||
return {
|
||||
red: Math.round(convert(5) * 255),
|
||||
green: Math.round(convert(3) * 255),
|
||||
blue: Math.round(convert(1) * 255),
|
||||
alpha: Math.round(a * 255),
|
||||
};
|
||||
}
|
||||
|
||||
// COLOR UTILITY FUNCTIONS
|
||||
|
||||
export function isColor(value: unknown): value is Color {
|
||||
export function isSRgba8(value: unknown): value is SRGBA8 {
|
||||
return typeof value === "object" && value !== null && "red" in value;
|
||||
}
|
||||
|
||||
export function colorFromCSS(colorCode: string): Color | undefined {
|
||||
// Parse a CSS color string into an `SRGBA8`. Uses a canvas to delegate parsing to the browser.
|
||||
export function sRgba8FromCSS(colorCode: string): SRGBA8 | undefined {
|
||||
// Allow single-digit hex value inputs
|
||||
let colorValue = colorCode.trim();
|
||||
if (colorValue.length === 2 && colorValue.charAt(0) === "#" && /[0-9a-f]/i.test(colorValue.charAt(1))) {
|
||||
@@ -52,52 +59,40 @@ export function colorFromCSS(colorCode: string): Color | undefined {
|
||||
// Invalid color
|
||||
if (comparisonA !== comparisonB) {
|
||||
// If this color code didn't start with a #, add it and try again
|
||||
if (colorValue.trim().charAt(0) !== "#") return colorFromCSS(`#${colorValue.trim()}`);
|
||||
if (colorValue.trim().charAt(0) !== "#") return sRgba8FromCSS(`#${colorValue.trim()}`);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
context.fillRect(0, 0, 1, 1);
|
||||
|
||||
const [r, g, b, a] = [...context.getImageData(0, 0, 1, 1).data];
|
||||
return createColor(r / 255, g / 255, b / 255, a / 255);
|
||||
return createSRgba8(r, g, b, a);
|
||||
}
|
||||
|
||||
export function colorToHexNoAlpha(color: Color): string {
|
||||
const r = Math.round(color.red * 255)
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
const g = Math.round(color.green * 255)
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
const b = Math.round(color.blue * 255)
|
||||
.toString(16)
|
||||
.padStart(2, "0");
|
||||
export function sRgba8ToHexNoAlpha(color: SRGBA8): string {
|
||||
const r = color.red.toString(16).padStart(2, "0");
|
||||
const g = color.green.toString(16).padStart(2, "0");
|
||||
const b = color.blue.toString(16).padStart(2, "0");
|
||||
|
||||
return `#${r}${g}${b}`;
|
||||
}
|
||||
|
||||
export function colorToRgb255(color: Color): RGB {
|
||||
return {
|
||||
r: Math.round(color.red * 255),
|
||||
g: Math.round(color.green * 255),
|
||||
b: Math.round(color.blue * 255),
|
||||
};
|
||||
export function sRgba8ToRgb255(color: SRGBA8): RGB {
|
||||
return { r: color.red, g: color.green, b: color.blue };
|
||||
}
|
||||
|
||||
export function colorToRgbCSS(color: Color): string {
|
||||
const rgb = colorToRgb255(color);
|
||||
|
||||
return `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
|
||||
export function sRgba8ToRgbCSS(color: SRGBA8): string {
|
||||
return `rgb(${color.red}, ${color.green}, ${color.blue})`;
|
||||
}
|
||||
|
||||
export function colorToRgbaCSS(color: Color): string {
|
||||
const rgb = colorToRgb255(color);
|
||||
|
||||
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${color.alpha})`;
|
||||
export function sRgba8ToRgbaCSS(color: SRGBA8): string {
|
||||
return `rgba(${color.red}, ${color.green}, ${color.blue}, ${color.alpha / 255})`;
|
||||
}
|
||||
|
||||
export function colorToHSV(color: Color): HSV {
|
||||
const { red: r, green: g, blue: b } = color;
|
||||
export function sRgba8ToHSV(color: SRGBA8): HSV {
|
||||
const r = color.red / 255;
|
||||
const g = color.green / 255;
|
||||
const b = color.blue / 255;
|
||||
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
@@ -126,15 +121,17 @@ export function colorToHSV(color: Color): HSV {
|
||||
return { h, s, v };
|
||||
}
|
||||
|
||||
export function colorOpaque(color: Color): Color {
|
||||
return createColor(color.red, color.green, color.blue, 1);
|
||||
export function sRgba8Opaque(color: SRGBA8): SRGBA8 {
|
||||
return createSRgba8(color.red, color.green, color.blue, 255);
|
||||
}
|
||||
|
||||
export function colorLuminance(color: Color): number {
|
||||
// WCAG-style relative luminance computed from an `SRGBA8` (alpha composited over white).
|
||||
export function sRgba8Luminance(color: SRGBA8): number {
|
||||
const a = color.alpha / 255;
|
||||
// Convert alpha into white
|
||||
const r = color.red * color.alpha + (1 - color.alpha);
|
||||
const g = color.green * color.alpha + (1 - color.alpha);
|
||||
const b = color.blue * color.alpha + (1 - color.alpha);
|
||||
const r = (color.red / 255) * a + (1 - a);
|
||||
const g = (color.green / 255) * a + (1 - a);
|
||||
const b = (color.blue / 255) * a + (1 - a);
|
||||
|
||||
// https://stackoverflow.com/a/3943023/775283
|
||||
|
||||
@@ -145,32 +142,32 @@ export function colorLuminance(color: Color): number {
|
||||
return linearR * 0.2126 + linearG * 0.7152 + linearB * 0.0722;
|
||||
}
|
||||
|
||||
export function colorContrastingColor(color: Color | undefined): "black" | "white" {
|
||||
export function sRgba8ContrastingColor(color: SRGBA8 | undefined): "black" | "white" {
|
||||
if (!color) return "black";
|
||||
|
||||
const luminance = colorLuminance(color);
|
||||
const luminance = sRgba8Luminance(color);
|
||||
|
||||
return luminance > Math.sqrt(1.05 * 0.05) - 0.05 ? "black" : "white";
|
||||
}
|
||||
|
||||
export function contrastingOutlineFactor(value: FillChoice, proximityColor: string | [string, string], proximityRange: number): number {
|
||||
export function contrastingOutlineFactor(value: FillChoiceUI, proximityColor: string | [string, string], proximityRange: number): number {
|
||||
const pair = Array.isArray(proximityColor) ? [proximityColor[0], proximityColor[1]] : [proximityColor, proximityColor];
|
||||
const [range1, range2] = pair.map((color) => colorFromCSS(window.getComputedStyle(document.body).getPropertyValue(color)));
|
||||
const [range1, range2] = pair.map((color) => sRgba8FromCSS(window.getComputedStyle(document.body).getPropertyValue(color)));
|
||||
|
||||
const contrast = (color: Color | undefined): number => {
|
||||
const contrast = (color: SRGBA8 | undefined): number => {
|
||||
if (!color) return 0;
|
||||
|
||||
const lum = colorLuminance(color);
|
||||
let rangeLuminance1 = range1 ? colorLuminance(range1) : 0;
|
||||
let rangeLuminance2 = range2 ? colorLuminance(range2) : 0;
|
||||
const lum = sRgba8Luminance(color);
|
||||
let rangeLuminance1 = range1 ? sRgba8Luminance(range1) : 0;
|
||||
let rangeLuminance2 = range2 ? sRgba8Luminance(range2) : 0;
|
||||
[rangeLuminance1, rangeLuminance2] = [Math.min(rangeLuminance1, rangeLuminance2), Math.max(rangeLuminance1, rangeLuminance2)];
|
||||
|
||||
const distance = Math.max(0, rangeLuminance1 - lum, lum - rangeLuminance2);
|
||||
|
||||
return (1 - Math.min(distance / proximityRange, 1)) * (1 - colorToHSV(color).s);
|
||||
return (1 - Math.min(distance / proximityRange, 1)) * (1 - sRgba8ToHSV(color).s);
|
||||
};
|
||||
|
||||
const gradientStops = fillChoiceGradientStops(value);
|
||||
const gradientStops = fillChoiceUIGradientStops(value);
|
||||
if (gradientStops) {
|
||||
if (gradientStops.color.length === 0) return 0;
|
||||
|
||||
@@ -180,30 +177,30 @@ export function contrastingOutlineFactor(value: FillChoice, proximityColor: stri
|
||||
return Math.min(first, last);
|
||||
}
|
||||
|
||||
return contrast(fillChoiceColor(value));
|
||||
return contrast(fillChoiceUIColor(value));
|
||||
}
|
||||
|
||||
// GRADIENT UTILITY FUNCTIONS
|
||||
|
||||
export function isGradientStops(value: unknown): value is GradientStops {
|
||||
export function isGradientStopsUI(value: unknown): value is GradientStopsUI {
|
||||
return typeof value === "object" && value !== null && "position" in value && "midpoint" in value && "color" in value;
|
||||
}
|
||||
|
||||
// FILL CHOICE UTILITY FUNCTIONS
|
||||
|
||||
export function fillChoiceColor(value: FillChoice): Color | undefined {
|
||||
export function fillChoiceUIColor(value: FillChoiceUI): SRGBA8 | undefined {
|
||||
if (typeof value === "object" && "Solid" in value) return value.Solid;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function fillChoiceGradientStops(value: FillChoice): GradientStops | undefined {
|
||||
export function fillChoiceUIGradientStops(value: FillChoiceUI): GradientStopsUI | undefined {
|
||||
if (typeof value === "object" && "Gradient" in value) return value.Gradient;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function parseFillChoice(value: unknown): FillChoice {
|
||||
export function parseFillChoiceUI(value: unknown): FillChoiceUI {
|
||||
if (value === "None" || value === undefined || value === null) return "None";
|
||||
if (typeof value === "object" && value !== null && "Solid" in value && isColor(value.Solid)) return { Solid: value.Solid };
|
||||
if (typeof value === "object" && value !== null && "Gradient" in value && isGradientStops(value.Gradient)) return { Gradient: value.Gradient };
|
||||
if (typeof value === "object" && value !== null && "Solid" in value && isSRgba8(value.Solid)) return { Solid: value.Solid };
|
||||
if (typeof value === "object" && value !== null && "Gradient" in value && isGradientStopsUI(value.Gradient)) return { Gradient: value.Gradient };
|
||||
return "None";
|
||||
}
|
||||
@@ -343,7 +343,12 @@ function detectShake(e: PointerEvent | MouseEvent): boolean {
|
||||
}
|
||||
|
||||
function targetIsTextField(target: EventTarget | HTMLElement | undefined): boolean {
|
||||
return target instanceof HTMLElement && (target.nodeName === "INPUT" || target.nodeName === "TEXTAREA" || target.isContentEditable);
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
return (
|
||||
target.isContentEditable ||
|
||||
target instanceof HTMLTextAreaElement ||
|
||||
(target instanceof HTMLInputElement && ["text", "password", "email", "url", "tel", "search", "number", "date", "datetime-local", "month", "time", "week"].includes(target.type))
|
||||
);
|
||||
}
|
||||
|
||||
function potentiallyRestoreCanvasFocus(e: Event) {
|
||||
|
||||
@@ -17,18 +17,23 @@ export async function rasterizeSVGCanvas(svg: string, width: number, height: num
|
||||
const svgBlob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
|
||||
const url = URL.createObjectURL(svgBlob);
|
||||
|
||||
// Load the Image from the URL and wait until it's done
|
||||
// Load the Image from the URL and wait until it's done. Reject on error so callers don't hang forever
|
||||
// if the SVG fails to decode (malformed markup, zero-sized viewport with no width/height attrs, etc.).
|
||||
const image = new Image();
|
||||
image.src = url;
|
||||
await new Promise<void>((resolve) => {
|
||||
image.onload = () => resolve();
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
image.onload = () => resolve();
|
||||
image.onerror = () => reject(new Error("Failed to decode SVG for rasterization"));
|
||||
});
|
||||
|
||||
// Draw our SVG to the canvas
|
||||
context?.drawImage(image, 0, 0, width, height);
|
||||
|
||||
// Clean up the SVG blob URL (once the URL is revoked, the SVG blob data itself is garbage collected after `svgBlob` goes out of scope)
|
||||
URL.revokeObjectURL(url);
|
||||
// Draw our SVG to the canvas
|
||||
context?.drawImage(image, 0, 0, width, height);
|
||||
} finally {
|
||||
// Always clean up the SVG blob URL (once the URL is revoked, the SVG blob data itself is garbage
|
||||
// collected after `svgBlob` goes out of scope), even if loading or drawing threw.
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
return canvas;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ editor = { path = "../../editor", package = "graphite-editor", features = ["gpu"
|
||||
graphene-std = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
bytemuck = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
@@ -38,6 +39,7 @@ web-sys = { workspace = true }
|
||||
ron = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
[package.metadata.wasm-pack.profile.dev]
|
||||
wasm-opt = false
|
||||
|
||||
@@ -16,14 +16,17 @@ use editor::consts::FILE_EXTENSION;
|
||||
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
||||
use editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||
use editor::messages::portfolio::utility_types::{DockingSplitDirection, FontCatalog, FontCatalogFamily, PanelGroupId, PanelType};
|
||||
use editor::messages::prelude::*;
|
||||
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::graphene_hash::CacheHashWrapper;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
|
||||
use serde::Serialize;
|
||||
use serde_wasm_bindgen::{self, from_value};
|
||||
use std::cell::RefCell;
|
||||
@@ -319,52 +322,58 @@ impl EditorWrapper {
|
||||
|
||||
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
||||
#[wasm_bindgen(js_name = widgetValueUpdate)]
|
||||
pub fn widget_value_update(&self, layout_target: JsValue, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
|
||||
}
|
||||
|
||||
/// Commit the value of a given UI widget to the history
|
||||
#[wasm_bindgen(js_name = widgetValueCommit)]
|
||||
pub fn widget_value_commit(&self, layout_target: JsValue, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
||||
pub fn widget_value_commit(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
||||
self.widget_value_commit_helper(layout_target, widget_id, value)
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, and commit it to the history
|
||||
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
|
||||
pub fn widget_value_commit_and_update(&self, layout_target: JsValue, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
self.widget_value_commit_helper(layout_target.clone(), widget_id, value.clone())?;
|
||||
pub fn widget_value_commit_and_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
self.widget_value_commit_helper(layout_target, widget_id, value.clone())?;
|
||||
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
|
||||
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
|
||||
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
|
||||
self.dispatch(DocumentMessage::EndTransaction);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn widget_value_update_helper(&self, layout_target: JsValue, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
|
||||
#[wasm_bindgen(js_name = widgetValueDragDrop)]
|
||||
pub fn widget_value_drag_drop(&self, layout_target: LayoutTarget, widget_id: u64) {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
match (from_value(layout_target), from_value(value)) {
|
||||
(Ok(layout_target), Ok(value)) => {
|
||||
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
|
||||
self.dispatch(message);
|
||||
|
||||
if resend_widget {
|
||||
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
|
||||
self.dispatch(resend_message);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
(target, val) => Err(Error::new(&format!("Could not update UI\nDetails:\nTarget: {target:?}\nValue: {val:?}")).into()),
|
||||
}
|
||||
self.dispatch(LayoutMessage::WidgetValueDragDrop { layout_target, widget_id });
|
||||
}
|
||||
|
||||
pub fn widget_value_commit_helper(&self, layout_target: JsValue, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
||||
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
|
||||
#[wasm_bindgen(js_name = endTransaction)]
|
||||
pub fn end_transaction(&self) {
|
||||
self.dispatch(DocumentMessage::EndTransaction);
|
||||
}
|
||||
|
||||
pub fn widget_value_update_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
match (from_value(layout_target), from_value(value)) {
|
||||
(Ok(layout_target), Ok(value)) => {
|
||||
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
|
||||
self.dispatch(message);
|
||||
Ok(())
|
||||
}
|
||||
(target, val) => Err(Error::new(&format!("Could not commit UI\nDetails:\nTarget: {target:?}\nValue: {val:?}")).into()),
|
||||
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not update UI: {e}")))?;
|
||||
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
|
||||
self.dispatch(message);
|
||||
if resend_widget {
|
||||
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
|
||||
self.dispatch(resend_message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn widget_value_commit_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not commit UI: {e}")))?;
|
||||
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
|
||||
self.dispatch(message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = loadPreferences)]
|
||||
@@ -380,14 +389,8 @@ impl EditorWrapper {
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = loadPersistedState)]
|
||||
pub fn load_persisted_state(&self, state: JsValue) {
|
||||
let Ok(state) = serde_wasm_bindgen::from_value(state) else {
|
||||
log::error!("Failed to deserialize persisted state");
|
||||
return;
|
||||
};
|
||||
|
||||
let message = PersistentStateMessage::LoadState { state };
|
||||
self.dispatch(message);
|
||||
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
|
||||
self.dispatch(PersistentStateMessage::LoadState { state });
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = loadDocumentContent)]
|
||||
@@ -485,9 +488,7 @@ impl EditorWrapper {
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = splitPanelGroup)]
|
||||
pub fn split_panel_group(&self, target_group: u64, direction: String, tabs: JsValue, active_tab_index: usize) {
|
||||
let direction: DockingSplitDirection = serde_wasm_bindgen::from_value(JsValue::from_str(&direction)).unwrap();
|
||||
let tabs: Vec<PanelType> = serde_wasm_bindgen::from_value(tabs).unwrap();
|
||||
pub fn split_panel_group(&self, target_group: u64, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) {
|
||||
let message = PortfolioMessage::SplitPanelGroup {
|
||||
target_group: PanelGroupId(target_group),
|
||||
direction,
|
||||
@@ -498,9 +499,8 @@ impl EditorWrapper {
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = setPanelGroupSizes)]
|
||||
pub fn set_panel_group_sizes(&self, split_path: JsValue, sizes: JsValue) {
|
||||
let split_path: Vec<usize> = serde_wasm_bindgen::from_value(split_path).unwrap();
|
||||
let sizes: Vec<f64> = serde_wasm_bindgen::from_value(sizes).unwrap();
|
||||
pub fn set_panel_group_sizes(&self, split_path: Vec<u32>, sizes: Vec<f64>) {
|
||||
let split_path = split_path.into_iter().map(|i| i as usize).collect();
|
||||
let message = PortfolioMessage::SetPanelGroupSizes { split_path, sizes };
|
||||
self.dispatch(message);
|
||||
}
|
||||
@@ -636,13 +636,8 @@ impl EditorWrapper {
|
||||
|
||||
/// The font catalog has been loaded
|
||||
#[wasm_bindgen(js_name = onFontCatalogLoad)]
|
||||
pub fn on_font_catalog_load(&self, catalog: JsValue) -> Result<(), JsValue> {
|
||||
// Deserializing from TS type: `{ name: string; styles: { weight: number, italic: boolean, url: string }[] }[]`
|
||||
let families = serde_wasm_bindgen::from_value::<Vec<FontCatalogFamily>>(catalog)?;
|
||||
let message = PortfolioMessage::FontCatalogLoaded { catalog: FontCatalog(families) };
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
pub fn on_font_catalog_load(&self, catalog: Vec<FontCatalogFamily>) {
|
||||
self.dispatch(PortfolioMessage::FontCatalogLoaded { catalog: FontCatalog(catalog) });
|
||||
}
|
||||
|
||||
/// A font has been downloaded
|
||||
@@ -670,44 +665,29 @@ impl EditorWrapper {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update primary color with values on a scale from 0 to 1.
|
||||
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
|
||||
#[wasm_bindgen(js_name = updatePrimaryColor)]
|
||||
pub fn update_primary_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let Some(primary_color) = Color::from_rgbaf32(red, green, blue, alpha) else {
|
||||
return Err(Error::new("Invalid color").into());
|
||||
};
|
||||
|
||||
let message = ToolMessage::SelectWorkingColor {
|
||||
color: primary_color.to_linear_srgb(),
|
||||
pub fn update_primary_color(&self, color: SRGBA8) {
|
||||
self.dispatch(ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: true,
|
||||
};
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
/// Update secondary color with values on a scale from 0 to 1.
|
||||
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
|
||||
#[wasm_bindgen(js_name = updateSecondaryColor)]
|
||||
pub fn update_secondary_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let Some(secondary_color) = Color::from_rgbaf32(red, green, blue, alpha) else {
|
||||
return Err(Error::new("Invalid color").into());
|
||||
};
|
||||
|
||||
let message = ToolMessage::SelectWorkingColor {
|
||||
color: secondary_color.to_linear_srgb(),
|
||||
pub fn update_secondary_color(&self, color: SRGBA8) {
|
||||
self.dispatch(ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: false,
|
||||
};
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
|
||||
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker>` opens).
|
||||
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
|
||||
#[wasm_bindgen(js_name = openColorPicker)]
|
||||
pub fn open_color_picker(&self, initial_value: JsValue, allow_none: bool, disabled: bool) -> Result<(), JsValue> {
|
||||
let initial_value = serde_wasm_bindgen::from_value(initial_value).map_err(|e| Error::new(&format!("Invalid initial picker value: {e}")))?;
|
||||
pub fn open_color_picker(&self, initial_value: FillChoiceUI, allow_none: bool, disabled: bool) {
|
||||
let initial_value = FillChoice::from(&initial_value);
|
||||
self.dispatch(ColorPickerMessage::Open { initial_value, allow_none, disabled });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Tell the Rust color picker handler that the popover is closing.
|
||||
@@ -716,14 +696,10 @@ impl EditorWrapper {
|
||||
self.dispatch(ColorPickerMessage::Close);
|
||||
}
|
||||
|
||||
/// Update the color of the currently-edited gradient stop
|
||||
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
|
||||
#[wasm_bindgen(js_name = updateGradientStopColor)]
|
||||
pub fn update_gradient_stop_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let Some(color) = Color::from_rgbaf32(red, green, blue, alpha) else {
|
||||
return Err(Error::new("Invalid color").into());
|
||||
};
|
||||
self.dispatch(GradientToolMessage::UpdateStopColor { color: color.to_linear_srgb() });
|
||||
Ok(())
|
||||
pub fn update_gradient_stop_color(&self, color: SRGBA8) {
|
||||
self.dispatch(GradientToolMessage::UpdateStopColor { color: Color::from(color) });
|
||||
}
|
||||
|
||||
/// Start a new undo transaction for gradient stop color editing
|
||||
@@ -998,6 +974,43 @@ impl EditorWrapper {
|
||||
// Static functions callable from JavaScript without an Editor instance
|
||||
// ====================================================================
|
||||
|
||||
/// Build an uncompressed (store-only) ZIP archive from a list of `[filename, bytes]` entries.
|
||||
///
|
||||
/// Used by the animation export flow on the web build: web APIs cannot offer a multi-file save,
|
||||
/// so the frontend packs all frames into a single `.zip` to download. On desktop, individual files
|
||||
/// are written to a user-chosen folder instead and this function is unused.
|
||||
#[wasm_bindgen(js_name = createZipFromFiles)]
|
||||
pub fn create_zip_from_files(entries: js_sys::Array) -> Result<Vec<u8>, JsValue> {
|
||||
use std::io::{Cursor, Write};
|
||||
use zip::write::{SimpleFileOptions, ZipWriter};
|
||||
|
||||
let mut buffer = Cursor::new(Vec::<u8>::new());
|
||||
let mut writer = ZipWriter::new(&mut buffer);
|
||||
|
||||
// Skip compression since raster/SVG payloads are already small or already compressed
|
||||
let options: SimpleFileOptions = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored).unix_permissions(0o644);
|
||||
|
||||
for entry in entries.iter() {
|
||||
let pair = entry
|
||||
.dyn_ref::<js_sys::Array>()
|
||||
.ok_or_else(|| JsValue::from_str("createZipFromFiles: each entry must be a [filename, bytes] array"))?;
|
||||
|
||||
let filename = pair.get(0).as_string().ok_or_else(|| JsValue::from_str("createZipFromFiles: filename must be a string"))?;
|
||||
// Defense in depth: callers should already sanitize, but if a stray path separator leaks through,
|
||||
// replace it here so the entry can't become a nested path inside the archive.
|
||||
let safe_filename: String = filename.chars().map(|c| if c == '/' || c == '\\' { '_' } else { c }).collect();
|
||||
let bytes = js_sys::Uint8Array::new(&pair.get(1)).to_vec();
|
||||
|
||||
writer
|
||||
.start_file(safe_filename, options)
|
||||
.map_err(|e| JsValue::from_str(&format!("createZipFromFiles: start_file failed: {e}")))?;
|
||||
writer.write_all(&bytes).map_err(|e| JsValue::from_str(&format!("createZipFromFiles: write_all failed: {e}")))?;
|
||||
}
|
||||
|
||||
writer.finish().map_err(|e| JsValue::from_str(&format!("createZipFromFiles: finish failed: {e}")))?;
|
||||
Ok(buffer.into_inner())
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = evaluateMathExpression)]
|
||||
pub fn evaluate_math_expression(expression: &str) -> Option<f64> {
|
||||
let value = math_parser::evaluate(expression)
|
||||
|
||||
@@ -6,8 +6,8 @@ use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER};
|
||||
use editor::application::Editor;
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use editor::messages::prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster::color::Color;
|
||||
use js_sys::{Object, Reflect};
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
@@ -119,7 +119,7 @@ pub(crate) fn auto_save_all_documents() {
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<Color>)]) {
|
||||
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)]) {
|
||||
let window = match window() {
|
||||
Some(window) => window,
|
||||
None => {
|
||||
@@ -167,11 +167,12 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<Color>)])
|
||||
.expect("2d context was not found")
|
||||
.dyn_into::<CanvasRenderingContext2d>()
|
||||
.expect("Failed to cast context to CanvasRenderingContext2d");
|
||||
let u8_data: Vec<u8> = image.data.iter().flat_map(|color| color.to_rgba8_srgb()).collect();
|
||||
let clamped_u8_data = wasm_bindgen::Clamped(&u8_data[..]);
|
||||
// `SRGBA8` is `#[repr(C)]` of four `u8`s, so the data buffer is already the byte format the canvas expects
|
||||
let u8_data: &[u8] = bytemuck::cast_slice(&image.data);
|
||||
let clamped_u8_data = wasm_bindgen::Clamped(u8_data);
|
||||
match ImageData::new_with_u8_clamped_array_and_sh(clamped_u8_data, image.width, image.height) {
|
||||
Ok(image_data_obj) => {
|
||||
if context.put_image_data(&image_data_obj, 0., 0.).is_err() {
|
||||
if context.put_image_data(&image_data_obj, 0, 0).is_err() {
|
||||
error!("Failed to put image data on canvas for id: {placeholder_id}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ winit = { workspace = true }
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
pretty_assertions = { workspace = true }
|
||||
criterion = { workspace = true }
|
||||
iai-callgrind = { workspace = true }
|
||||
gungraun = { workspace = true }
|
||||
|
||||
# Benchmarks
|
||||
[[bench]]
|
||||
@@ -70,5 +70,5 @@ name = "compile_demo_art_criterion"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "compile_demo_art_iai"
|
||||
name = "compile_demo_art_gungraun"
|
||||
harness = false
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::util::*;
|
||||
use iai_callgrind::{library_benchmark, library_benchmark_group, main};
|
||||
use gungraun::prelude::*;
|
||||
|
||||
#[library_benchmark]
|
||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
|
||||
@@ -2,6 +2,7 @@ use super::DocumentNode;
|
||||
use crate::application_io::PlatformEditorApi;
|
||||
use crate::proto::{Any as DAny, FutureAny};
|
||||
use brush_nodes::brush_stroke::BrushStroke;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
@@ -63,7 +64,7 @@ macro_rules! tagged_value {
|
||||
/// Stored compactly as a `GradientStops`, materializes as a single-row `List<GradientStops>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
/// (Old documents that stored a full `Gradient` struct under this same `"Gradient"` tag are routed to `FillGradient` by `deserialize_tagged_value_with_legacy_migration`.)
|
||||
#[serde(deserialize_with = "graphic_types::vector_types::gradient::migrate_to_gradient_stops")] // TODO: Eventually remove this migration document upgrade code
|
||||
#[serde(alias = "GradientTable", alias = "GradientPositions")]
|
||||
#[serde(alias = "GradientTable", alias = "GradientPositions", alias = "GradientStops")]
|
||||
Gradient(GradientStops),
|
||||
/// Stored compactly as a `Vec<BrushStroke>`, materializes as `List<BrushStroke>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "brush_nodes::migrations::migrate_to_brush_strokes")] // TODO: Eventually remove this migration document upgrade code
|
||||
@@ -464,7 +465,7 @@ impl TaggedValue {
|
||||
// String syntax (e.g. "000000ff")
|
||||
if input.starts_with('"') && input.ends_with('"') {
|
||||
let hex = input.trim().trim_matches('"').trim().trim_start_matches('#');
|
||||
let color = Color::from_hex_str(hex);
|
||||
let color = SRGBA8::from_hex_str(hex).map(Color::from);
|
||||
if color.is_none() {
|
||||
log::error!("Invalid default value color string: {input}");
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ pub async fn export_document(
|
||||
// Encode and write raster image when buffer is already provided
|
||||
write_raster_image(output_path, file_type, data, width, height, transparent)?;
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
other => {
|
||||
return Err(format!("Unexpected render output type: {:?}. Expected Texture, Buffer for raster export or Svg for SVG export.", other).into());
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ serde = { workspace = true }
|
||||
# Workspace dependencies
|
||||
graph-craft = { workspace = true, features = ["loading"] }
|
||||
criterion = { workspace = true }
|
||||
iai-callgrind = { workspace = true }
|
||||
gungraun = { workspace = true }
|
||||
preprocessor = { workspace = true }
|
||||
|
||||
# Benchmarks
|
||||
@@ -47,13 +47,13 @@ name = "run_cached"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "update_executor_iai"
|
||||
name = "update_executor_gungraun"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "run_once_iai"
|
||||
name = "run_once_gungraun"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "run_cached_iai"
|
||||
name = "run_cached_gungraun"
|
||||
harness = false
|
||||
Loaded 100 of 134 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user