Compare commits

..
Author SHA1 Message Date
Timon 5a16e18b2a Add time since pointerdown to input event handling (#4443)
Add event time to the editor pointer states

The brush trace's hot core is position plus per-sample time, and the
frame clock is too coarse for high-rate tablets: several samples share
one timestamp and speed dynamics see dt = 0. The desktop stamps
editor-routed pointer input with a monotonic arrival time since winit
does not surface hardware timestamps; the web path can thread the
PointerEvent timeStamp through later.
2026-08-27 13:09:55 +00:00
Timon 3c5e1b8a38 Desktop: Support input from drawing tablets (#4354)
* Rename the editor mouse state types to Pointer* and the input_ modules

* Add optional pen attributes to the editor pointer state types

* Desktop: Send tablet pointer clicks to CEF as mouse clicks

* Desktop: End pointer lock and pending window drags on any left-equivalent release

* Desktop: Route pointer input carrying pen attributes directly to the editor

* Desktop: Route wheel and pinch input inside the viewport directly to the editor

* Desktop: Track double clicks on the direct editor route

* Desktop: Move the pointer lock position into InputState

* Restore the input state pointer position when pointer lock ends (review)

* Fix pen input being swallowed by Windows resize helper

* Update winit to 0.31.0-beta.2 from crates.io
2026-08-27 13:09:55 +00:00
Keavon Chambers 404d9f3047 Fix corrupted font resource loading in older documents 2026-08-25 14:10:22 -07:00
Keavon Chambers c8667edacc Make Data panel scalars selectable inline, denoise float display, and standardize breadcrumb string truncation (#4470)
* Make Data panel scalars selectable inline, denoise float display, and move breadcrumb truncation to Rust

* Code review fixes

* Remove denoising from f32
2026-08-22 01:28:23 -07:00
Keavon Chambers 2fa6b743fe Reintroduce improved logic for mesh interior region fill determination (#4464)
* Decide branching mesh fill insideness by winding, normalizing drawn direction at the Path node

* Fix dead connector click targets by explicitly closing the kurbo ellipse port paths

* Fix hole subtraction when a hole vertex is snapped exactly onto its covering contour

* Classify embedded negative space by its single surrounding face so fully enclosed mesh cells still fill
2026-08-19 00:59:40 -07:00
Keavon Chambers daa8b6a5a4 Delete the vestigial region domain, reverting to naive logic for mesh region fill determination (#4463)
Delete the vestigial region domain, reverting the face fill decision to the bare branching test
2026-08-18 23:50:16 -07:00
Keavon Chambers 39425ca7ea Delete the dead StrokeId and FillId attributes from the Vector segment and region domains (#4461) 2026-08-18 17:51:29 -07:00
Keavon Chambers 48e776c1af Auto-recover stuck npm installs blocked on files locked by zombie processes (#4460) 2026-08-18 16:45:35 -07:00
Keavon Chambers c19f79977b Dedupe code for BezPath emission, epsilon constants, and Polynomial internals (#4459)
* Collapse duplicated BezPath emission, constants, and Polynomial surface across the vector algorithms

* Fix the quadratic segment length lower bound using a control leg instead of the chord
2026-08-18 16:24:12 -07:00
Keavon Chambers 5c580f9dac Clean up the Vector struct implementations by privatizing and deleting unused APIs (#4458)
Trim the Vector API surface by privatizing and deleting caller-less items
2026-08-18 15:54:55 -07:00
Keavon Chambers e3b968f7e2 Port all remaining Subpath producers to BezPath and delete the legacy subpath module (#4457)
* Port all remaining Subpath producers to BezPath and delete the legacy subpath module

* Reset contour state at each MoveTo so an open contour's segments don't leak into the next region

* Give the polygon and star constructors a true center and radius instead of compensated arguments
2026-08-18 15:28:58 -07:00
Keavon Chambers 8f1b2bed5f Collapse ClickTargetType to a single multi-contour BezPath variant (#4456)
* Collapse ClickTargetType to a single multi-contour BezPath variant

* Restrict no-stroke point hits to a path's closed contours
2026-08-18 14:31:52 -07:00
Keavon Chambers c111308c67 Replace the legacy Bezier struct with kurbo::PathSeg throughout (#4455) 2026-08-18 13:08:28 -07:00
Keavon Chambers 20af96c1d9 Remove remnant dead code across the Subpath, Vector, and editor geometry API surfaces (#4454) 2026-08-18 12:34:34 -07:00
Keavon Chambers 2df0bd25c3 Add the "Type Assertion" node catalog category (#4452) 2026-08-17 23:39:02 -07:00
139 changed files with 3474 additions and 4832 deletions

No files matched your search

Generated
+35 -23
View File
@@ -1375,7 +1375,8 @@ dependencies = [
[[package]]
name = "dpi"
version = "0.1.2"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
dependencies = [
"serde",
]
@@ -7667,8 +7668,9 @@ checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
[[package]]
name = "winit"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2879d2854d1a43e48f67322d4bd097afcb6eb8f8f775c8de0260a71aea1df1aa"
dependencies = [
"bitflags 2.11.0",
"cfg_aliases",
@@ -7694,8 +7696,9 @@ dependencies = [
[[package]]
name = "winit-android"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51d9c0d2cd93efec3a9f9ad819cfaf0834782403af7c0d248c784ec0c61761df"
dependencies = [
"android-activity",
"bitflags 2.11.0",
@@ -7709,8 +7712,9 @@ dependencies = [
[[package]]
name = "winit-appkit"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "21310ca07851a49c348e0c2cc768e36b52ca65afda2c2354d78ed4b90074d8aa"
dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
@@ -7731,8 +7735,9 @@ dependencies = [
[[package]]
name = "winit-common"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "45375fbac4cbb77260d83a30b1f9d8105880dbac99a9ae97f56656694680ff69"
dependencies = [
"memmap2 0.9.10",
"objc2 0.6.3",
@@ -7746,8 +7751,9 @@ dependencies = [
[[package]]
name = "winit-core"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4f0ccd7abb43740e2c6124ac7cae7d865ecec74eec63783e8922577ac232583"
dependencies = [
"bitflags 2.11.0",
"cursor-icon",
@@ -7761,8 +7767,9 @@ dependencies = [
[[package]]
name = "winit-orbital"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51ea1fb262e7209f265f12bd0cc792c399b14355675e65531e9c8a87db287d46"
dependencies = [
"bitflags 2.11.0",
"dpi",
@@ -7776,8 +7783,9 @@ dependencies = [
[[package]]
name = "winit-uikit"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "680a356e798837d8eb274d4556e83bceaf81698194e31aafc5cfb8a9f2fab643"
dependencies = [
"bitflags 2.11.0",
"block2 0.6.2",
@@ -7797,8 +7805,9 @@ dependencies = [
[[package]]
name = "winit-wayland"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce5afb2ba07da603f84b722c95f9f9396d2cedae3944fb6c0cda4a6f88de545"
dependencies = [
"ahash",
"bitflags 2.11.0",
@@ -7823,8 +7832,9 @@ dependencies = [
[[package]]
name = "winit-web"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c2490a953fb776fbbd5e295d54f1c3847f4f15b6c3929ec53c09acda6487a92"
dependencies = [
"atomic-waker",
"bitflags 2.11.0",
@@ -7845,8 +7855,9 @@ dependencies = [
[[package]]
name = "winit-win32"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "644ea78af0e858aa3b092e5d1c67c41995a98220c81813f1353b28bc8bb91eaa"
dependencies = [
"bitflags 2.11.0",
"cursor-icon",
@@ -7861,8 +7872,9 @@ dependencies = [
[[package]]
name = "winit-x11"
version = "0.30.12"
source = "git+https://github.com/rust-windowing/winit.git#bd6fef1d80ba063cbe91e150b3fb343927cdc72b"
version = "0.31.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa5b600756534c7041aa93cd0d244d44b09fca1b89e202bd1cd80dd9f3636c46"
dependencies = [
"bitflags 2.11.0",
"bytemuck",
+1 -3
View File
@@ -160,7 +160,7 @@ web-sys = { version = "=0.3.98", features = [
"HtmlImageElement",
"ImageBitmapRenderingContext",
] }
winit = { git = "https://github.com/rust-windowing/winit.git" }
winit = "0.31.0-beta.2"
keyboard-types = "0.8"
url = "2.5"
tokio = { version = "1.29", features = ["fs", "macros", "io-std", "rt", "rt-multi-thread"] }
@@ -260,8 +260,6 @@ lto = "thin"
debug = true
[patch.crates-io]
# 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-149" }
cef-dll-sys = { git = "https://github.com/timon-schelling/cef-rs.git", branch = "graphite-149" }
+32 -56
View File
@@ -9,19 +9,21 @@ use std::sync::mpsc::{Receiver, SyncSender};
use std::thread;
use std::time::{Duration, Instant};
use winit::application::ApplicationHandler;
use winit::dpi::{PhysicalPosition, PhysicalSize};
use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEvent};
use winit::dpi::PhysicalSize;
use winit::event::{ElementState, MouseButton, StartCause, WindowEvent};
use winit::event_loop::run_on_demand::EventLoopExtRunOnDemand;
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::window::WindowId;
use crate::dirs;
use crate::event::{AppEvent, AppEventScheduler};
use crate::input::{InputAction, InputState};
use crate::persist;
use crate::preferences;
use crate::render::{RenderError, RenderState};
use crate::ui::{UiCommand, UiInstance};
use crate::window::Window;
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, InputMessage, MouseKeys, MouseState, Preferences};
use crate::wrapper::messages::{DesktopFrontendMessage, DesktopWrapperMessage, Preferences};
use crate::wrapper::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
pub(crate) struct App {
@@ -33,8 +35,7 @@ pub(crate) struct App {
window_maximized: bool,
window_fullscreen: bool,
window_pending_drag: bool,
pointer_position: PhysicalPosition<f64>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
input_state: InputState,
ui_scale: f64,
app_event_receiver: Receiver<AppEvent>,
app_event_scheduler: AppEventScheduler,
@@ -106,8 +107,7 @@ impl App {
window_maximized: false,
window_fullscreen: false,
window_pending_drag: false,
pointer_position: Default::default(),
pointer_lock_position: Default::default(),
input_state: InputState::new(),
ui_scale: 1.,
app_event_receiver,
app_event_scheduler,
@@ -125,8 +125,8 @@ impl App {
}
}
pub(crate) fn run(mut self, event_loop: EventLoop) -> ExitReason {
event_loop.run_app(&mut self).unwrap();
pub(crate) fn run(mut self, mut event_loop: EventLoop) -> ExitReason {
event_loop.run_app_on_demand(&mut self).unwrap();
self.exit_reason
}
@@ -264,6 +264,8 @@ impl App {
});
}
DesktopFrontendMessage::UpdateViewportPhysicalBounds { x, y, width, height } => {
self.input_state.set_viewport_info(x, y, width, height, self.window_scale);
if let Some(render_state) = &mut self.render_state
&& let Some(window) = &self.window
{
@@ -342,7 +344,7 @@ impl App {
}
}
DesktopFrontendMessage::PointerLock => {
self.pointer_lock_position = Some(self.pointer_position);
self.input_state.lock_pointer();
if let Some(window) = &self.window {
window.start_pointer_lock();
}
@@ -535,14 +537,13 @@ impl ApplicationHandler for App {
fn window_event(&mut self, _event_loop: &dyn ActiveEventLoop, _window_id: WindowId, event: WindowEvent) {
// Handle pointer lock release
if let Some(pointer_lock_position) = self.pointer_lock_position
&& let WindowEvent::PointerButton {
state: ElementState::Released,
button: ButtonSource::Mouse(MouseButton::Left),
..
} = event
if let WindowEvent::PointerButton {
state: ElementState::Released,
button,
..
} = &event && button.clone().mouse_button() == Some(MouseButton::Left)
&& let Some(pointer_lock_position) = self.input_state.unlock_pointer()
{
self.pointer_lock_position = None;
if let Some(window) = &self.window {
window.end_pointer_lock();
}
@@ -554,7 +555,12 @@ impl ApplicationHandler for App {
}));
}
self.ui.send(UiCommand::Input(event.clone()));
for action in self.input_state.process(&event) {
match action {
InputAction::Ui(event) => self.ui.send(UiCommand::Input(event)),
InputAction::Editor(message) => self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message)),
}
}
match event {
WindowEvent::CloseRequested => {
@@ -611,50 +617,20 @@ impl ApplicationHandler for App {
}
}
// Forward and Back buttons are not supported by CEF and thus need to be directly forwarded the editor
WindowEvent::PointerButton {
button: ButtonSource::Mouse(button),
state: ElementState::Pressed,
..
} => {
let mouse_keys = match button {
MouseButton::Back => Some(MouseKeys::BACK),
MouseButton::Forward => Some(MouseKeys::FORWARD),
_ => None,
};
if let Some(mouse_keys) = mouse_keys {
let message = DesktopWrapperMessage::Input(InputMessage::PointerDown {
editor_mouse_state: MouseState { mouse_keys, ..Default::default() },
modifier_keys: Default::default(),
});
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
let message = DesktopWrapperMessage::Input(InputMessage::PointerUp {
editor_mouse_state: Default::default(),
modifier_keys: Default::default(),
});
self.app_event_scheduler.schedule(AppEvent::DesktopWrapperMessage(message));
}
}
WindowEvent::PointerMoved { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } | WindowEvent::PointerEntered { position, .. }
if self.pointer_lock_position.is_none() =>
WindowEvent::PointerMoved { .. } | WindowEvent::PointerLeft { position: Some(_), .. } | WindowEvent::PointerEntered { .. }
if !self.input_state.pointer_locked() && self.window_pending_drag =>
{
self.pointer_position = position;
if self.window_pending_drag {
self.window_pending_drag = false;
if let Some(window) = &self.window {
window.start_drag();
}
self.window_pending_drag = false;
if let Some(window) = &self.window {
window.start_drag();
}
}
WindowEvent::PointerButton {
button: ButtonSource::Mouse(MouseButton::Left),
button,
state: ElementState::Released,
..
} => {
} if button.clone().mouse_button() == Some(MouseButton::Left) => {
self.window_pending_drag = false;
}
@@ -663,7 +639,7 @@ impl ApplicationHandler for App {
}
fn device_event(&mut self, _event_loop: &dyn ActiveEventLoop, _device_id: Option<winit::event::DeviceId>, event: winit::event::DeviceEvent) {
if self.pointer_lock_position.is_some()
if self.input_state.pointer_locked()
&& let winit::event::DeviceEvent::PointerMotion { delta: (x, y) } = event
{
let message = DesktopWrapperMessage::PointerLockMove { x, y };
+245
View File
@@ -0,0 +1,245 @@
use std::time::Instant;
use winit::dpi::PhysicalPosition;
use winit::event::{ButtonSource, ElementState, MouseButton, MouseScrollDelta, PointerSource, TabletToolData, TabletToolKind, WindowEvent};
use crate::ui::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
use crate::wrapper::messages::{DesktopWrapperMessage, InputMessage, ModifierKeys, MouseKeys, PointerState, ScrollDelta};
pub(crate) struct InputState {
start: Instant,
viewport_info: Option<ViewportInfo>,
pointer_lock_position: Option<PhysicalPosition<f64>>,
modifier_keys: ModifierKeys,
pointer_position: PhysicalPosition<f64>,
pointer_keys: MouseKeys,
ui_capture: bool,
multiclick: Option<Multiclick>,
}
pub(crate) enum InputAction {
Ui(WindowEvent),
Editor(DesktopWrapperMessage),
}
impl InputAction {
fn editor(message: InputMessage) -> Self {
Self::Editor(DesktopWrapperMessage::Input(message))
}
}
impl InputState {
pub(crate) fn new() -> Self {
Self {
start: Instant::now(),
viewport_info: None,
pointer_lock_position: None,
modifier_keys: ModifierKeys::empty(),
pointer_position: PhysicalPosition::default(),
pointer_keys: MouseKeys::empty(),
ui_capture: true,
multiclick: None,
}
}
pub(crate) fn set_viewport_info(&mut self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
self.viewport_info = Some(ViewportInfo { x, y, width, height, scale });
}
pub(crate) fn lock_pointer(&mut self) {
self.pointer_lock_position = Some(self.pointer_position);
}
pub(crate) fn unlock_pointer(&mut self) -> Option<PhysicalPosition<f64>> {
let position = self.pointer_lock_position.take();
if let Some(position) = position {
self.pointer_position = position;
}
position
}
pub(crate) fn pointer_locked(&self) -> bool {
self.pointer_lock_position.is_some()
}
pub(crate) fn process(&mut self, event: &WindowEvent) -> Vec<InputAction> {
match event {
WindowEvent::PointerMoved { position, source, .. } => {
self.pointer_position = *position;
let PointerSource::TabletTool { kind, data } = source else {
return vec![InputAction::Ui(event.clone())];
};
let ui_capture = if self.pointer_keys.is_empty() {
self.pointer_locked() || !self.in_viewport(*position)
} else {
self.ui_capture
};
if ui_capture {
return vec![InputAction::Ui(event.clone())];
}
vec![InputAction::editor(InputMessage::PointerMove {
editor_mouse_state: self.tablet_pointer_state(kind, data),
modifier_keys: self.modifier_keys,
})]
}
WindowEvent::PointerEntered { position, .. } | WindowEvent::PointerLeft { position: Some(position), .. } => {
self.pointer_position = *position;
vec![InputAction::Ui(event.clone())]
}
WindowEvent::PointerButton { state, button, position, .. } => {
self.pointer_position = *position;
let tablet = matches!(button, ButtonSource::TabletTool { .. });
// Stroke keeps capture decided from first button press until all buttons are released.
if state.is_pressed() && self.pointer_keys.is_empty() {
self.ui_capture = self.pointer_locked() || !tablet || !self.in_viewport(*position);
}
let mouse_button = button.clone().mouse_button();
let keys = match mouse_button {
Some(MouseButton::Left) => MouseKeys::LEFT,
Some(MouseButton::Right) => MouseKeys::RIGHT,
Some(MouseButton::Middle) => MouseKeys::MIDDLE,
Some(MouseButton::Back) => MouseKeys::BACK,
Some(MouseButton::Forward) => MouseKeys::FORWARD,
_ => MouseKeys::NONE,
};
match state {
ElementState::Pressed => self.pointer_keys.insert(keys),
ElementState::Released => self.pointer_keys.remove(keys),
}
let back_or_forward = matches!(mouse_button, Some(MouseButton::Back | MouseButton::Forward));
if self.pointer_locked() || !(back_or_forward || (tablet && !self.ui_capture)) {
return vec![InputAction::Ui(event.clone())];
}
let editor_mouse_state = match button {
ButtonSource::TabletTool { kind, data, .. } => self.tablet_pointer_state(kind, data),
_ => self.pointer_state(),
};
let modifier_keys = self.modifier_keys;
match state {
ElementState::Pressed => vec![InputAction::editor(InputMessage::PointerDown { editor_mouse_state, modifier_keys })],
ElementState::Released => {
let mut actions = vec![InputAction::editor(InputMessage::PointerUp { editor_mouse_state, modifier_keys })];
if let Some(mouse_button) = mouse_button
&& self.track_multiclick(mouse_button, *position)
{
actions.push(InputAction::editor(InputMessage::DoubleClick {
editor_mouse_state: PointerState {
mouse_keys: keys,
..editor_mouse_state
},
modifier_keys,
}));
}
actions
}
}
}
WindowEvent::MouseWheel { delta, .. } => {
if self.pointer_locked() || !self.in_viewport(self.pointer_position) {
return vec![InputAction::Ui(event.clone())];
}
let (x, y) = match delta {
MouseScrollDelta::LineDelta(x, y) => (f64::from(*x) * SCROLL_LINE_WIDTH, f64::from(*y) * SCROLL_LINE_HEIGHT),
MouseScrollDelta::PixelDelta(position) => (position.x, position.y),
};
let scroll_delta = ScrollDelta::new(-x * SCROLL_SPEED_X, -y * SCROLL_SPEED_Y, 0.);
vec![InputAction::editor(InputMessage::WheelScroll {
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys,
})]
}
WindowEvent::PinchGesture { delta, .. } => {
if self.pointer_locked() || !self.in_viewport(self.pointer_position) || !delta.is_normal() {
return vec![InputAction::Ui(event.clone())];
}
// TODO: This is a temporary solution to handle pinch gestures, we should handle pinch gestures editor-side instead.
let scroll_delta = ScrollDelta::new(0., -delta * PINCH_ZOOM_SPEED, 0.);
vec![InputAction::editor(InputMessage::WheelScroll {
editor_mouse_state: PointerState { scroll_delta, ..self.pointer_state() },
modifier_keys: self.modifier_keys | ModifierKeys::CONTROL,
})]
}
WindowEvent::ModifiersChanged(modifiers) => {
let modifiers = modifiers.state();
self.modifier_keys = ModifierKeys::empty();
self.modifier_keys.set(ModifierKeys::SHIFT, modifiers.shift_key());
self.modifier_keys.set(ModifierKeys::CONTROL, modifiers.control_key());
self.modifier_keys.set(ModifierKeys::ALT, modifiers.alt_key());
self.modifier_keys.set(ModifierKeys::META_OR_COMMAND, modifiers.meta_key());
vec![InputAction::Ui(event.clone())]
}
_ => vec![InputAction::Ui(event.clone())],
}
}
fn scale(&self) -> f64 {
self.viewport_info.as_ref().map_or(1., |info| info.scale)
}
fn in_viewport(&self, position: PhysicalPosition<f64>) -> bool {
self.viewport_info.as_ref().is_some_and(|info| info.contains(position))
}
fn pointer_state(&self) -> PointerState {
PointerState {
editor_position: (self.pointer_position.x / self.scale(), self.pointer_position.y / self.scale()).into(),
mouse_keys: self.pointer_keys,
time: Some(self.start.elapsed().as_secs_f64() * 1000.),
..Default::default()
}
}
fn tablet_pointer_state(&self, kind: &TabletToolKind, data: &TabletToolData) -> PointerState {
PointerState {
pressure: data.force.map(|force| force.normalized(None)),
tilt: data.clone().tilt().map(|tilt| (f64::from(tilt.x), f64::from(tilt.y)).into()),
twist: data.twist.map(f64::from),
wheel: data.tangential_force.map(f64::from),
eraser: matches!(kind, TabletToolKind::Eraser),
..self.pointer_state()
}
}
fn track_multiclick(&mut self, button: MouseButton, position: PhysicalPosition<f64>) -> bool {
let now = Instant::now();
let travel = MULTICLICK_ALLOWED_TRAVEL as f64;
let double = self.multiclick.take().is_some_and(|click| {
click.button == button && now.duration_since(click.time) <= MULTICLICK_TIMEOUT && (position.x - click.position.x).abs() <= travel && (position.y - click.position.y).abs() <= travel
});
if !double {
self.multiclick = Some(Multiclick { button, time: now, position });
}
double
}
}
struct ViewportInfo {
x: f64,
y: f64,
width: f64,
height: f64,
scale: f64,
}
impl ViewportInfo {
fn contains(&self, position: PhysicalPosition<f64>) -> bool {
position.x >= self.x && position.y >= self.y && position.x <= self.x + self.width && position.y <= self.y + self.height
}
}
struct Multiclick {
button: MouseButton,
time: Instant,
position: PhysicalPosition<f64>,
}
+1
View File
@@ -17,6 +17,7 @@ mod cli;
mod dirs;
mod event;
mod gpu_context;
mod input;
mod persist;
mod preferences;
mod render;
+8
View File
@@ -344,6 +344,14 @@ unsafe fn position_helper(main: HWND, helper: HWND) {
let h = (r.bottom - r.top) + RESIZE_BAND_THICKNESS * 2;
let _ = unsafe { SetWindowPos(helper, Some(main), x, y, w, h, SWP_NOACTIVATE | SWP_NOSENDCHANGING) };
let outer = unsafe { CreateRectRgn(0, 0, w, h) };
let inner = unsafe { CreateRectRgn(RESIZE_BAND_THICKNESS, RESIZE_BAND_THICKNESS, w - RESIZE_BAND_THICKNESS, h - RESIZE_BAND_THICKNESS) };
let _ = unsafe { CombineRgn(Some(outer), Some(outer), Some(inner), RGN_DIFF) };
let _ = unsafe { DeleteObject(inner.into()) };
if unsafe { SetWindowRgn(helper, Some(outer), false) } == 0 {
let _ = unsafe { DeleteObject(outer.into()) };
}
}
unsafe fn calculate_hit(helper: HWND, lparam: LPARAM) -> u32 {
+18 -18
View File
@@ -1,5 +1,23 @@
use std::time::Duration;
pub const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
pub const SCROLL_LINE_HEIGHT: f64 = 40.;
pub const SCROLL_LINE_WIDTH: f64 = 40.;
#[cfg(target_os = "linux")]
pub const SCROLL_SPEED_X: f64 = 3.;
#[cfg(target_os = "linux")]
pub const SCROLL_SPEED_Y: f64 = 3.;
#[cfg(not(target_os = "linux"))]
pub const SCROLL_SPEED_X: f64 = 1.;
#[cfg(not(target_os = "linux"))]
pub const SCROLL_SPEED_Y: f64 = 1.;
pub const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const RESOURCE_SCHEME: &str = "resources";
pub(crate) const RESOURCE_DOMAIN: &str = "resources";
@@ -17,21 +35,3 @@ pub(crate) const HOST_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(target_os = "macos")]
pub(crate) const IPC_BOOTSTRAP_PREFIX: &str = "art.graphite.Graphite.ipc.";
pub(crate) const SCROLL_LINE_HEIGHT: usize = 40;
pub(crate) const SCROLL_LINE_WIDTH: usize = 40;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_X: f32 = 3.;
#[cfg(target_os = "linux")]
pub(crate) const SCROLL_SPEED_Y: f32 = 3.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_X: f32 = 1.;
#[cfg(not(target_os = "linux"))]
pub(crate) const SCROLL_SPEED_Y: f32 = 1.;
pub(crate) const PINCH_ZOOM_SPEED: f64 = 300.;
pub(crate) const MULTICLICK_TIMEOUT: Duration = Duration::from_millis(500);
pub(crate) const MULTICLICK_ALLOWED_TRAVEL: usize = 4;
+9 -7
View File
@@ -82,14 +82,16 @@ pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Ve
}
WindowEvent::PointerButton { state, button, position, .. } => {
let mouse_button = match button {
ButtonSource::Mouse(mouse_button) => mouse_button,
_ => {
return Vec::new(); // TODO: Handle touch input
}
ButtonSource::Mouse(mouse_button) => Some(*mouse_button),
ButtonSource::TabletTool { button, .. } => (*button).into(),
_ => None, // TODO: Handle touch input
};
let Some(mouse_button) = mouse_button else {
return Vec::new();
};
let _ = input_state.cursor_move(position);
let click_count = input_state.mouse_input(mouse_button, state).into();
let click_count = input_state.mouse_input(&mouse_button, state).into();
let up = matches!(state, ElementState::Released);
let button = match mouse_button {
MouseButton::Left => MouseButtonKind::Left,
@@ -110,8 +112,8 @@ pub(crate) fn translate(input_state: &mut InputState, event: &WindowEvent) -> Ve
MouseScrollDelta::LineDelta(x, y) => (x * SCROLL_LINE_WIDTH as f32, y * SCROLL_LINE_HEIGHT as f32),
MouseScrollDelta::PixelDelta(physical_position) => (physical_position.x as f32, physical_position.y as f32),
};
delta_x *= SCROLL_SPEED_X;
delta_y *= SCROLL_SPEED_Y;
delta_x *= SCROLL_SPEED_X as f32;
delta_y *= SCROLL_SPEED_Y as f32;
vec![InputEvent::MouseWheel {
data: input_state.mouse_data(),
+2
View File
@@ -22,6 +22,8 @@ mod resources;
mod utility;
mod view;
pub use consts::{MULTICLICK_ALLOWED_TRAVEL, MULTICLICK_TIMEOUT, PINCH_ZOOM_SPEED, SCROLL_LINE_HEIGHT, SCROLL_LINE_WIDTH, SCROLL_SPEED_X, SCROLL_SPEED_Y};
pub struct UiContext<S: Stage = Started> {
inner: S::ContextData,
}
+2 -2
View File
@@ -4,8 +4,8 @@ use std::path::PathBuf;
pub(crate) use graphite_editor::messages::prelude::Message as EditorMessage;
pub use graphite_editor::messages::frontend::utility_types::{DocumentInfo, PersistedState};
pub use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState as MouseState, EditorPosition as Position, MouseKeys};
pub use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
pub use graphite_editor::messages::input_mapper::utility_types::pointer::{EditorPointerState as PointerState, EditorPosition as Position, MouseKeys, ScrollDelta};
pub use graphite_editor::messages::prelude::DocumentId;
pub use graphite_editor::messages::prelude::InputPreprocessorMessage as InputMessage;
pub use graphite_editor::messages::prelude::PreferencesMessageHandler as Preferences;
+1 -1
View File
@@ -3,7 +3,7 @@ pub(crate) mod menu {
use base64::engine::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use graphite_editor::messages::input_mapper::utility_types::input_keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::keyboard::{Key, LabeledKeyOrMouseMotion, LabeledShortcut};
use graphite_editor::messages::input_mapper::utility_types::misc::ActionShortcut;
use graphite_editor::messages::layout::LayoutMessage;
use graphite_editor::messages::tool::tool_messages::tool_prelude::{Layout, LayoutGroup, LayoutTarget, MenuListEntry, Widget, WidgetId, WidgetRow};
+2 -2
View File
@@ -92,7 +92,7 @@ impl Delta {
/// Op payload. Timestamps live on the wrapping `Delta` — one per delta, applied to all LWW-eligible
/// writes within. See `notes/document-format-collaboration.md`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum RegistryDelta {
AddNode {
id: NodeId,
@@ -190,7 +190,7 @@ pub enum RegistryDelta {
}
/// `value: None` means remove. The timestamp comes from the wrapping `Delta`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AttributeDelta {
pub key: String,
pub value: Option<serde_json::Value>,
+26 -211
View File
@@ -182,40 +182,33 @@ fn convert_resources(resources: &graphene_resource::ResourceRegistry, referenced
if !referenced.contains(&id) {
continue;
}
if let Some(entry) = convert_resource_entry(resources, id, peer)? {
registry.resources.insert(id, entry);
let Some(info) = resources.info(&id) else { continue };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
registry.resources.insert(id, entry);
}
Ok(())
}
/// Snapshot one runtime resource into a storage entry, or `None` if the runtime has no such resource.
pub fn convert_resource_entry(resources: &graphene_resource::ResourceRegistry, id: ResourceId, peer: PeerId) -> Result<Option<crate::ResourceEntry>, ConversionError> {
let Some(info) = resources.info(&id) else { return Ok(None) };
let mut entry = crate::ResourceEntry {
hash: info.hash.copied(),
hash_timestamp: TimeStamp::ORIGIN,
..Default::default()
};
for (position, source) in info.sources.iter().enumerate() {
let key = crate::SourceKey {
priority: crate::Priority::new(position as f64).expect("enumerate index is finite"),
peer,
};
let body = serde_json::to_value(source).map_err(|error| ConversionError::SerializationError(error.to_string()))?;
entry.set_source(
key,
crate::SourceValue {
source: body,
timestamp: TimeStamp::ORIGIN,
},
);
}
Ok(Some(entry))
}
/// Collect the `ResourceId`s referenced by `TaggedValue::Resource` inputs anywhere in the network
/// (recursively through nested networks). These are the resources the document actually uses; the
/// runtime cache may hold more (history-retained orphans) that shouldn't be snapshotted into storage.
@@ -286,7 +279,7 @@ fn convert_network<M: NodeMetadataSource + ?Sized>(
metadata_path,
runtime_node_id: *runtime_node_id,
};
let mut node = convert_node(doc_node, location, registry, ctx, true)?;
let mut node = convert_node(doc_node, location, registry, ctx)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(runtime_node_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(global_id, node);
}
@@ -358,13 +351,7 @@ struct NodeLocation<'a> {
runtime_node_id: RuntimeNodeId,
}
fn convert_node<M: NodeMetadataSource + ?Sized>(
doc_node: &DocumentNode,
location: NodeLocation<'_>,
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Node, ConversionError> {
fn convert_node<M: NodeMetadataSource + ?Sized>(doc_node: &DocumentNode, location: NodeLocation<'_>, registry: &mut Registry, ctx: &mut ConversionContext<'_, M>) -> Result<Node, ConversionError> {
let NodeLocation {
network_id,
parent_path,
@@ -396,7 +383,7 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
} else {
metadata_path
};
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx, recurse)?;
let implementation = convert_implementation(&doc_node.implementation, &node_path, child_metadata_path, registry, ctx)?;
// Defaults match `DocumentNode::default()`; `to_runtime` rehydrates absent keys from the same defaults.
let mut attributes = crate::Attributes::new();
@@ -423,29 +410,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
})
}
/// Public form of the node ui-attribute encoding, for staging paths that encode single nodes.
pub fn encode_node_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_attributes(attributes, metadata, metadata_path, runtime_node_id, timestamp)
}
/// Public form of the per-input ui-attribute encoding, matching `encode_node_ui_attributes`.
pub fn encode_input_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
metadata_path: &[RuntimeNodeId],
runtime_node_id: RuntimeNodeId,
input_index: usize,
timestamp: TimeStamp,
) -> Result<(), ConversionError> {
write_ui_input_attributes(attributes, metadata, metadata_path, runtime_node_id, input_index, timestamp)
}
fn write_ui_attributes<M: NodeMetadataSource + ?Sized>(
attributes: &mut crate::Attributes,
metadata: &M,
@@ -569,7 +533,6 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
child_metadata_path: &[RuntimeNodeId],
registry: &mut Registry,
ctx: &mut ConversionContext<'_, M>,
recurse: bool,
) -> Result<Implementation, ConversionError> {
Ok(match implementation {
DocumentNodeImplementation::ProtoNode(identifier) => {
@@ -601,158 +564,10 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
// `to_runtime` -> `from_runtime` round trip reproduces the same `NetworkId` (and thus the
// same node-path hashes underneath it).
let nested_network_id = current_node_path.owned_network_id(ctx.peer);
if recurse {
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
}
convert_network(nested_network, nested_network_id, Some(current_node_path), child_metadata_path, registry, ctx)?;
Implementation::Network(nested_network_id)
}
// TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
})
}
/// Derives the stable storage IDs for entities addressed by runtime network paths, walking the
/// same path-hash chain as a full conversion so scoped and whole-document conversions agree.
pub struct PathResolver {
peer: PeerId,
}
impl PathResolver {
pub fn new(peer: PeerId) -> Self {
Self { peer }
}
/// The storage `NetworkId` of the network at `local_path` (`ROOT_NETWORK` for the empty path).
pub fn network_id(&self, local_path: &[RuntimeNodeId]) -> NetworkId {
match self.owner_path(local_path) {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
}
}
/// The storage `NodeId` of the node with `local_id` inside the network at `local_path`.
pub fn node_id(&self, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId) -> NodeId {
let owner = self.owner_path(local_path);
child_path(owner.as_ref(), self.network_id(local_path), local_id).to_global_id(self.peer)
}
/// Converts one runtime input inside the network at `local_path` to its storage form, resolving
/// node references to their stable global IDs.
pub fn convert_input_at(&self, input: &GraphCraftNodeInput, local_path: &[RuntimeNodeId]) -> Result<NodeInput, ConversionError> {
let owner = self.owner_path(local_path);
convert_input(input, owner.as_ref(), self.network_id(local_path), self.peer)
}
/// The `NodePath` of the node owning the network at `local_path`, or `None` for the root network.
fn owner_path(&self, local_path: &[RuntimeNodeId]) -> Option<NodePath> {
let mut owner: Option<NodePath> = None;
for &local_id in local_path {
let network_id = match &owner {
None => ROOT_NETWORK,
Some(owner) => owner.owned_network_id(self.peer),
};
owner = Some(child_path(owner.as_ref(), network_id, local_id));
}
owner
}
}
/// Converts a chosen subset of runtime entities into a scratch [`Registry`] through the same
/// encoders as a whole-document conversion, so staging can derive deltas for just those entities.
pub struct ScopedConversion<'m, M: NodeMetadataSource + ?Sized> {
ctx: ConversionContext<'m, M>,
resolver: PathResolver,
}
impl<'m, M: NodeMetadataSource + ?Sized> ScopedConversion<'m, M> {
pub fn new(metadata: &'m M, peer: PeerId) -> Self {
Self {
ctx: ConversionContext {
declaration_ids: HashMap::new(),
declaration_bytes: HashMap::new(),
network_ids: HashMap::new(),
metadata,
peer,
},
resolver: PathResolver::new(peer),
}
}
/// Converts the node with `local_id` in the network at `local_path` into `registry` under its
/// stable IDs. `recurse` also converts the contents of any nested network the node implements;
/// without it only the node itself is converted, with its nested network referenced by ID.
pub fn convert_node_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], local_id: RuntimeNodeId, doc_node: &DocumentNode, recurse: bool) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let location = NodeLocation {
network_id: self.resolver.network_id(local_path),
parent_path: owner_path.as_ref(),
metadata_path: local_path,
runtime_node_id: local_id,
};
let mut node = convert_node(doc_node, location, registry, &mut self.ctx, recurse)?;
node.attributes.set(node::ORIGINAL_NODE_ID, serde_json::json!(local_id.0), TimeStamp::ORIGIN);
registry.node_instances.insert(self.resolver.node_id(local_path, local_id), node);
Ok(())
}
/// Converts the entry of the network at `local_path` (its export slots and network-level
/// attributes, not its nodes) into `registry`.
pub fn convert_network_entry_at(&mut self, registry: &mut Registry, local_path: &[RuntimeNodeId], node_network: &NodeNetwork) -> Result<(), ConversionError> {
let owner_path = self.resolver.owner_path(local_path);
let network_id = self.resolver.network_id(local_path);
let exports = node_network
.exports
.iter()
.map(|export| {
Ok(ExportSlot {
target: Some(convert_input(export, owner_path.as_ref(), network_id, self.ctx.peer)?),
timestamp: TimeStamp::ORIGIN,
})
})
.collect::<Result<Vec<_>, ConversionError>>()?;
let mut attributes = crate::Attributes::new();
write_ui_network_attributes(&mut attributes, self.ctx.metadata, local_path, TimeStamp::ORIGIN)?;
write_scope_injections(&mut attributes, node_network, owner_path.as_ref(), network_id, self.ctx.peer, TimeStamp::ORIGIN)?;
registry.networks.insert(network_id, Network { exports, attributes });
Ok(())
}
/// The extracted proto-node declaration bytes, for the caller to persist into its byte store.
pub fn finish(self) -> DeclarationBytes {
self.ctx.declaration_bytes
}
}
/// The `TaggedValue::Resource` IDs referenced by a stored node's value inputs.
///
/// Peeks at the externally-tagged serde shape (`{"Resource": <id>}`) rather than deserializing the
/// whole `TaggedValue`, which can be arbitrarily large. `resource_ref_shape_matches_serde` asserts
/// this stays in lockstep with the real serialization.
pub fn node_value_resource_refs(node: &Node) -> impl Iterator<Item = ResourceId> + '_ {
node.inputs.iter().filter_map(|slot| value_resource_ref(&slot.input))
}
/// The `TaggedValue::Resource` ID referenced by a stored value input, if any.
pub fn value_resource_ref(input: &NodeInput) -> Option<ResourceId> {
match input {
NodeInput::Value { value, .. } => value.get("Resource").and_then(|id| serde_json::from_value(id.clone()).ok()),
_ => None,
}
}
#[cfg(test)]
mod resource_ref_shape {
use super::*;
#[test]
fn resource_ref_shape_matches_serde() {
let id = ResourceId::from_hash(&ResourceHash::from(b"shape test".as_slice()));
let value = serde_json::to_value(TaggedValue::Resource(id)).expect("TaggedValue::Resource serializes");
let parsed: Option<ResourceId> = value.get("Resource").and_then(|inner| serde_json::from_value(inner.clone()).ok());
assert_eq!(parsed, Some(id), "The shape peek in node_value_resource_refs must match TaggedValue's serde form");
}
}
+1 -4
View File
@@ -29,10 +29,7 @@ pub use resources::*;
pub use session::*;
#[cfg(any(feature = "conversion", test))]
pub use from_runtime::{
PathResolver, RuntimeConversion, ScopedConversion, convert_resource_entry, decode_declaration, encode_declaration, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs,
value_resource_ref,
};
pub use from_runtime::{RuntimeConversion, decode_declaration, encode_declaration};
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
-6
View File
@@ -129,12 +129,6 @@ impl Session {
Ok(revs)
}
/// Stages ops computed outside the session (an incremental runtime projection) as hot ops, the
/// same way `stage_from_runtime` stages a diff's ops.
pub fn stage_computed_ops(&mut self, ops: Vec<RegistryDelta>) -> Result<Vec<HotOp>, CrdtError> {
self.stage_ops(ops)
}
/// Apply each op as a hot op with a freshly-ticked timestamp, returning the staged frames in
/// order. Each tick is strictly later than the last, so the final frame carries the latest
/// timestamp, which is what the caller passes to `retire`.
@@ -12,10 +12,10 @@ use graph_craft::application_io::resource::{DataSource, ResourceHash};
use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::Image;
use graphene_std::subpath::BezierHandles;
use graphene_std::vector::misc::HandleId;
use graphene_std::vector::misc::{BezierHandles, HandleId, point_to_dvec2, segment_to_handles};
use graphene_std::vector::{PointId, SegmentId, VectorModificationType};
use graphite_proc_macros::{ExtractField, message_handler_data};
use kurbo::ParamCurve;
use std::sync::Arc;
const CLIPBOARD_PREFIX: &str = "graphite: ";
@@ -425,7 +425,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
// Create new segment ids and add the segments into the existing Vector path
let mut segments_map = HashMap::new();
for (segment_id, bezier, start, end) in new_vector.segment_bezier_iter() {
for (segment_id, segment, start, end) in new_vector.segment_iter() {
let (Some(&start_point), Some(&end_point)) = (points_map.get(&start), points_map.get(&end)) else {
warn!("Skipping pasted vector segment with an unknown endpoint");
continue;
@@ -434,10 +434,12 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
let new_segment_id = SegmentId::generate();
segments_map.insert(segment_id, new_segment_id);
let handles = match bezier.handles {
let segment_start = point_to_dvec2(segment.start());
let segment_end = point_to_dvec2(segment.end());
let handles = match segment_to_handles(&segment) {
BezierHandles::Linear => [None, None],
BezierHandles::Quadratic { handle } => [Some(handle - bezier.start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - bezier.start), Some(handle_end - bezier.end)],
BezierHandles::Quadratic { handle } => [Some(handle - segment_start), None],
BezierHandles::Cubic { handle_start, handle_end } => [Some(handle_start - segment_start), Some(handle_end - segment_end)],
};
let points = [start_point, end_point];
@@ -1,5 +1,5 @@
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
use crate::messages::prelude::*;
#[impl_message(Message, KeyMappingMessage, Lookup)]
@@ -1,7 +1,7 @@
use super::utility_types::input_keyboard::KeysGroup;
use super::utility_types::keyboard::KeysGroup;
use super::utility_types::misc::Mapping;
use crate::application::Editor;
use crate::messages::input_mapper::utility_types::input_keyboard::{self, Key};
use crate::messages::input_mapper::utility_types::keyboard::{self, Key};
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
use crate::messages::prelude::*;
@@ -58,7 +58,7 @@ impl InputMapperMessageHandler {
.map(|i| {
// TODO: Use a safe solution eventually
assert!(
i < input_keyboard::NUMBER_OF_KEYS,
i < keyboard::NUMBER_OF_KEYS,
"Attempting to convert a Key with enum index {i}, which is larger than the number of Key enums",
);
(i as u8).try_into().unwrap()
@@ -1,11 +1,11 @@
use crate::application::Editor;
use crate::consts::{BIG_NUDGE_AMOUNT, BRUSH_SIZE_CHANGE_KEYBOARD, NUDGE_AMOUNT};
use crate::messages::input_mapper::key_mapping::MappingVariant;
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates};
use crate::messages::input_mapper::utility_types::input_mouse::MouseButton;
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates};
use crate::messages::input_mapper::utility_types::macros::*;
use crate::messages::input_mapper::utility_types::misc::MappingEntry;
use crate::messages::input_mapper::utility_types::misc::{KeyMappingEntries, Mapping};
use crate::messages::input_mapper::utility_types::pointer::MouseButton;
use crate::messages::portfolio::document::node_graph::utility_types::Direction;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::prelude::*;
@@ -1,5 +1,5 @@
use crate::messages::input_mapper::input_mapper_message_handler::InputMapperMessageContext;
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
use crate::messages::prelude::*;
#[derive(ExtractField)]
@@ -162,7 +162,7 @@ macro_rules! action_shortcut {
macro_rules! action_shortcut_manual {
($($keys:expr),*) => {
Some(crate::messages::input_mapper::utility_types::misc::ActionShortcut::Shortcut(
crate::messages::input_mapper::utility_types::input_keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
crate::messages::input_mapper::utility_types::keyboard::LabeledShortcut(vec![$($keys.into()),*]).into(),
))
};
}
@@ -1,7 +1,7 @@
use super::input_keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
use super::keyboard::{KeysGroup, LabeledShortcut, all_required_modifiers_pressed};
use crate::messages::input_mapper::key_mapping::MappingVariant;
use crate::messages::input_mapper::utility_types::input_keyboard::{KeyStates, NUMBER_OF_KEYS};
use crate::messages::input_mapper::utility_types::input_mouse::NUMBER_OF_MOUSE_BUTTONS;
use crate::messages::input_mapper::utility_types::keyboard::{KeyStates, NUMBER_OF_KEYS};
use crate::messages::input_mapper::utility_types::pointer::NUMBER_OF_MOUSE_BUTTONS;
use crate::messages::prelude::*;
use core::time::Duration;
@@ -1,4 +1,5 @@
pub mod input_keyboard;
pub mod input_mouse;
pub mod keyboard;
pub mod pointer;
pub mod macros;
pub mod misc;
@@ -50,15 +50,21 @@ impl ScrollDelta {
}
}
// TODO: Document the difference between this and EditorMouseState
// TODO: Document the difference between this and EditorPointerState
#[derive(Debug, Copy, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MouseState {
pub struct PointerState {
pub position: ViewportPosition,
pub mouse_keys: MouseKeys,
pub scroll_delta: ScrollDelta,
pub time: Option<f64>,
pub pressure: Option<f64>,
pub tilt: Option<DVec2>,
pub twist: Option<f64>,
pub wheel: Option<f64>,
pub eraser: bool,
}
impl MouseState {
impl PointerState {
pub fn finish_transaction(&self, drag_start: DVec2, responses: &mut VecDeque<Message>) {
let drag_too_small = drag_start.distance(self.position) <= DRAG_THRESHOLD;
let response = if drag_too_small { DocumentMessage::AbortTransaction } else { DocumentMessage::EndTransaction };
@@ -66,15 +72,21 @@ impl MouseState {
}
}
// TODO: Document the difference between this and MouseState
// TODO: Document the difference between this and PointerState
#[derive(Debug, Copy, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct EditorMouseState {
pub struct EditorPointerState {
pub editor_position: EditorPosition,
pub mouse_keys: MouseKeys,
pub scroll_delta: ScrollDelta,
pub time: Option<f64>,
pub pressure: Option<f64>,
pub tilt: Option<DVec2>,
pub twist: Option<f64>,
pub wheel: Option<f64>,
pub eraser: bool,
}
impl EditorMouseState {
impl EditorPointerState {
pub fn from_keys_and_editor_position(keys: u8, editor_position: EditorPosition) -> Self {
// TODO: Some graphic tablets send key codes not mentioned in the spec. In the future we would like to support these as well.
let mouse_keys = MouseKeys::from_bits_truncate(keys);
@@ -82,15 +94,21 @@ impl EditorMouseState {
Self {
editor_position,
mouse_keys,
scroll_delta: ScrollDelta::default(),
..Default::default()
}
}
pub fn to_mouse_state(&self, viewport: &ViewportMessageHandler) -> MouseState {
MouseState {
pub fn to_pointer_state(&self, viewport: &ViewportMessageHandler) -> PointerState {
PointerState {
position: (viewport.logical(self.editor_position) - viewport.offset()).into(),
mouse_keys: self.mouse_keys,
scroll_delta: self.scroll_delta,
time: self.time,
pressure: self.pressure,
tilt: self.tilt,
twist: self.twist,
wheel: self.wheel,
eraser: self.eraser,
}
}
}
@@ -1,17 +1,17 @@
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::prelude::*;
#[impl_message(Message, InputPreprocessor)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub enum InputPreprocessorMessage {
DoubleClick { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
DoubleClick { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
KeyDown { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
KeyUp { key: Key, key_repeat: bool, modifier_keys: ModifierKeys },
PointerDown { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerMove { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerUp { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerShake { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
PointerDown { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
PointerMove { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
PointerUp { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
PointerShake { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
CurrentTime { timestamp: u64 },
WheelScroll { editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys },
WheelScroll { editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys },
}
@@ -1,7 +1,7 @@
use crate::application::Editor;
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeyStates, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::{MouseButton, MouseKeys, MouseState};
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeyStates, ModifierKeys};
use crate::messages::input_mapper::utility_types::misc::FrameTimeInfo;
use crate::messages::input_mapper::utility_types::pointer::{MouseButton, MouseKeys, PointerState};
use crate::messages::prelude::*;
use std::time::Duration;
@@ -15,7 +15,8 @@ pub struct InputPreprocessorMessageHandler {
pub frame_time: FrameTimeInfo,
pub time: u64,
pub keyboard: KeyStates,
pub mouse: MouseState,
pub mouse: PointerState,
pointer_down_time: f64,
}
#[message_handler_data]
@@ -27,10 +28,10 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
self.mouse.position = pointer_state.position;
for key in mouse_state.mouse_keys {
for key in pointer_state.mouse_keys {
responses.add(InputMapperMessage::DoubleClick(match key {
MouseKeys::LEFT => MouseButton::Left,
MouseKeys::RIGHT => MouseButton::Right,
@@ -60,35 +61,35 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
self.mouse.position = pointer_state.position;
self.translate_mouse_event(mouse_state, true, responses);
self.translate_mouse_event(pointer_state, true, responses);
}
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
self.mouse.position = pointer_state.position;
responses.add(InputMapperMessage::PointerMove);
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events
self.translate_mouse_event(mouse_state, false, responses);
self.translate_mouse_event(pointer_state, false, responses);
}
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
self.mouse.position = pointer_state.position;
self.translate_mouse_event(mouse_state, false, responses);
self.translate_mouse_event(pointer_state, false, responses);
}
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
self.mouse.position = pointer_state.position;
responses.add(InputMapperMessage::PointerShake);
}
@@ -100,9 +101,9 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys } => {
self.update_states_of_modifier_keys(modifier_keys, responses);
let mouse_state = editor_mouse_state.to_mouse_state(viewport);
self.mouse.position = mouse_state.position;
self.mouse.scroll_delta = mouse_state.scroll_delta;
let pointer_state = editor_mouse_state.to_pointer_state(viewport);
self.mouse.position = pointer_state.position;
self.mouse.scroll_delta = pointer_state.scroll_delta;
responses.add(InputMapperMessage::WheelScroll);
}
@@ -116,7 +117,7 @@ impl<'a> MessageHandler<InputPreprocessorMessage, InputPreprocessorMessageContex
}
impl InputPreprocessorMessageHandler {
fn translate_mouse_event(&mut self, mut new_state: MouseState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
fn translate_mouse_event(&mut self, mut new_state: PointerState, allow_first_button_down: bool, responses: &mut VecDeque<Message>) {
let click_mappings = [
(MouseKeys::LEFT, Key::MouseLeft),
(MouseKeys::RIGHT, Key::MouseRight),
@@ -144,6 +145,13 @@ impl InputPreprocessorMessageHandler {
}
}
let raw_time = new_state.time.unwrap_or(self.time as f64);
if self.mouse.mouse_keys == MouseKeys::empty() {
self.pointer_down_time = raw_time;
}
let interacting = (self.mouse.mouse_keys | new_state.mouse_keys) != MouseKeys::empty();
new_state.time = interacting.then_some(raw_time - self.pointer_down_time);
self.mouse = new_state;
}
@@ -185,18 +193,17 @@ impl InputPreprocessorMessageHandler {
#[cfg(test)]
mod test {
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::prelude::*;
#[test]
fn process_action_mouse_move_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let editor_mouse_state = EditorMouseState {
let editor_mouse_state = EditorPointerState {
editor_position: (4., 809.).into(),
mouse_keys: MouseKeys::default(),
scroll_delta: ScrollDelta::default(),
..Default::default()
};
let modifier_keys = ModifierKeys::ALT;
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
@@ -216,7 +223,7 @@ mod test {
fn process_action_mouse_down_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let editor_mouse_state = EditorMouseState::default();
let editor_mouse_state = EditorPointerState::default();
let modifier_keys = ModifierKeys::CONTROL;
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
@@ -235,7 +242,7 @@ mod test {
fn process_action_mouse_up_handle_modifier_keys() {
let mut input_preprocessor = InputPreprocessorMessageHandler::default();
let editor_mouse_state = EditorMouseState::default();
let editor_mouse_state = EditorPointerState::default();
let modifier_keys = ModifierKeys::SHIFT;
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
@@ -1,4 +1,4 @@
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*;
@@ -2,7 +2,7 @@ use super::widgets::button_widgets::*;
use super::widgets::input_widgets::*;
use super::widgets::label_widgets::*;
use crate::application::generate_uuid;
use crate::messages::input_mapper::utility_types::input_keyboard::KeysGroup;
use crate::messages::input_mapper::utility_types::keyboard::KeysGroup;
use crate::messages::prelude::*;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
@@ -233,6 +233,24 @@ pub struct ColorInput {
pub on_commit: WidgetCallback<()>,
}
/// Shortens a breadcrumb label to fit the trail, replacing the tail with an ellipsis.
/// Quotes delimit a string value, so a quoted label budgets only the text between them.
pub fn truncate_breadcrumb_label(label: &str) -> String {
const MAX_CHARACTERS: usize = 40;
let quoted = label.len() >= 2 && label.starts_with('"') && label.ends_with('"');
let content = if quoted { &label[1..label.len() - 1] } else { label };
if content.chars().count() <= MAX_CHARACTERS {
return label.to_string();
}
let mut truncated: String = content.chars().take(MAX_CHARACTERS - 1).collect();
truncated.push('…');
if quoted { format!("\"{truncated}\"") } else { truncated }
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, serde::Serialize, serde::Deserialize, Derivative, Default, WidgetBuilder)]
#[derivative(Debug, PartialEq)]
@@ -64,6 +64,8 @@ pub struct TextLabel {
pub italic: bool,
pub monospace: bool,
pub multiline: bool,
pub enquote: bool,
pub selectable: bool,
#[serde(rename = "centerAlign")]
pub center_align: bool,
#[serde(rename = "tableAlign")]
@@ -39,6 +39,5 @@ pub enum VectorTableTab {
#[default]
Points,
Segments,
Regions,
Handles,
}
@@ -13,17 +13,18 @@ use graphene_std::color::SRGBA8;
use graphene_std::extract_xy::XY;
use graphene_std::gradient::Gradient;
use graphene_std::list::{Item, List, NodeIdPath};
use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::memo::IORecord;
use graphene_std::raster::{
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, LuminanceCalculation, NoiseType, RedGreenBlue, RedGreenBlueAlpha, RelativeAbsolute, SelectiveColorChoice,
};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::subpath::BezierHandles;
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::StringCapitalization;
use graphene_std::transform::{ReferencePoint, ScaleType};
use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, SpiralType,
ArcType, BezierHandles, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridType, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns,
SpiralType,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
@@ -150,7 +151,8 @@ impl DataPanelMessageHandler {
// Element path breadcrumbs
if !layout_data.breadcrumbs.is_empty() {
let breadcrumb = BreadcrumbTrailButtons::new(layout_data.breadcrumbs)
let labels = layout_data.breadcrumbs.iter().map(|label| truncate_breadcrumb_label(label)).collect();
let breadcrumb = BreadcrumbTrailButtons::new(labels)
.on_update(|&len| DataPanelMessage::TruncateElementPath { len: len as usize }.into())
.widget_instance();
widgets.push(breadcrumb);
@@ -647,7 +649,7 @@ impl TableItemLayout for Vector {
)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Regions, VectorTableTab::Handles]
let table_tab_entries = [VectorTableTab::Points, VectorTableTab::Segments, VectorTableTab::Handles]
.into_iter()
.map(|tab| {
RadioEntryData::new(format!("{tab:?}"))
@@ -694,17 +696,6 @@ impl TableItemLayout for Vector {
]
}));
}
VectorTableTab::Regions => {
table_rows.push(column_headings(&["", "segment_range"]));
table_rows.extend(self.region_domain.iter().map(|(id, segment_range, _)| {
vec![
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
TextLabel::new(format!("Segment {} – Segment {}", segment_range.start().inner(), segment_range.end().inner()))
.narrow(true)
.widget_instance(),
]
}));
}
}
vec![LayoutGroup::row(table_tabs), LayoutGroup::table(table_rows, false)]
@@ -807,18 +798,41 @@ impl TableItemLayout for Gradient {
}
}
macro_rules! impl_table_item_layout_for_number {
($($ty:ty => $type_name:literal),* $(,)?) => {
$(
impl TableItemLayout for $ty {
fn type_name() -> &'static str {
$type_name
}
fn identifier(&self) -> String {
format!("{self}")
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
)*
}
}
impl_table_item_layout_for_number!(
f32 => "Number (f32)",
u32 => "Number (u32)",
i32 => "Number (i32)",
u64 => "Number (u64)",
i64 => "Number (i64)",
);
// Denoised so 0.1 + 0.2 reads as 0.3 rather than 0.30000000000000004. We don't do this for f32 because it lacks precision to reliably distinguish between intentional digits and noise.
impl TableItemLayout for f64 {
fn type_name() -> &'static str {
"Number (f64)"
"Number"
}
fn identifier(&self) -> String {
format!("{self}")
format!("{}", round_away_float_noise(*self))
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
@@ -827,88 +841,10 @@ impl TableItemLayout for u8 {
"Byte"
}
fn identifier(&self) -> String {
format!("{self:02X}")
format!("0x{self:02X} ({self})")
}
// Values fall back to the default drill-in button (labeled with the hex string via `identifier`); the value page shows the same hex value as a label.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![TextLabel::new(self.identifier()).widget_instance()])]
}
}
impl TableItemLayout for f32 {
fn type_name() -> &'static str {
"Number (f32)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for u32 {
fn type_name() -> &'static str {
"Number (u32)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for i32 {
fn type_name() -> &'static str {
"Number (i32)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for i64 {
fn type_name() -> &'static str {
"Number (i64)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
// TODO: Make this robust for large i64 values that don't fit in f64 (beyond roughly 2^53), as with u64.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
}
}
impl TableItemLayout for u64 {
fn type_name() -> &'static str {
"Number (u64)"
}
fn identifier(&self) -> String {
format!("{self}")
}
// Values fall back to the default drill-in button (labeled via `identifier`); the value page shows the rich `NumberInput`.
// TODO: Make this robust for large u64 values that don't fit in f64 (above roughly 2^53). Perhaps using a bigint kind of approach through the widget's data flow.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![
NumberInput::new(Some(*self as f64)).disabled(true).max_width(220).display_decimal_places(20).widget_instance(),
])]
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(self.identifier()).selectable(true).narrow(true).widget_instance()]
}
}
@@ -932,20 +868,50 @@ impl TableItemLayout for String {
"String"
}
fn identifier(&self) -> String {
// Show the first line, and if there are more, indicate that with an ellipsis
let first_line = self.lines().next().unwrap_or("");
if self.lines().count() > 1 {
format!("\"{} …\"", first_line)
} else {
format!("\"{}\"", first_line)
}
format!("\"{}\"", string_preview(self))
}
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
data.breadcrumbs.push(character_count_label(self));
self.value_page(data)
}
// The preview truncates for length and line breaks, so a button beside it reaches the full text, labeled by length
fn value_widgets(&self, target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![
TextLabel::new(string_preview(self)).enquote(true).selectable(true).monospace(true).narrow(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextButton::new(character_count_label(self))
.on_update(move |_| DataPanelMessage::PushToElementPath { step: target.clone() }.into())
.narrow(true)
.widget_instance(),
]
}
// Values fall back to the default drill-in button (labeled with the truncated quoted preview via `identifier`); the value page shows the full multi-line text in a `TextAreaInput`.
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(vec![TextAreaInput::new(self.to_string()).monospace(true).disabled(true).widget_instance()])]
}
}
fn character_count_label(value: &str) -> String {
let character_count = value.chars().count();
format!("{character_count} Char{}", if character_count == 1 { "" } else { "s" })
}
/// Shortens a string to fit a table cell, cutting at the first line break or 40 characters with an ellipsis.
/// The 40 matches `truncate_breadcrumb_label`, so a preview reaching the trail isn't cut twice.
fn string_preview(value: &str) -> String {
const MAX_CHARACTERS: usize = 40;
let first_line = value.lines().next().unwrap_or_default();
let cut_by_line_break = value.contains('\n');
let cut_by_length = first_line.chars().count() > MAX_CHARACTERS;
if !cut_by_line_break && !cut_by_length {
return value.to_string();
}
first_line.chars().take(MAX_CHARACTERS - 1).chain(['…']).collect()
}
impl TableItemLayout for Option<f64> {
fn type_name() -> &'static str {
"Option<f64>"
@@ -954,7 +920,12 @@ impl TableItemLayout for Option<f64> {
"Option<f64>".to_string()
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(format!("{self:?}")).narrow(true).widget_instance()]
let text = match self {
Some(value) => format!("Some({})", round_away_float_noise(*value)),
None => "None".to_string(),
};
vec![TextLabel::new(text).selectable(true).narrow(true).widget_instance()]
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
@@ -999,7 +970,7 @@ impl TableItemLayout for DAffine2 {
"Transform".to_string()
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
vec![TextLabel::new(format_transform_matrix(*self)).narrow(true).widget_instance()]
transform_widgets(*self)
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
@@ -1014,8 +985,7 @@ impl TableItemLayout for Affine2 {
"Transform".to_string()
}
fn value_widgets(&self, _target: PathStep, _data: &LayoutData) -> Vec<WidgetInstance> {
let matrix = DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64));
vec![TextLabel::new(format_transform_matrix(matrix)).narrow(true).widget_instance()]
transform_widgets(DAffine2::from_cols_array(&self.to_cols_array().map(|x| x as f64)))
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
vec![LayoutGroup::row(self.value_widgets(PathStep::Element(0), _data))]
@@ -1396,7 +1366,8 @@ fn drilldown_attribute_layout(any: &dyn Any, data: &mut LayoutData) -> Option<Ve
None
}
fn format_transform_matrix(transform: DAffine2) -> String {
/// Decomposes a transform into location, rotation, and scale, each headed by the icon of its Layer menu action.
fn transform_widgets(transform: DAffine2) -> Vec<WidgetInstance> {
let (scale, angle, translation) = if transform.matrix2.determinant().abs() <= f64::EPSILON {
let [col_0, col_1] = transform.matrix2.to_cols_array_2d().map(|[x, y]| DVec2::new(x, y));
@@ -1414,15 +1385,24 @@ fn format_transform_matrix(transform: DAffine2) -> String {
} else {
transform.to_scale_angle_translation()
};
let rotation = format_rounded(angle.to_degrees(), 3);
format!(
"Location: ({} px, {} px) — Rotation: {rotation}° — Scale: ({}x, {}x)",
format_rounded(translation.x, 3),
format_rounded(translation.y, 3),
format_rounded(scale.x, 3),
format_rounded(scale.y, 3)
)
let location_text = format!("({} px, {} px)", format_rounded(translation.x, 3), format_rounded(translation.y, 3));
let rotation_text = format!("{}°", format_rounded(angle.to_degrees(), 3));
let scale_text = format!("({}x, {}x)", format_rounded(scale.x, 3), format_rounded(scale.y, 3));
vec![
IconLabel::new("TransformationGrab").tooltip_label("Location").widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextLabel::new(location_text).narrow(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
IconLabel::new("TransformationRotate").tooltip_label("Rotation").widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextLabel::new(rotation_text).narrow(true).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
IconLabel::new("TransformationScale").tooltip_label("Scale").widget_instance(),
Separator::new(SeparatorStyle::Related).widget_instance(),
TextLabel::new(scale_text).narrow(true).widget_instance(),
]
}
fn format_dvec2(value: DVec2) -> String {
@@ -2,7 +2,7 @@ use std::path::PathBuf;
use std::sync::Arc;
use super::utility_types::misc::{GroupFolderType, SnappingState};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::portfolio::document::data_panel::DataPanelMessage;
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, OverlaysType};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -41,12 +41,12 @@ use graphene_std::Cover;
use graphene_std::math::quad::Quad;
use graphene_std::path_bool_nodes::boolean_intersect;
use graphene_std::raster::BlendMode;
use graphene_std::subpath::Subpath;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::graphic_types;
use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{PointId, graphic_types};
use kurbo::{Affine, BezPath, Line, PathSeg};
use kurbo::{Affine, BezPath, Line, PathSeg, Shape};
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::Arc;
@@ -299,7 +299,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
graph_operation_message_handler.process_message(message, responses, context);
}
DocumentMessage::Resource(message) => {
let context = ResourceMessageContext { document_id, fonts };
let context = ResourceMessageContext { document_id, fonts, resource_storage };
self.resources.process_message(message, responses, context);
}
DocumentMessage::AlignSelectedLayers { axis, aggregate } => {
@@ -1831,16 +1831,16 @@ impl DocumentMessageHandler {
self.intersect_quad(viewport_quad, viewport).filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
}
/// Runs an intersection test with all layers and a viewport space subpath
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
/// Runs an intersection test with all layers and a viewport space polygon path
pub fn intersect_polygon<'a>(&'a self, mut viewport_polygon: BezPath, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
viewport_polygon.apply_transform(document_to_viewport.inverse());
viewport_polygon.apply_affine(Affine::new(document_to_viewport.inverse().to_cols_array()));
ClickXRayIter::new(&self.network_interface, XRayTarget::Polygon(viewport_polygon))
ClickXRayIter::new(&self.network_interface, XRayTarget::Path(viewport_polygon))
}
/// Runs an intersection test with all layers and a viewport space subpath; ignoring artboards
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: Subpath<PointId>, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
/// Runs an intersection test with all layers and a viewport space polygon path; ignoring artboards
pub fn intersect_polygon_no_artboards<'a>(&'a self, viewport_polygon: BezPath, viewport: &ViewportMessageHandler) -> impl Iterator<Item = LayerNodeIdentifier> + use<'a> {
self.intersect_polygon(viewport_polygon, viewport)
.filter(|layer| !self.network_interface.is_artboard(&layer.to_node(), &[]))
}
@@ -1868,29 +1868,24 @@ impl DocumentMessageHandler {
layer_left >= quad_left && layer_right <= quad_right && layer_top <= quad_top && layer_bottom >= quad_bottom
}
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: Subpath<PointId>) -> bool {
pub fn is_layer_fully_inside_polygon(&self, layer: &LayerNodeIdentifier, viewport: &ViewportMessageHandler, mut viewport_polygon: BezPath) -> bool {
let document_to_viewport = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
viewport_polygon.apply_transform(document_to_viewport.inverse());
viewport_polygon.apply_affine(Affine::new(document_to_viewport.inverse().to_cols_array()));
let layer_click_targets = self.network_interface.document_metadata().click_targets(*layer);
let layer_transform = self.network_interface.document_metadata().transform_to_document(*layer);
layer_click_targets.is_some_and(|targets| {
targets.iter().all(|target| match target.target_type() {
ClickTargetType::Subpath(subpath) => {
let mut subpath = subpath.clone();
subpath.apply_transform(layer_transform);
subpath.is_inside_subpath(&viewport_polygon, None, None)
ClickTargetType::Path(path) => {
let mut path = path.clone();
path.apply_affine(Affine::new(layer_transform.to_cols_array()));
bezpath_is_inside_bezpath(&path, &viewport_polygon, None, None)
}
ClickTargetType::CompoundPath(subpaths) => subpaths.iter().all(|subpath| {
let mut subpath = subpath.clone();
subpath.apply_transform(layer_transform);
subpath.is_inside_subpath(&viewport_polygon, None, None)
}),
ClickTargetType::FreePoint(point) => {
let mut point = *point;
point.apply_transform(layer_transform);
viewport_polygon.contains_point(point.position)
viewport_polygon.contains(dvec2_to_point(point.position))
}
})
})
@@ -3791,7 +3786,6 @@ enum XRayTarget {
Point(DVec2),
Quad(Quad),
Path(BezPath),
Polygon(Subpath<PointId>),
}
/// The result for the [`ClickXRayIter`] on the layer
@@ -3814,13 +3808,7 @@ fn quad_to_kurbo(quad: Quad) -> BezPath {
fn click_targets_to_kurbo<'a>(click_targets: impl Iterator<Item = &'a ClickTarget>, transform: DAffine2) -> BezPath {
let segments = click_targets
.filter_map(|target| {
if let ClickTargetType::Subpath(subpath) = target.target_type() {
Some(subpath.iter())
} else {
None
}
})
.filter_map(|target| if let ClickTargetType::Path(path) = target.target_type() { Some(path.segments()) } else { None })
.flatten()
.map(|bezier| Affine::new(transform.to_cols_array()) * bezier);
BezPath::from_path_segments(segments)
@@ -3891,10 +3879,6 @@ impl<'a> ClickXRayIter<'a> {
}
XRayTarget::Quad(quad) => self.check_layer_area_target(click_targets, clip, layer, quad_to_kurbo(*quad), transform),
XRayTarget::Path(path) => self.check_layer_area_target(click_targets, clip, layer, path.clone(), transform),
XRayTarget::Polygon(polygon) => {
let polygon = BezPath::from_path_segments(polygon.iter_closed());
self.check_layer_area_target(click_targets, clip, layer, polygon, transform)
}
}
}
}
@@ -8,10 +8,9 @@ use graphene_std::Color;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, PointId, VectorModificationType};
use graphene_std::vector::{Gradient, VectorModificationType};
#[impl_message(Message, DocumentMessage, GraphOperation)]
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
@@ -162,12 +161,6 @@ pub enum GraphOperationMessage {
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewVectorLayer {
id: NodeId,
subpaths: Vec<Subpath<PointId>>,
parent: LayerNodeIdentifier,
insert_index: usize,
},
NewTextLayer {
id: NodeId,
text: String,
@@ -363,13 +363,6 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index } => {
let mut modify_inputs = ModifyInputsContext::new(network_interface, responses);
let layer = modify_inputs.create_layer(id);
modify_inputs.insert_vector(subpaths, layer, true, true, true);
network_interface.move_layer_to_stack(layer, parent, insert_index, &[]);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
GraphOperationMessage::NewTextLayer {
id,
text,
@@ -856,13 +849,13 @@ fn import_usvg_node_inner(
/// Helper to apply path data (vector geometry, fill, stroke, transform) to a layer.
fn import_usvg_path(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node, path: &usvg::Path, layer: LayerNodeIdentifier, gradient_info: &SvgGradientInfo) {
let subpaths = convert_usvg_path(path);
let bezpath = convert_usvg_path(path);
// Skip creating a Transform node entirely when the SVG-native transform is identity.
let node_transform = usvg_transform(node.abs_transform());
let has_transform = node_transform != DAffine2::IDENTITY;
modify_inputs.insert_vector(subpaths, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
modify_inputs.insert_vector(bezpath, layer, has_transform, path.fill().is_some(), path.stroke().is_some());
if has_transform && let Some(transform_node_id) = modify_inputs.existing_proto_node_id(graphene_std::transform_nodes::transform::IDENTIFIER, false) {
transform_utils::update_transform(modify_inputs.network_interface, &transform_node_id, node_transform);
@@ -2,9 +2,7 @@ use crate::messages::portfolio::document::utility_types::network_interface::{Inp
use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::subpath::Subpath;
use graphene_std::transform::Transform;
use graphene_std::vector::PointId;
/// Update the inputs of the transform node to match a new transform
pub fn update_transform(network_interface: &mut NodeNetworkInterface, node_id: &NodeId, transform: DAffine2) {
@@ -87,32 +85,6 @@ pub fn get_current_normalized_pivot(inputs: &[NodeInput]) -> DVec2 {
if let Some(&TaggedValue::DVec2(pivot)) = inputs[5].as_value() { pivot } else { DVec2::splat(0.5) }
}
/// Expand a bounds to avoid div zero errors
fn clamp_bounds(bounds_min: DVec2, mut bounds_max: DVec2) -> [DVec2; 2] {
let bounds_size = bounds_max - bounds_min;
if bounds_size.x < 1e-10 {
bounds_max.x = bounds_min.x + 1.;
}
if bounds_size.y < 1e-10 {
bounds_max.y = bounds_min.y + 1.;
}
[bounds_min, bounds_max]
}
/// Returns corners of all subpaths
fn subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
subpaths
.iter()
.filter_map(|subpath| subpath.bounding_box())
.reduce(|b1, b2| [b1[0].min(b2[0]), b1[1].max(b2[1])])
.unwrap_or_default()
}
/// Returns corners of all subpaths (but expanded to avoid division-by-zero errors)
pub fn nonzero_subpath_bounds(subpaths: &[Subpath<PointId>]) -> [DVec2; 2] {
let [bounds_min, bounds_max] = subpath_bounds(subpaths);
clamp_bounds(bounds_min, bounds_max)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -16,11 +16,11 @@ use graph_craft::{ProtoNodeIdentifier, list};
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, GradientRamp, PointId, Vector, VectorModification, VectorModificationType};
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic};
use kurbo::BezPath;
#[derive(PartialEq, Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum TransformIn {
@@ -146,9 +146,9 @@ impl<'a> ModifyInputsContext<'a> {
path_id
}
pub fn insert_vector(&mut self, subpaths: Vec<Subpath<PointId>>, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
pub fn insert_vector(&mut self, bezpath: BezPath, layer: LayerNodeIdentifier, include_transform: bool, include_fill: bool, include_stroke: bool) {
// Build a VectorModification that reproduces the geometry (same format the Pen tool uses)
let vector = Vector::from_subpaths(subpaths, true);
let vector = Vector::from_bezpath(bezpath);
let modification = Box::new(VectorModification::create_from_vector(&vector));
let shape = resolve_network_node_type("Path")
@@ -1,4 +1,4 @@
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::prelude::*;
use glam::DVec2;
@@ -4,8 +4,8 @@ use crate::consts::{
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
};
use crate::messages::frontend::utility_types::MouseCursorIcon;
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
use crate::messages::portfolio::document::utility_types::misc::PTZ;
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
@@ -1,5 +1,5 @@
use super::utility_types::Direction;
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
@@ -2429,7 +2429,7 @@ impl NodeGraphMessageHandler {
if subgraph_path_names_length >= 2 {
widgets.extend([
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
BreadcrumbTrailButtons::new(subgraph_path_names)
BreadcrumbTrailButtons::new(subgraph_path_names.iter().map(|name| truncate_breadcrumb_label(name)).collect())
.on_update(move |index| {
DocumentMessage::ExitNestedNetwork {
steps_back: subgraph_path_names_length - (*index as usize) - 1,
@@ -6,9 +6,9 @@ pub use crate::messages::portfolio::document::utility_types::text_metrics::text_
use crate::messages::tool::common_functionality::shape_editor::{SelectedLayerState, ShapeState};
use crate::messages::tool::tool_messages::tool_prelude::DocumentMessageHandler;
use glam::{DAffine2, DVec2};
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::misc::{BezierHandles, ManipulatorPointId, point_to_dvec2, segment_to_handles};
use graphene_std::vector::{PointId, SegmentId, Vector};
use kurbo::{Affine, ParamCurve, PathSeg};
use std::collections::HashMap;
#[cfg(target_family = "wasm")]
use wasm_bindgen::JsCast;
@@ -59,7 +59,7 @@ pub fn selected_segments_for_layer(vector: &Vector, state: &SelectedLayerState)
.collect::<Vec<_>>();
// Adding segments which are are connected to selected anchors
for (segment_id, _bezier, start, end) in vector.segment_bezier_iter() {
for (segment_id, _, start, end) in vector.segment_iter() {
if selected_anchors.contains(&start) || selected_anchors.contains(&end) {
selected_segments.push(segment_id);
}
@@ -67,23 +67,25 @@ pub fn selected_segments_for_layer(vector: &Vector, state: &SelectedLayerState)
selected_segments
}
fn overlay_bezier_handles(bezier: Bezier, segment_id: SegmentId, transform: DAffine2, is_selected: impl Fn(ManipulatorPointId) -> bool, overlay_context: &mut OverlayContext) {
let bezier = bezier.apply_transformation(|point| transform.transform_point2(point));
fn overlay_bezier_handles(segment: PathSeg, segment_id: SegmentId, transform: DAffine2, is_selected: impl Fn(ManipulatorPointId) -> bool, overlay_context: &mut OverlayContext) {
let segment = Affine::new(transform.to_cols_array()) * segment;
let segment_start = point_to_dvec2(segment.start());
let segment_end = point_to_dvec2(segment.end());
let not_under_anchor = |position: DVec2, anchor: DVec2| position.distance_squared(anchor) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
match bezier.handles {
BezierHandles::Quadratic { handle } if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) => {
overlay_context.line(handle, bezier.start, None, None);
overlay_context.line(handle, bezier.end, None, None);
match segment_to_handles(&segment) {
BezierHandles::Quadratic { handle } if not_under_anchor(handle, segment_start) && not_under_anchor(handle, segment_end) => {
overlay_context.line(handle, segment_start, None, None);
overlay_context.line(handle, segment_end, None, None);
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
BezierHandles::Cubic { handle_start, handle_end } => {
if not_under_anchor(handle_start, bezier.start) {
overlay_context.line(handle_start, bezier.start, None, None);
if not_under_anchor(handle_start, segment_start) {
overlay_context.line(handle_start, segment_start, None, None);
overlay_context.manipulator_handle(handle_start, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
if not_under_anchor(handle_end, bezier.end) {
overlay_context.line(handle_end, bezier.end, None, None);
if not_under_anchor(handle_end, segment_end) {
overlay_context.line(handle_end, segment_end, None, None);
overlay_context.manipulator_handle(handle_end, is_selected(ManipulatorPointId::EndHandle(segment_id)), None);
}
}
@@ -92,7 +94,7 @@ fn overlay_bezier_handles(bezier: Bezier, segment_id: SegmentId, transform: DAff
}
fn overlay_bezier_handle_specific_point(
bezier: Bezier,
segment: PathSeg,
segment_id: SegmentId,
(start, end): (PointId, PointId),
point_to_render: PointId,
@@ -100,24 +102,24 @@ fn overlay_bezier_handle_specific_point(
is_selected: impl Fn(ManipulatorPointId) -> bool,
overlay_context: &mut OverlayContext,
) {
let bezier = bezier.apply_transformation(|point| transform.transform_point2(point));
let segment = Affine::new(transform.to_cols_array()) * segment;
let segment_start = point_to_dvec2(segment.start());
let segment_end = point_to_dvec2(segment.end());
let not_under_anchor = |position: DVec2, anchor: DVec2| position.distance_squared(anchor) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
match bezier.handles {
BezierHandles::Quadratic { handle } => {
if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) {
let end = if start == point_to_render { bezier.start } else { bezier.end };
overlay_context.line(handle, end, None, None);
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
match segment_to_handles(&segment) {
BezierHandles::Quadratic { handle } if not_under_anchor(handle, segment_start) && not_under_anchor(handle, segment_end) => {
let anchor = if start == point_to_render { segment_start } else { segment_end };
overlay_context.line(handle, anchor, None, None);
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
BezierHandles::Cubic { handle_start, handle_end } => {
if not_under_anchor(handle_start, bezier.start) && (point_to_render == start) {
overlay_context.line(handle_start, bezier.start, None, None);
if not_under_anchor(handle_start, segment_start) && (point_to_render == start) {
overlay_context.line(handle_start, segment_start, None, None);
overlay_context.manipulator_handle(handle_start, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
if not_under_anchor(handle_end, bezier.end) && (point_to_render == end) {
overlay_context.line(handle_end, bezier.end, None, None);
if not_under_anchor(handle_end, segment_end) && (point_to_render == end) {
overlay_context.line(handle_end, segment_end, None, None);
overlay_context.manipulator_handle(handle_end, is_selected(ManipulatorPointId::EndHandle(segment_id)), None);
}
}
@@ -152,23 +154,23 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
match draw_handles {
DrawHandles::All => {
vector.segment_bezier_iter().for_each(|(segment_id, bezier, _start, _end)| {
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
vector.segment_iter().for_each(|(segment_id, segment, _start, _end)| {
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context);
});
}
DrawHandles::SelectedAnchors(ref selected_segments) => {
let Some(focused_segments) = selected_segments.get(&layer) else { continue };
vector
.segment_bezier_iter()
.segment_iter()
.filter(|(segment_id, ..)| focused_segments.contains(segment_id))
.for_each(|(segment_id, bezier, _start, _end)| {
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
.for_each(|(segment_id, segment, _start, _end)| {
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context);
});
for (segment_id, bezier, start, end) in vector.segment_bezier_iter() {
for (segment_id, segment, start, end) in vector.segment_iter() {
if let Some((corresponding_anchor, _)) = opposite_handles_data.iter().find(|(_, adj_segment_id)| adj_segment_id == &segment_id) {
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
overlay_bezier_handle_specific_point(segment, segment_id, (start, end), *corresponding_anchor, transform, is_selected, overlay_context);
}
}
}
@@ -176,14 +178,14 @@ pub fn path_overlays(document: &DocumentMessageHandler, draw_handles: DrawHandle
let Some(segment_endpoints) = segment_endpoints_by_layer.get(&layer) else { continue };
vector
.segment_bezier_iter()
.segment_iter()
.filter(|(segment_id, ..)| segment_endpoints.contains_key(segment_id))
.for_each(|(segment_id, bezier, start, end)| {
.for_each(|(segment_id, segment, start, end)| {
if segment_endpoints.get(&segment_id).unwrap().len() == 1 {
let point_to_render = segment_endpoints.get(&segment_id).unwrap()[0];
overlay_bezier_handle_specific_point(bezier, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context);
overlay_bezier_handle_specific_point(segment, segment_id, (start, end), point_to_render, transform, is_selected, overlay_context);
} else {
overlay_bezier_handles(bezier, segment_id, transform, is_selected, overlay_context);
overlay_bezier_handles(segment, segment_id, transform, is_selected, overlay_context);
}
});
}
@@ -15,7 +15,6 @@ use glam::{DAffine2, DVec2};
use graphene_std::ATTR_TRANSFORM;
use graphene_std::list::List;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::{self, Subpath};
use graphene_std::text::{TextAlign, TextContext, TypesettingConfig};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::point_to_dvec2;
@@ -404,14 +403,14 @@ impl OverlayContext {
/// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed.
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.internal().fill_path(subpaths, transform, color);
pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
self.internal().fill_path(bezpath, transform, color);
}
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
/// Used by the fill tool to show the area to be filled.
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.internal().fill_path_pattern(subpaths, transform, color);
pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
self.internal().fill_path_pattern(bezpath, transform, color);
}
pub fn text(&self, text: &str, font_color: &str, background_color: Option<&str>, transform: DAffine2, padding: f64, pivot: [Pivot; 2]) {
@@ -978,49 +977,25 @@ impl OverlayContextInternal {
path.push(bezier.as_path_el());
}
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) -> BezPath {
fn push_path(&mut self, bezpath: &BezPath, transform: DAffine2) -> BezPath {
let mut path = BezPath::new();
for subpath in subpaths {
let subpath = subpath.borrow();
let mut curves = subpath.iter().peekable();
let snap_start = |context: &Self, point: kurbo::Point| {
let snapped = context.snap_to_physical_pixel(transform.transform_point2(point_to_dvec2(point)));
kurbo::Point::new(snapped.x, snapped.y)
};
let snap_center = |context: &Self, point: kurbo::Point| {
let snapped = context.snap_to_physical_pixel_center(transform.transform_point2(point_to_dvec2(point)));
kurbo::Point::new(snapped.x, snapped.y)
};
let Some(first) = curves.peek() else {
continue;
};
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
let start_point = self.snap_to_physical_pixel(start_point);
path.move_to(kurbo::Point::new(start_point.x, start_point.y));
for curve in curves {
match curve {
PathSeg::Line(line) => {
let a = transform.transform_point2(point_to_dvec2(line.p1));
let a = self.snap_to_physical_pixel_center(a);
path.line_to(kurbo::Point::new(a.x, a.y));
}
PathSeg::Quad(quad_bez) => {
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
path.quad_to(kurbo::Point::new(a.x, a.y), kurbo::Point::new(b.x, b.y));
}
PathSeg::Cubic(cubic_bez) => {
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
let c = self.snap_to_physical_pixel_center(c);
path.curve_to(kurbo::Point::new(a.x, a.y), kurbo::Point::new(b.x, b.y), kurbo::Point::new(c.x, c.y));
}
}
}
if subpath.closed() {
path.close_path();
for element in bezpath.elements() {
match *element {
kurbo::PathEl::MoveTo(point) => path.move_to(snap_start(self, point)),
kurbo::PathEl::LineTo(point) => path.line_to(snap_center(self, point)),
kurbo::PathEl::QuadTo(a, b) => path.quad_to(snap_center(self, a), snap_center(self, b)),
kurbo::PathEl::CurveTo(a, b, c) => path.curve_to(snap_center(self, a), snap_center(self, b), snap_center(self, c)),
kurbo::PathEl::ClosePath => path.close_path(),
}
}
@@ -1029,20 +1004,19 @@ impl OverlayContextInternal {
/// Used by the Select tool to outline a path or a free point when selected or hovered.
fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
let mut subpaths: Vec<subpath::Subpath<PointId>> = vec![];
let mut combined = BezPath::new();
for target_type in target_types {
match target_type.borrow() {
ClickTargetType::FreePoint(point) => {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
ClickTargetType::CompoundPath(compound) => subpaths.extend(compound.iter().cloned()),
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
}
}
if !subpaths.is_empty() {
let path = self.push_path(subpaths.iter(), transform);
if !combined.is_empty() {
let path = self.push_path(&combined, transform);
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
self.scene.stroke(&kurbo::Stroke::new(1.), self.get_transform(), Self::parse_color(color), None, &path);
@@ -1051,15 +1025,15 @@ impl OverlayContextInternal {
/// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed.
fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
let path = self.push_path(subpaths, transform);
fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
let path = self.push_path(bezpath, transform);
self.scene.fill(peniko::Fill::NonZero, self.get_transform(), Self::parse_color(color), None, &path);
}
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
/// Used by the fill tool to show the area to be filled.
fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
const PATTERN_WIDTH: u32 = 4;
const PATTERN_HEIGHT: u32 = 4;
@@ -1096,7 +1070,7 @@ impl OverlayContextInternal {
},
};
let path = self.push_path(subpaths, transform);
let path = self.push_path(bezpath, transform);
let brush = peniko::Brush::Image(image);
self.scene.fill(peniko::Fill::NonZero, self.get_transform(), &brush, None, &path);
@@ -13,11 +13,10 @@ use core::borrow::Borrow;
use core::f64::consts::{FRAC_PI_2, PI, TAU};
use glam::{DAffine2, DVec2};
use graphene_std::math::quad::Quad;
use graphene_std::subpath::Subpath;
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::{dvec2_to_point, point_to_dvec2};
use graphene_std::vector::{PointId, SegmentId, Vector};
use kurbo::{self, Affine, CubicBez, ParamCurve, PathSeg};
use kurbo::{self, Affine, BezPath, CubicBez, ParamCurve, PathSeg};
use std::collections::HashMap;
use wasm_bindgen::{JsCast, JsValue};
use web_sys::{OffscreenCanvas, OffscreenCanvasRenderingContext2d};
@@ -931,50 +930,33 @@ impl OverlayContext {
self.end_dpi_aware_transform();
}
fn push_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2) {
fn push_path(&mut self, bezpath: &BezPath, transform: DAffine2) {
self.start_dpi_aware_transform();
self.render_context.begin_path();
for subpath in subpaths {
let subpath = subpath.borrow();
let mut curves = subpath.iter().peekable();
let Some(&first) = curves.peek() else {
continue;
};
let snap_start = |context: &Self, point: kurbo::Point| context.snap_to_physical_pixel(transform.transform_point2(point_to_dvec2(point)));
let snap_center = |context: &Self, point: kurbo::Point| context.snap_to_physical_pixel_center(transform.transform_point2(point_to_dvec2(point)));
let start_point = transform.transform_point2(point_to_dvec2(first.start()));
let start_point = self.snap_to_physical_pixel(start_point);
self.render_context.move_to(start_point.x, start_point.y);
for curve in curves {
match curve {
PathSeg::Line(line) => {
let a = transform.transform_point2(point_to_dvec2(line.p1));
let a = self.snap_to_physical_pixel_center(a);
self.render_context.line_to(a.x, a.y);
}
PathSeg::Quad(quad_bez) => {
let a = transform.transform_point2(point_to_dvec2(quad_bez.p1));
let b = transform.transform_point2(point_to_dvec2(quad_bez.p2));
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
self.render_context.quadratic_curve_to(a.x, a.y, b.x, b.y);
}
PathSeg::Cubic(cubic_bez) => {
let a = transform.transform_point2(point_to_dvec2(cubic_bez.p1));
let b = transform.transform_point2(point_to_dvec2(cubic_bez.p2));
let c = transform.transform_point2(point_to_dvec2(cubic_bez.p3));
let a = self.snap_to_physical_pixel_center(a);
let b = self.snap_to_physical_pixel_center(b);
let c = self.snap_to_physical_pixel_center(c);
self.render_context.bezier_curve_to(a.x, a.y, b.x, b.y, c.x, c.y);
}
for element in bezpath.elements() {
match *element {
kurbo::PathEl::MoveTo(point) => {
let point = snap_start(self, point);
self.render_context.move_to(point.x, point.y);
}
}
if subpath.closed() {
self.render_context.close_path();
kurbo::PathEl::LineTo(point) => {
let point = snap_center(self, point);
self.render_context.line_to(point.x, point.y);
}
kurbo::PathEl::QuadTo(a, b) => {
let (a, b) = (snap_center(self, a), snap_center(self, b));
self.render_context.quadratic_curve_to(a.x, a.y, b.x, b.y);
}
kurbo::PathEl::CurveTo(a, b, c) => {
let (a, b, c) = (snap_center(self, a), snap_center(self, b), snap_center(self, c));
self.render_context.bezier_curve_to(a.x, a.y, b.x, b.y, c.x, c.y);
}
kurbo::PathEl::ClosePath => self.render_context.close_path(),
}
}
@@ -983,18 +965,17 @@ impl OverlayContext {
/// Used by the Select tool to outline a path or a free point when selected or hovered.
pub fn outline(&mut self, target_types: impl Iterator<Item = impl Borrow<ClickTargetType>>, transform: DAffine2, color: Option<&str>) {
let mut subpaths: Vec<Subpath<PointId>> = vec![];
let mut combined = BezPath::new();
target_types.for_each(|target_type| match target_type.borrow() {
ClickTargetType::FreePoint(point) => {
self.manipulator_anchor(transform.transform_point2(point.position), false, None);
}
ClickTargetType::Subpath(subpath) => subpaths.push(subpath.clone()),
ClickTargetType::CompoundPath(compound) => subpaths.extend(compound.iter().cloned()),
ClickTargetType::Path(bezpath) => combined.extend(bezpath.elements().iter().copied()),
});
if !subpaths.is_empty() {
self.push_path(subpaths.iter(), transform);
if !combined.is_empty() {
self.push_path(&combined, transform);
let color = color.unwrap_or(COLOR_OVERLAY_BLUE);
self.render_context.set_stroke_style_str(color);
@@ -1005,8 +986,8 @@ impl OverlayContext {
/// Fills the area inside the path. Assumes `color` is in gamma space.
/// Used by the Pen tool to show the path being closed.
pub fn fill_path(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
self.push_path(subpaths, transform);
pub fn fill_path(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
self.push_path(bezpath, transform);
self.render_context.set_fill_style_str(color);
self.render_context.fill();
@@ -1014,7 +995,7 @@ impl OverlayContext {
/// Fills the area inside the path with a pattern. Assumes `color` is an sRGB hex string.
/// Used by the fill tool to show the area to be filled.
pub fn fill_path_pattern(&mut self, subpaths: impl Iterator<Item = impl Borrow<Subpath<PointId>>>, transform: DAffine2, color: &str) {
pub fn fill_path_pattern(&mut self, bezpath: &BezPath, transform: DAffine2, color: &str) {
const PATTERN_WIDTH: usize = 4;
const PATTERN_HEIGHT: usize = 4;
@@ -1047,7 +1028,7 @@ impl OverlayContext {
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);
self.push_path(bezpath, transform);
self.render_context.set_fill_style_canvas_pattern(&pattern);
self.render_context.fill();
@@ -12,6 +12,7 @@ use url::Url;
pub struct ResourceMessageContext<'a> {
pub document_id: DocumentId,
pub fonts: &'a FontsMessageHandler,
pub resource_storage: &'a ResourceStorageMessageHandler,
}
#[derive(Debug, Clone, PartialEq, Default, serde::Serialize, ExtractField)]
@@ -25,7 +26,7 @@ pub struct ResourceMessageHandler {
#[message_handler_data]
impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMessageHandler {
fn process_message(&mut self, message: ResourceMessage, responses: &mut VecDeque<Message>, context: ResourceMessageContext) {
let ResourceMessageContext { document_id, fonts } = context;
let ResourceMessageContext { document_id, fonts, resource_storage } = context;
match message {
ResourceMessage::StoreEmbedded { resource_id, data } => {
@@ -48,8 +49,16 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
responses.add(ResourceMessage::Resolve { resource_id });
}
ResourceMessage::ResolveAll => {
let unresolved_ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).collect();
for id in unresolved_ids {
// A resource keeps its hash when storage evicts its data, so only a fetchable source can repair it
let refetchable = self
.registry
.resolved()
.filter(|info| info.hash.is_some_and(|hash| !resource_storage.contains(hash)))
.filter(|info| info.sources.iter().any(|source| matches!(source, DataSource::Url(_) | DataSource::Font { .. })))
.map(|info| info.id);
let ids: Vec<ResourceId> = self.registry.unresolved().map(|info| info.id).chain(refetchable).collect();
for id in ids {
if self.pending_resolves.contains(&id) {
continue;
}
@@ -65,7 +74,9 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
log::error!("Resolve for {resource_id}: no registry entry");
return;
};
if info.hash.is_some() {
// This hash names the very data that is missing, so it cannot stand in for fetching that data
let data_missing = info.hash.is_some_and(|hash| !resource_storage.contains(hash));
if info.hash.is_some() && !data_missing {
log::warn!("Resource {resource_id} already resolved");
return;
}
@@ -78,7 +89,7 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
.sources
.iter()
.map(|source| match source {
DataSource::Font { family, style } => {
DataSource::Font { family, style } if !data_missing => {
let font = match style {
Some(style) => Font::new(family.clone(), style.clone()),
None => Font::new_with_default_style(family.clone()),
@@ -214,16 +225,20 @@ impl ResourceMessageHandler {
.resolved()
.filter(|info| info.sources.contains(&DataSource::Embedded))
.filter_map(|info| {
if let Some(hash) = info.hash {
let resource = resources_load_handle.load(*hash);
Some(async move { resource.await.map(|resource| (*hash, resource)) })
} else {
None
}
let (id, hash) = (info.id, *info.hash?);
let resource = resources_load_handle.load(hash);
Some(async move { (id, hash, resource.await) })
})
.collect::<Vec<_>>();
self.embedded = EmbeddedResources::from_iter(futures::future::join_all(embedded).await.into_iter().flatten());
let loaded = futures::future::join_all(embedded).await;
// Saving without these bytes writes a document whose registry claims to carry them
for (id, hash, _) in loaded.iter().filter(|(_, _, resource)| resource.is_none()) {
log::error!("Resource {id} ({hash}) is marked as embedded but its data is missing from storage, so the saved document will not contain it");
}
self.embedded = EmbeddedResources::from_iter(loaded.into_iter().filter_map(|(_, hash, resource)| resource.map(|resource| (hash, resource))));
}
pub fn collect_garbage(&mut self, used: &[ResourceId]) {
@@ -297,3 +312,65 @@ impl<'de> serde::Deserialize<'de> for ResourceMessageHandler {
deserializer.deserialize_map(EmbeddedResourcesVisitor { human_readable })
}
}
#[cfg(test)]
mod tests {
use super::*;
use graph_craft::application_io::resource::ResourceStorage;
/// Storage can lose a resource's data while the document keeps the hash naming it, which leaves the graph
/// pointing at bytes that are gone. Only sources that can be fetched again are worth re-resolving.
#[test]
fn resolve_all_refetches_resources_whose_data_is_missing() {
let mut handler = ResourceMessageHandler::default();
let storage = ResourceStorageMessageHandler::default();
// Present: its bytes are in storage, so it is already usable
let present = ResourceId::new();
let present_hash = storage.resources_mut().store(b"stored font bytes");
handler.registry.resolve(&present, present_hash);
handler.registry.push_source_back(&present, DataSource::Embedded);
handler.registry.push_source_back(
&present,
DataSource::Font {
family: "Lato".into(),
style: Some("Regular (400)".into()),
},
);
// Recoverable: its bytes are gone, but the font it came from can be downloaded again
let recoverable = ResourceId::new();
handler.registry.resolve(&recoverable, ResourceHash::from(b"evicted font bytes".as_slice()));
handler.registry.push_source_back(&recoverable, DataSource::Embedded);
handler.registry.push_source_back(
&recoverable,
DataSource::Font {
family: "Lato".into(),
style: Some("Black (900)".into()),
},
);
// Unrecoverable: its bytes are gone and nothing records where to fetch them from
let unrecoverable = ResourceId::new();
handler.registry.resolve(&unrecoverable, ResourceHash::from(b"evicted image bytes".as_slice()));
handler.registry.push_source_back(&unrecoverable, DataSource::Embedded);
let mut responses = VecDeque::new();
let fonts = FontsMessageHandler::default();
handler.process_message(
ResourceMessage::ResolveAll,
&mut responses,
ResourceMessageContext {
document_id: DocumentId(0),
fonts: &fonts,
resource_storage: &storage,
},
);
let resolve_requested = |id: ResourceId| responses.contains(&Message::from(ResourceMessage::Resolve { resource_id: id }));
assert!(resolve_requested(recoverable), "a missing resource with a font source should be fetched again");
assert!(!resolve_requested(present), "a resource whose data is in storage should be left alone");
assert!(!resolve_requested(unrecoverable), "a missing resource with no fetchable source has nowhere to fetch from");
}
}
@@ -8,10 +8,10 @@ use glam::{DAffine2, DVec2};
use graph_craft::document::NodeId;
use graphene_std::Appearance;
use graphene_std::math::quad::Quad;
use graphene_std::subpath;
use graphene_std::transform::Footprint;
use graphene_std::vector::Vector;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType};
use graphene_std::vector::{PointId, Vector};
use kurbo::{Affine, BezPath};
use std::collections::{HashMap, HashSet};
use std::num::NonZeroU64;
use std::sync::Arc;
@@ -188,11 +188,13 @@ impl DocumentMetadata {
self.visual_targets(layer)?
.iter()
.filter_map(|click_target| match click_target.target_type() {
ClickTargetType::Subpath(subpath) => subpath.loose_bounding_box_with_transform(transform),
ClickTargetType::CompoundPath(subpaths) => subpaths
.iter()
.filter_map(|subpath| subpath.loose_bounding_box_with_transform(transform))
.reduce(|[a_min, a_max], [b_min, b_max]| [a_min.min(b_min), a_max.max(b_max)]),
ClickTargetType::Path(path) => {
let mut transformed = path.clone();
transformed.apply_affine(Affine::new(transform.to_cols_array()));
let control_box = transformed.control_box();
(!transformed.is_empty()).then(|| [DVec2::new(control_box.min_x(), control_box.min_y()), DVec2::new(control_box.max_x(), control_box.max_y())])
}
ClickTargetType::FreePoint(_) => click_target.bounding_box_with_transform(transform),
})
.reduce(Quad::combine_bounds)
@@ -251,11 +253,10 @@ impl DocumentMetadata {
self.all_layers().filter_map(|layer| self.bounding_box_viewport(layer)).reduce(Quad::combine_bounds)
}
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &subpath::Subpath<PointId>> {
self.visual_targets(layer).unwrap_or(&[]).iter().flat_map(|target| match target.target_type() {
ClickTargetType::Subpath(subpath) => std::slice::from_ref(subpath),
ClickTargetType::CompoundPath(subpaths) => subpaths.as_slice(),
ClickTargetType::FreePoint(_) => &[],
pub fn layer_outline(&self, layer: LayerNodeIdentifier) -> impl Iterator<Item = &BezPath> {
self.visual_targets(layer).unwrap_or(&[]).iter().filter_map(|target| match target.target_type() {
ClickTargetType::Path(path) => Some(path),
ClickTargetType::FreePoint(_) => None,
})
}
@@ -2,9 +2,6 @@ mod caches;
#[cfg(test)]
mod characterization_tests;
mod deserialization;
pub mod editor_delta;
#[cfg(test)]
mod editor_delta_tests;
mod hit_tests;
mod layout;
mod memo_network;
@@ -46,10 +43,9 @@ use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, No
use graphene_std::Appearance;
use graphene_std::ContextDependencies;
use graphene_std::math::quad::Quad;
use graphene_std::subpath::Subpath;
use graphene_std::transform::Footprint;
use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint};
use graphene_std::vector::{PointId, Vector, VectorModificationType};
use graphene_std::vector::{Vector, VectorModificationType};
use kurbo::BezPath;
use memo_network::MemoNetwork;
use serde_json::{Value, json};
@@ -397,12 +397,12 @@ impl NodeNetworkInterface {
if *import_index == 0 {
let remove_import_center = reorder_import_center + DVec2::new(-4., 0.);
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
} else {
let remove_import_center = reorder_import_center + DVec2::new(-12., 0.);
let reorder_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
let reorder_import = ClickTarget::new_with_path(rectangle_path(reorder_import_center - DVec2::new(3., 4.), reorder_import_center + DVec2::new(3., 4.)), 0.);
let remove_import = ClickTarget::new_with_path(rectangle_path(remove_import_center - DVec2::new(8., 8.), remove_import_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_output_port(*import_index, reorder_import);
remove_imports_exports.insert_custom_output_port(*import_index, remove_import);
}
@@ -417,12 +417,12 @@ impl NodeNetworkInterface {
if *export_index == 0 {
let remove_export_center = reorder_export_center + DVec2::new(4., 0.);
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
} else {
let remove_export_center = reorder_export_center + DVec2::new(12., 0.);
let reorder_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_subpath(Subpath::new_rectangle(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
let reorder_export = ClickTarget::new_with_path(rectangle_path(reorder_export_center - DVec2::new(3., 4.), reorder_export_center + DVec2::new(3., 4.)), 0.);
let remove_export = ClickTarget::new_with_path(rectangle_path(remove_export_center - DVec2::new(8., 8.), remove_export_center + DVec2::new(8., 8.)), 0.);
reorder_imports_exports.insert_custom_input_port(*export_index, reorder_export);
remove_imports_exports.insert_custom_input_port(*export_index, remove_export);
}
@@ -1001,8 +1001,8 @@ impl NodeNetworkInterface {
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let subpath = Subpath::new_rounded_rectangle(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
@@ -1032,22 +1032,22 @@ impl NodeNetworkInterface {
// Update visibility button click target
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let subpath = Subpath::new_rounded_rectangle(
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_subpath(subpath, 0.);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let subpath = Subpath::new_rounded_rectangle(
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_subpath(subpath, 0.))
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
@@ -1057,12 +1057,12 @@ impl NodeNetworkInterface {
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let subpath = Subpath::new_rounded_rectangle(
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_subpath(subpath, 0.);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// Update display-name text click target, used to detect double-click rename. Sized to the text bounds
// (not the surrounding `.details` area) so the rest of the layer still drills into the subgraph on double-click.
@@ -1091,8 +1091,8 @@ impl NodeNetworkInterface {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let subpath = Subpath::new_rounded_rectangle(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_subpath(subpath, 0.))
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
@@ -1104,8 +1104,8 @@ impl NodeNetworkInterface {
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let subpath = Subpath::new_rounded_rectangle(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_subpath(subpath, 0.);
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
@@ -1,452 +0,0 @@
use super::{DocumentNodeMetadata, DocumentNodePersistentMetadata, LayerPosition, NodePosition, NodeTypePersistentMetadata};
use document_graph_storage::attr::node as node_attr;
use document_graph_storage::from_runtime::{ConversionError, DeclarationBytes};
use document_graph_storage::{AttributeDelta, Attributes, Implementation, NoMetadata, PathResolver, Position, Registry, RegistryDelta, ScopedConversion, TimeStamp};
use document_graph_storage::{convert_resource_entry, encode_input_ui_attributes, encode_node_ui_attributes, node_value_resource_refs, value_resource_ref};
use graph_craft::application_io::resource::{ResourceId, ResourceRegistry};
use graph_craft::document::NodeId;
use graph_craft::runtime_delta::RuntimeDelta;
use std::collections::HashSet;
/// A [`RuntimeDelta`] extended with the editor-only change kind: a wholesale copy of a node's
/// persistent metadata, which storage diffs against the working registry so minimal attribute ops
/// fall out. The compiler consumes only the `Graph` variant.
#[derive(Debug, Clone, PartialEq)]
pub enum EditorDelta {
Graph(RuntimeDelta),
/// The copy includes the metadata of everything nested under the node, so one delta covers a
/// group and its contents.
NodeMetadata {
network_path: Vec<NodeId>,
node_id: NodeId,
metadata: Box<DocumentNodePersistentMetadata>,
},
}
pub struct ConstructedOps {
pub ops: Vec<RegistryDelta>,
pub declaration_bytes: DeclarationBytes,
}
/// Constructs the storage ops for one gesture's deltas, in delta order. Removal closures and
/// resource liveness are computed against the whole batch, since several removals in one gesture
/// can jointly orphan a resource that each alone would not. Op timestamps are placeholders,
/// re-stamped by the staging clock.
pub fn construct_batch(deltas: &[EditorDelta], working: &Registry, resources: &ResourceRegistry, peer: document_graph_storage::PeerId) -> Result<ConstructedOps, ConversionError> {
let resolver = PathResolver::new(peer);
let mut ops = Vec::new();
let mut declaration_bytes = DeclarationBytes::new();
let mut batch_removed_nodes = Vec::new();
let mut batch_removed_networks = Vec::new();
let mut batch_added_resources = HashSet::new();
for delta in deltas {
if let EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id } | RuntimeDelta::ReplaceNode { network_path, node_id, .. }) = delta {
collect_removal_closure(resolver.node_id(network_path, *node_id), working, &mut batch_removed_nodes, &mut batch_removed_networks);
}
}
batch_removed_nodes.sort();
batch_removed_nodes.dedup();
batch_removed_networks.sort();
batch_removed_networks.dedup();
for delta in deltas {
delta.construct(working, resources, peer, &resolver, &batch_removed_nodes, &mut batch_added_resources, &mut ops, &mut declaration_bytes)?;
}
construct_resource_removals(&batch_removed_nodes, working, &mut ops);
Ok(ConstructedOps { ops, declaration_bytes })
}
impl EditorDelta {
#[allow(clippy::too_many_arguments)]
fn construct(
&self,
working: &Registry,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
resolver: &PathResolver,
batch_removed_nodes: &[document_graph_storage::NodeId],
batch_added_resources: &mut HashSet<ResourceId>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
match self {
EditorDelta::Graph(RuntimeDelta::AddNode { network_path, node_id, node }) => {
construct_structural_additions(network_path, *node_id, node, working, resources, peer, batch_added_resources, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::ReplaceNode { network_path, node_id, node }) => {
construct_removals(resolver.node_id(network_path, *node_id), working, ops);
construct_structural_additions(network_path, *node_id, node, working, resources, peer, batch_added_resources, ops, declaration_bytes)?;
}
EditorDelta::Graph(RuntimeDelta::RemoveNode { network_path, node_id }) => {
construct_removals(resolver.node_id(network_path, *node_id), working, ops);
}
EditorDelta::Graph(RuntimeDelta::SetVisibility { network_path, node_id, visible }) => {
ops.push(RegistryDelta::ChangeNodeAttribute {
id: resolver.node_id(network_path, *node_id),
delta: AttributeDelta {
key: node_attr::VISIBLE.to_string(),
value: (!visible).then_some(serde_json::Value::Bool(false)),
},
});
}
EditorDelta::Graph(RuntimeDelta::SetInput {
network_path,
node_id,
input_index,
input,
}) => {
ops.push(RegistryDelta::ChangeNodeInput {
id: resolver.node_id(network_path, *node_id),
index: (*input_index).try_into().map_err(|_| ConversionError::IndexOverflow(*input_index))?,
new_input: resolver.convert_input_at(input, network_path)?,
});
}
EditorDelta::Graph(RuntimeDelta::SetExport { network_path, export_index, input }) => {
ops.push(RegistryDelta::SetNetworkExport {
id: resolver.network_id(network_path),
index: (*export_index).try_into().map_err(|_| ConversionError::IndexOverflow(*export_index))?,
export: Some(resolver.convert_input_at(input, network_path)?),
});
}
EditorDelta::NodeMetadata { network_path, node_id, metadata } => {
construct_metadata_changes(network_path, *node_id, metadata, working, resolver, ops)?;
}
}
let _ = batch_removed_nodes;
Ok(())
}
}
/// Converts through the same encoders as a whole-document conversion, with `NoMetadata` as the
/// source: ui attributes arrive via the gesture's paired `NodeMetadata` delta.
#[allow(clippy::too_many_arguments)]
fn construct_structural_additions(
network_path: &[NodeId],
node_id: NodeId,
node: &graph_craft::document::DocumentNode,
working: &Registry,
resources: &ResourceRegistry,
peer: document_graph_storage::PeerId,
batch_added_resources: &mut HashSet<ResourceId>,
ops: &mut Vec<RegistryDelta>,
declaration_bytes: &mut DeclarationBytes,
) -> Result<(), ConversionError> {
let mut scoped = ScopedConversion::new(&NoMetadata, peer);
let mut scratch = Registry::default();
scoped.convert_node_at(&mut scratch, network_path, node_id, node, true)?;
declaration_bytes.extend(scoped.finish());
let mut networks: Vec<_> = scratch.networks.iter().collect();
networks.sort_by_key(|(id, _)| **id);
for (id, network) in networks {
ops.push(RegistryDelta::AddNetwork { id: *id, network: network.clone() });
}
let mut nodes: Vec<_> = scratch.node_instances.iter().collect();
nodes.sort_by_key(|(id, _)| **id);
for (id, node) in nodes {
ops.push(RegistryDelta::AddNode { id: *id, node: node.clone() });
}
let mut new_resources: Vec<_> = scratch.resources.iter().filter(|(id, _)| !working.resources.contains_key(id)).collect();
new_resources.sort_by_key(|(id, _)| **id);
for (id, entry) in new_resources {
if batch_added_resources.insert(*id) {
ops.push(RegistryDelta::AddResource { id: *id, entry: entry.clone() });
}
}
let mut tagged: Vec<ResourceId> = scratch.node_instances.values().flat_map(node_value_resource_refs).collect();
tagged.sort();
tagged.dedup();
for id in tagged {
if !working.resources.contains_key(&id)
&& !scratch.resources.contains_key(&id)
&& !batch_added_resources.contains(&id)
&& let Some(entry) = convert_resource_entry(resources, id, peer)?
{
batch_added_resources.insert(id);
ops.push(RegistryDelta::AddResource { id, entry });
}
}
Ok(())
}
fn construct_metadata_changes(
network_path: &[NodeId],
node_id: NodeId,
metadata: &DocumentNodePersistentMetadata,
working: &Registry,
resolver: &PathResolver,
ops: &mut Vec<RegistryDelta>,
) -> Result<(), ConversionError> {
let source = MetadataCopySource {
anchor_path: network_path,
anchor_id: node_id,
metadata,
};
let mut pending = vec![(network_path.to_vec(), node_id, metadata)];
while let Some((path, id, node_metadata)) = pending.pop() {
let global_id = resolver.node_id(&path, id);
let working_node = working.node_instances.get(&global_id);
let mut encoded = Attributes::new();
encode_node_ui_attributes(&mut encoded, &source, &path, id, TimeStamp::ORIGIN)?;
for delta in ui_attribute_deltas(working_node.map(|node| node.attributes()), &encoded) {
ops.push(RegistryDelta::ChangeNodeAttribute { id: global_id, delta });
}
for input_index in 0..node_metadata.input_metadata.len() {
let mut encoded = Attributes::new();
encode_input_ui_attributes(&mut encoded, &source, &path, id, input_index, TimeStamp::ORIGIN)?;
let current = working_node.and_then(|node| node.inputs().get(input_index)).map(|slot| &slot.attributes);
for delta in ui_attribute_deltas(current, &encoded) {
ops.push(RegistryDelta::ChangeNodeInputAttribute {
id: global_id,
index: input_index.try_into().map_err(|_| ConversionError::IndexOverflow(input_index))?,
delta,
});
}
}
if let Some(network_metadata) = &node_metadata.network_metadata {
let mut nested_path = path.clone();
nested_path.push(id);
let network_id = resolver.network_id(&nested_path);
let target = network_metadata.persistent_metadata.reference.clone().map(serde_json::Value::String);
let current = working
.networks
.get(&network_id)
.and_then(|network| network.attributes.get(node_attr::ui::REFERENCE))
.map(|value| value.value.clone());
if current != target {
ops.push(RegistryDelta::ChangeNetworkAttribute {
id: network_id,
delta: AttributeDelta {
key: node_attr::ui::REFERENCE.to_string(),
value: target,
},
});
}
for (child_id, child) in &network_metadata.persistent_metadata.node_metadata {
pending.push((nested_path.clone(), *child_id, &child.persistent_metadata));
}
}
}
Ok(())
}
/// Minimal ops transforming the `ui::`-prefixed subset of `current` into `encoded`, comparing
/// values only, since timestamps are re-stamped at staging.
fn ui_attribute_deltas(current: Option<&Attributes>, encoded: &Attributes) -> Vec<AttributeDelta> {
let owned = |key: &str| key.starts_with("ui::");
let mut deltas = Vec::new();
if let Some(current) = current {
for key in current.keys() {
if owned(key) && !encoded.contains_key(key) {
deltas.push(AttributeDelta { key: key.clone(), value: None });
}
}
}
for (key, value) in encoded {
let unchanged = current.and_then(|current| current.get(key)).is_some_and(|existing| existing.value == value.value);
if !unchanged {
deltas.push(AttributeDelta {
key: key.clone(),
value: Some(value.value.clone()),
});
}
}
deltas.sort_by(|a, b| a.key.cmp(&b.key));
deltas
}
fn construct_removals(node_id: document_graph_storage::NodeId, working: &Registry, ops: &mut Vec<RegistryDelta>) {
let mut removed_nodes = Vec::new();
let mut removed_networks = Vec::new();
collect_removal_closure(node_id, working, &mut removed_nodes, &mut removed_networks);
removed_nodes.sort();
removed_networks.sort();
for id in &removed_nodes {
ops.push(RegistryDelta::RemoveNode {
id: *id,
snapshot: working.node_instances[id].clone(),
});
}
for id in &removed_networks {
ops.push(RegistryDelta::RemoveNetwork {
id: *id,
snapshot: working.networks[id].clone(),
});
}
}
/// Emits removals for resources referenced only by the batch's removed nodes, checked after every
/// removal is known.
fn construct_resource_removals(batch_removed_nodes: &[document_graph_storage::NodeId], working: &Registry, ops: &mut Vec<RegistryDelta>) {
let removed_node_set: HashSet<_> = batch_removed_nodes.iter().copied().collect();
let mut candidates: Vec<ResourceId> = batch_removed_nodes
.iter()
.flat_map(|id| {
let node = &working.node_instances[id];
let declaration = match node.implementation() {
Implementation::ProtoNode(declaration) => Some(*declaration),
Implementation::Network(_) => None,
};
declaration.into_iter().chain(node_value_resource_refs(node))
})
.collect();
candidates.sort();
candidates.dedup();
for candidate in candidates {
let still_referenced = working
.node_instances
.iter()
.filter(|(id, _)| !removed_node_set.contains(id))
.any(|(_, node)| matches!(node.implementation(), Implementation::ProtoNode(declaration) if *declaration == candidate) || node_value_resource_refs(node).any(|id| id == candidate))
|| working
.networks
.values()
.any(|network| network.exports.iter().any(|slot| slot.target.as_ref().and_then(value_resource_ref) == Some(candidate)));
if !still_referenced && let Some(entry) = working.resources.get(&candidate) {
ops.push(RegistryDelta::RemoveResource {
id: candidate,
snapshot: entry.clone(),
});
}
}
}
fn collect_removal_closure(node_id: document_graph_storage::NodeId, working: &Registry, nodes: &mut Vec<document_graph_storage::NodeId>, networks: &mut Vec<document_graph_storage::NetworkId>) {
let Some(node) = working.node_instances.get(&node_id) else { return };
nodes.push(node_id);
if let &Implementation::Network(network_id) = node.implementation() {
networks.push(network_id);
for (child_id, child) in &working.node_instances {
if child.network() == network_id {
collect_removal_closure(*child_id, working, nodes, networks);
}
}
}
}
/// Serves a metadata copy as the [`document_graph_storage::NodeMetadataSource`] for its own
/// encoding, resolving requested paths relative to the anchor node the copy was taken from.
struct MetadataCopySource<'a> {
anchor_path: &'a [NodeId],
anchor_id: NodeId,
metadata: &'a DocumentNodePersistentMetadata,
}
impl MetadataCopySource<'_> {
fn metadata_for(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
let relative = metadata_path.strip_prefix(self.anchor_path)?;
let (mut current, rest) = match relative.split_first() {
None => return (node_id == self.anchor_id).then_some(self.metadata),
Some((first, rest)) if *first == self.anchor_id => (self.metadata, rest),
Some(_) => return None,
};
for step in rest {
current = child_metadata(current, *step)?;
}
child_metadata(current, node_id)
}
}
fn child_metadata(metadata: &DocumentNodePersistentMetadata, child_id: NodeId) -> Option<&DocumentNodePersistentMetadata> {
metadata
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.node_metadata.get(&child_id))
.map(|child: &DocumentNodeMetadata| &child.persistent_metadata)
}
impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
fn position(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<Position> {
match &self.metadata_for(metadata_path, node_id)?.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
LayerPosition::Stack(offset) => Position::Stack(offset),
}),
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
NodePosition::Chain => Position::Chain,
}),
}
}
fn is_layer(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id)
.is_some_and(|metadata| matches!(metadata.node_type_metadata, NodeTypePersistentMetadata::Layer(_)))
}
fn display_name(&self, metadata_path: &[NodeId], node_id: NodeId) -> Option<&str> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.display_name.as_str())
}
fn locked(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.locked)
}
fn pinned(&self, metadata_path: &[NodeId], node_id: NodeId) -> bool {
self.metadata_for(metadata_path, node_id).is_some_and(|metadata| metadata.pinned)
}
fn output_names(&self, metadata_path: &[NodeId], node_id: NodeId) -> Vec<String> {
self.metadata_for(metadata_path, node_id).map(|metadata| metadata.output_names.clone()).unwrap_or_default()
}
fn input_name(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_name.as_str())
}
fn input_description(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_description.as_str())
}
fn widget_override(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> Option<&str> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.and_then(|input| input.persistent_metadata.widget_override.as_deref())
}
fn input_data(&self, metadata_path: &[NodeId], node_id: NodeId, input_index: usize) -> std::collections::HashMap<String, serde_json::Value> {
self.metadata_for(metadata_path, node_id)
.and_then(|metadata| metadata.input_metadata.get(input_index))
.map(|input| input.persistent_metadata.input_data.clone())
.unwrap_or_default()
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let (owner_path, owner_id) = network_path.split_last().map(|(last, rest)| (rest, *last))?;
self.metadata_for(owner_path, owner_id)?
.network_metadata
.as_ref()
.and_then(|network| network.persistent_metadata.reference.as_deref())
}
}
@@ -1,241 +0,0 @@
use super::InputConnector;
use super::editor_delta::{EditorDelta, construct_batch};
use super::storage_metadata::StorageMetadataView;
use crate::test_utils::test_prelude::*;
use document_graph_storage::delta::compute_deltas;
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graph_craft::runtime_delta::RuntimeDelta;
use graphene_std::uuid::NodeId;
const PEER: PeerId = PeerId(7);
fn rectangle_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
fn convert(editor: &EditorTestUtils) -> Registry {
let document = editor.active_document();
Registry::convert_from_runtime(
document.network_interface.document_network(),
&StorageMetadataView::new(&document.network_interface),
&document.resources.registry,
PEER,
)
.expect("conversion should succeed")
.registry
}
fn construct(editor: &EditorTestUtils, deltas: &[EditorDelta], working: &Registry) -> Vec<RegistryDelta> {
construct_batch(deltas, working, &editor.active_document().resources.registry, PEER)
.expect("construction should succeed")
.ops
}
fn node_metadata_delta(editor: &EditorTestUtils, node_id: NodeId) -> EditorDelta {
let metadata = editor
.active_document()
.network_interface
.node_metadata(&node_id, &[])
.expect("node metadata should exist")
.persistent_metadata
.clone();
EditorDelta::NodeMetadata {
network_path: Vec::new(),
node_id,
metadata: Box::new(metadata),
}
}
fn assert_same_stored_effect(working: &Registry, constructed: Vec<RegistryDelta>, diffed: Vec<RegistryDelta>, at: &str) {
let baseline = compute_deltas(&Registry::default(), working);
let mut from_construction = Session::with_peer(PEER);
from_construction.stage_computed_ops(baseline.clone()).expect("baseline should stage");
from_construction.stage_computed_ops(constructed).expect("constructed ops should stage");
let mut from_diff = Session::with_peer(PEER);
from_diff.stage_computed_ops(baseline).expect("baseline should stage");
from_diff.stage_computed_ops(diffed).expect("diffed ops should stage");
assert!(
from_construction.registry().value_equal(from_diff.registry()),
"Constructed ops must produce the same stored state as the whole-document diff: {at}\nresidual: {:#?}",
compute_deltas(from_construction.registry(), from_diff.registry())
);
}
#[tokio::test]
async fn set_input_value_constructs_the_exact_diff_op() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let input = NodeInput::value(TaggedValue::F64(42.), false);
editor.active_document_mut().network_interface.set_input(&InputConnector::node(node, 1), input.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: node,
input_index: 1,
input,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A value edit should construct exactly the diff's op");
}
#[tokio::test]
async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let a = editor.create_node_by_name(rectangle_definition()).await;
let b = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
let wire = NodeInput::node(b, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::node(a, 1), wire.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: a,
input_index: 1,
input: wire,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "A wiring edit should construct exactly the diff's op");
let working = convert(&editor);
let export = NodeInput::node(a, 0);
editor.active_document_mut().network_interface.set_input(&InputConnector::Export(0), export.clone(), &[]);
let delta = EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: 0,
input: export,
});
let constructed = construct(&editor, std::slice::from_ref(&delta), &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "An export edit should construct exactly the diff's op");
}
#[tokio::test]
async fn adding_a_node_as_structure_plus_metadata_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let working = convert(&editor);
let template = crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type(&rectangle_definition())
.expect("rectangle definition")
.default_node_template();
let node_id = NodeId(0xDE17A);
let (document_node, metadata) = template.clone().into_parts();
editor.active_document_mut().network_interface.insert_node(node_id, template, &[]);
let deltas = [
EditorDelta::Graph(RuntimeDelta::AddNode {
network_path: Vec::new(),
node_id,
node: Box::new(document_node),
}),
EditorDelta::NodeMetadata {
network_path: Vec::new(),
node_id,
metadata: Box::new(metadata),
},
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "node addition");
}
#[tokio::test]
async fn metadata_edits_construct_the_exact_diff_ops() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let working = convert(&editor);
{
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.set_display_name(&node, "Renamed".to_string(), &[]);
network_interface.set_visibility(&node, &[], false);
network_interface.set_locked(&node, &[], true);
network_interface.set_pinned(&node, &[], true);
network_interface.shift_node(&node, glam::IVec2::new(3, 5), &[]);
}
let deltas = [
node_metadata_delta(&editor, node),
EditorDelta::Graph(RuntimeDelta::SetVisibility {
network_path: Vec::new(),
node_id: node,
visible: false,
}),
];
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_eq!(constructed, diffed, "Metadata edits should construct exactly the diff's attribute ops");
}
#[tokio::test]
async fn removing_a_nested_network_node_matches_the_diff() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 100., 100.).await;
editor
.handle_message(DocumentMessage::GroupSelectedLayers {
group_folder_type: crate::messages::portfolio::document::utility_types::misc::GroupFolderType::Layer,
})
.await;
let before: Vec<NodeId> = editor.active_document().network_interface.document_network().nodes.keys().copied().collect();
let working = convert(&editor);
let group = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(node.implementation, graph_craft::document::DocumentNodeImplementation::Network(_)))
.map(|(id, _)| *id)
.expect("the group should be a network node");
editor.active_document_mut().network_interface.delete_nodes(vec![group], true, &[]);
let network = editor.active_document().network_interface.document_network().clone();
let mut deltas: Vec<EditorDelta> = before
.iter()
.filter(|id| !network.nodes.contains_key(id))
.map(|id| {
EditorDelta::Graph(RuntimeDelta::RemoveNode {
network_path: Vec::new(),
node_id: *id,
})
})
.collect();
for (index, export) in network.exports.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetExport {
network_path: Vec::new(),
export_index: index,
input: export.clone(),
}));
}
for (node_id, node) in &network.nodes {
for (index, input) in node.inputs.iter().enumerate() {
deltas.push(EditorDelta::Graph(RuntimeDelta::SetInput {
network_path: Vec::new(),
node_id: *node_id,
input_index: index,
input: input.clone(),
}));
}
}
let constructed = construct(&editor, &deltas, &working);
let diffed = compute_deltas(&working, &convert(&editor));
assert_same_stored_effect(&working, constructed, diffed, "nested network removal");
}
@@ -33,8 +33,8 @@ impl NodeNetworkInterface {
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
self.with_import_export_ports(network_path, |import_export_click_targets| {
for port in import_export_click_targets.click_targets() {
if let ClickTargetType::Subpath(subpath) = port.target_type() {
connector_click_targets.push(subpath.to_bezpath().to_svg());
if let ClickTargetType::Path(path) = port.target_type() {
connector_click_targets.push(path.to_svg());
}
}
});
@@ -42,29 +42,29 @@ impl NodeNetworkInterface {
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
let mut node_path = String::new();
if let ClickTargetType::Subpath(subpath) = node_click_targets.node_click_target.target_type() {
node_path.push_str(subpath.to_bezpath().to_svg().as_str())
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
node_path.push_str(path.to_svg().as_str())
}
all_node_click_targets.push((node_id, node_path));
for port in node_click_targets.port_click_targets.click_targets() {
if let ClickTargetType::Subpath(subpath) = port.target_type() {
connector_click_targets.push(subpath.to_bezpath().to_svg());
if let ClickTargetType::Path(path) = port.target_type() {
connector_click_targets.push(path.to_svg());
}
}
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
// Visibility button (eye icon)
if let ClickTargetType::Subpath(subpath) = layer_metadata.visibility_click_target.target_type() {
icon_click_targets.push(subpath.to_bezpath().to_svg());
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
icon_click_targets.push(path.to_svg());
}
// Lock button (padlock icon), only when the layer is locked
if let Some(lock_click_target) = &layer_metadata.lock_click_target
&& let ClickTargetType::Subpath(subpath) = lock_click_target.target_type()
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
{
icon_click_targets.push(subpath.to_bezpath().to_svg());
icon_click_targets.push(path.to_svg());
}
// Drag grip (dotted symbol)
if let ClickTargetType::Subpath(subpath) = layer_metadata.grip_click_target.target_type() {
icon_click_targets.push(subpath.to_bezpath().to_svg());
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
icon_click_targets.push(path.to_svg());
}
}
});
@@ -80,8 +80,7 @@ impl NodeNetworkInterface {
});
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
let rect = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
let all_nodes_bounding_box = rect.to_bezpath().to_svg();
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
let mut modify_import_export = Vec::new();
self.with_modify_import_export(network_path, |modify_import_export_click_targets| {
@@ -90,8 +89,8 @@ impl NodeNetworkInterface {
.click_targets()
.chain(modify_import_export_click_targets.reorder_imports_exports.click_targets())
{
if let ClickTargetType::Subpath(subpath) = click_target.target_type() {
modify_import_export.push(subpath.to_bezpath().to_svg());
if let ClickTargetType::Path(path) = click_target.target_type() {
modify_import_export.push(path.to_svg());
}
}
});
@@ -342,8 +341,8 @@ impl NodeNetworkInterface {
return None;
};
let bounding_box_subpath = Subpath::<PointId>::new_rectangle(bounds[0], bounds[1]);
bounding_box_subpath.bounding_box_with_transform(network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport)
let node_graph_to_viewport = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport;
Some((node_graph_to_viewport * Quad::from_box(bounds)).bounding_box())
}
pub fn collect_layer_widths(&self, network_path: &[NodeId]) -> (HashMap<NodeId, u32>, HashMap<NodeId, u32>, HashMap<NodeId, bool>) {
@@ -38,9 +38,12 @@ impl NodeNetworkInterface {
let vector = self.upstream_path_node_vector(layer)?;
let mut targets = Vec::new();
let subpaths: Vec<Subpath<PointId>> = vector.stroke_bezier_paths().collect();
if !subpaths.is_empty() {
targets.push(ClickTargetType::CompoundPath(subpaths));
let mut combined = BezPath::new();
for bezpath in vector.stroke_bezpath_iter() {
combined.extend(bezpath.elements().iter().copied());
}
if !combined.is_empty() {
targets.push(ClickTargetType::Path(combined));
}
for &point_id in vector.point_domain.ids() {
@@ -1,5 +1,33 @@
use super::*;
use graphene_std::ParameterRef;
use graphene_std::vector::misc::dvec2_to_point;
use kurbo::{DEFAULT_ACCURACY, Shape};
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
}
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
if radii.iter().all(|radius| *radius == 0.) {
return rect.to_path(DEFAULT_ACCURACY);
}
let [top_left, top_right, bottom_right, bottom_left] = radii;
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
}
/// Ellipse inscribed in the box spanning the two opposite corners.
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
path.close_path();
path
}
#[derive(PartialEq)]
pub enum FlowType {
@@ -227,8 +255,8 @@ impl Ports {
}
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
self.insert_custom_input_port(input_index, ClickTarget::new_with_subpath(subpath, 0.));
let path = ellipse_path(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
self.insert_custom_input_port(input_index, ClickTarget::new_with_path(path, 0.));
}
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
@@ -236,8 +264,8 @@ impl Ports {
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
let subpath = Subpath::new_ellipse(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
self.insert_custom_output_port(output_index, ClickTarget::new_with_subpath(subpath, 0.));
let path = ellipse_path(center - DVec2::new(8., 8.), center + DVec2::new(8., 8.));
self.insert_custom_output_port(output_index, ClickTarget::new_with_path(path, 0.));
}
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
@@ -864,3 +892,23 @@ pub(crate) fn collect_input_resource(input: &NodeInput, out: &mut HashSet<Resour
out.insert(*id);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn port_click_targets_are_clickable_at_their_center() {
let center = DVec2::new(100., 50.);
let mut ports = Ports::new();
ports.insert_input_port_at_center(0, center);
ports.insert_output_port_at_center(0, center + DVec2::new(200., 0.));
assert_eq!(ports.clicked_input_port_from_point(center), Some(0));
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(5., 5.)), Some(0));
assert_eq!(ports.clicked_input_port_from_point(center + DVec2::new(20., 0.)), None);
assert_eq!(ports.clicked_output_port_from_point(center + DVec2::new(200., 0.)), Some(0));
assert_eq!(ports.clicked_output_port_from_point(center), None);
}
}
@@ -93,7 +93,7 @@ impl OriginalTransforms {
let mut selected_points = selected_points.clone();
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
for (segment_id, _, start, end) in vector.segment_iter() {
if selected_segments.contains(&segment_id) {
selected_points.insert(ManipulatorPointId::Anchor(start));
selected_points.insert(ManipulatorPointId::Anchor(end));
@@ -392,7 +392,7 @@ impl TransformOperation {
}
pub fn hints(&self, responses: &mut VecDeque<Message>, local: bool) {
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
let mut input_hints = Vec::new();
@@ -479,7 +479,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
if locations.len() == 2 {
let p1 = to_point(locations[0]);
let p2 = to_point(locations[1]);
Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
return Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
}
let corner_radius = 10;
@@ -1979,79 +1979,38 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
// Upgrade Text node to include line height and character spacing, which were previously hardcoded to 1, from https://github.com/GraphiteEditor/Graphite/pull/2016
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && inputs_count == 8 {
// Every Text node era before alignment only appended inputs, so each is a prefix of the 11-input layout.
// Alignment (#2920) is the exception: it landed at index 9 and pushed Per-Glyph Instances out to 10.
if reference == DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")) && (4..=10).contains(&inputs_count) {
let mut template: NodeTemplate = legacy_text_node_template()?;
document.network_interface.replace_implementation(node_id, network_path, &mut template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 2), old_inputs[2].clone(), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 3), old_inputs[3].clone(), network_path);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 4),
if inputs_count == 6 {
old_inputs[4].clone()
} else {
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().line_height_ratio), false)
},
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 5),
if inputs_count == 6 {
old_inputs[5].clone()
} else {
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_spacing), false)
},
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 6),
if inputs_count >= 7 {
old_inputs[6].clone()
} else {
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().max_width.unwrap_or_default()), false)
},
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 7),
if inputs_count >= 8 {
old_inputs[7].clone()
} else {
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().max_width.unwrap_or_default()), false)
},
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 8),
if inputs_count >= 9 {
old_inputs[8].clone()
} else {
NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)
},
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 9),
if inputs_count >= 10 {
old_inputs[9].clone()
} else {
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false)
},
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 10),
if inputs_count >= 11 {
old_inputs[10].clone()
} else {
NodeInput::value(TaggedValue::Bool(false), false)
},
network_path,
);
// Line height and character spacing were hardcoded to 1 in the era before they became inputs
let hardcoded_to_one = || NodeInput::value(TaggedValue::F64(1.), false);
// Zero is how an absent `Option<f64>` maximum reads to the split below
let unset_maximum = || NodeInput::value(TaggedValue::F64(0.), false);
let upgraded_inputs = [
old_inputs[0].clone(),
old_inputs[1].clone(),
old_inputs[2].clone(),
old_inputs[3].clone(),
old_inputs.get(4).cloned().unwrap_or_else(hardcoded_to_one),
old_inputs.get(5).cloned().unwrap_or_else(hardcoded_to_one),
old_inputs.get(6).cloned().unwrap_or_else(unset_maximum),
old_inputs.get(7).cloned().unwrap_or_else(unset_maximum),
old_inputs
.get(8)
.cloned()
.unwrap_or_else(|| NodeInput::value(TaggedValue::F64(TypesettingConfig::default().letter_tilt), false)),
NodeInput::value(TaggedValue::TextAlign(TextAlign::default()), false),
old_inputs.get(9).cloned().unwrap_or_else(|| NodeInput::value(TaggedValue::Bool(false), false)),
];
for (index, input) in upgraded_inputs.into_iter().enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
inputs_count = 11
}
@@ -2068,31 +2027,26 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i), old_inputs[i].clone(), network_path);
}
// The old `Option<f64>` maximum becomes a bool plus a value, with zero standing in for the absent option.
// A wired maximum has no value to read, so it keeps its connection and counts as present.
let split_maximum = |input: &NodeInput| match input.as_value() {
Some(&TaggedValue::F64(maximum)) => (maximum != 0., NodeInput::value(TaggedValue::F64(if maximum == 0. { 100. } else { maximum }), false)),
_ => (true, input.clone()),
};
// Max Width
let Some(&TaggedValue::F64(old_max_width)) = old_inputs[6].as_value() else { return None };
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 6),
NodeInput::value(TaggedValue::Bool(old_max_width != 0.), false),
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 7),
NodeInput::value(TaggedValue::F64(if old_max_width == 0. { 100. } else { old_max_width }), false),
network_path,
);
let (has_max_width, max_width) = split_maximum(&old_inputs[6]);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 6), NodeInput::value(TaggedValue::Bool(has_max_width), false), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 7), max_width, network_path);
// Max Height
let Some(&TaggedValue::F64(old_max_height)) = old_inputs[7].as_value() else { return None };
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 8),
NodeInput::value(TaggedValue::Bool(old_max_height != 0.), false),
network_path,
);
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 9),
NodeInput::value(TaggedValue::F64(if old_max_height == 0. { 100. } else { old_max_height }), false),
network_path,
);
let (has_max_height, max_height) = split_maximum(&old_inputs[7]);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 8), NodeInput::value(TaggedValue::Bool(has_max_height), false), network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 9), max_height, network_path);
// Copy over old inputs
#[allow(clippy::needless_range_loop)]
@@ -2441,6 +2395,39 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.add_import(TaggedValue::U32(0), false, 1, "Loop Level", "TODO", &node_path);
}
// Drop the placeholder primary input the "Read Vector" node used to carry, since it reads its value from the context
if reference == DefinitionIdentifier::ProtoNode(graphene_std::context::read_vector::IDENTIFIER) && inputs_count > 0 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
}
// The "Dot Product" node gained a "Normalize" toggle, which older nodes predate by always taking the raw dot product
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::dot_product::IDENTIFIER) && inputs_count == 2 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.iter().take(2).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(false), false), network_path);
}
// The "Query JSON" node succeeded "JSON Get", whose object lookups always returned their strings unquoted
if reference == DefinitionIdentifier::ProtoNode(graphene_std::text_nodes::json::query_json::IDENTIFIER) && inputs_count == 2 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.iter().take(2).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Bool(true), false), network_path);
}
// Upgrade the "Animation" node to add the "Rate" input
if reference == DefinitionIdentifier::ProtoNode(graphene_std::animation::animation_time::IDENTIFIER) && inputs_count < 2 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -2883,19 +2870,39 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
/// definition by its old reference name, swaps it to a still-supported implementation, and preserves the user's inputs.
/// After this runs, the node's reference resolves cleanly so the rest of `migrate_node` proceeds normally.
fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId], document: &mut DocumentMessageHandler) -> Option<()> {
// Collapse the legacy "Sample Polyline" wrapper network into the standalone `sample_polyline` proto node.
// The proto node now computes per-bezpath segment lengths inline, so the wrapper's separate `subpath_segment_lengths`
// and `Memoize` nodes are no longer needed. The 7 user-facing inputs are positionally identical between the
// old wrapper and the new proto node.
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Sample Polyline"
&& node.inputs.len() == 7
// Collapse the legacy "Sample Points" and "Sample Polyline" wrapper networks into the standalone `sample_polyline`
// proto node, which now computes per-bezpath segment lengths inline instead of through the wrapper's helper nodes.
// The oldest documents lose their stored reference on load, so the wrapper is recognized by the nodes it encloses.
let wrapper_inputs = match &node.implementation {
DocumentNodeImplementation::Network(inner) => {
let helpers = [graphene_std::ops::passthrough::IDENTIFIER, graphene_std::memo::memoize::IDENTIFIER];
let mut sample_nodes = 0;
let only_helpers = inner.nodes.values().all(|inner_node| match &inner_node.implementation {
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::vector::sample_polyline::IDENTIFIER => {
sample_nodes += 1;
true
}
DocumentNodeImplementation::ProtoNode(identifier) => helpers.contains(identifier),
_ => false,
});
(only_helpers && sample_nodes == 1).then_some(node.inputs.len())
}
_ => None,
};
if let Some(wrapper_inputs) = wrapper_inputs
&& (wrapper_inputs == 5 || wrapper_inputs == 7)
{
let mut node_template = resolve_proto_node_type(graphene_std::vector::sample_polyline::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.iter().take(7).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
// The 5-input era predates the separation/quantity choice, so its lone spacing distance becomes the separation
let upgraded_inputs: Vec<(usize, NodeInput)> = match wrapper_inputs {
5 => [0, 2, 4, 5, 6].into_iter().zip(old_inputs.iter().cloned()).collect(),
_ => old_inputs.iter().take(7).cloned().enumerate().collect(),
};
for (index, input) in upgraded_inputs {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
@@ -2984,6 +2991,93 @@ mod tests {
}
}
// The Text node produced geometry until it became a string source, so every shape it ever had must reach the
// current one and gain the converter that turns its string back into geometry
#[test]
fn every_legacy_text_shape_gains_its_geometry_converter() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use graphene_std::NodeParameter;
use graphene_std::text::Font;
// Each era only appended to the one before it, so the shorter shapes are prefixes of this longest pre-alignment one
let legacy_inputs = [
NodeInput::scope("editor-api"),
NodeInput::value(TaggedValue::String("Lorem".into()), false),
NodeInput::value(TaggedValue::Font(Font::new("Lato".to_string(), "Regular (400)".to_string())), false),
NodeInput::value(TaggedValue::F64(48.), false),
NodeInput::value(TaggedValue::F64(1.5), false),
NodeInput::value(TaggedValue::F64(2.), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::F64(0.), false),
NodeInput::value(TaggedValue::F64(10.), false),
NodeInput::value(TaggedValue::Bool(false), false),
];
for shape in [4, 6, 8, 9, 10] {
let (text_id, consumer_id) = (NodeId(1), NodeId(2));
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node(
text_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_std::text::TextNode")),
inputs: legacy_inputs[..shape].to_vec(),
..Default::default()
},
&[],
);
document.network_interface.insert_node(
consumer_id,
NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false)],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(consumer_id, 0), NodeInput::node(text_id, 0), &[]);
document_migration_upgrades(&mut document, false);
let network = document.network_interface.document_network();
let text_node = network.nodes.get(&text_id).expect("the upgraded text node should keep its ID");
assert_eq!(text_node.inputs.len(), 12, "a {shape}-input text node should reach the current shape");
// The converter is a new node, so it is found by identity rather than by ID
let converter = network
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::text::text_to_vector::IDENTIFIER))
.map(|(converter_id, _)| *converter_id)
.unwrap_or_else(|| panic!("a {shape}-input text node should gain a string converter"));
assert_eq!(
network.nodes[&consumer_id].inputs.first(),
Some(&NodeInput::node(converter, 0)),
"the converter should be spliced onto the wire leaving a {shape}-input text node"
);
let input_value = |index: usize| text_node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(input_value(graphene_std::text::text::SizeInput::INDEX), Some(TaggedValue::F64(48.)), "shape {shape} lost its size");
if shape >= 6 {
assert_eq!(
input_value(graphene_std::text::text::LineHeightInput::INDEX),
Some(TaggedValue::F64(1.5)),
"shape {shape} lost its line height"
);
assert_eq!(
input_value(graphene_std::text::text::LetterSpacingInput::INDEX),
Some(TaggedValue::F64(2.)),
"shape {shape} lost its letter spacing"
);
}
if shape >= 9 {
assert_eq!(
input_value(graphene_std::text::text::LetterTiltInput::INDEX),
Some(TaggedValue::F64(10.)),
"shape {shape} lost its letter tilt"
);
}
}
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -6,7 +6,7 @@ use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
use crate::messages::animation::TimingInformation;
use crate::messages::dialog::simple_dialogs;
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::DocumentMessageContext;
@@ -48,6 +48,11 @@ impl ResourceStorageMessageHandler {
inner: self.storage.clone().expect("Resource storage not initialized"),
}
}
/// Whether the resource's data is held in storage, assuming it is until storage is initialized.
pub fn contains(&self, hash: &ResourceHash) -> bool {
self.storage.as_ref().is_none_or(|storage| storage.contains(hash))
}
}
impl std::fmt::Debug for ResourceStorageMessageHandler {
@@ -12,7 +12,7 @@ use crate::messages::tool::common_functionality::shapes::spiral_shape::calculate
use glam::DVec2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::subpath::{calculate_growth_factor, spiral_point};
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
use std::f64::consts::TAU;
@@ -10,7 +10,6 @@ use graph_craft::document::{DocumentNode, NodeId, NodeInput};
use graphene_std::Color;
use graphene_std::raster::BlendMode;
use graphene_std::raster_types::Image;
use graphene_std::subpath::Subpath;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
@@ -169,7 +168,7 @@ pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifie
let transform = document.metadata().transform_to_document(layer);
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { return };
let segment = vector.segment_bezier_iter().find(|(_, _, start, end)| *end == second_endpont || *start == second_endpont);
let segment = vector.segment_iter().find(|(_, _, start, end)| *end == second_endpont || *start == second_endpont);
let Some((segment, _, mut segment_start_point, mut segment_end_point)) = segment else {
log::error!("Could not get the segment for second_endpoint.");
return;
@@ -207,15 +206,6 @@ pub fn merge_points(document: &DocumentMessageHandler, layer: LayerNodeIdentifie
responses.add(GraphOperationMessage::Vector { layer, modification_type });
}
/// Create a new vector layer.
pub fn new_vector_layer(subpaths: Vec<Subpath<PointId>>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
let insert_index = 0;
responses.add(GraphOperationMessage::NewVectorLayer { id, subpaths, parent, insert_index });
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![id] });
LayerNodeIdentifier::new_unchecked(id)
}
/// Create a new bitmap layer.
pub fn new_image_layer(image: Image<Color>, id: NodeId, parent: LayerNodeIdentifier, responses: &mut VecDeque<Message>) -> LayerNodeIdentifier {
let insert_index = 0;
@@ -1,4 +1,4 @@
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::prelude::*;
@@ -12,10 +12,9 @@ use crate::messages::tool::common_functionality::snapping::SnapTypeConfiguration
use crate::messages::tool::common_functionality::utility_functions::is_visible_point;
use crate::messages::tool::tool_messages::path_tool::{PathOverlayMode, PointSelectState};
use glam::{DAffine2, DVec2};
use graphene_std::subpath::{BezierHandles, Subpath};
use graphene_std::subpath::{PathSegPoints, pathseg_points};
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2};
use graphene_std::vector::algorithms::shapes::polyline_bezpath;
use graphene_std::vector::misc::{BezierHandles, HandleId, ManipulatorPointId, PathSegPoints, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2, segment_to_handles};
use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModificationType};
use kurbo::{Affine, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveNearest, PathSeg, Rect, Shape};
use std::f64::consts::TAU;
@@ -251,7 +250,7 @@ impl ClosestSegment {
// Transform to viewport space
let transform = document_metadata.transform_to_viewport_if_feeds(self.layer, network_interface);
// Split the Bezier at the parameter `t`
// Split the segment at the parameter `t`
let first = self.bezier.subsegment(0_f64..self.t);
let second = self.bezier.subsegment(self.t..1.);
@@ -750,9 +749,9 @@ impl ShapeState {
let mut selected_stack = Vec::new();
// Find all subpaths that have been clicked
for stroke in vector.stroke_bezier_paths() {
if stroke.contains_point(layer_mouse)
&& let Some(first) = stroke.manipulator_groups().first()
for (groups, closed) in vector.stroke_manipulator_groups() {
if bezpath_from_manipulator_groups(&groups, closed).contains(dvec2_to_point(layer_mouse))
&& let Some(first) = groups.first()
{
selected_stack.push(first.id);
}
@@ -788,7 +787,7 @@ impl ShapeState {
}
if segments {
for (id, _, start, end) in vector.segment_bezier_iter() {
for (id, _, start, end) in vector.segment_iter() {
if connected_points.contains(&start) || connected_points.contains(&end) {
state.select_segment(id);
}
@@ -950,14 +949,14 @@ impl ShapeState {
// Move the other handle for a quadratic bezier
for segment in vector.end_connected(point) {
let Some((start, _end, bezier)) = vector.segment_points_from_id(segment) else { continue };
let Some((start, _end, path_segment)) = vector.segment_points_from_id(segment) else { continue };
if let BezierHandles::Quadratic { handle } = bezier.handles {
if let BezierHandles::Quadratic { handle } = segment_to_handles(&path_segment) {
if selected.is_some_and(|selected| selected.is_point_selected(ManipulatorPointId::Anchor(start))) {
continue;
}
let relative_position = handle - bezier.start + delta;
let relative_position = handle - point_to_dvec2(path_segment.start()) + delta;
let modification_type = VectorModificationType::SetPrimaryHandle { segment, relative_position };
responses.add(GraphOperationMessage::Vector { layer, modification_type });
@@ -1284,7 +1283,7 @@ impl ShapeState {
// Make a new set of anchor points which needs to be moved
let mut affected_points = state.selected_points.clone();
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
for (segment_id, _, start, end) in vector.segment_iter() {
if state.is_segment_selected(segment_id) {
affected_points.insert(ManipulatorPointId::Anchor(start));
affected_points.insert(ManipulatorPointId::Anchor(end));
@@ -1570,7 +1569,7 @@ impl ShapeState {
for (&layer, state) in &self.selected_shape_state {
let Some(vector) = document.network_interface.compute_modified_vector(layer) else { continue };
for (segment, _, start, end) in vector.segment_bezier_iter() {
for (segment, _, start, end) in vector.segment_iter() {
if state.selected_segments.contains(&segment) {
if start_transaction && !transaction_started {
responses.add(DocumentMessage::AddTransaction);
@@ -1785,20 +1784,23 @@ impl ShapeState {
let viewspace = network_interface.document_metadata().transform_to_viewport_if_feeds(layer, network_interface);
// Handles
for (segment_id, bezier, _, _) in vector.segment_bezier_iter() {
let bezier = bezier.apply_transformation(|point| viewspace.transform_point2(point));
for (segment_id, segment, _, _) in vector.segment_iter() {
let segment = Affine::new(viewspace.to_cols_array()) * segment;
let handles = segment_to_handles(&segment);
let segment_start = point_to_dvec2(segment.start());
let segment_end = point_to_dvec2(segment.end());
let valid = |handle: DVec2, control: DVec2| handle.distance_squared(control) > crate::consts::HIDE_HANDLE_DISTANCE.powi(2);
if let Some(primary_handle) = bezier.handle_start()
&& valid(primary_handle, bezier.start)
&& (bezier.handle_end().is_some() || valid(primary_handle, bezier.end))
if let Some(primary_handle) = handles.start()
&& valid(primary_handle, segment_start)
&& (handles.end().is_some() || valid(primary_handle, segment_end))
&& primary_handle.distance_squared(pos) <= closest_distance_squared
{
closest_distance_squared = primary_handle.distance_squared(pos);
manipulator_point = Some(ManipulatorPointId::PrimaryHandle(segment_id));
}
if let Some(end_handle) = bezier.handle_end()
&& valid(end_handle, bezier.end)
if let Some(end_handle) = handles.end()
&& valid(end_handle, segment_end)
&& end_handle.distance_squared(pos) <= closest_distance_squared
{
closest_distance_squared = end_handle.distance_squared(pos);
@@ -2071,9 +2073,9 @@ impl ShapeState {
self.convert_manipulator_handles_to_colinear(&vector, point_id, responses, layer);
} else {
for handle in vector.all_connected(point_id) {
let Some(bezier) = vector.segment_from_id(handle.segment) else { continue };
let Some(path_segment) = vector.segment_from_id(handle.segment) else { continue };
match bezier.handles {
match segment_to_handles(&path_segment) {
BezierHandles::Linear => {}
BezierHandles::Quadratic { .. } => {
let segment = handle.segment;
@@ -2173,7 +2175,7 @@ impl ShapeState {
let Some(vector) = network_interface.compute_modified_vector(layer) else { continue };
if !select_points && select_segments {
vector
.segment_bezier_iter()
.segment_iter()
.filter(|(segment, _, _, _)| segments.contains(segment))
.for_each(|(_, _, start, end)| match selection_change {
SelectionChange::Shrink => {
@@ -2220,12 +2222,11 @@ impl ShapeState {
assert!(vector.point_domain.ids().contains(&end));
}
let polygon_subpath = if let SelectionShape::Lasso(polygon) = selection_shape {
let polygon_bezpath = if let SelectionShape::Lasso(polygon) = selection_shape {
if polygon.len() < 2 {
return (points_inside, segments_inside);
}
let polygon: Subpath<PointId> = Subpath::from_anchors(polygon.to_vec(), true);
Some(polygon)
Some(polyline_bezpath(polygon.iter().copied(), true))
} else {
None
};
@@ -2253,13 +2254,13 @@ impl ShapeState {
}
}
SelectionShape::Lasso(_) => {
let polygon = polygon_subpath.as_ref().expect("If `selection_shape` is a polygon then subpath is constructed beforehand.");
let polygon = polygon_bezpath.as_ref().expect("If `selection_shape` is a polygon then its path is constructed beforehand.");
// Sample 10 points on the bezier and check if all or some lie inside the polygon
let points = pathseg_compute_lookup_table(segment, Some(10), false);
match selection_mode {
SelectionMode::Enclosed => points.map(|p| transform.transform_point2(p)).all(|p| polygon.contains_point(p)),
_ => points.map(|p| transform.transform_point2(p)).any(|p| polygon.contains_point(p)),
SelectionMode::Enclosed => points.map(|p| transform.transform_point2(p)).all(|p| polygon.contains(dvec2_to_point(p))),
_ => points.map(|p| transform.transform_point2(p)).any(|p| polygon.contains(dvec2_to_point(p))),
}
}
};
@@ -2278,10 +2279,10 @@ impl ShapeState {
let select = match selection_shape {
SelectionShape::Box(rect) => rect.contains(dvec2_to_point(transformed_position)),
SelectionShape::Lasso(_) => polygon_subpath
SelectionShape::Lasso(_) => polygon_bezpath
.as_ref()
.expect("If `selection_shape` is a polygon then subpath is constructed beforehand.")
.contains_point(transformed_position),
.expect("If `selection_shape` is a polygon then its path is constructed beforehand.")
.contains(dvec2_to_point(transformed_position)),
};
if select && select_points {
@@ -2303,10 +2304,10 @@ impl ShapeState {
let select = match selection_shape {
SelectionShape::Box(rect) => rect.contains(dvec2_to_point(transformed_position)),
SelectionShape::Lasso(_) => polygon_subpath
SelectionShape::Lasso(_) => polygon_bezpath
.as_ref()
.expect("If `selection_shape` is a polygon then subpath is constructed beforehand.")
.contains_point(transformed_position),
.expect("If `selection_shape` is a polygon then its path is constructed beforehand.")
.contains(dvec2_to_point(transformed_position)),
};
if select && select_points {
@@ -16,7 +16,8 @@ use crate::messages::tool::utility_types::*;
use glam::{DAffine2, DMat2, DVec2};
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::subpath::{self, Subpath};
use graphene_std::math::float_noise::round_away_float_noise;
use graphene_std::vector::algorithms::shapes::{arc_bezpath, regular_polygon_bezpath, star_polygon_bezpath};
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::{ArcType, GridType, SpiralType, dvec2_to_point};
use kurbo::{BezPath, PathEl, Shape};
@@ -442,12 +443,9 @@ pub fn star_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessa
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let diameter: f64 = radius1 * 2.;
let inner_diameter = radius2 * 2.;
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2))];
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::new_star_polygon(DVec2::splat(-diameter), points, diameter, inner_diameter))];
overlay_context.outline(subpath.iter(), viewport, None);
overlay_context.outline(targets.iter(), viewport, None);
}
/// Outlines the geometric shape made by polygon-node
@@ -460,11 +458,9 @@ pub fn polygon_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMe
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let radius: f64 = radius * 2.;
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(regular_polygon_bezpath(DVec2::ZERO, points, radius))];
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::new_regular_polygon(DVec2::splat(-radius), points, radius))];
overlay_context.outline(subpath.iter(), viewport, None);
overlay_context.outline(targets.iter(), viewport, None);
}
/// Outlines the geometric shape made by an Arc node
@@ -475,19 +471,11 @@ pub fn arc_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessag
return;
};
let subpath: Vec<ClickTargetType> = vec![ClickTargetType::Subpath(Subpath::new_arc(
radius,
start_angle / 360. * std::f64::consts::TAU,
sweep_angle / 360. * std::f64::consts::TAU,
match arc_type {
ArcType::Open => subpath::ArcType::Open,
ArcType::Closed => subpath::ArcType::Closed,
ArcType::PieSlice => subpath::ArcType::PieSlice,
},
))];
let arc = arc_bezpath(radius, start_angle / 360. * std::f64::consts::TAU, sweep_angle / 360. * std::f64::consts::TAU, arc_type);
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(arc)];
let viewport = document.metadata().transform_to_viewport(layer);
overlay_context.outline(subpath.iter(), viewport, None);
overlay_context.outline(targets.iter(), viewport, None);
}
/// Check if the the cursor is inside the geometric star shape made by the Star node without any upstream node modifications
@@ -583,26 +571,6 @@ pub fn format_rounded(value: f64, precision: usize) -> String {
}
}
/// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
/// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
/// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
pub fn round_away_float_noise(value: f64) -> f64 {
if value == 0. || !value.is_finite() {
return if value == 0. { 0. } else { value };
}
let exponent = value.abs().log10().floor() as i32;
for significant_digits in 1..=12 {
let scale = 10_f64.powi(significant_digits - 1 - exponent);
let rounded = (value * scale).round() / scale;
if ((rounded - value) / value).abs() < 1e-13 {
return rounded;
}
}
value
}
/// Gives the approximated angle to display in degrees, given an angle in degrees.
pub fn calculate_display_angle(angle: f64) -> f64 {
if angle.is_sign_positive() {
@@ -647,37 +615,6 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
mod tests {
use super::*;
#[test]
fn round_away_float_noise_snaps_noisy_values() {
assert_eq!(round_away_float_noise(0.1 + 0.2), 0.3);
assert_eq!(round_away_float_noise(0.3000000000000012), 0.3);
assert_eq!(round_away_float_noise(2.99999999999993), 3.);
assert_eq!(round_away_float_noise(45.00000000000001), 45.);
}
#[test]
fn round_away_float_noise_keeps_honest_values() {
assert_eq!(round_away_float_noise(1. / 3.), 1. / 3.);
assert_eq!(round_away_float_noise(0.2394023940209349), 0.2394023940209349);
assert_eq!(round_away_float_noise(0.25), 0.25);
assert_eq!(round_away_float_noise(-17.5), -17.5);
}
#[test]
fn round_away_float_noise_keeps_deliberate_values_with_zero_runs() {
assert_eq!(round_away_float_noise(0.30000005), 0.30000005);
assert_eq!(round_away_float_noise(0.3000000000001), 0.3000000000001);
assert_eq!(round_away_float_noise(1.00000001), 1.00000001);
assert_eq!(round_away_float_noise(2.9999993), 2.9999993);
}
#[test]
fn round_away_float_noise_normalizes_zero() {
let result = round_away_float_noise(-0.);
assert_eq!(result, 0.);
assert!(result.is_sign_positive());
}
#[test]
fn format_rounded_trims_trailing_zeros_when_exact() {
assert_eq!(format_rounded(0.25, 2), "0.25");
@@ -14,7 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::subpath::{calculate_growth_factor, spiral_point};
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
@@ -6,14 +6,12 @@ use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, FloatExt};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::renderer::Quad;
use graphene_std::subpath::pathseg_points;
use graphene_std::subpath::{Identifier, ManipulatorGroup, Subpath};
use graphene_std::vector::PointId;
use graphene_std::vector::algorithms::bezpath_algorithms::{pathseg_normals_to_point, pathseg_tangents_to_point};
use graphene_std::vector::algorithms::intersection::filtered_segment_intersections;
use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::misc::point_to_dvec2;
use kurbo::{Affine, ParamCurve, PathSeg};
use graphene_std::vector::algorithms::shapes::{ellipse_bezpath, line_bezpath};
use graphene_std::vector::misc::{ManipulatorGroup, bezpath_from_manipulator_groups, dvec2_to_point, pathseg_points, point_to_dvec2};
use kurbo::{Affine, BezPath, ParamCurve, PathEl, PathSeg};
#[derive(Clone, Debug, Default)]
pub struct LayerSnapper {
@@ -47,7 +45,7 @@ impl LayerSnapper {
self.paths_to_snap.push(SnapCandidatePath {
document_curve,
layer,
start: PointId::new(),
start: PointId::generate(),
target,
bounds: Some(bounds),
});
@@ -74,26 +72,20 @@ impl LayerSnapper {
}
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::IntersectionPoint)) || document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AlongPath)) {
let mut push_candidates = |subpath: &Subpath<PointId>, transform: DAffine2| {
for (start_index, curve) in subpath.iter().enumerate() {
let document_curve = Affine::new(transform.to_cols_array()) * curve;
let start = subpath.manipulator_groups()[start_index].id;
if snap_data.ignore_manipulator(layer, start) || snap_data.ignore_manipulator(layer, subpath.manipulator_groups()[(start_index + 1) % subpath.len()].id) {
continue;
// Post-solidified outline (the layer's recorded geometry). Its anchors carry no point IDs,
// so while this layer's manipulators are being dragged the whole outline is skipped instead of filtering per manipulator.
if !snap_data.ignore_bounds(layer) {
for bezpath in document.metadata().layer_outline(layer) {
for curve in bezpath.segments() {
self.paths_to_snap.push(SnapCandidatePath {
document_curve: Affine::new(transform.to_cols_array()) * curve,
layer,
start: PointId::generate(),
target: SnapTarget::Path(PathSnapTarget::AlongPath),
bounds: None,
});
}
self.paths_to_snap.push(SnapCandidatePath {
document_curve,
layer,
start,
target: SnapTarget::Path(PathSnapTarget::AlongPath),
bounds: None,
});
}
};
// Post-solidified outline (the layer's recorded geometry)
for subpath in document.metadata().layer_outline(layer) {
push_candidates(subpath, transform);
}
// Pre-solidified centerline (the Path tool's view) when an upstream Path node exists,
@@ -101,8 +93,22 @@ impl LayerSnapper {
if let Some(vector) = document.network_interface.upstream_path_node_vector(layer) {
let path_aware_transform = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface);
if path_aware_transform.is_finite() {
for subpath in vector.stroke_bezier_paths() {
push_candidates(&subpath, path_aware_transform);
for (groups, closed) in vector.stroke_manipulator_groups() {
let bezpath = bezpath_from_manipulator_groups(&groups, closed);
for (start_index, curve) in bezpath.segments().enumerate() {
let start = groups[start_index].id;
let end = groups[(start_index + 1) % groups.len()].id;
if snap_data.ignore_manipulator(layer, start) || snap_data.ignore_manipulator(layer, end) {
continue;
}
self.paths_to_snap.push(SnapCandidatePath {
document_curve: Affine::new(path_aware_transform.to_cols_array()) * curve,
layer,
start,
target: SnapTarget::Path(PathSnapTarget::AlongPath),
bounds: None,
});
}
}
}
}
@@ -156,17 +162,17 @@ impl LayerSnapper {
let tolerance = snap_tolerance(document);
let constraint_path = if let SnapConstraint::Circle { center, radius } = constraint {
Subpath::new_ellipse(center - DVec2::splat(radius), center + DVec2::splat(radius))
ellipse_bezpath(center - DVec2::splat(radius), center + DVec2::splat(radius))
} else {
let constrained_point = constraint.projection(point.document_point);
let direction = constraint.direction().normalize_or_zero();
let start = constrained_point - tolerance * direction;
let end = constrained_point + tolerance * direction;
Subpath::<PointId>::new_line(start, end)
line_bezpath(start, end)
};
for path in &self.paths_to_snap {
for constraint_path in constraint_path.iter() {
for constraint_path in constraint_path.segments() {
for time in filtered_segment_intersections(path.document_curve, constraint_path, None, None) {
let snapped_point_document = point_to_dvec2(path.document_curve.eval(time));
@@ -548,13 +554,14 @@ fn handle_not_under(to_document: DAffine2) -> impl Fn(&DVec2) -> bool {
move |&offset: &DVec2| to_document.transform_vector2(offset).length_squared() >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE
}
fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<PointId>, snap_data: &SnapData, points: &mut Vec<SnapCandidatePoint>, to_document: DAffine2) {
fn manipulator_groups_anchor_snap_points(layer: LayerNodeIdentifier, groups: &[ManipulatorGroup], closed: bool, snap_data: &SnapData, points: &mut Vec<SnapCandidatePoint>, to_document: DAffine2) {
let document = snap_data.document;
let bezpath = bezpath_from_manipulator_groups(groups, closed);
// Midpoints of linear segments
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::LineMidpoint)) {
for (index, curve) in subpath.iter().enumerate() {
if snap_data.ignore_manipulator(layer, subpath.manipulator_groups()[index].id) || snap_data.ignore_manipulator(layer, subpath.manipulator_groups()[(index + 1) % subpath.len()].id) {
for (index, curve) in bezpath.segments().enumerate() {
if snap_data.ignore_manipulator(layer, groups[index].id) || snap_data.ignore_manipulator(layer, groups[(index + 1) % groups.len()].id) {
continue;
}
if points.len() >= crate::consts::MAX_LAYER_SNAP_POINTS {
@@ -576,7 +583,7 @@ fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<Poin
}
// Anchors
for (index, manipulators) in subpath.manipulator_groups().iter().enumerate() {
for (index, manipulators) in groups.iter().enumerate() {
if snap_data.ignore_manipulator(layer, manipulators.id) {
continue;
}
@@ -585,7 +592,7 @@ fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<Poin
return;
}
let colinear = are_manipulator_handles_colinear(manipulators, to_document, subpath, index);
let colinear = are_manipulator_handles_colinear(manipulators, to_document, closed, index, groups.len());
// Colinear handles
if colinear && document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithColinearHandles)) {
@@ -608,11 +615,101 @@ fn subpath_anchor_snap_points(layer: LayerNodeIdentifier, subpath: &Subpath<Poin
}
}
pub fn are_manipulator_handles_colinear(manipulators: &ManipulatorGroup<PointId>, to_document: DAffine2, subpath: &Subpath<PointId>, index: usize) -> bool {
fn bezpath_anchor_snap_points(layer: LayerNodeIdentifier, bezpath: &BezPath, snap_data: &SnapData, points: &mut Vec<SnapCandidatePoint>, to_document: DAffine2) {
let document = snap_data.document;
// Split the path into contours so endpoint and wraparound handling stays per-subpath
let mut contours = Vec::new();
let mut current = BezPath::new();
for element in bezpath.elements() {
if matches!(element, PathEl::MoveTo(_)) && !current.elements().is_empty() {
contours.push(std::mem::take(&mut current));
}
current.push(*element);
}
if !current.elements().is_empty() {
contours.push(current);
}
for contour in contours {
let closed = matches!(contour.elements().last(), Some(PathEl::ClosePath));
let segments: Vec<PathSeg> = contour.segments().collect();
if segments.is_empty() {
continue;
}
// Midpoints of linear segments
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::LineMidpoint)) {
for &segment in &segments {
if points.len() >= crate::consts::MAX_LAYER_SNAP_POINTS {
return;
}
let curve = pathseg_points(segment);
let in_handle = curve.p1.map(|handle| handle - curve.p0).filter(handle_not_under(to_document));
let out_handle = curve.p2.map(|handle| handle - curve.p3).filter(handle_not_under(to_document));
if in_handle.is_none() && out_handle.is_none() {
points.push(SnapCandidatePoint::new(
to_document.transform_point2(curve.p0 * 0.5 + curve.p3 * 0.5),
SnapSource::Path(PathSnapSource::LineMidpoint),
SnapTarget::Path(PathSnapTarget::LineMidpoint),
Some(layer),
));
}
}
}
// Anchors
let anchor_count = segments.len() + if closed { 0 } else { 1 };
for index in 0..anchor_count {
if points.len() >= crate::consts::MAX_LAYER_SNAP_POINTS {
return;
}
let anchor = if index < segments.len() {
pathseg_points(segments[index]).p0
} else {
pathseg_points(segments[index - 1]).p3
};
let in_handle = if index > 0 {
pathseg_points(segments[index - 1]).p2
} else if closed {
pathseg_points(segments[segments.len() - 1]).p2
} else {
None
};
let out_handle = if index < segments.len() { pathseg_points(segments[index]).p1 } else { None };
let handle_in = in_handle.map(|handle| anchor - handle).filter(handle_not_under(to_document));
let handle_out = out_handle.map(|handle| handle - anchor).filter(handle_not_under(to_document));
let anchor_is_endpoint = !closed && (index == 0 || index == anchor_count - 1);
let colinear = !anchor_is_endpoint && handle_in.is_some_and(|handle_in| handle_out.is_some_and(|handle_out| handle_in.angle_to(handle_out) < 1e-5));
if colinear && document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithColinearHandles)) {
points.push(SnapCandidatePoint::new(
to_document.transform_point2(anchor),
SnapSource::Path(PathSnapSource::AnchorPointWithColinearHandles),
SnapTarget::Path(PathSnapTarget::AnchorPointWithColinearHandles),
Some(layer),
));
} else if !colinear && document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithFreeHandles)) {
points.push(SnapCandidatePoint::new(
to_document.transform_point2(anchor),
SnapSource::Path(PathSnapSource::AnchorPointWithFreeHandles),
SnapTarget::Path(PathSnapTarget::AnchorPointWithFreeHandles),
Some(layer),
));
}
}
}
}
pub fn are_manipulator_handles_colinear(manipulators: &ManipulatorGroup, to_document: DAffine2, closed: bool, index: usize, count: usize) -> bool {
let anchor = manipulators.anchor;
let handle_in = manipulators.in_handle.map(|handle| anchor - handle).filter(handle_not_under(to_document));
let handle_out = manipulators.out_handle.map(|handle| handle - anchor).filter(handle_not_under(to_document));
let anchor_is_endpoint = !subpath.closed() && (index == 0 || index == subpath.len() - 1);
let anchor_is_endpoint = !closed && (index == 0 || index == count - 1);
// Unless this is an endpoint, check if both handles are colinear (within an angular epsilon)
!anchor_is_endpoint && handle_in.is_some_and(|handle_in| handle_out.is_some_and(|handle_out| handle_in.angle_to(handle_out) < 1e-5))
@@ -633,11 +730,11 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
get_layer_snap_points(child, snap_data, points);
}
} else {
// Post-solidified outline (the layer's recorded geometry)
if document.metadata().layer_outline(layer).next().is_some() {
// Post-solidified outline (the layer's recorded geometry), skipped wholesale while this layer's manipulators are being dragged since the outline carries no point IDs
if !snap_data.ignore_bounds(layer) {
let to_document = document.metadata().transform_to_document(layer);
for subpath in document.metadata().layer_outline(layer) {
subpath_anchor_snap_points(layer, subpath, snap_data, points, to_document);
for bezpath in document.metadata().layer_outline(layer) {
bezpath_anchor_snap_points(layer, bezpath, snap_data, points, to_document);
}
}
@@ -646,8 +743,8 @@ pub fn get_layer_snap_points(layer: LayerNodeIdentifier, snap_data: &SnapData, p
// matching what the Path tool's overlay shows
if let Some(vector) = document.network_interface.upstream_path_node_vector(layer) {
let to_document = document.metadata().transform_to_document_if_feeds(layer, &document.network_interface);
for subpath in vector.stroke_bezier_paths() {
subpath_anchor_snap_points(layer, &subpath, snap_data, points, to_document);
for (groups, closed) in vector.stroke_manipulator_groups() {
manipulator_groups_anchor_snap_points(layer, &groups, closed, snap_data, points, to_document);
}
if document.snapping_state.target_enabled(SnapTarget::Path(PathSnapTarget::AnchorPointWithFreeHandles)) {
@@ -13,11 +13,10 @@ use crate::messages::tool::utility_types::ToolType;
use glam::{DAffine2, DVec2};
use graph_craft::document::value::TaggedValue;
use graphene_std::renderer::Quad;
use graphene_std::subpath::{Bezier, BezierHandles};
use graphene_std::vector::algorithms::bezpath_algorithms::pathseg_compute_lookup_table;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point};
use graphene_std::vector::{HandleExt, PointId, SegmentId, Vector, VectorModification, VectorModificationType};
use kurbo::{CubicBez, DEFAULT_ACCURACY, Line, ParamCurve, PathSeg, Point, QuadBez, Shape};
use kurbo::{CubicBez, DEFAULT_ACCURACY, ParamCurve, PathSeg, Point, Shape};
/// Determines if a path should be extended. Goal in viewport space. Returns the path and if it is extending from the start, if applicable.
pub fn should_extend(document: &DocumentMessageHandler, goal: DVec2, tolerance: f64, layers: impl Iterator<Item = LayerNodeIdentifier>) -> Option<(LayerNodeIdentifier, PointId, DVec2)> {
@@ -196,51 +195,6 @@ pub fn is_visible_point(
}
}
pub fn is_intersecting(bezier: Bezier, quad: [DVec2; 2], transform: DAffine2) -> bool {
let to_layerspace = transform.inverse();
let quad = [to_layerspace.transform_point2(quad[0]), to_layerspace.transform_point2(quad[1])];
let start = Point::new(bezier.start.x, bezier.start.y);
let end = Point::new(bezier.end.x, bezier.end.y);
let segment = match bezier.handles {
BezierHandles::Cubic { handle_start, handle_end } => {
let p1 = Point::new(handle_start.x, handle_start.y);
let p2 = Point::new(handle_end.x, handle_end.y);
PathSeg::Cubic(CubicBez::new(start, p1, p2, end))
}
BezierHandles::Quadratic { handle } => {
let p1 = Point::new(handle.x, handle.y);
PathSeg::Quad(QuadBez::new(start, p1, end))
}
BezierHandles::Linear => PathSeg::Line(Line::new(start, end)),
};
// Create a list of all the sides
let sides = [
Line::new((quad[0].x, quad[0].y), (quad[1].x, quad[0].y)),
Line::new((quad[0].x, quad[0].y), (quad[0].x, quad[1].y)),
Line::new((quad[1].x, quad[1].y), (quad[1].x, quad[0].y)),
Line::new((quad[1].x, quad[1].y), (quad[0].x, quad[1].y)),
];
let mut is_intersecting = false;
for line in sides {
let intersections = segment.intersect_line(line);
let mut intersects = false;
for intersection in intersections {
if intersection.line_t <= 1. && intersection.line_t >= 0. && intersection.segment_t <= 1. && intersection.segment_t >= 0. {
// There is a valid intersection point
intersects = true;
break;
}
}
if intersects {
is_intersecting = true;
break;
}
}
is_intersecting
}
#[allow(clippy::too_many_arguments)]
pub fn resize_bounds(
document: &DocumentMessageHandler,
@@ -6,9 +6,9 @@ use crate::messages::tool::common_functionality::color_selector::solid;
use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, get_upstream_color_value_node_id, gradient_chain_target_input, replaceable_paint_chain};
use graphene_std::color::SRGBA8;
use graphene_std::raster::color::Color;
use graphene_std::subpath::Subpath;
use graphene_std::vector::PointId;
use graphene_std::vector::misc::dvec2_to_point;
use graphene_std::vector::style::FillChoice;
use kurbo::{BezPath, DEFAULT_ACCURACY, Rect, Shape};
#[derive(Default, ExtractField)]
pub struct FillTool {
@@ -150,9 +150,13 @@ impl Fsm for FillToolFsmState {
if paints_whole_expanse(layer, &document.network_interface) {
let expanse = whole_expanse_rect(layer, document, overlay_context.viewport.size().into_dvec2());
overlay_context.fill_path_pattern(std::iter::once(expanse), DAffine2::IDENTITY, &color_hex);
overlay_context.fill_path_pattern(&expanse, DAffine2::IDENTITY, &color_hex);
} else {
overlay_context.fill_path_pattern(document.metadata().layer_outline(layer), document.metadata().transform_to_viewport(layer), &color_hex);
let mut outline = BezPath::new();
for path in document.metadata().layer_outline(layer) {
outline.extend(path.elements().iter().copied());
}
overlay_context.fill_path_pattern(&outline, document.metadata().transform_to_viewport(layer), &color_hex);
}
}
@@ -244,15 +248,16 @@ fn paints_whole_expanse(layer: LayerNodeIdentifier, network_interface: &NodeNetw
/// The viewport-space area a whole-expanse color paints: the artboard containing the layer, since the color fills it,
/// or else the visible viewport for a layer living outside any artboard.
fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport_size: DVec2) -> Subpath<PointId> {
fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport_size: DVec2) -> BezPath {
let containing_artboard = layer
.ancestors(document.metadata())
.find(|&ancestor| ancestor != LayerNodeIdentifier::ROOT_PARENT && document.network_interface.is_artboard(&ancestor.to_node(), &[]));
match containing_artboard.and_then(|artboard| document.metadata().bounding_box_viewport(artboard)) {
Some([min, max]) => Subpath::new_rectangle(min, max),
None => Subpath::new_rectangle(DVec2::ZERO, viewport_size),
}
let [min, max] = containing_artboard
.and_then(|artboard| document.metadata().bounding_box_viewport(artboard))
.unwrap_or([DVec2::ZERO, viewport_size]);
Rect::from_points(dvec2_to_point(min), dvec2_to_point(max)).to_path(DEFAULT_ACCURACY)
}
#[cfg(test)]
@@ -422,7 +422,7 @@ fn extend_path_with_next_segment(tool_data: &mut FreehandToolData, position: DVe
#[cfg(test)]
mod test_freehand {
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta};
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys};
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;
@@ -530,10 +530,10 @@ mod test_freehand {
let last_initial_point = initial_points[initial_points.len() - 1];
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: last_initial_point,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -589,10 +589,10 @@ mod test_freehand {
let last_extension_point = extension_points[extension_points.len() - 1];
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: last_extension_point,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -643,10 +643,10 @@ mod test_freehand {
let last_initial_point = initial_points[initial_points.len() - 1];
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: last_initial_point,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -678,10 +678,10 @@ mod test_freehand {
editor
.mousedown(
EditorMouseState {
EditorPointerState {
editor_position: first_second_point,
mouse_keys: MouseKeys::LEFT,
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::SHIFT,
)
@@ -694,10 +694,10 @@ mod test_freehand {
let last_second_point = second_path_points[second_path_points.len() - 1];
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: last_second_point,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::SHIFT,
)
@@ -767,10 +767,10 @@ mod test_freehand {
let last_point = points[points.len() - 1];
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: last_point,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -2051,8 +2051,7 @@ enum GradientDragHintState {
mod test_gradient {
use super::{gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
use crate::messages::input_mapper::utility_types::input_mouse::EditorMouseState;
use crate::messages::input_mapper::utility_types::input_mouse::ScrollDelta;
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
@@ -2525,10 +2524,10 @@ mod test_gradient {
editor.move_mouse(end_pos.x, end_pos.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: end_pos,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -2579,10 +2578,10 @@ mod test_gradient {
let click_position = DVec2::new(25., 0.);
editor
.mousedown(
EditorMouseState {
EditorPointerState {
editor_position: click_position,
mouse_keys: MouseKeys::LEFT,
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -2593,10 +2592,10 @@ mod test_gradient {
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: drag_position,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -2658,10 +2657,10 @@ mod test_gradient {
editor.left_mousedown(position2.x, position2.y, ModifierKeys::empty()).await;
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: position2,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -2907,10 +2906,10 @@ mod test_gradient {
editor.move_mouse(new_viewport_end.x, new_viewport_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: new_viewport_end,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -2984,10 +2983,10 @@ mod test_gradient {
editor.move_mouse(new_viewport_end.x, new_viewport_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor
.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: new_viewport_end,
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::empty(),
)
@@ -14,7 +14,7 @@ pub mod text_tool;
pub mod tool_prelude {
pub use crate::messages::frontend::utility_types::MouseCursorIcon;
pub use crate::messages::input_mapper::utility_types::input_keyboard::{Key, MouseMotion};
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
pub use crate::messages::layout::utility_types::widget_prelude::*;
pub use crate::messages::prelude::*;
pub use crate::messages::tool::utility_types::{EventToMessageMap, Fsm, ToolActionMessageContext, ToolMetadata, ToolTransition, ToolType};
@@ -25,12 +25,12 @@ use crate::messages::tool::common_functionality::snapping::{SnapCache, SnapCandi
use crate::messages::tool::common_functionality::utility_functions::{calculate_segment_angle, find_two_param_best_approximate, make_path_editable_is_allowed};
use graphene_std::Color;
use graphene_std::renderer::Quad;
use graphene_std::subpath::pathseg_points;
use graphene_std::transform::ReferencePoint;
use graphene_std::uuid::NodeId;
use graphene_std::vector::algorithms::util::pathseg_tangent;
use graphene_std::vector::click_target::ClickTargetType;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2};
use graphene_std::vector::misc::pathseg_points;
use graphene_std::vector::misc::{HandleId, ManipulatorPointId, dvec2_to_point, point_to_dvec2, segment_to_handles};
use graphene_std::vector::{HandleExt, NoHashBuilder, PointId, SegmentId, Vector, VectorModificationType};
use kurbo::{DEFAULT_ACCURACY, ParamCurve, ParamCurveNearest, PathSeg, Rect};
use std::vec;
@@ -1647,7 +1647,7 @@ impl Fsm for PathToolFsmState {
let selected_state = shape_editor.selected_shape_state.entry(layer).or_default();
for (segment, _, start, end) in vector.segment_bezier_iter() {
for (segment, _, start, end) in vector.segment_iter() {
if selected_state.is_segment_selected(segment) {
selected_state.select_point(ManipulatorPointId::Anchor(start));
selected_state.select_point(ManipulatorPointId::Anchor(end));
@@ -1700,7 +1700,7 @@ impl Fsm for PathToolFsmState {
let selected_state = shape_editor.selected_shape_state.entry(layer).or_default();
for (segment, _, start, end) in vector.segment_bezier_iter() {
for (segment, _, start, end) in vector.segment_iter() {
let first_selected = selected_state.is_point_selected(ManipulatorPointId::Anchor(start));
let second_selected = selected_state.is_point_selected(ManipulatorPointId::Anchor(end));
if first_selected && second_selected {
@@ -1764,7 +1764,7 @@ impl Fsm for PathToolFsmState {
// The points which are part of only one segment will be rendered
let mut selected_segments_by_point: HashMap<PointId, Vec<SegmentId>> = HashMap::new();
for (segment_id, _bezier, start, end) in vector.segment_bezier_iter() {
for (segment_id, _, start, end) in vector.segment_iter() {
if focused_segments.contains(&segment_id) {
selected_segments_by_point.entry(start).or_default().push(segment_id);
selected_segments_by_point.entry(end).or_default().push(segment_id);
@@ -2764,7 +2764,7 @@ impl Fsm for PathToolFsmState {
let mut selected_points_by_segment = HashSet::new();
old_vector
.segment_bezier_iter()
.segment_iter()
.filter(|(segment, _, _, _)| layer_selection_state.is_segment_selected(*segment))
.for_each(|(_, _, start, end)| {
selected_points_by_segment.insert(start);
@@ -2781,7 +2781,7 @@ impl Fsm for PathToolFsmState {
let find_index = |id: PointId| new_vector.point_domain.iter().enumerate().find(|(_, (point_id, _))| *point_id == id).map(|(index, _)| index);
// Add segments which have selected ends
for ((segment_id, bezier, start, end), stroke) in old_vector.segment_bezier_iter().zip(old_vector.segment_domain.stroke().iter()) {
for (segment_id, segment, start, end) in old_vector.segment_iter() {
let both_ends_selected = layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(start)) && layer_selection_state.is_point_selected(ManipulatorPointId::Anchor(end));
let segment_selected = layer_selection_state.is_segment_selected(segment_id);
@@ -2791,7 +2791,7 @@ impl Fsm for PathToolFsmState {
error!("Point does not exist in point domain");
return PathToolFsmState::Ready;
};
new_vector.segment_domain.push(segment_id, start_index, end_index, bezier.handles, *stroke);
new_vector.segment_domain.push(segment_id, start_index, end_index, segment_to_handles(&segment));
}
}
@@ -2945,7 +2945,7 @@ impl Fsm for PathToolFsmState {
// Add all the selected points
let mut selected_points_by_segment = HashSet::new();
old_vector
.segment_bezier_iter()
.segment_iter()
.filter(|(segment, _, _, _)| layer_selection_state.is_segment_selected(*segment))
.for_each(|(_, _, start, end)| {
selected_points_by_segment.insert(start);
@@ -3398,7 +3398,7 @@ fn calculate_adjacent_anchor_tangent(currently_dragged_handle: ManipulatorPointI
0 => {
// Find non-shared segments
let non_shared_segment: Vec<_> = vector
.segment_bezier_iter()
.segment_iter()
.filter_map(|(segment_id, _, start, end)| {
let touches_adjacent = start == adjacent_anchor || end == adjacent_anchor;
let shares_with_dragged = start == dragged_handle_anchor || end == dragged_handle_anchor;
@@ -1,6 +1,6 @@
use super::tool_prelude::*;
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::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
@@ -18,11 +18,11 @@ use crate::messages::tool::common_functionality::stroke_options::{StrokeOptionsU
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::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};
use graphene_std::vector::{NoHashBuilder, PointId, SegmentId, Vector, VectorModificationType};
use kurbo::{BezPath, CubicBez, PathSeg};
#[derive(Default, ExtractField)]
pub struct PenTool {
@@ -1852,26 +1852,27 @@ impl Fsm for PenToolFsmState {
// We have the point. Join the 2 vertices and check if any path is closed.
if let Some(end) = closest_point {
let segment_id = SegmentId::generate();
vector.push(segment_id, start, end, (Some(handle_start), Some(handle_end)), StrokeId::ZERO);
vector.push(segment_id, start, end, (Some(handle_start), Some(handle_end)));
let grouped_segments = vector.auto_join_paths();
let closed_paths = grouped_segments.iter().filter(|path| path.is_closed() && path.contains(segment_id));
let subpaths: Vec<_> = closed_paths
.filter_map(|path| {
let segments = path.edges.iter().filter_map(|edge| {
vector
.segment_domain
.iter()
.find(|(id, _, _, _)| id == &edge.id)
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
});
vector.subpath_from_segments_ignore_discontinuities(segments)
})
.collect();
let mut fill_region = BezPath::new();
for path in closed_paths {
let segments = path.edges.iter().filter_map(|edge| {
vector
.segment_domain
.iter()
.find(|(id, _, _, _)| id == &edge.id)
.map(|(_, start, end, bezier)| if start == edge.start { (bezier, start, end) } else { (bezier.reversed(), end, start) })
});
if let Some(bezpath) = vector.bezpath_from_segments_ignore_discontinuities(segments) {
fill_region.extend(bezpath.elements().iter().copied());
}
}
let fill_color = COLOR_OVERLAY_BLUE_05;
overlay_context.fill_path(subpaths.iter(), transform, fill_color);
overlay_context.fill_path(&fill_region, transform, fill_color);
}
}
}
@@ -2,7 +2,7 @@
use super::tool_prelude::*;
use crate::consts::*;
use crate::messages::input_mapper::utility_types::input_mouse::ViewportPosition;
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
@@ -28,8 +28,8 @@ 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::algorithms::shapes::polyline_bezpath;
use graphene_std::vector::misc::BooleanOperation;
use graphene_std::vector::style::FillChoice;
use std::fmt;
@@ -575,7 +575,7 @@ impl SelectToolData {
if self.lasso_polygon.len() < 2 {
return Vec::new();
}
let polygon = Subpath::from_anchors(self.lasso_polygon.clone(), true);
let polygon = polyline_bezpath(self.lasso_polygon.iter().copied(), true);
document.intersect_polygon_no_artboards(polygon, viewport).collect()
}
@@ -583,7 +583,7 @@ impl SelectToolData {
if self.lasso_polygon.len() < 2 {
return false;
}
let polygon = Subpath::from_anchors(self.lasso_polygon.clone(), true);
let polygon = polyline_bezpath(self.lasso_polygon.iter().copied(), true);
document.is_layer_fully_inside_polygon(layer, viewport, polygon)
}
@@ -1,6 +1,6 @@
use super::tool_prelude::*;
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
use crate::messages::portfolio::document::overlays::utility_functions::path_endpoint_overlays;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
@@ -1,4 +1,4 @@
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
use crate::messages::input_mapper::utility_types::keyboard::Key;
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
use crate::messages::portfolio::document::utility_types::transformation::TransformType;
use crate::messages::prelude::*;
@@ -1,5 +1,5 @@
use crate::consts::{ANGLE_MEASURE_RADIUS_FACTOR, ARC_MEASURE_RADIUS_FACTOR_RANGE, COLOR_OVERLAY_BLUE, COLOR_OVERLAY_GRAY, SLOWING_DIVISOR};
use crate::messages::input_mapper::utility_types::input_mouse::{DocumentPosition, ViewportPosition};
use crate::messages::input_mapper::utility_types::pointer::{DocumentPosition, ViewportPosition};
use crate::messages::portfolio::document::overlays::utility_functions::text_width;
use crate::messages::portfolio::document::overlays::utility_types::{OverlayProvider, Pivot};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
@@ -162,7 +162,7 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
let selected_segments = shape_editor.selected_segments().collect::<HashSet<_>>();
let mut affected_points = shape_editor.selected_points().copied().collect::<Vec<_>>();
for (segment_id, _, start, end) in vector.segment_bezier_iter() {
for (segment_id, _, start, end) in vector.segment_iter() {
if selected_segments.contains(&segment_id) {
affected_points.push(ManipulatorPointId::Anchor(start));
affected_points.push(ManipulatorPointId::Anchor(end));
+1 -1
View File
@@ -4,7 +4,7 @@ use super::common_functionality::shape_editor::ShapeState;
use super::tool_messages::*;
use crate::messages::broadcast::BroadcastMessage;
use crate::messages::broadcast::event::EventMessage;
use crate::messages::input_mapper::utility_types::input_keyboard::{Key, KeysGroup, LabeledKeyOrMouseMotion, LabeledShortcut, MouseMotion};
use crate::messages::input_mapper::utility_types::keyboard::{Key, KeysGroup, LabeledKeyOrMouseMotion, LabeledShortcut, MouseMotion};
use crate::messages::input_mapper::utility_types::macros::action_shortcut;
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::widget_prelude::*;
+21 -21
View File
@@ -1,6 +1,6 @@
use crate::application::Editor;
use crate::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
use crate::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, MouseKeys, ScrollDelta, ViewportPosition};
use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys;
use crate::messages::input_mapper::utility_types::pointer::{EditorPointerState, MouseKeys, ViewportPosition};
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::tool_prelude::Key;
@@ -105,7 +105,7 @@ impl EditorTestUtils {
self.move_mouse(position.x, position.y, modifier_keys, MouseKeys::empty()).await;
self.mousedown(
EditorMouseState {
EditorPointerState {
editor_position: position,
mouse_keys: button,
..Default::default()
@@ -115,7 +115,7 @@ impl EditorTestUtils {
.await;
self.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: position,
..Default::default()
},
@@ -134,10 +134,10 @@ impl EditorTestUtils {
self.move_mouse(x2, y2, modifier_keys, MouseKeys::LEFT).await;
self.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: (x2, y2).into(),
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
modifier_keys,
)
@@ -154,10 +154,10 @@ impl EditorTestUtils {
self.move_mouse(100., 100., ModifierKeys::default(), MouseKeys::LEFT).await;
self.mousedown(
EditorMouseState {
EditorPointerState {
editor_position: (100., 100.).into(),
mouse_keys: MouseKeys::LEFT | MouseKeys::RIGHT,
scroll_delta: ScrollDelta::default(),
..Default::default()
},
ModifierKeys::default(),
)
@@ -173,7 +173,7 @@ impl EditorTestUtils {
}
pub async fn move_mouse(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys, mouse_keys: MouseKeys) {
let editor_mouse_state = EditorMouseState {
let editor_mouse_state = EditorPointerState {
editor_position: ViewportPosition::new(x, y),
mouse_keys,
..Default::default()
@@ -181,11 +181,11 @@ impl EditorTestUtils {
self.input(InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }).await;
}
pub async fn mousedown(&mut self, editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys) {
pub async fn mousedown(&mut self, editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys) {
self.input(InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }).await;
}
pub async fn mouseup(&mut self, editor_mouse_state: EditorMouseState, modifier_keys: ModifierKeys) {
pub async fn mouseup(&mut self, editor_mouse_state: EditorPointerState, modifier_keys: ModifierKeys) {
self.handle_message(InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }).await;
}
@@ -198,10 +198,10 @@ impl EditorTestUtils {
pub async fn left_mousedown(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
self.mousedown(
EditorMouseState {
EditorPointerState {
editor_position: (x, y).into(),
mouse_keys: MouseKeys::LEFT,
scroll_delta: ScrollDelta::default(),
..Default::default()
},
modifier_keys,
)
@@ -210,10 +210,10 @@ impl EditorTestUtils {
pub async fn left_mouseup(&mut self, x: f64, y: f64, modifier_keys: ModifierKeys) {
self.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: (x, y).into(),
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
modifier_keys,
)
@@ -266,10 +266,10 @@ impl EditorTestUtils {
pub async fn double_click(&mut self, position: DVec2) {
self.handle_message(InputPreprocessorMessage::DoubleClick {
editor_mouse_state: EditorMouseState {
editor_mouse_state: EditorPointerState {
editor_position: position,
mouse_keys: MouseKeys::LEFT,
scroll_delta: ScrollDelta::default(),
..Default::default()
},
modifier_keys: ModifierKeys::empty(),
})
@@ -290,10 +290,10 @@ impl EditorTestUtils {
}
self.mouseup(
EditorMouseState {
EditorPointerState {
editor_position: points[points.len() - 1],
mouse_keys: MouseKeys::empty(),
scroll_delta: ScrollDelta::default(),
..Default::default()
},
modifier_keys,
)
@@ -352,8 +352,8 @@ pub mod test_prelude {
pub use crate::application::Editor;
pub use crate::float_eq;
pub use crate::messages::clipboard::utility_types::ClipboardContentRaw;
pub use crate::messages::input_mapper::utility_types::input_keyboard::{Key, ModifierKeys};
pub use crate::messages::input_mapper::utility_types::input_mouse::MouseKeys;
pub use crate::messages::input_mapper::utility_types::keyboard::{Key, ModifierKeys};
pub use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
pub use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
pub use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
pub use crate::messages::prelude::*;
+1
View File
@@ -3,3 +3,4 @@ wrapper/pkg/
wrapper/pkg-native/
public/build/
dist/
node_modules.locked-*/
@@ -12,31 +12,11 @@
export let tooltipShortcut: ActionShortcut | undefined = undefined;
// Callbacks
export let action: (index: number) => void;
function truncate(label: string): string {
let maxLength = 40;
if (label.length <= maxLength) return label;
let truncated = label;
const hasQuotes = label.startsWith(`"`) && label.endsWith(`"`);
if (hasQuotes) {
truncated = label.slice(1, -1);
maxLength -= 2;
}
truncated = truncated.slice(0, maxLength - 1) + "…";
if (hasQuotes) truncated = `"${truncated}"`;
return truncated;
}
</script>
<LayoutRow class="breadcrumb-trail-buttons" {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
{#each labels as label, index}
<TextButton label={truncate(label)} emphasized={index === labels.length - 1} {disabled} action={() => !disabled && index !== labels.length - 1 && action(index)} />
<TextButton {label} emphasized={index === labels.length - 1} {disabled} action={() => !disabled && index !== labels.length - 1 && action(index)} />
{/each}
</LayoutRow>
@@ -205,6 +205,10 @@
textarea {
color: var(--color-8-uppergray);
}
input {
pointer-events: none;
}
}
}
</style>
@@ -19,6 +19,8 @@
export let italic = false;
export let monospace = false;
export let multiline = false;
export let enquote = false;
export let selectable = false;
export let centerAlign = false;
export let tableAlign = false;
// Sizing
@@ -76,6 +78,8 @@
class:italic
class:monospace
class:multiline
class:enquote
class:selectable
class:center-align={centerAlign}
class:table-align={tableAlign}
style:min-width={minWidthCharacters ? `${minWidthCharacters}ch` : minWidth > 0 ? `${minWidth}px` : undefined}
@@ -125,6 +129,17 @@
margin: 4px 0;
}
&.enquote::before,
&.enquote::after {
content: '"';
user-select: none;
}
&.selectable {
user-select: text;
cursor: text;
}
&.center-align {
text-align: center;
}
+15
View File
@@ -128,6 +128,7 @@ export function onPointerMove(e: PointerEvent, editor: EditorWrapper, documentSt
export function onPointerDown(e: PointerEvent, editor: EditorWrapper, dialogStore: DialogStore) {
potentiallyRestoreCanvasFocus(e);
potentiallyClearTextSelection(e);
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
const isTargetingCanvas = !inFloatingMenu && e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
@@ -351,6 +352,20 @@ function targetIsTextField(target: EventTarget | HTMLElement | undefined): boole
);
}
function potentiallyClearTextSelection(e: PointerEvent) {
const target = e.target instanceof Element ? e.target : undefined;
if (target && (targetIsTextField(target) || window.getComputedStyle(target).userSelect !== "none")) return;
// A text control's selection lives in its shadow tree, which the document's `Selection` reports as collapsed and cannot clear, so each control holding one is collapsed through its own API
const controls = window.document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>("textarea, input[type='text']");
controls.forEach((control) => {
const caret = control.selectionStart;
if (typeof caret === "number" && caret !== control.selectionEnd) control.setSelectionRange(caret, caret);
});
window.getSelection()?.removeAllRanges();
}
function potentiallyRestoreCanvasFocus(e: Event) {
const appElement = window.document.querySelector("[data-app-container]");
const app = appElement instanceof HTMLElement ? appElement : undefined;
+8 -8
View File
@@ -15,8 +15,8 @@ use wasm_bindgen::prelude::*;
mod editor_commands {
use crate::helpers::translate_key;
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::input_mapper::utility_types::keyboard::ModifierKeys;
use editor::messages::input_mapper::utility_types::pointer::{EditorPointerState, ScrollDelta};
use editor::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
@@ -300,14 +300,14 @@ mod editor_commands {
/// Mouse movement within the screenspace bounds of the viewport
fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys }.into()
}
/// Mouse scrolling within the screenspace bounds of the viewport
fn on_wheel_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) -> Message {
let mut editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let mut editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys }.into()
@@ -315,28 +315,28 @@ mod editor_commands {
/// A mouse button depressed within screenspace the bounds of the viewport
fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys }.into()
}
/// A mouse button released
fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys }.into()
}
/// Mouse shaken
fn on_mouse_shake(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys }.into()
}
/// Mouse double clicked
fn on_double_click(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Message {
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let editor_mouse_state = EditorPointerState::from_keys_and_editor_position(mouse_keys, (x, y).into());
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
}
+1 -1
View File
@@ -8,7 +8,7 @@ use crate::native_communication::RasterizedImage;
#[cfg(not(feature = "native"))]
use editor::application::Editor;
#[cfg(feature = "editor")]
use editor::messages::input_mapper::utility_types::input_keyboard::Key;
use editor::messages::input_mapper::utility_types::keyboard::Key;
#[cfg(not(feature = "native"))]
use editor::messages::prelude::*;
use js_sys::{Object, Reflect};
@@ -153,6 +153,9 @@ async fn drain_queue(inner: Arc<Mutex<Inner>>) {
Mutation::Write { hash, bytes } => {
if let Err(error) = write_file(&directory, &hash, &bytes).await {
log::error!("OPFS write for {hash} failed: {error:?}");
// Nothing reached disk, so leaving the hash listed would claim a file that later sessions cannot read
inner.lock().unwrap().on_disk.remove(&hash);
}
}
Mutation::Delete { hash } => {
@@ -390,7 +390,6 @@ macro_rules! tagged_value {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
let name = concrete_type.name.as_ref();
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
if name == std::any::type_name::<()>() { return Some(TaggedValue::None) }
if name == std::any::type_name::<Gradient>() { return Some(TaggedValue::GradientRamp(GradientRamp::default())) }
@@ -671,7 +670,6 @@ impl TaggedValue {
Type::Concrete(concrete_type) => {
let ty = concrete_type.id?;
use std::any::TypeId;
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
// Tries using the default for the tagged value type. If it not implemented, then uses the default used in document_node_types. If it is not used there, then TaggedValue::None is returned.
let ty = match () {
() if ty == TypeId::of::<()>() => TaggedValue::None,
-1
View File
@@ -7,7 +7,6 @@ pub use core_types::{ProtoNodeIdentifier, Type, TypeDescriptor, concrete, descri
pub mod application_io;
pub mod document;
pub mod runtime_delta;
pub use document::{DocumentNode, NodeNetwork};
pub mod graphene_compiler;
pub mod proto;
@@ -1,40 +0,0 @@
use crate::document::{DocumentNode, NodeId, NodeInput};
/// One mutation's worth of structural graph change, carrying its post-change data as plain runtime
/// types. Constructed by the mutation itself; a compound mutation emits several. Consumed typed and
/// unserialized by the compiler, and paired with `EditorDelta` metadata for storage staging.
#[derive(Debug, Clone, PartialEq)]
pub enum RuntimeDelta {
/// The node's nested network, if it implements one, rides inside the `DocumentNode`.
AddNode {
network_path: Vec<NodeId>,
node_id: NodeId,
node: Box<DocumentNode>,
},
ReplaceNode {
network_path: Vec<NodeId>,
node_id: NodeId,
node: Box<DocumentNode>,
},
/// Address-only: removal snapshots come from the storage layer's working registry.
RemoveNode {
network_path: Vec<NodeId>,
node_id: NodeId,
},
SetInput {
network_path: Vec<NodeId>,
node_id: NodeId,
input_index: usize,
input: NodeInput,
},
SetExport {
network_path: Vec<NodeId>,
export_index: usize,
input: NodeInput,
},
SetVisibility {
network_path: Vec<NodeId>,
node_id: NodeId,
visible: bool,
},
}
@@ -0,0 +1,71 @@
use std::fmt::Write;
/// Recovers the intended number from floating point imprecision noise when that can be done reliably, e.g. 0.30000000000000004 -> 0.3.
/// Rounding to each significant digit count from 1 to 12, the first candidate within a relative 1e-13 of the original is accepted.
/// Actual high-precision values (like 0.3333333333333333) never pass the tolerance and are returned unchanged.
/// f64 only, as f32 lacks precision to reliably distinguish between intentional digits and noise.
pub fn round_away_float_noise(value: f64) -> f64 {
if value == 0. || !value.is_finite() {
return if value == 0. { 0. } else { value };
}
// Candidates come from decimal formatting rather than scaling by a power of ten, which is inexact enough to invent
// noise of its own: it turns 1e300 into 9.999999999999999e299 and 999999.9999999 into 999999.9999999999.
// One buffer serves every candidate, since the digit counts are tried in turn.
let mut buffer = String::with_capacity(32);
for significant_digits in 1..=12 {
buffer.clear();
let _ = write!(buffer, "{value:.*e}", significant_digits - 1);
let Ok(rounded) = buffer.parse::<f64>() else { continue };
if ((rounded - value) / value).abs() < 1e-13 {
return rounded;
}
}
value
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_away_float_noise_snaps_noisy_values() {
assert_eq!(round_away_float_noise(0.1 + 0.2), 0.3);
assert_eq!(round_away_float_noise(0.3000000000000012), 0.3);
assert_eq!(round_away_float_noise(2.99999999999993), 3.);
assert_eq!(round_away_float_noise(45.00000000000001), 45.);
}
#[test]
fn round_away_float_noise_keeps_honest_values() {
assert_eq!(round_away_float_noise(1. / 3.), 1. / 3.);
assert_eq!(round_away_float_noise(0.2394023940209349), 0.2394023940209349);
assert_eq!(round_away_float_noise(0.25), 0.25);
assert_eq!(round_away_float_noise(-17.5), -17.5);
}
#[test]
fn round_away_float_noise_keeps_deliberate_values_with_zero_runs() {
assert_eq!(round_away_float_noise(0.30000005), 0.30000005);
assert_eq!(round_away_float_noise(0.3000000000001), 0.3000000000001);
assert_eq!(round_away_float_noise(1.00000001), 1.00000001);
assert_eq!(round_away_float_noise(2.9999993), 2.9999993);
}
#[test]
fn round_away_float_noise_normalizes_zero() {
let result = round_away_float_noise(-0.);
assert_eq!(result, 0.);
assert!(result.is_sign_positive());
}
#[test]
fn round_away_float_noise_keeps_extreme_magnitudes_exact() {
assert_eq!(round_away_float_noise(1e300), 1e300);
assert_eq!(round_away_float_noise(1.5e300), 1.5e300);
assert_eq!(round_away_float_noise(1e-300), 1e-300);
assert_eq!(round_away_float_noise(f64::MIN_POSITIVE), f64::MIN_POSITIVE);
}
}
@@ -1,4 +1,5 @@
pub mod bbox;
pub mod float_noise;
pub mod polynomial;
pub mod quad;
pub mod rect;
@@ -1,10 +1,9 @@
use kurbo::PathSeg;
use std::fmt::{self, Display, Formatter};
use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use std::ops::{Mul, MulAssign};
/// A struct that represents a polynomial with a maximum degree of `N-1`.
///
/// It provides basic mathematical operations for polynomials like addition, multiplication, differentiation, integration, etc.
/// It provides basic mathematical operations for polynomials like multiplication, differentiation, integration, etc.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Polynomial<const N: usize> {
coefficients: [f64; N],
@@ -18,18 +17,6 @@ impl<const N: usize> Polynomial<N> {
Polynomial { coefficients }
}
/// Create a polynomial where all its coefficients are zero.
pub fn zero() -> Polynomial<N> {
Polynomial { coefficients: [0.; N] }
}
/// Return an immutable reference to the coefficients.
///
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
pub fn coefficients(&self) -> &[f64; N] {
&self.coefficients
}
/// Return a mutable reference to the coefficients.
///
/// The coefficient for nth degree is at the nth index in array. Therefore the order of coefficients are reversed than the usual order for writing polynomials mathematically.
@@ -83,98 +70,6 @@ impl<const N: usize> Polynomial<N> {
ans.derivative_mut();
ans
}
/// Computes the antiderivative at `C = 0`.
///
/// Returns `None` if the polynomial is not big enough to accommodate the extra degree.
pub fn antiderivative(&self) -> Option<Polynomial<N>> {
let mut ans = *self;
ans.antiderivative_mut()?;
Some(ans)
}
}
impl<const N: usize> Default for Polynomial<N> {
fn default() -> Self {
Self::zero()
}
}
impl<const N: usize> Display for Polynomial<N> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
let mut first = true;
for (index, coefficient) in self.coefficients.iter().enumerate().rev().filter(|&(_, &coefficient)| coefficient != 0.) {
if first {
first = false;
} else {
f.write_str(" + ")?
}
coefficient.fmt(f)?;
if index == 0 {
continue;
}
f.write_str("x")?;
if index == 1 {
continue;
}
f.write_str("^")?;
index.fmt(f)?;
}
Ok(())
}
}
impl<const N: usize> AddAssign<&Polynomial<N>> for Polynomial<N> {
fn add_assign(&mut self, rhs: &Polynomial<N>) {
self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a += b);
}
}
impl<const N: usize> Add for &Polynomial<N> {
type Output = Polynomial<N>;
fn add(self, other: &Polynomial<N>) -> Polynomial<N> {
let mut output = *self;
output += other;
output
}
}
impl<const N: usize> Neg for &Polynomial<N> {
type Output = Polynomial<N>;
fn neg(self) -> Polynomial<N> {
let mut output = *self;
output.coefficients.iter_mut().for_each(|x| *x = -*x);
output
}
}
impl<const N: usize> Neg for Polynomial<N> {
type Output = Polynomial<N>;
fn neg(mut self) -> Polynomial<N> {
self.coefficients.iter_mut().for_each(|x| *x = -*x);
self
}
}
impl<const N: usize> SubAssign<&Polynomial<N>> for Polynomial<N> {
fn sub_assign(&mut self, rhs: &Polynomial<N>) {
self.coefficients.iter_mut().zip(rhs.coefficients.iter()).for_each(|(a, b)| *a -= b);
}
}
impl<const N: usize> Sub for &Polynomial<N> {
type Output = Polynomial<N>;
fn sub(self, other: &Polynomial<N>) -> Polynomial<N> {
let mut output = *self;
output -= other;
output
}
}
impl<const N: usize> MulAssign<&Polynomial<N>> for Polynomial<N> {
@@ -248,18 +143,6 @@ mod test {
assert_eq!(p2.as_size::<2>(), None);
}
#[test]
fn addition_and_subtaction() {
let p1 = Polynomial::new([1., 2., 3.]);
let p2 = Polynomial::new([4., 5., 6.]);
let addition = Polynomial::new([5., 7., 9.]);
let subtraction = Polynomial::new([-3., -3., -3.]);
assert_eq!(&p1 + &p2, addition);
assert_eq!(&p1 - &p2, subtraction);
}
#[test]
fn multiplication() {
let p1 = Polynomial::new([1., 2., 3.]).as_size().unwrap();
@@ -278,15 +161,10 @@ mod test {
assert_eq!(p.derivative(), p_deriv);
p.coefficients_mut()[0] = 0.;
assert_eq!(p_deriv.antiderivative().unwrap(), p);
let mut antiderivative = p_deriv;
assert_eq!(antiderivative.antiderivative_mut(), Some(()));
assert_eq!(antiderivative, p);
assert_eq!(p.antiderivative(), None);
}
#[test]
fn display() {
let p = Polynomial::new([1., 2., 0., 3.]);
assert_eq!(format!("{p:.2}"), "3.00x^3 + 2.00x + 1.00");
assert_eq!(p.antiderivative_mut(), None);
}
}
@@ -36,13 +36,6 @@ impl Rect {
bounds
}
/// Get all the edges in the rect.
#[must_use]
pub fn edges(&self) -> [[DVec2; 2]; 4] {
let corners = [self[0], DVec2::new(self[0].x, self[1].y), self[1], DVec2::new(self[1].y, self[0].x)];
[[corners[0], corners[1]], [corners[1], corners[2]], [corners[2], corners[3]], [corners[3], corners[0]]]
}
/// Gets the center of a rect
#[must_use]
pub fn center(&self) -> DVec2 {
+20 -4
View File
@@ -1,6 +1,7 @@
use crate::Node;
use crate::math::float_noise::round_away_float_noise;
use crate::transform::Footprint;
use glam::DVec2;
use glam::{DAffine2, DVec2};
use std::future::Future;
use std::marker::PhantomData;
@@ -45,11 +46,26 @@ pub trait Convert<T, C>: Sized {
fn convert(self, footprint: Footprint, converter: C) -> impl Future<Output = T> + Send;
}
impl<T: ToString + Send> Convert<String, ()> for T {
/// Converts this type into a `String` using its `ToString` implementation.
/// Implements the [`Convert`] trait for formatting a type into a `String` via [`ToString`].
macro_rules! impl_convert_to_string {
($($from:ty),* $(,)?) => {
$(
impl Convert<String, ()> for $from {
#[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string()
}
}
)*
};
}
impl_convert_to_string!(f32, u32, u64, i32, i64, bool, DVec2, DAffine2);
// Denoised so 0.1 + 0.2 reaches the string as "0.3" rather than "0.30000000000000004"
impl Convert<String, ()> for f64 {
#[inline]
async fn convert(self, _: Footprint, _converter: ()) -> String {
self.to_string()
round_away_float_noise(self).to_string()
}
}
@@ -24,7 +24,7 @@ pub mod migrations {
use core_types::Color;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use vector_types::vector::{PointDomain, RegionDomain, SegmentDomain, misc::HandleId, style::Stroke};
use vector_types::vector::{PointDomain, SegmentDomain, misc::HandleId, style::Stroke};
use vector_types::{GradientRamp, Vector, vector};
#[derive(Default, Debug, Clone, PartialEq, graphene_hash::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
@@ -111,7 +111,6 @@ pub mod migrations {
pub colinear_manipulators: Vec<[HandleId; 2]>,
pub point_domain: PointDomain,
pub segment_domain: SegmentDomain,
pub region_domain: RegionDomain,
}
#[derive(serde::Deserialize)]
@@ -142,7 +141,6 @@ pub mod migrations {
colinear_manipulators: old.colinear_manipulators,
point_domain: old.point_domain,
segment_domain: old.segment_domain,
region_domain: old.region_domain,
}),
VectorFormat::Vector(vector) => Some(vector),
VectorFormat::List(list) => list.element.into_iter().next(),
@@ -1,47 +1,35 @@
use glam::DVec2;
use vector_types::subpath::{ManipulatorGroup, Subpath};
use vector_types::vector::PointId;
use kurbo::{BezPath, Point};
pub fn convert_usvg_path(path: &usvg::Path) -> Vec<Subpath<PointId>> {
let mut subpaths = Vec::new();
let mut manipulators_list = Vec::new();
pub fn convert_usvg_path(path: &usvg::Path) -> BezPath {
let mut bezpath = BezPath::new();
let mut points = path.data().points().iter();
let to_vec = |p: &usvg::tiny_skia_path::Point| DVec2::new(p.x as f64, p.y as f64);
let to_point = |p: &usvg::tiny_skia_path::Point| Point::new(p.x as f64, p.y as f64);
for verb in path.data().verbs() {
match verb {
usvg::tiny_skia_path::PathVerb::Move => {
subpaths.push(Subpath::new(std::mem::take(&mut manipulators_list), false));
let Some(start) = points.next().map(to_vec) else { continue };
manipulators_list.push(ManipulatorGroup::new(start, Some(start), Some(start)));
let Some(start) = points.next().map(to_point) else { continue };
bezpath.move_to(start);
}
usvg::tiny_skia_path::PathVerb::Line => {
let Some(end) = points.next().map(to_vec) else { continue };
manipulators_list.push(ManipulatorGroup::new(end, Some(end), Some(end)));
let Some(end) = points.next().map(to_point) else { continue };
bezpath.line_to(end);
}
usvg::tiny_skia_path::PathVerb::Quad => {
let Some(handle) = points.next().map(to_vec) else { continue };
let Some(end) = points.next().map(to_vec) else { continue };
if let Some(last) = manipulators_list.last_mut() {
last.out_handle = Some(last.anchor + (2. / 3.) * (handle - last.anchor));
}
manipulators_list.push(ManipulatorGroup::new(end, Some(end + (2. / 3.) * (handle - end)), Some(end)));
let Some(handle) = points.next().map(to_point) else { continue };
let Some(end) = points.next().map(to_point) else { continue };
bezpath.quad_to(handle, end);
}
usvg::tiny_skia_path::PathVerb::Cubic => {
let Some(first_handle) = points.next().map(to_vec) else { continue };
let Some(second_handle) = points.next().map(to_vec) else { continue };
let Some(end) = points.next().map(to_vec) else { continue };
if let Some(last) = manipulators_list.last_mut() {
last.out_handle = Some(first_handle);
}
manipulators_list.push(ManipulatorGroup::new(end, Some(second_handle), Some(end)));
}
usvg::tiny_skia_path::PathVerb::Close => {
subpaths.push(Subpath::new(std::mem::take(&mut manipulators_list), true));
let Some(first_handle) = points.next().map(to_point) else { continue };
let Some(second_handle) = points.next().map(to_point) else { continue };
let Some(end) = points.next().map(to_point) else { continue };
bezpath.curve_to(first_handle, second_handle, end);
}
usvg::tiny_skia_path::PathVerb::Close => bezpath.close_path(),
}
}
subpaths.push(Subpath::new(manipulators_list, false));
subpaths
bezpath
}
+59 -44
View File
@@ -24,11 +24,11 @@ use graphene_hash::CacheHashWrapper;
use graphene_resource::Resource;
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster, Texture};
use graphic_types::vector_types::gradient::{Gradient, GradientForm};
use graphic_types::vector_types::subpath::Subpath;
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint};
use graphic_types::vector_types::vector::misc::dvec2_to_point;
use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
use graphic_types::{Appearance, Artboard, Cover, Coverage, FillAndStroke, Graphic, Vector};
use kurbo::{Affine, BezPath, Cap, Join, Shape, StrokeOpts};
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape, StrokeOpts};
use num_traits::Zero;
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
@@ -475,11 +475,9 @@ fn get_outline_styles(render_params: &RenderParams) -> (kurbo::Stroke, peniko::C
}
fn draw_raster_outline(scene: &mut Scene, outline_transform: &DAffine2, render_params: &RenderParams) {
use graphic_types::vector_types::vector::PointId;
let (outline_stroke, outline_color_peniko) = get_outline_styles(render_params);
let mut outline_path = Subpath::<PointId>::new_rectangle(DVec2::ZERO, DVec2::ONE).to_bezpath();
let mut outline_path = rectangle_path(DVec2::ZERO, DVec2::ONE);
outline_path.apply_affine(Affine::new(outline_transform.to_cols_array()));
scene.stroke(&outline_stroke, Affine::IDENTITY, outline_color_peniko, None, &outline_path);
@@ -1361,8 +1359,9 @@ impl Render for List<Artboard> {
let element_id = layer_path.iter_element_values().next_back().copied();
if let Some(element_id) = element_id {
let subpath = Subpath::new_rectangle(DVec2::ZERO, dimensions);
metadata.click_targets.insert(element_id, vec![ClickTarget::new_with_subpath(subpath, 0.).into()]);
metadata
.click_targets
.insert(element_id, vec![ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, dimensions), 0.).into()]);
metadata.upstream_footprints.insert(element_id, footprint);
metadata.local_transforms.insert(element_id, DAffine2::from_translation(location));
if clip {
@@ -1381,8 +1380,7 @@ impl Render for List<Artboard> {
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>, _inherited_appearance: Option<&Appearance>) {
for index in 0..self.len() {
let dimensions: DVec2 = self.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
let subpath_rectangle = Subpath::new_rectangle(DVec2::ZERO, dimensions);
click_targets.push(ClickTarget::new_with_subpath(subpath_rectangle, 0.));
click_targets.push(ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, dimensions), 0.));
}
}
@@ -1485,7 +1483,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &
MaskType::Mask
};
let path_is_closed = vector.stroke_bezier_paths().all(|path| path.closed());
let path_is_closed = vector.stroke_bezpath_iter().all(|path| matches!(path.elements().last(), Some(PathEl::ClosePath)));
let can_draw_aligned_stroke = path_is_closed
&& stroke_params.as_ref().is_some_and(|stroke| stroke.has_renderable_stroke() && stroke.align.is_not_centered())
&& stroke_paint.is_some_and(|graphic| !graphic.is_guaranteed_fully_transparent());
@@ -1524,7 +1522,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &
});
if use_face_fill {
for mut face_path in vector.construct_faces().filter(|face| face.area() >= 0.) {
for mut face_path in vector.construct_faces() {
face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
let face_d = face_path.to_svg();
@@ -1614,10 +1612,6 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, render: &
attributes.push_val(stroke_shape_attribute);
attributes.push_val(stroke_attribute);
if vector.is_branching() && !use_face_fill {
attributes.push("fill-rule", "evenodd");
}
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
if opacity < 1. {
attributes.push("opacity", opacity.to_string());
@@ -1749,7 +1743,9 @@ fn render_vector_item_to_vello(
// the function ignores the arg for Center align) and the `SrcIn`/`SrcOut` aligned-stroke branch further down.
let stroke = stroke_params.as_ref();
let stroke_fully_transparent = stroke_paint.is_none_or(|paint| paint.is_guaranteed_fully_transparent());
let can_draw_aligned_stroke = !stroke_fully_transparent && stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered()) && element.stroke_bezier_paths().all(|p| p.closed());
let can_draw_aligned_stroke = !stroke_fully_transparent
&& stroke.is_some_and(|s| s.has_renderable_stroke() && s.align.is_not_centered())
&& element.stroke_bezpath_iter().all(|p| matches!(p.elements().last(), Some(PathEl::ClosePath)));
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
let needs_blend_layer = opacity < 1. || blend_mode_attr != BlendMode::default();
@@ -1848,11 +1844,10 @@ fn render_vector_item_to_vello(
};
};
// Branching vectors without regions (e.g. mesh grids) need face-by-face fill rendering.
let use_face_fill = element.use_face_fill();
let do_fill = |scene: &mut Scene, context: &mut RenderContext| {
if use_face_fill {
for mut face_path in element.construct_faces().filter(|face| face.area() >= 0.) {
for mut face_path in element.construct_faces() {
face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
let mut kurbo_path = kurbo::BezPath::new();
for element in face_path {
@@ -1860,8 +1855,6 @@ fn render_vector_item_to_vello(
}
do_fill_path(scene, context, &kurbo_path, peniko::Fill::NonZero);
}
} else if element.is_branching() {
do_fill_path(scene, context, &path, peniko::Fill::EvenOdd);
} else {
do_fill_path(scene, context, &path, peniko::Fill::NonZero);
}
@@ -2210,20 +2203,20 @@ impl Render for List<Vector> {
}
}
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
/// Build one multi-contour `Path` (non-zero fill rule, so holes like the inside of an "O" work
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, appearance: Option<&Appearance>, geometry: &Vector, transform: DAffine2) {
// A coverage whose paint is `Graphic::None` exists but paints nothing, so it does not close subpaths for hit testing
let filled = appearance.is_some_and(|appearance| appearance.has_painted_cover(Cover::Fill));
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
let mut bezpaths: Vec<BezPath> = geometry.stroke_bezpath_iter().filter(|bezpath| !bezpath.elements().is_empty()).collect();
let all_contours_closed = bezpaths.iter().all(|bezpath| matches!(bezpath.elements().last(), Some(PathEl::ClosePath)));
// Inside/Outside-aligned strokes reach `weight` from the centerline rather than `weight / 2` per side,
// so they need double the click inflation. Alignment is only honored by the renderer for fully-closed paths.
let stroke_width = appearance.and_then(|appearance| appearance.first_coverage_of(Cover::Stroke)).map_or(0., |coverage| {
let stroke = coverage.stroke_params();
if stroke.align.is_not_centered() && all_subpaths_closed {
if stroke.align.is_not_centered() && all_contours_closed {
stroke.weight * 2.
} else {
stroke.weight
@@ -2231,13 +2224,20 @@ fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, appearance: Option
});
if filled {
for subpath in &mut subpaths {
subpath.set_closed(true);
for bezpath in &mut bezpaths {
if !matches!(bezpath.elements().last(), Some(PathEl::ClosePath)) {
bezpath.close_path();
}
}
}
if !subpaths.is_empty() {
let mut click_target = ClickTarget::new_with_compound_path(subpaths, stroke_width);
if !bezpaths.is_empty() {
let mut combined_path = BezPath::new();
for bezpath in bezpaths {
combined_path.extend(bezpath);
}
let mut click_target = ClickTarget::new_with_path(combined_path, stroke_width);
click_target.apply_transform(transform);
targets.push(click_target);
}
@@ -2412,9 +2412,9 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut S
/// plus the first item's transform and any merged-layers snapshot when a first item exists.
fn collect_raster_metadata<T>(first_row: Option<ItemRef<'_, T>>, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
let Some(element_id) = element_id else { return };
let subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
metadata.click_targets.insert(element_id, vec![ClickTarget::new_with_subpath(subpath, 0.).into()]);
metadata
.click_targets
.insert(element_id, vec![ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, DVec2::ONE), 0.).into()]);
metadata.upstream_footprints.insert(element_id, footprint);
// TODO: Find a way to handle more than one item of the `List<Raster<...>>`
if let Some(item) = first_row {
@@ -2437,10 +2437,10 @@ fn collect_raster_metadata<T>(first_row: Option<ItemRef<'_, T>>, metadata: &mut
/// Adds the unit-square click target every raster item presents, placed by the item's transform.
fn add_unit_square_click_target(transform: DAffine2, click_targets: &mut Vec<ClickTarget>) {
// The unit square is the raster's own space, so its placement only exists in the item transform
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
subpath.apply_transform(transform);
let mut path = rectangle_path(DVec2::ZERO, DVec2::ONE);
path.apply_affine(Affine::new(transform.to_cols_array()));
click_targets.push(ClickTarget::new_with_subpath(subpath, 0.));
click_targets.push(ClickTarget::new_with_path(path, 0.));
}
impl Render for List<Raster<CPU>> {
@@ -2630,11 +2630,28 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut Scene, rende
}
}
/// The closed rectangular path spanning the two opposite corners, used for the box-shaped click targets.
fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(kurbo::DEFAULT_ACCURACY)
}
/// A gradient's control geometry in its local space: the unit circle a radial gradient's transform carries to its drawn ellipse, or the (0,0) to (1,0) gradient line for a linear one.
fn gradient_control_outline(gradient_form: GradientForm) -> Subpath<graphic_types::vector_types::vector::PointId> {
fn gradient_control_outline(gradient_form: GradientForm) -> BezPath {
match gradient_form {
GradientForm::Linear => Subpath::new_line(DVec2::ZERO, DVec2::X),
GradientForm::Radial => Subpath::new_ellipse(DVec2::splat(-1.), DVec2::splat(1.)),
GradientForm::Linear => BezPath::from_path_segments(std::iter::once(kurbo::PathSeg::Line(kurbo::Line::new(dvec2_to_point(DVec2::ZERO), dvec2_to_point(DVec2::X))))),
GradientForm::Radial => {
// Four-cubic kappa circle with anchors on the axes, so the tight bounding box is exactly the unit square
// <https://en.wikipedia.org/wiki/Composite_B%C3%A9zier_curve#Using_four_curves>
const KAPPA: f64 = 4. / 3. * (std::f64::consts::SQRT_2 - 1.);
let mut path = BezPath::new();
path.move_to((1., 0.));
path.curve_to((1., KAPPA), (KAPPA, 1.), (0., 1.));
path.curve_to((-KAPPA, 1.), (-1., KAPPA), (-1., 0.));
path.curve_to((-1., -KAPPA), (-KAPPA, -1.), (0., -1.));
path.curve_to((KAPPA, -1.), (1., -KAPPA), (1., 0.));
path.close_path();
path
}
}
}
@@ -2867,7 +2884,7 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, G
// The first item's transform is the reference all targets bake against
let item_zero_inverse = *item_zero_inverse.get_or_insert_with(|| if transform_is_invertible(item_transform) { item_transform.inverse() } else { DAffine2::IDENTITY });
let mut target = ClickTarget::new_with_subpath(gradient_control_outline(gradient_form), 0.);
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
target.apply_transform(item_zero_inverse * item_transform);
let target = Arc::new(target);
@@ -2895,7 +2912,7 @@ fn add_gradient_item_click_targets(item: ItemRef<'_, Gradient>, click_targets: &
}
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut target = ClickTarget::new_with_subpath(gradient_control_outline(gradient_form), 0.);
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
target.apply_transform(transform);
click_targets.push(target);
}
@@ -2905,7 +2922,7 @@ fn add_gradient_item_outline_targets(item: ItemRef<'_, Gradient>, outlines: &mut
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut target = ClickTarget::new_with_subpath(gradient_control_outline(gradient_form), 0.);
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
target.apply_transform(transform);
outlines.push(target);
}
@@ -3273,8 +3290,7 @@ fn collect_text_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, Strin
}
let Some((size, item_transform)) = text_item_size_and_transform(item) else { continue };
let subpath = Subpath::new_rectangle(DVec2::ZERO, size);
let mut target = ClickTarget::new_with_subpath(subpath, 0.);
let mut target = ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, size), 0.);
target.apply_transform(item_zero_inverse * item_transform);
accumulated_click_targets.entry(element_id).or_default().push(Arc::new(target));
}
@@ -3289,8 +3305,7 @@ fn collect_text_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, Strin
/// Collects one text item's laid-out rectangle as a click target.
fn add_text_item_click_targets(item: ItemRef<'_, String>, click_targets: &mut Vec<ClickTarget>) {
let Some((size, transform)) = text_item_size_and_transform(item) else { return };
let subpath = Subpath::new_rectangle(DVec2::ZERO, size);
let mut target = ClickTarget::new_with_subpath(subpath, 0.);
let mut target = ClickTarget::new_with_path(rectangle_path(DVec2::ZERO, size), 0.);
target.apply_transform(transform);
click_targets.push(target);
}
+1 -3
View File
@@ -3,14 +3,12 @@ extern crate log;
pub mod gradient;
pub mod math;
pub mod subpath;
pub mod vector;
// Re-export commonly used types at the crate root
pub use core_types as gcore;
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
pub use math::{QuadExt, RectExt};
pub use subpath::Subpath;
pub use math::QuadExt;
pub use vector::Vector;
pub use vector::reference_point::ReferencePoint;
Loaded 100 of 139 files, more files were not shown because too many files have changed in this diff. Show more