mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f67dbc4b41 | ||
|
|
3d6b50a99b | ||
|
|
475c67facc | ||
|
|
58178fd48e | ||
|
|
3d7e85c054 | ||
|
|
95f2b3bbad | ||
|
|
515a5265fe | ||
|
|
2f65a3aee2 | ||
|
|
1964fdb99e | ||
|
|
117da97dd5 | ||
|
|
f88896a887 |
No files matched your search
Generated
+5
-3
@@ -2323,9 +2323,9 @@ dependencies = [
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphite-editor",
|
||||
"graphite-wasm-wrapper",
|
||||
"image",
|
||||
"keyboard-types",
|
||||
"ron",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.18",
|
||||
@@ -2385,6 +2385,7 @@ dependencies = [
|
||||
name = "graphite-proc-macros"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"convert_case",
|
||||
"graphite-editor",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -2396,17 +2397,18 @@ dependencies = [
|
||||
name = "graphite-wasm-wrapper"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphite-editor",
|
||||
"graphite-proc-macros",
|
||||
"js-sys",
|
||||
"log",
|
||||
"node-macro",
|
||||
"ron",
|
||||
"serde",
|
||||
"serde-wasm-bindgen",
|
||||
"serde_bytes",
|
||||
"serde_json",
|
||||
"tsify",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
|
||||
+1
-2
@@ -14,13 +14,12 @@ use winit::event::{ButtonSource, ElementState, MouseButton, StartCause, WindowEv
|
||||
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
|
||||
use winit::window::WindowId;
|
||||
|
||||
use graphite_desktop_ui::{UiCommand, UiInstance};
|
||||
|
||||
use crate::dirs;
|
||||
use crate::event::{AppEvent, AppEventScheduler};
|
||||
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::{DesktopWrapper, MmapResourceStorage, NodeGraphExecutionResult, WgpuContext, serialize_frontend_messages};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use crate::ui::Cursor;
|
||||
use crate::wrapper::NodeGraphExecutionResult;
|
||||
use crate::wrapper::messages::DesktopWrapperMessage;
|
||||
|
||||
pub(crate) enum AppEvent {
|
||||
UiUpdate(wgpu::Texture),
|
||||
CursorChange(graphite_desktop_ui::Cursor),
|
||||
CursorChange(Cursor),
|
||||
WebCommunicationInitialized,
|
||||
DesktopWrapperMessage(DesktopWrapperMessage),
|
||||
NodeGraphExecutionResult(NodeGraphExecutionResult),
|
||||
|
||||
+3
-2
@@ -3,12 +3,13 @@ use crate::cli::Cli;
|
||||
use crate::consts::APP_LOCK_FILE_NAME;
|
||||
use crate::event::{AppEvent, CreateAppEventSchedulerEventLoopExt};
|
||||
use clap::Parser;
|
||||
use graphite_desktop_ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
|
||||
use std::io::Write;
|
||||
use std::process::ExitCode;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
use ui::{Acceleration, UiConfig, UiContext, UiEvent, UiSetupResult};
|
||||
use winit::event_loop::EventLoop;
|
||||
|
||||
pub(crate) use graphite_desktop_ui as ui;
|
||||
pub(crate) use graphite_desktop_wrapper as wrapper;
|
||||
|
||||
mod app;
|
||||
@@ -69,7 +70,7 @@ pub fn start() -> ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
dirs::clear_dir(&graphite_desktop_ui::temp_dir_root());
|
||||
dirs::clear_dir(&ui::temp_dir_root());
|
||||
|
||||
// TODO: Eventually remove this cleanup code for the old "browser" CEF directory
|
||||
dirs::delete_old_cef_browser_directory();
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::consts::APP_NAME;
|
||||
use crate::event::AppEventScheduler;
|
||||
use crate::ui::Cursor;
|
||||
use crate::wrapper::messages::MenuItem;
|
||||
use crate::wrapper::{WgpuInstance, WgpuSurface};
|
||||
use graphite_desktop_ui::Cursor;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use winit::cursor::{CustomCursor, CustomCursorSource};
|
||||
|
||||
@@ -14,6 +14,7 @@ gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
graphite-editor = { workspace = true }
|
||||
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
|
||||
graphene-std = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
@@ -22,7 +23,6 @@ wgpu = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
dirs = { workspace = true }
|
||||
ron = { workspace = true}
|
||||
vello = { workspace = true }
|
||||
image = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
use graph_craft::application_io::resource::ResourceStorage;
|
||||
use graphite_editor::application::{Editor, Environment, Host, Platform};
|
||||
use graphite_editor::messages::prelude::{FrontendMessage, Message, Wake};
|
||||
use graphite_editor::messages::frontend::FrontendMessage;
|
||||
use graphite_editor::messages::prelude::Wake;
|
||||
|
||||
use message_dispatcher::DesktopWrapperMessageDispatcher;
|
||||
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
|
||||
use std::sync::Arc;
|
||||
@@ -65,21 +67,10 @@ pub enum NodeGraphExecutionResult {
|
||||
}
|
||||
|
||||
pub fn deserialize_editor_message(data: &[u8]) -> Option<DesktopWrapperMessage> {
|
||||
if let Ok(string) = std::str::from_utf8(data) {
|
||||
if let Ok(message) = ron::de::from_str::<Message>(string) {
|
||||
Some(DesktopWrapperMessage::FromWeb(message.into()))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
let message = graphite_wasm_wrapper::native_communication::decode_editor_command(data)?;
|
||||
Some(DesktopWrapperMessage::FromWeb(message.into()))
|
||||
}
|
||||
|
||||
pub fn serialize_frontend_messages(messages: Vec<FrontendMessage>) -> Option<Vec<u8>> {
|
||||
if let Ok(serialized) = ron::ser::to_string(&messages) {
|
||||
Some(serialized.into_bytes())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
graphite_wasm_wrapper::native_communication::encode_frontend_messages(messages)
|
||||
}
|
||||
@@ -45,7 +45,7 @@ impl<'de> Deserialize<'de> for ResourceEntry {
|
||||
}
|
||||
|
||||
let Raw { mut sources, hash, hash_timestamp } = Raw::deserialize(deserializer)?;
|
||||
sources.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
sources.sort_by_key(|(a, _)| *a);
|
||||
sources.dedup_by(|(later_key, later_value), (kept_key, kept_value)| {
|
||||
// `dedup_by` keeps the first of each run; sorting is stable, so resolve duplicates by LWW.
|
||||
if later_key != kept_key {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::IconName;
|
||||
use super::utility_types::{MouseCursorIcon, PersistedState};
|
||||
use crate::messages::app_window::app_window_message_handler::AppWindowPlatform;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, EyedropperPreviewImage, RasterizedImage};
|
||||
use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
@@ -14,7 +14,6 @@ use crate::messages::prelude::*;
|
||||
use crate::messages::tool::tool_messages::eyedropper_tool::PrimarySecondary;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -235,7 +234,7 @@ pub enum FrontendMessage {
|
||||
svg: String,
|
||||
},
|
||||
UpdateImageData {
|
||||
image_data: Vec<(u64, Image<SRGBA8>)>,
|
||||
image_data: Vec<RasterizedImage>,
|
||||
},
|
||||
UpdateDocumentLayerDetails {
|
||||
data: LayerPanelEntry,
|
||||
|
||||
@@ -82,3 +82,12 @@ pub struct EyedropperPreviewImage {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(large_number_types_as_bigints))]
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub struct RasterizedImage {
|
||||
pub id: u64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixels: serde_bytes::ByteBuf,
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::messages::input_mapper::utility_types::input_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::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::FillChoiceUI;
|
||||
@@ -291,7 +292,11 @@ impl LayoutMessageHandler {
|
||||
responses.add(callback_message);
|
||||
}
|
||||
WidgetValueAction::Update => {
|
||||
let callback_message = (node_type_input.on_update.callback)(&value.into());
|
||||
let Value::String(ref node_type) = value else {
|
||||
error!("NodeCatalog update was not of type: String, found {value:?}");
|
||||
return;
|
||||
};
|
||||
let callback_message = (node_type_input.on_update.callback)(&DefinitionIdentifier::from_serialized(node_type));
|
||||
responses.add(callback_message);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ use crate::messages::layout::utility_types::layout_widget::{Layout, LayoutGroup,
|
||||
use crate::messages::portfolio::document::data_panel::{DataPanelMessage, PathStep};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::{format_rounded, round_away_float_noise};
|
||||
use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -623,6 +624,7 @@ impl TableItemLayout for Vector {
|
||||
VectorTableTab::Points => {
|
||||
table_rows.push(column_headings(&["", "position"]));
|
||||
table_rows.extend(self.point_domain.iter().map(|(id, position)| {
|
||||
let position = DVec2::new(round_away_float_noise(position.x), round_away_float_noise(position.y));
|
||||
vec![
|
||||
TextLabel::new(format!("{}", id.inner())).narrow(true).widget_instance(),
|
||||
TextLabel::new(format!("{position}")).narrow(true).widget_instance(),
|
||||
@@ -1339,19 +1341,17 @@ fn format_transform_matrix(transform: DAffine2) -> String {
|
||||
} else {
|
||||
transform.to_scale_angle_translation()
|
||||
};
|
||||
let rotation = if angle == -0. { 0. } else { angle.to_degrees() };
|
||||
let round = |x: f64| (x * 1e3).round() / 1e3;
|
||||
let rotation = format_rounded(angle.to_degrees(), 3);
|
||||
|
||||
format!(
|
||||
"Location: ({} px, {} px) — Rotation: {rotation:2}° — Scale: ({}x, {}x)",
|
||||
round(translation.x),
|
||||
round(translation.y),
|
||||
round(scale.x),
|
||||
round(scale.y)
|
||||
"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)
|
||||
)
|
||||
}
|
||||
|
||||
fn format_dvec2(value: DVec2) -> String {
|
||||
let round = |x: f64| (x * 1e3).round() / 1e3;
|
||||
format!("({} px, {} px)", round(value.x), round(value.y))
|
||||
format!("({} px, {} px)", format_rounded(value.x, 3), format_rounded(value.y, 3))
|
||||
}
|
||||
@@ -2774,7 +2774,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
let has_fill = fill_graphic_list.is_some_and(|list| is_paint_present(list));
|
||||
// `Vector.stroke` captures stroke geometry, even with weight 0 or transparent paint.
|
||||
// So stroke visibility must be checked from `ATTR_STROKE`, the paint source of truth.
|
||||
// So stroke visibility must be checked from `graphic_types::attr::Stroke`, the paint source of truth.
|
||||
let stroke_visible = stroke_graphic_list.is_some_and(|list| list.element(0).is_some_and(|g| !g.is_fully_transparent()));
|
||||
let has_stroke = stroke.as_ref().is_some_and(|s| s.has_renderable_stroke()) && stroke_visible;
|
||||
|
||||
|
||||
@@ -22,7 +22,6 @@ use graphene_std::raster_types::{CPU, Raster};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::*;
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
pub struct NodePropertiesContext<'a> {
|
||||
@@ -88,12 +87,8 @@ impl DefinitionIdentifier {
|
||||
DefinitionIdentifier::Network(data) => format!("NETWORK:{}", data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Value> for DefinitionIdentifier {
|
||||
fn from(value: Value) -> Self {
|
||||
let s = value.as_str().expect("DefinitionIdentifier value must be a string");
|
||||
|
||||
pub fn from_serialized(s: &str) -> Self {
|
||||
match s.split_once(':') {
|
||||
Some(("PROTONODE", data)) => DefinitionIdentifier::ProtoNode(ProtoNodeIdentifier::with_owned_string(data.to_string())),
|
||||
Some(("NETWORK", data)) => DefinitionIdentifier::Network(data.to_string()),
|
||||
@@ -180,7 +175,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::value(TaggedValue::String(attr::editor::LayerPath::name().to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
@@ -310,7 +305,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::value(TaggedValue::String(attr::editor::LayerPath::name().to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
@@ -1175,7 +1170,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Split Vec2",
|
||||
category: "Math: Vector",
|
||||
category: "Math: Vec2",
|
||||
node_template: NodeTemplate {
|
||||
document_node: DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(NodeNetwork {
|
||||
|
||||
@@ -8,10 +8,11 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::messages::prelude::ViewportMessageHandler;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_std::ATTR_TRANSFORM;
|
||||
use graphene_std::attr;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::subpath::{self, Subpath};
|
||||
@@ -1168,7 +1169,7 @@ impl OverlayContextInternal {
|
||||
// Use the existing bezier_to_path infrastructure to convert Vector to BezPath
|
||||
let mut path = BezPath::new();
|
||||
let mut last_point = None;
|
||||
let transform: DAffine2 = text_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform = text_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
let Some(element) = text_list.element(index) else { continue };
|
||||
for (_, bezier, start_id, end_id) in element.segment_iter() {
|
||||
@@ -1189,7 +1190,7 @@ impl OverlayContextInternal {
|
||||
|
||||
let width = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.x).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.x, 2),
|
||||
};
|
||||
let x_transform = DAffine2::from_translation((quad.top_left() + quad.top_right()) / 2.);
|
||||
self.text(width, COLOR_OVERLAY_BLUE, None, x_transform, 4., [Pivot::Middle, Pivot::End]);
|
||||
@@ -1200,7 +1201,7 @@ impl OverlayContextInternal {
|
||||
|
||||
let height = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.y).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.y, 2),
|
||||
};
|
||||
let y_transform = DAffine2::from_translation((quad.top_left() + quad.bottom_left()) / 2.);
|
||||
let height_pivot = if translation.x > -1e-3 { Pivot::Start } else { Pivot::End };
|
||||
|
||||
@@ -7,6 +7,7 @@ use crate::consts::{
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::prelude::Message;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
|
||||
use crate::messages::viewport::ViewportMessageHandler;
|
||||
use core::borrow::Borrow;
|
||||
use core::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
@@ -1090,7 +1091,7 @@ impl OverlayContext {
|
||||
|
||||
let width = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.x).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.x, 2),
|
||||
};
|
||||
let x_transform = DAffine2::from_translation((quad.top_left() + quad.top_right()) / 2.);
|
||||
self.text(width, COLOR_OVERLAY_BLUE, None, x_transform, 4., [Pivot::Middle, Pivot::End]);
|
||||
@@ -1101,7 +1102,7 @@ impl OverlayContext {
|
||||
|
||||
let height = match typed_string {
|
||||
Some(ref typed_string) => typed_string,
|
||||
None => &format!("{:.2}", translation.y).trim_end_matches('0').trim_end_matches('.').to_string(),
|
||||
None => &format_rounded(translation.y, 2),
|
||||
};
|
||||
let y_transform = DAffine2::from_translation((quad.top_left() + quad.bottom_left()) / 2.);
|
||||
let height_pivot = if translation.x > -1e-3 { Pivot::Start } else { Pivot::End };
|
||||
|
||||
@@ -41,10 +41,10 @@ pub struct DocumentMetadata {
|
||||
/// Vector data keyed by layer ID, used as fallback when no Path node exists.
|
||||
/// This provides accurate SegmentIds for layers without explicit Path nodes.
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` attribute, exposed so message handlers can read paint
|
||||
/// Per-layer `graphic_types::attr::Fill` attribute, exposed so message handlers can read paint
|
||||
/// information that lives on the list.
|
||||
pub layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
||||
/// Per-layer `ATTR_STROKE` attribute, exposed so message handlers can read
|
||||
/// Per-layer `graphic_types::attr::Stroke` attribute, exposed so message handlers can read
|
||||
/// stroke paint information that lives on the list.
|
||||
pub layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>,
|
||||
/// Transform from document space to viewport space.
|
||||
|
||||
@@ -3454,12 +3454,12 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_vector_data = new_layer_vector_data;
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_FILL` snapshot.
|
||||
/// Update the per-layer `graphic_types::attr::Fill` snapshot.
|
||||
pub fn update_fill_attributes(&mut self, new_layer_fill_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
||||
self.document_metadata.layer_fill_attributes = new_layer_fill_attributes;
|
||||
}
|
||||
|
||||
/// Update the per-layer `ATTR_STROKE` snapshot.
|
||||
/// Update the per-layer `graphic_types::attr::Stroke` snapshot.
|
||||
pub fn update_stroke_attributes(&mut self, new_layer_stroke_attributes: HashMap<LayerNodeIdentifier, Arc<List<Graphic>>>) {
|
||||
self.document_metadata.layer_stroke_attributes = new_layer_stroke_attributes;
|
||||
}
|
||||
|
||||
@@ -571,7 +571,37 @@ pub fn wrap_to_tau(angle: f64) -> f64 {
|
||||
}
|
||||
|
||||
pub fn format_rounded(value: f64, precision: usize) -> String {
|
||||
format!("{value:.precision$}").trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
// Denoised values within floating point noise of zero (including -0) display as unsigned zero, unless the precision is fine enough to display them
|
||||
let value = round_away_float_noise(value);
|
||||
let value = if value.abs() < f64::min(1e-12, 0.5 * 10_f64.powi(-(precision as i32))) { 0. } else { value };
|
||||
let formatted = format!("{value:.precision$}");
|
||||
|
||||
// Trailing zeros are trimmed only when the display is exact, so a truncated value keeps its decimal places (like "0.00" or "3.10") to indicate the truncation
|
||||
if formatted.parse::<f64>() == Ok(value) {
|
||||
formatted.trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
} else {
|
||||
formatted
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -613,3 +643,78 @@ pub fn extract_grid_parameters(layer: LayerNodeIdentifier, document: &DocumentMe
|
||||
|
||||
Some((grid_type, spacing, columns, rows, angles))
|
||||
}
|
||||
|
||||
#[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 format_rounded_trims_trailing_zeros_when_exact() {
|
||||
assert_eq!(format_rounded(0.25, 2), "0.25");
|
||||
assert_eq!(format_rounded(3.1, 2), "3.1");
|
||||
assert_eq!(format_rounded(45., 2), "45");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_keeps_decimal_places_when_truncated() {
|
||||
assert_eq!(format_rounded(0.0003, 2), "0.00");
|
||||
assert_eq!(format_rounded(-0.0003, 2), "-0.00");
|
||||
assert_eq!(format_rounded(0.0003, 3), "0.000");
|
||||
assert_eq!(format_rounded(3.10001, 2), "3.10");
|
||||
assert_eq!(format_rounded(45.001, 2), "45.00");
|
||||
assert_eq!(format_rounded(std::f64::consts::PI, 2), "3.14");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_denoises_before_judging_exactness() {
|
||||
assert_eq!(format_rounded(29.999999999999996, 2), "30");
|
||||
assert_eq!(format_rounded(45.00000000000001, 2), "45");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_shows_true_and_noise_zeros_plainly() {
|
||||
assert_eq!(format_rounded(0., 2), "0");
|
||||
assert_eq!(format_rounded(-0., 2), "0");
|
||||
assert_eq!(format_rounded(1e-15, 2), "0");
|
||||
assert_eq!(format_rounded(-1e-15, 2), "0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_rounded_keeps_tiny_values_at_displayable_precision() {
|
||||
assert_eq!(format_rounded(5e-13, 20), "0.0000000000005");
|
||||
assert_eq!(format_rounded(-5e-13, 20), "-0.0000000000005");
|
||||
assert_eq!(format_rounded(0., 20), "0");
|
||||
assert_eq!(format_rounded(-0., 20), "0");
|
||||
}
|
||||
}
|
||||
@@ -572,6 +572,7 @@ impl Fsm for ArtboardToolFsmState {
|
||||
mod test_artboard {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::Artboard;
|
||||
use graphene_std::attr;
|
||||
use graphene_std::list::List;
|
||||
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
||||
@@ -601,8 +602,8 @@ mod test_artboard {
|
||||
let artboards = get_artboards(editor).await;
|
||||
let artboards = (0..artboards.len())
|
||||
.map(|index| {
|
||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||
let location = artboards.attr_cloned_or_default::<attr::Location>(index);
|
||||
let dimensions = artboards.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
ArtboardLayoutDocument::new(location, dimensions)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
@@ -8,6 +8,7 @@ use crate::messages::portfolio::document::utility_types::transformation::{Axis,
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::pivot::{PivotGizmo, PivotGizmoType};
|
||||
use crate::messages::tool::common_functionality::shape_editor::ShapeState;
|
||||
use crate::messages::tool::common_functionality::shapes::shape_utility::format_rounded;
|
||||
use crate::messages::tool::tool_messages::select_tool;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::Key;
|
||||
use crate::messages::tool::utility_types::{ToolData, ToolType};
|
||||
@@ -217,7 +218,7 @@ impl MessageHandler<TransformLayerMessage, TransformLayerMessageContext<'_>> for
|
||||
|
||||
let format_rounded = |value: f64, precision: usize| {
|
||||
if self.typing.digits.is_empty() || !self.transform_operation.can_begin_typing() {
|
||||
format!("{value:.precision$}").trim_end_matches('0').trim_end_matches('.').to_string()
|
||||
format_rounded(value, precision)
|
||||
} else {
|
||||
self.typing.string.clone()
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
@@ -15,7 +15,7 @@ use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, graphic_types};
|
||||
use graphene_std::{ATTR_TRANSFORM, Context, Graphic, NodeInputDecleration};
|
||||
use graphene_std::{Context, Graphic, NodeInputDecleration, attr};
|
||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -662,19 +662,15 @@ impl NodeGraphExecutor {
|
||||
|
||||
match render_output.data {
|
||||
RenderOutputType::Svg { svg, image_data } => {
|
||||
// Convert each linear-light `Image<Color>` into the JS-boundary `Image<SRGBA8>` form (gamma byte channels) before dispatching.
|
||||
// Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
|
||||
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
|
||||
let image_data = image_data
|
||||
.into_iter()
|
||||
.map(|(id, image)| {
|
||||
(
|
||||
id,
|
||||
graphene_std::raster::Image {
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
data: image.data.iter().map(|&c| SRGBA8::from(c)).collect(),
|
||||
base64_string: image.base64_string,
|
||||
},
|
||||
)
|
||||
.map(|(id, image)| RasterizedImage {
|
||||
id,
|
||||
width: image.width,
|
||||
height: image.height,
|
||||
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
|
||||
})
|
||||
.collect();
|
||||
responses.add(FrontendMessage::UpdateImageData { image_data });
|
||||
@@ -874,7 +870,7 @@ fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[NodeId]) -> boo
|
||||
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
||||
if let Some(list) = introspected_output::<List<Vector>>(data) {
|
||||
let vector = list.element(0)?;
|
||||
let item_transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let item_transform = list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let bounds = vector.nonzero_bounding_box();
|
||||
let bounding_box_affine = DAffine2::from_scale_angle_translation(bounds[1] - bounds[0], 0., bounds[0]);
|
||||
return Some((bounding_box_affine, item_transform));
|
||||
|
||||
@@ -9,6 +9,7 @@ use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateMessage, NodeGraphUpdateSender, RenderConfig, Texture};
|
||||
use graphene_std::attr;
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::memo::IORecord;
|
||||
@@ -536,8 +537,8 @@ impl NodeRuntime {
|
||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
||||
let mut combined: Option<[DVec2; 2]> = None;
|
||||
for index in 0..artboards.len() {
|
||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||
let location = artboards.attr_cloned_or_default::<attr::Location>(index);
|
||||
let dimensions = artboards.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
let bounds = [location, location + dimensions];
|
||||
combined = Some(match combined {
|
||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
node_modules/
|
||||
wrapper/pkg/
|
||||
wrapper/pkg-native/
|
||||
public/build/
|
||||
dist/
|
||||
@@ -29,6 +29,7 @@ export default defineConfig([
|
||||
"**/node_modules/",
|
||||
"**/dist/",
|
||||
"**/pkg/",
|
||||
"**/pkg-native/",
|
||||
"wasm/pkg/",
|
||||
// Don't ignore JS and TS dotfiles in this folder
|
||||
"!**/.*.js",
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { preventEscapeClosingParentFloatingMenu } from "/src/components/layout/FloatingMenu.svelte";
|
||||
import FieldInput from "/src/components/widgets/inputs/FieldInput.svelte";
|
||||
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "/src/managers/input";
|
||||
import { roundAwayFloatNoise } from "/src/utility-functions/numbers";
|
||||
import { browserVersion } from "/src/utility-functions/platform";
|
||||
import type { ActionShortcut, EditorWrapper, NumberInputIncrementBehavior, NumberInputMode } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
@@ -213,9 +214,19 @@
|
||||
function displayText(displayValue: number | undefined, unit: string): string {
|
||||
if (displayValue === undefined) return "-";
|
||||
|
||||
const roundingPower = 10 ** Math.max(displayDecimalPlaces, 0);
|
||||
const decimalPlaces = Math.max(displayDecimalPlaces, 0);
|
||||
const roundingPower = 10 ** decimalPlaces;
|
||||
|
||||
// Values within floating point noise of zero (including -0) display as unsigned zero, unless the field's decimal precision is fine enough to display them
|
||||
const effectiveValue = Math.abs(displayValue) < Math.min(1e-12, 0.5 / roundingPower) ? 0 : roundAwayFloatNoise(displayValue);
|
||||
const unitlessDisplayValue = Math.round(effectiveValue * roundingPower) / roundingPower;
|
||||
|
||||
// Trailing zeros are trimmed only when the display is exact, so a truncated value keeps its decimal places (like "0.00" or "3.10") to indicate the truncation
|
||||
if (unitlessDisplayValue !== effectiveValue) {
|
||||
const sign = unitlessDisplayValue === 0 && effectiveValue < 0 ? "-" : "";
|
||||
return `${sign}${unitlessDisplayValue.toFixed(decimalPlaces)}${unPluralize(unit, displayValue)}`;
|
||||
}
|
||||
|
||||
const unitlessDisplayValue = Math.round(displayValue * roundingPower) / roundingPower;
|
||||
return `${unitlessDisplayValue}${unPluralize(unit, displayValue)}`;
|
||||
}
|
||||
|
||||
@@ -230,9 +241,8 @@
|
||||
// ===========================
|
||||
|
||||
function onTextFocused() {
|
||||
// The degree of precision allowed in the number that's shown when editing the number field, where additional precision is removed to round out floating point errors.
|
||||
const MAX_PRECISION = 12;
|
||||
const noFloatingImprecisionValue = value === undefined ? undefined : Number(value.toPrecision(MAX_PRECISION));
|
||||
// The number shown when editing the field, with floating point imprecision noise removed
|
||||
const noFloatingImprecisionValue = value === undefined ? undefined : roundAwayFloatNoise(value);
|
||||
|
||||
if (value === undefined) text = "";
|
||||
else if (unitIsHiddenWhenEditing) text = `${noFloatingImprecisionValue}`;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// 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.
|
||||
export function roundAwayFloatNoise(value: number): number {
|
||||
if (value === 0 || !Number.isFinite(value)) return value === 0 ? 0 : value;
|
||||
|
||||
const exponent = Math.floor(Math.log10(Math.abs(value)));
|
||||
for (let significantDigits = 1; significantDigits <= 12; significantDigits += 1) {
|
||||
const scale = 10 ** (significantDigits - 1 - exponent);
|
||||
const rounded = Math.round(value * scale) / scale;
|
||||
if (Math.abs((rounded - value) / value) < 1e-13) return rounded;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
@@ -23,7 +23,10 @@ export default defineConfig(({ mode }) => {
|
||||
// Default for builds that exclude the `wasmSplitting` plugin, which overrides this when active
|
||||
define: { __WASM_PART_COUNT__: "1" },
|
||||
resolve: {
|
||||
alias: [{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") }],
|
||||
alias: [
|
||||
...(mode === "native" ? [{ find: /^\/wrapper\/pkg\//, replacement: "/wrapper/pkg-native/" }] : []),
|
||||
{ find: /\/..\/branding\/(.*\.svg)/, replacement: path.resolve(projectRootDir, "../branding", "$1?raw") },
|
||||
],
|
||||
},
|
||||
server: {
|
||||
port: 8080,
|
||||
|
||||
+16
-11
@@ -11,33 +11,38 @@ repository = "https://github.com/GraphiteEditor/Graphite"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[features]
|
||||
default = ["gpu", "shader-nodes"]
|
||||
gpu = ["editor/gpu"]
|
||||
shader-nodes = ["graphene-std/shader-nodes", "gpu"]
|
||||
native = ["node-macro/disable-registration"]
|
||||
default = ["gpu", "shader-nodes", "web"]
|
||||
web = ["editor", "editor?/wasm"]
|
||||
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:node-macro", "dep:wgpu"]
|
||||
gpu = ["editor?/gpu"]
|
||||
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
|
||||
native = ["node-macro?/disable-registration"]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
# Local dependencies
|
||||
editor = { path = "../../editor", package = "graphite-editor", features = ["gpu", "wasm"] }
|
||||
graphene-std = { workspace = true }
|
||||
editor = { path = "../../editor", package = "graphite-editor", optional = true }
|
||||
graphite-proc-macros = { workspace = true }
|
||||
graphene-std = { workspace = true, optional = true }
|
||||
|
||||
# Workspace dependencies
|
||||
bytemuck = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graph-craft = { workspace = true, optional = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
wasm-bindgen = { workspace = true }
|
||||
serde-wasm-bindgen = { workspace = true }
|
||||
js-sys = { workspace = true }
|
||||
wasm-bindgen-futures = { workspace = true }
|
||||
wgpu = { workspace = true }
|
||||
wgpu = { workspace = true, optional = true }
|
||||
web-sys = { workspace = true }
|
||||
ron = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
tsify = { workspace = true }
|
||||
node-macro = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_bytes = { workspace = true }
|
||||
|
||||
[lints.rust]
|
||||
unexpected_cfgs = { level = "warn", check-cfg = [
|
||||
|
||||
@@ -0,0 +1,690 @@
|
||||
//! Commands that JS can call on the editor. Each function maps its arguments to a `Message`. On web the generated
|
||||
//! stub dispatches it directly, on native the arguments are sent as an `EditorCommand` and the same body runs in
|
||||
//! the editor process.
|
||||
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
#[cfg(target_family = "wasm")]
|
||||
use crate::editor_wrapper::EditorWrapper;
|
||||
use graphite_proc_macros::editor_commands;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tsify::Tsify;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[editor_commands]
|
||||
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::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;
|
||||
use editor::messages::portfolio::utility_types::PanelGroupId;
|
||||
use editor::messages::prelude::*;
|
||||
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::FillChoice;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
|
||||
fn resend_all_layouts() -> Message {
|
||||
LayoutMessage::ResendAllLayouts.into()
|
||||
}
|
||||
|
||||
/// First message of a session, sent once the frontend is ready
|
||||
fn init_portfolio() -> Message {
|
||||
PortfolioMessage::Init.into()
|
||||
}
|
||||
|
||||
/// Per-frame tick: advances the animation clock and broadcasts the animation frame event
|
||||
fn animation_frame(timestamp: u64) -> Message {
|
||||
Message::Batched {
|
||||
messages: Box::new([
|
||||
InputPreprocessorMessage::CurrentTime { timestamp }.into(),
|
||||
AnimationMessage::IncrementFrameCounter.into(),
|
||||
// Used by auto-panning, but this could possibly be refactored in the future, see:
|
||||
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
|
||||
BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into(),
|
||||
]),
|
||||
}
|
||||
}
|
||||
|
||||
fn auto_save_all_documents() -> Message {
|
||||
PortfolioMessage::AutoSaveAllDocuments.into()
|
||||
}
|
||||
|
||||
fn add_primary_import() -> Message {
|
||||
Message::Batched {
|
||||
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryImport.into()]),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_secondary_import() -> Message {
|
||||
Message::Batched {
|
||||
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryImport.into()]),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_primary_export() -> Message {
|
||||
Message::Batched {
|
||||
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddPrimaryExport.into()]),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_secondary_export() -> Message {
|
||||
Message::Batched {
|
||||
messages: Box::new([DocumentMessage::AddTransaction.into(), NodeGraphMessage::AddSecondaryExport.into()]),
|
||||
}
|
||||
}
|
||||
|
||||
/// Start Pointer Lock
|
||||
fn app_window_pointer_lock() -> Message {
|
||||
AppWindowMessage::PointerLock.into()
|
||||
}
|
||||
|
||||
/// Minimizes the application window to the taskbar or dock
|
||||
fn app_window_minimize() -> Message {
|
||||
AppWindowMessage::Minimize.into()
|
||||
}
|
||||
|
||||
/// Toggles minimizing or restoring down the application window
|
||||
fn app_window_maximize() -> Message {
|
||||
AppWindowMessage::Maximize.into()
|
||||
}
|
||||
|
||||
fn app_window_fullscreen() -> Message {
|
||||
AppWindowMessage::Fullscreen.into()
|
||||
}
|
||||
|
||||
/// Closes the application window
|
||||
fn app_window_close() -> Message {
|
||||
AppWindowMessage::Close.into()
|
||||
}
|
||||
|
||||
/// Drag the application window
|
||||
fn app_window_drag() -> Message {
|
||||
AppWindowMessage::Drag.into()
|
||||
}
|
||||
|
||||
/// Displays a dialog with an error message
|
||||
fn error_dialog(title: String, description: String) -> Message {
|
||||
DialogMessage::DisplayDialogError { title, description }.into()
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
||||
fn widget_value_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let update = LayoutMessage::WidgetValueUpdate {
|
||||
layout_target,
|
||||
widget_id,
|
||||
value: value.cast(),
|
||||
};
|
||||
if resend_widget {
|
||||
Message::Batched {
|
||||
messages: Box::new([update.into(), LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into()]),
|
||||
}
|
||||
} else {
|
||||
update.into()
|
||||
}
|
||||
}
|
||||
|
||||
/// Commit the value of a given UI widget to the history
|
||||
fn widget_value_commit(layout_target: LayoutTarget, widget_id: u64, value: Any) -> Message {
|
||||
LayoutMessage::WidgetValueCommit {
|
||||
layout_target,
|
||||
widget_id: WidgetId(widget_id),
|
||||
value: value.cast(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, and commit it to the history
|
||||
fn widget_value_commit_and_update(layout_target: LayoutTarget, widget_id: u64, value: Any, resend_widget: bool) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let mut messages: Vec<Message> = vec![
|
||||
LayoutMessage::WidgetValueCommit {
|
||||
layout_target,
|
||||
widget_id,
|
||||
value: value.cast(),
|
||||
}
|
||||
.into(),
|
||||
LayoutMessage::WidgetValueUpdate {
|
||||
layout_target,
|
||||
widget_id,
|
||||
value: value.cast(),
|
||||
}
|
||||
.into(),
|
||||
];
|
||||
if resend_widget {
|
||||
messages.push(LayoutMessage::ResendActiveWidget { layout_target, widget_id }.into());
|
||||
}
|
||||
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
|
||||
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
|
||||
messages.push(DocumentMessage::EndTransaction.into());
|
||||
Message::Batched { messages: messages.into() }
|
||||
}
|
||||
|
||||
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
|
||||
fn widget_value_drag_drop(layout_target: LayoutTarget, widget_id: u64) -> Message {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
LayoutMessage::WidgetValueDragDrop { layout_target, widget_id }.into()
|
||||
}
|
||||
|
||||
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
|
||||
fn end_transaction() -> Message {
|
||||
DocumentMessage::EndTransaction.into()
|
||||
}
|
||||
|
||||
fn load_preferences(preferences: Option<String>) -> Message {
|
||||
let Some(preferences) = preferences else { return Message::NoOp };
|
||||
let Ok(preferences) = serde_json::from_str(&preferences) else {
|
||||
log::error!("Failed to deserialize preferences");
|
||||
return Message::NoOp;
|
||||
};
|
||||
PreferencesMessage::Load { preferences }.into()
|
||||
}
|
||||
|
||||
fn load_document_content(document_id: u64, document: String) -> Message {
|
||||
PersistentStateMessage::LoadDocument {
|
||||
document_id: DocumentId(document_id),
|
||||
document,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn select_document(document_id: u64) -> Message {
|
||||
PortfolioMessage::SelectDocument { document_id: DocumentId(document_id) }.into()
|
||||
}
|
||||
|
||||
/// Rename the currently active document.
|
||||
fn rename_document(new_name: String) -> Message {
|
||||
PortfolioMessage::RenameDocument { new_name }.into()
|
||||
}
|
||||
|
||||
fn new_document_dialog() -> Message {
|
||||
DialogMessage::RequestNewDocumentDialog.into()
|
||||
}
|
||||
|
||||
fn open_file(path: String, content: Vec<u8>) -> Message {
|
||||
PortfolioMessage::OpenFile { path: PathBuf::from(path), content }.into()
|
||||
}
|
||||
|
||||
fn import_file(path: String, content: Vec<u8>) -> Message {
|
||||
PortfolioMessage::ImportFile { path: PathBuf::from(path), content }.into()
|
||||
}
|
||||
|
||||
fn trigger_auto_save(document_id: u64) -> Message {
|
||||
PortfolioMessage::AutoSaveDocument { document_id: DocumentId(document_id) }.into()
|
||||
}
|
||||
|
||||
fn reorder_document(document_id: u64, new_index: usize) -> Message {
|
||||
PortfolioMessage::ReorderDocument {
|
||||
document_id: DocumentId(document_id),
|
||||
new_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn reorder_panel_group_tab(group: u64, old_index: usize, new_index: usize) -> Message {
|
||||
PortfolioMessage::ReorderPanelGroupTab {
|
||||
group: PanelGroupId(group),
|
||||
old_index,
|
||||
new_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn move_all_panel_tabs(source_group: u64, target_group: u64, insert_index: usize) -> Message {
|
||||
PortfolioMessage::MoveAllPanelTabs {
|
||||
source_group: PanelGroupId(source_group),
|
||||
target_group: PanelGroupId(target_group),
|
||||
insert_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn move_panel_tab(source_group: u64, target_group: u64, insert_index: usize) -> Message {
|
||||
PortfolioMessage::MovePanelTab {
|
||||
source_group: PanelGroupId(source_group),
|
||||
target_group: PanelGroupId(target_group),
|
||||
insert_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn set_panel_group_active_tab(group: u64, tab_index: usize) -> Message {
|
||||
PortfolioMessage::SetPanelGroupActiveTab {
|
||||
group: PanelGroupId(group),
|
||||
tab_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn split_panel_group(target_group: u64, direction: DockingSplitDirection, tabs: PanelTypes, active_tab_index: usize) -> Message {
|
||||
PortfolioMessage::SplitPanelGroup {
|
||||
target_group: PanelGroupId(target_group),
|
||||
direction,
|
||||
tabs,
|
||||
active_tab_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn set_panel_group_sizes(split_path: Vec<u32>, sizes: Vec<f64>) -> Message {
|
||||
let split_path = split_path.into_iter().map(|i| i as usize).collect();
|
||||
PortfolioMessage::SetPanelGroupSizes { split_path, sizes }.into()
|
||||
}
|
||||
|
||||
fn close_document_with_confirmation(document_id: u64) -> Message {
|
||||
PortfolioMessage::CloseDocumentWithConfirmation { document_id: DocumentId(document_id) }.into()
|
||||
}
|
||||
|
||||
fn request_about_graphite_dialog_with_localized_commit_date(localized_commit_date: String, localized_commit_year: String) -> Message {
|
||||
DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
|
||||
localized_commit_date,
|
||||
localized_commit_year,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
fn request_licenses_third_party_dialog_with_license_text(license_text: String) -> Message {
|
||||
DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text }.into()
|
||||
}
|
||||
|
||||
/// Send new viewport info to the backend
|
||||
fn update_viewport(x: f64, y: f64, width: f64, height: f64, scale: f64) -> Message {
|
||||
ViewportMessage::Update { x, y, width, height, scale }.into()
|
||||
}
|
||||
|
||||
/// 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 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());
|
||||
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()
|
||||
}
|
||||
|
||||
/// 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 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 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 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 modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// A keyboard button depressed within screenspace the bounds of the viewport
|
||||
fn on_key_down(name: String, modifiers: u8, key_repeat: bool) -> Message {
|
||||
let key = translate_key(&name);
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
|
||||
InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// A keyboard button released
|
||||
fn on_key_up(name: String, modifiers: u8, key_repeat: bool) -> Message {
|
||||
let key = translate_key(&name);
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
|
||||
InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys }.into()
|
||||
}
|
||||
|
||||
/// A text box was committed
|
||||
fn on_change_text(new_text: String, is_left_or_right_click: bool) -> Message {
|
||||
TextToolMessage::TextChange { new_text, is_left_or_right_click }.into()
|
||||
}
|
||||
|
||||
/// Dialog got dismissed
|
||||
fn on_dialog_dismiss() -> Message {
|
||||
DialogMessage::Dismiss.into()
|
||||
}
|
||||
|
||||
/// A text box was changed
|
||||
fn update_bounds(new_text: String) -> Message {
|
||||
TextToolMessage::UpdateBounds { new_text }.into()
|
||||
}
|
||||
|
||||
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
|
||||
fn update_primary_color(color: SRGBA8) -> Message {
|
||||
ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: true,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
|
||||
fn update_secondary_color(color: SRGBA8) -> Message {
|
||||
ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: false,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
|
||||
fn open_color_picker(initial_value: FillChoiceUI, allow_none: bool, disabled: bool) -> Message {
|
||||
ColorPickerMessage::Open {
|
||||
initial_value: FillChoice::from(&initial_value),
|
||||
allow_none,
|
||||
disabled,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Tell the Rust color picker handler that the popover is closing.
|
||||
fn close_color_picker() -> Message {
|
||||
ColorPickerMessage::Close.into()
|
||||
}
|
||||
|
||||
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
|
||||
fn update_gradient_stop_color(color: SRGBA8) -> Message {
|
||||
GradientToolMessage::UpdateStopColor { color: Color::from(color) }.into()
|
||||
}
|
||||
|
||||
/// Start a new undo transaction for gradient stop color editing
|
||||
fn start_gradient_stop_color_transaction() -> Message {
|
||||
GradientToolMessage::StartTransactionForColorStop.into()
|
||||
}
|
||||
|
||||
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
|
||||
fn commit_gradient_stop_color_transaction() -> Message {
|
||||
GradientToolMessage::CommitTransactionForColorStop.into()
|
||||
}
|
||||
|
||||
/// Close the gradient stop color picker and commit any pending transaction
|
||||
fn close_gradient_stop_color_picker() -> Message {
|
||||
GradientToolMessage::CloseStopColorPicker.into()
|
||||
}
|
||||
|
||||
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
|
||||
fn clip_layer(id: u64) -> Message {
|
||||
DocumentMessage::ClipLayer { id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
|
||||
fn select_layer(id: u64, ctrl: bool, shift: bool) -> Message {
|
||||
DocumentMessage::SelectLayer { id: NodeId(id), ctrl, shift }.into()
|
||||
}
|
||||
|
||||
/// Deselect all layers
|
||||
fn deselect_all_layers() -> Message {
|
||||
DocumentMessage::DeselectAllLayers.into()
|
||||
}
|
||||
|
||||
/// Move a layer to within a folder and placed down at the given index.
|
||||
/// If the folder is `None`, it is inserted into the document root.
|
||||
/// If the insert index is `None`, it is inserted at the start of the folder.
|
||||
fn move_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
|
||||
let insert_parent_id = insert_parent_id.map(NodeId);
|
||||
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
|
||||
|
||||
DocumentMessage::MoveSelectedLayersTo {
|
||||
parent,
|
||||
insert_index: insert_index.unwrap_or_default(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Reorder a draggable Properties panel section to the given index among its peers.
|
||||
fn reorder_properties_section(node_id: u64, insert_index: usize) -> Message {
|
||||
DocumentMessage::ReorderPropertiesSection {
|
||||
node_id: NodeId(node_id),
|
||||
insert_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
|
||||
/// If the folder is `None`, they are inserted into the document root.
|
||||
/// If the insert index is `None`, they are inserted at the start of the folder.
|
||||
fn duplicate_layer_in_tree(insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
|
||||
DocumentMessage::DuplicateSelectedLayersTo {
|
||||
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
|
||||
insert_index: insert_index.unwrap_or_default(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Set the name for the layer
|
||||
fn set_layer_name(id: u64, name: String) -> Message {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
|
||||
NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
fn pan_canvas_abort_prepare(x_not_y_axis: bool) -> Message {
|
||||
NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis }.into()
|
||||
}
|
||||
|
||||
fn pan_canvas_abort(x_not_y_axis: bool) -> Message {
|
||||
NavigationMessage::CanvasPanAbort { x_not_y_axis }.into()
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
fn pan_canvas(delta_x: f64, delta_y: f64) -> Message {
|
||||
NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() }.into()
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
fn pan_canvas_by_fraction(delta_x: f64, delta_y: f64) -> Message {
|
||||
NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() }.into()
|
||||
}
|
||||
|
||||
/// Merge the selected nodes into a subnetwork
|
||||
fn merge_selected_nodes() -> Message {
|
||||
NodeGraphMessage::MergeSelectedNodes.into()
|
||||
}
|
||||
|
||||
/// Toggle lock state of all selected layers
|
||||
fn toggle_selected_locked() -> Message {
|
||||
NodeGraphMessage::ToggleSelectedLocked.into()
|
||||
}
|
||||
|
||||
/// Creates a new document node in the node graph
|
||||
fn create_node(node_type: String, x: i32, y: i32) -> Message {
|
||||
let id = NodeId::new();
|
||||
NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(id),
|
||||
node_type: DefinitionIdentifier::from_serialized(&node_type),
|
||||
xy: Some((x / 24, y / 24)),
|
||||
add_transaction: true,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Respond to selection read
|
||||
fn read_selection(content: Option<String>, cut: bool) -> Message {
|
||||
ClipboardMessage::ReadSelection { content, cut }.into()
|
||||
}
|
||||
|
||||
/// Paste from a serialized JSON representation
|
||||
fn paste_text(data: String) -> Message {
|
||||
ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(data),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Pastes an image
|
||||
fn paste_image(
|
||||
name: Option<String>,
|
||||
image_data: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
mouse_x: Option<f64>,
|
||||
mouse_y: Option<f64>,
|
||||
insert_parent_id: Option<u64>,
|
||||
insert_index: Option<usize>,
|
||||
) -> Message {
|
||||
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
||||
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
|
||||
|
||||
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
||||
let insert_parent_id = NodeId(insert_parent_id);
|
||||
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
||||
Some((parent, insert_index))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
PortfolioMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Pastes an SVG given its string representation
|
||||
fn paste_svg(name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) -> Message {
|
||||
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
||||
|
||||
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
||||
let insert_parent_id = NodeId(insert_parent_id);
|
||||
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
||||
Some((parent, insert_index))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
PortfolioMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Toggle visibility of a layer or node given its node ID
|
||||
fn toggle_node_visibility_layer_panel(id: u64) -> Message {
|
||||
NodeGraphMessage::ToggleVisibility {
|
||||
node_id: NodeId(id),
|
||||
network_path: Vec::new(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Pin or unpin a node given its node ID
|
||||
fn set_node_pinned(id: u64, pinned: bool) -> Message {
|
||||
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
|
||||
}
|
||||
|
||||
/// Collapse or expand a node's section in the Properties panel
|
||||
fn toggle_node_properties_section_expanded(id: u64) -> Message {
|
||||
DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Delete a layer or node given its node ID
|
||||
fn delete_node(id: u64) -> Message {
|
||||
DocumentMessage::DeleteNode { node_id: NodeId(id) }.into()
|
||||
}
|
||||
|
||||
/// Toggle lock state of a layer from the layer list
|
||||
fn toggle_layer_lock(node_id: u64) -> Message {
|
||||
NodeGraphMessage::ToggleLocked {
|
||||
node_id: NodeId(node_id),
|
||||
network_path: Vec::new(),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Toggle expansions state of a layer from the layer list
|
||||
fn toggle_layer_expansion(tree_path: Vec<u64>, recursive: bool) -> Message {
|
||||
let tree_path = tree_path.into_iter().map(NodeId).collect();
|
||||
DocumentMessage::ToggleLayerExpansion { tree_path, recursive }.into()
|
||||
}
|
||||
|
||||
/// Set the active panel to the most recently clicked panel
|
||||
fn set_active_panel(panel: String) -> Message {
|
||||
DocumentMessage::SetActivePanel { active_panel: panel.into() }.into()
|
||||
}
|
||||
|
||||
/// Toggle display type for a layer
|
||||
fn set_to_node_or_layer(id: u64, is_layer: bool) -> Message {
|
||||
DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer }.into()
|
||||
}
|
||||
|
||||
/// Set the name of an import or export
|
||||
fn set_import_name(index: usize, name: String) -> Message {
|
||||
NodeGraphMessage::SetImportExportName {
|
||||
name,
|
||||
index: ImportOrExport::Import(index),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Set the name of an export
|
||||
fn set_export_name(index: usize, name: String) -> Message {
|
||||
NodeGraphMessage::SetImportExportName {
|
||||
name,
|
||||
index: ImportOrExport::Export(index),
|
||||
}
|
||||
.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Tsify)]
|
||||
#[tsify(from_wasm_abi)]
|
||||
pub struct Any(#[tsify(type = "any")] serde_json::Value);
|
||||
impl Any {
|
||||
#[cfg(feature = "editor")]
|
||||
pub(crate) fn cast<T: for<'de> Deserialize<'de>>(&self) -> T {
|
||||
serde_json::from_value(self.0.clone()).unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! editor_proxy_types {
|
||||
($($name:ident = $real:ty;)*) => {
|
||||
$(
|
||||
#[cfg(feature = "editor")]
|
||||
pub type $name = $real;
|
||||
#[cfg(not(feature = "editor"))]
|
||||
pub type $name = Any;
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
editor_proxy_types! {
|
||||
LayoutTarget = editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
DockingSplitDirection = editor::messages::portfolio::utility_types::DockingSplitDirection;
|
||||
PanelTypes = Vec<editor::messages::portfolio::utility_types::PanelType>;
|
||||
SRGBA8 = graphene_std::color::SRGBA8;
|
||||
FillChoiceUI = graphene_std::vector::style::FillChoiceUI;
|
||||
}
|
||||
@@ -1,44 +1,33 @@
|
||||
#![allow(clippy::too_many_arguments)]
|
||||
//
|
||||
// This file is where functions are defined to be called directly from JS.
|
||||
// It serves as a thin wrapper over the editor backend API that relies
|
||||
// on the dispatcher messaging system and more complex Rust data types.
|
||||
//
|
||||
//! JS-facing editor handle. Owns the callback that delivers `FrontendMessage`s to JS; on web `dispatch` runs
|
||||
//! messages through the in-process editor, on native `send` forwards them as `EditorCommand`s.
|
||||
|
||||
#[cfg(not(feature = "native"))]
|
||||
use crate::EDITOR;
|
||||
#[cfg(not(feature = "native"))]
|
||||
use crate::helpers::poll_node_graph_evaluation;
|
||||
use crate::helpers::{auto_save_all_documents, calculate_hash, render_image_data_to_canvases, request_animation_frame, set_timeout, translate_key, wrapper};
|
||||
use crate::{EDITOR_HAS_CRASHED, Error, FRONTEND_READY, MESSAGE_BUFFER};
|
||||
use crate::MESSAGE_BUFFER;
|
||||
#[cfg(all(feature = "native", target_family = "wasm"))]
|
||||
use crate::editor_commands::EditorCommand;
|
||||
#[cfg(not(feature = "native"))]
|
||||
use crate::helpers::poll_node_graph_evaluation;
|
||||
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
|
||||
use crate::helpers::wrapper;
|
||||
#[cfg(feature = "editor")]
|
||||
use crate::helpers::{calculate_hash, render_image_data_to_canvases};
|
||||
use crate::helpers::{request_animation_frame, set_timeout};
|
||||
use crate::{EDITOR_HAS_CRASHED, FRONTEND_READY};
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
use editor::application::{Editor, Environment, Host, Platform};
|
||||
use editor::consts::{FILE_EXTENSION, GDD_FILE_EXTENSION};
|
||||
use editor::messages::clipboard::utility_types::ClipboardContentRaw;
|
||||
use editor::messages::input_mapper::utility_types::input_keyboard::ModifierKeys;
|
||||
use editor::messages::input_mapper::utility_types::input_mouse::{EditorMouseState, ScrollDelta};
|
||||
use editor::messages::layout::utility_types::layout_widget::LayoutTarget;
|
||||
use editor::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use editor::messages::portfolio::document::utility_types::network_interface::ImportOrExport;
|
||||
use editor::messages::portfolio::utility_types::{DockingSplitDirection, PanelGroupId, PanelType};
|
||||
#[cfg(feature = "editor")]
|
||||
use editor::messages::prelude::*;
|
||||
use editor::messages::tool::tool_messages::tool_prelude::WidgetId;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::graphene_hash::CacheHashWrapper;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::vector::style::{FillChoice, FillChoiceUI};
|
||||
#[cfg(feature = "editor")]
|
||||
use serde::Serialize;
|
||||
use serde_wasm_bindgen::{self, from_value};
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
|
||||
pub(crate) static IMAGE_DATA_HASH: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// This struct is, via wasm-bindgen, used by JS to interact with the editor backend. It does this by calling functions, which are `impl`ed
|
||||
#[wasm_bindgen]
|
||||
#[derive(Clone)]
|
||||
pub struct EditorWrapper {
|
||||
@@ -46,13 +35,7 @@ pub struct EditorWrapper {
|
||||
frontend_message_handler_callback: js_sys::Function,
|
||||
}
|
||||
|
||||
// Defined separately from the `impl` block below since this `impl` block lacks the `#[wasm_bindgen]` attribute.
|
||||
// Quirks in wasm-bindgen prevent functions in `#[wasm_bindgen]` `impl` blocks from being made publicly accessible from Rust.
|
||||
impl EditorWrapper {
|
||||
pub fn send_frontend_message_to_js_rust_proxy(&self, message: FrontendMessage) {
|
||||
self.send_frontend_message_to_js(message);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "native", target_family = "wasm"))]
|
||||
fn initialize_wrapper(frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
|
||||
use crate::{EDITOR_WRAPPER, PANIC_DIALOG_MESSAGE_CALLBACK};
|
||||
@@ -69,10 +52,6 @@ impl EditorWrapper {
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl EditorWrapper {
|
||||
// ========================
|
||||
// Editor wrapper machinery
|
||||
// ========================
|
||||
|
||||
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
|
||||
pub async fn create(platform: String, uuid_random_seed: u64, frontend_message_handler_callback: js_sys::Function) -> EditorWrapper {
|
||||
use graph_craft::application_io::PlatformApplicationIo;
|
||||
@@ -115,7 +94,6 @@ impl EditorWrapper {
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
|
||||
// Process no further messages after a crash to avoid spamming the console
|
||||
use crate::MESSAGE_BUFFER;
|
||||
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
@@ -137,24 +115,15 @@ impl EditorWrapper {
|
||||
self.send_frontend_message_to_js(message);
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "native")]
|
||||
pub(crate) fn dispatch<T: Into<Message>>(&self, message: T) {
|
||||
let message: Message = message.into();
|
||||
let Ok(serialized_message) = ron::to_string(&message) else {
|
||||
log::error!("Failed to serialize message");
|
||||
return;
|
||||
};
|
||||
crate::native_communication::send_message_to_cef(serialized_message)
|
||||
}
|
||||
|
||||
// Sends a FrontendMessage to JavaScript
|
||||
#[cfg(feature = "editor")]
|
||||
pub(crate) fn send_frontend_message_to_js(&self, message: FrontendMessage) {
|
||||
if let FrontendMessage::UpdateImageData { ref image_data } = message {
|
||||
let new_hash = calculate_hash(&CacheHashWrapper(image_data));
|
||||
let new_hash = calculate_hash(image_data);
|
||||
let prev_hash = IMAGE_DATA_HASH.load(Ordering::Relaxed);
|
||||
|
||||
if new_hash != prev_hash {
|
||||
render_image_data_to_canvases(image_data.as_slice());
|
||||
render_image_data_to_canvases(image_data.iter());
|
||||
IMAGE_DATA_HASH.store(new_hash, Ordering::Relaxed);
|
||||
}
|
||||
return;
|
||||
@@ -172,16 +141,31 @@ impl EditorWrapper {
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================
|
||||
// Functions for calling the editor in Rust from JS
|
||||
// ================================================
|
||||
pub(crate) fn forward_serialized_frontend_message_to_js(&self, name: &str, data: crate::wasm_value::WasmValue) {
|
||||
let js_return_value = self.frontend_message_handler_callback.call2(&JsValue::null(), &JsValue::from(name), &data.into());
|
||||
|
||||
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
|
||||
#[wasm_bindgen(js_name = resendAllLayouts)]
|
||||
pub fn resend_all_layouts(&self) {
|
||||
self.dispatch(LayoutMessage::ResendAllLayouts);
|
||||
if let Err(error) = js_return_value {
|
||||
error!("While handling FrontendMessage {name:?}, JavaScript threw an error:\n{error:?}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "native", target_family = "wasm"))]
|
||||
pub(crate) fn send(&self, command: EditorCommand) {
|
||||
// Process no further commands after a crash to avoid spamming the console
|
||||
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Ok(serialized) = serde_json::to_string(&command) else {
|
||||
log::error!("Failed to serialize editor command");
|
||||
return;
|
||||
};
|
||||
crate::native_communication::send_message_to_cef(serialized)
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl EditorWrapper {
|
||||
#[wasm_bindgen(js_name = initAfterFrontendReady)]
|
||||
pub fn init_after_frontend_ready(&self) {
|
||||
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice
|
||||
@@ -192,7 +176,8 @@ impl EditorWrapper {
|
||||
#[cfg(feature = "native")]
|
||||
crate::native_communication::initialize_native_communication();
|
||||
|
||||
self.dispatch(PortfolioMessage::Init);
|
||||
#[cfg(target_family = "wasm")]
|
||||
self.init_portfolio();
|
||||
|
||||
// Poll node graph evaluation on `requestAnimationFrame`
|
||||
{
|
||||
@@ -203,25 +188,19 @@ impl EditorWrapper {
|
||||
#[cfg(not(feature = "native"))]
|
||||
wasm_bindgen_futures::spawn_local(poll_node_graph_evaluation());
|
||||
|
||||
if !EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
||||
wrapper(|wrapper| {
|
||||
// Process all messages that have been queued up
|
||||
let mut messages = MESSAGE_BUFFER.take();
|
||||
messages.push(
|
||||
InputPreprocessorMessage::CurrentTime {
|
||||
timestamp: js_sys::Date::now() as u64,
|
||||
}
|
||||
.into(),
|
||||
);
|
||||
messages.push(AnimationMessage::IncrementFrameCounter.into());
|
||||
|
||||
// Used by auto-panning, but this could possibly be refactored in the future, see:
|
||||
// <https://github.com/GraphiteEditor/Graphite/pull/2562#discussion_r2041102786>
|
||||
messages.push(BroadcastMessage::TriggerEvent(EventMessage::AnimationFrame).into());
|
||||
|
||||
wrapper.dispatch(Message::Batched { messages: messages.into() });
|
||||
});
|
||||
}
|
||||
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
|
||||
wrapper(|wrapper| {
|
||||
// On web, flush the messages that queued up while the editor was locked before this frame's tick
|
||||
#[cfg(not(feature = "native"))]
|
||||
{
|
||||
let messages = MESSAGE_BUFFER.take();
|
||||
if !messages.is_empty() {
|
||||
wrapper.dispatch(Message::Batched { messages: messages.into() });
|
||||
}
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
wrapper.animation_frame(js_sys::Date::now() as u64);
|
||||
});
|
||||
|
||||
// Schedule ourself for another requestAnimationFrame callback
|
||||
request_animation_frame(f.borrow().as_ref().unwrap());
|
||||
@@ -230,94 +209,25 @@ impl EditorWrapper {
|
||||
request_animation_frame(g.borrow().as_ref().unwrap());
|
||||
}
|
||||
|
||||
const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
// Auto save all documents on `setTimeout`
|
||||
{
|
||||
let f = std::rc::Rc::new(RefCell::new(None));
|
||||
let g = f.clone();
|
||||
|
||||
*g.borrow_mut() = Some(Closure::new(move || {
|
||||
auto_save_all_documents();
|
||||
#[cfg(target_family = "wasm")]
|
||||
wrapper(|wrapper| wrapper.auto_save_all_documents());
|
||||
|
||||
// Schedule ourself for another setTimeout callback
|
||||
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
|
||||
set_timeout(f.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
|
||||
}));
|
||||
|
||||
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(editor::consts::AUTO_SAVE_TIMEOUT_SECONDS));
|
||||
set_timeout(g.borrow().as_ref().unwrap(), Duration::from_secs(AUTO_SAVE_TIMEOUT_SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = addPrimaryImport)]
|
||||
pub fn add_primary_import(&self) {
|
||||
self.dispatch(DocumentMessage::AddTransaction);
|
||||
self.dispatch(NodeGraphMessage::AddPrimaryImport);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = addSecondaryImport)]
|
||||
pub fn add_secondary_import(&self) {
|
||||
self.dispatch(DocumentMessage::AddTransaction);
|
||||
self.dispatch(NodeGraphMessage::AddSecondaryImport);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = addPrimaryExport)]
|
||||
pub fn add_primary_export(&self) {
|
||||
self.dispatch(DocumentMessage::AddTransaction);
|
||||
self.dispatch(NodeGraphMessage::AddPrimaryExport);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = addSecondaryExport)]
|
||||
pub fn add_secondary_export(&self) {
|
||||
self.dispatch(DocumentMessage::AddTransaction);
|
||||
self.dispatch(NodeGraphMessage::AddSecondaryExport);
|
||||
}
|
||||
|
||||
/// Start Pointer Lock
|
||||
#[wasm_bindgen(js_name = appWindowPointerLock)]
|
||||
pub fn app_window_pointer_lock(&self) {
|
||||
let message = AppWindowMessage::PointerLock;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Minimizes the application window to the taskbar or dock
|
||||
#[wasm_bindgen(js_name = appWindowMinimize)]
|
||||
pub fn app_window_minimize(&self) {
|
||||
let message = AppWindowMessage::Minimize;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggles minimizing or restoring down the application window
|
||||
#[wasm_bindgen(js_name = appWindowMaximize)]
|
||||
pub fn app_window_maximize(&self) {
|
||||
let message = AppWindowMessage::Maximize;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = appWindowFullscreen)]
|
||||
pub fn app_window_fullscreen(&self) {
|
||||
let message = AppWindowMessage::Fullscreen;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Closes the application window
|
||||
#[wasm_bindgen(js_name = appWindowClose)]
|
||||
pub fn app_window_close(&self) {
|
||||
let message = AppWindowMessage::Close;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Drag the application window
|
||||
#[wasm_bindgen(js_name = appWindowDrag)]
|
||||
pub fn app_window_start_drag(&self) {
|
||||
let message = AppWindowMessage::Drag;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Displays a dialog with an error message
|
||||
#[wasm_bindgen(js_name = errorDialog)]
|
||||
pub fn error_dialog(&self, title: String, description: String) {
|
||||
let message = DialogMessage::DisplayDialogError { title, description };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Answer whether or not the editor has crashed
|
||||
#[wasm_bindgen(js_name = hasCrashed)]
|
||||
pub fn has_crashed(&self) -> bool {
|
||||
@@ -330,676 +240,25 @@ impl EditorWrapper {
|
||||
cfg!(debug_assertions)
|
||||
}
|
||||
|
||||
/// Get the constant `FILE_EXTENSION`
|
||||
#[wasm_bindgen(js_name = fileExtension)]
|
||||
pub fn file_extension(&self) -> String {
|
||||
FILE_EXTENSION.into()
|
||||
"graphite".into()
|
||||
}
|
||||
|
||||
/// Get the constant `GDD_FILE_EXTENSION`
|
||||
#[wasm_bindgen(js_name = gddFileExtension)]
|
||||
pub fn gdd_file_extension(&self) -> String {
|
||||
GDD_FILE_EXTENSION.into()
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, but don't commit it to the history (unless `commit_layout()` is called, which handles that)
|
||||
#[wasm_bindgen(js_name = widgetValueUpdate)]
|
||||
pub fn widget_value_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)
|
||||
}
|
||||
|
||||
/// Commit the value of a given UI widget to the history
|
||||
#[wasm_bindgen(js_name = widgetValueCommit)]
|
||||
pub fn widget_value_commit(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
||||
self.widget_value_commit_helper(layout_target, widget_id, value)
|
||||
}
|
||||
|
||||
/// Update the value of a given UI widget, and commit it to the history
|
||||
#[wasm_bindgen(js_name = widgetValueCommitAndUpdate)]
|
||||
pub fn widget_value_commit_and_update(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
self.widget_value_commit_helper(layout_target, widget_id, value.clone())?;
|
||||
self.widget_value_update_helper(layout_target, widget_id, value, resend_widget)?;
|
||||
// Close out a transaction that the widget's `on_commit` opened (if any), so a single click on widgets like the
|
||||
// NumberInput's increment buttons collapses into one history step instead of leaving the transaction in `Modified`
|
||||
self.dispatch(DocumentMessage::EndTransaction);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Fire a widget's drag-drop action (e.g. when a draggable item is dropped on a button)
|
||||
#[wasm_bindgen(js_name = widgetValueDragDrop)]
|
||||
pub fn widget_value_drag_drop(&self, layout_target: LayoutTarget, widget_id: u64) {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
self.dispatch(LayoutMessage::WidgetValueDragDrop { layout_target, widget_id });
|
||||
}
|
||||
|
||||
/// Closes out the current transaction (drag-end / text-commit end), so emits during a slider drag collapse into one history step instead of N
|
||||
#[wasm_bindgen(js_name = endTransaction)]
|
||||
pub fn end_transaction(&self) {
|
||||
self.dispatch(DocumentMessage::EndTransaction);
|
||||
}
|
||||
|
||||
pub fn widget_value_update_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue, resend_widget: bool) -> Result<(), JsValue> {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not update UI: {e}")))?;
|
||||
let message = LayoutMessage::WidgetValueUpdate { layout_target, widget_id, value };
|
||||
self.dispatch(message);
|
||||
if resend_widget {
|
||||
let resend_message = LayoutMessage::ResendActiveWidget { layout_target, widget_id };
|
||||
self.dispatch(resend_message);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn widget_value_commit_helper(&self, layout_target: LayoutTarget, widget_id: u64, value: JsValue) -> Result<(), JsValue> {
|
||||
let widget_id = WidgetId(widget_id);
|
||||
let value: serde_json::Value = from_value(value).map_err(|e| Error::new(&format!("Could not commit UI: {e}")))?;
|
||||
let message = LayoutMessage::WidgetValueCommit { layout_target, widget_id, value };
|
||||
self.dispatch(message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = loadPreferences)]
|
||||
pub fn load_preferences(&self, preferences: Option<String>) {
|
||||
if let Some(preferences) = preferences {
|
||||
let Ok(preferences) = serde_json::from_str(&preferences) else {
|
||||
log::error!("Failed to deserialize preferences");
|
||||
return;
|
||||
};
|
||||
let message = PreferencesMessage::Load { preferences };
|
||||
self.dispatch(message);
|
||||
}
|
||||
"gdd".into()
|
||||
}
|
||||
|
||||
/// Load persisted browser storage state (web only; on desktop, persistence is handled natively and this is never triggered)
|
||||
#[cfg(all(feature = "web", not(feature = "native")))]
|
||||
#[wasm_bindgen(js_name = loadPersistedState)]
|
||||
pub fn load_persisted_state(&self, state: editor::messages::frontend::utility_types::PersistedState) {
|
||||
self.dispatch(PersistentStateMessage::LoadState { state });
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = loadDocumentContent)]
|
||||
pub fn load_document_content(&self, document_id: u64, document: String) {
|
||||
let message = PersistentStateMessage::LoadDocument {
|
||||
document_id: DocumentId(document_id),
|
||||
document,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = selectDocument)]
|
||||
pub fn select_document(&self, document_id: u64) {
|
||||
let document_id = DocumentId(document_id);
|
||||
let message = PortfolioMessage::SelectDocument { document_id };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Rename the currently active document.
|
||||
#[wasm_bindgen(js_name = renameDocument)]
|
||||
pub fn rename_document(&self, new_name: String) {
|
||||
let message = PortfolioMessage::RenameDocument { new_name };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = newDocumentDialog)]
|
||||
pub fn new_document_dialog(&self) {
|
||||
let message = DialogMessage::RequestNewDocumentDialog;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = openFile)]
|
||||
pub fn open_file(&self, path: String, content: Vec<u8>) {
|
||||
let message = PortfolioMessage::OpenFile { path: PathBuf::from(path), content };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = importFile)]
|
||||
pub fn import_file(&self, path: String, content: Vec<u8>) {
|
||||
let message = PortfolioMessage::ImportFile { path: PathBuf::from(path), content };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = triggerAutoSave)]
|
||||
pub fn trigger_auto_save(&self, document_id: u64) {
|
||||
let document_id = DocumentId(document_id);
|
||||
let message = PortfolioMessage::AutoSaveDocument { document_id };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = reorderDocument)]
|
||||
pub fn reorder_document(&self, document_id: u64, new_index: usize) {
|
||||
let document_id = DocumentId(document_id);
|
||||
let message = PortfolioMessage::ReorderDocument { document_id, new_index };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = reorderPanelGroupTab)]
|
||||
pub fn reorder_panel_group_tab(&self, group: u64, old_index: usize, new_index: usize) {
|
||||
let message = PortfolioMessage::ReorderPanelGroupTab {
|
||||
group: PanelGroupId(group),
|
||||
old_index,
|
||||
new_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = moveAllPanelTabs)]
|
||||
pub fn move_all_panel_tabs(&self, source_group: u64, target_group: u64, insert_index: usize) {
|
||||
let message = PortfolioMessage::MoveAllPanelTabs {
|
||||
source_group: PanelGroupId(source_group),
|
||||
target_group: PanelGroupId(target_group),
|
||||
insert_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = movePanelTab)]
|
||||
pub fn move_panel_tab(&self, source_group: u64, target_group: u64, insert_index: usize) {
|
||||
let message = PortfolioMessage::MovePanelTab {
|
||||
source_group: PanelGroupId(source_group),
|
||||
target_group: PanelGroupId(target_group),
|
||||
insert_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = setPanelGroupActiveTab)]
|
||||
pub fn set_panel_group_active_tab(&self, group: u64, tab_index: usize) {
|
||||
let message = PortfolioMessage::SetPanelGroupActiveTab {
|
||||
group: PanelGroupId(group),
|
||||
tab_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = splitPanelGroup)]
|
||||
pub fn split_panel_group(&self, target_group: u64, direction: DockingSplitDirection, tabs: Vec<PanelType>, active_tab_index: usize) {
|
||||
let message = PortfolioMessage::SplitPanelGroup {
|
||||
target_group: PanelGroupId(target_group),
|
||||
direction,
|
||||
tabs,
|
||||
active_tab_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = setPanelGroupSizes)]
|
||||
pub fn set_panel_group_sizes(&self, split_path: Vec<u32>, sizes: Vec<f64>) {
|
||||
let split_path = split_path.into_iter().map(|i| i as usize).collect();
|
||||
let message = PortfolioMessage::SetPanelGroupSizes { split_path, sizes };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = closeDocumentWithConfirmation)]
|
||||
pub fn close_document_with_confirmation(&self, document_id: u64) {
|
||||
let document_id = DocumentId(document_id);
|
||||
let message = PortfolioMessage::CloseDocumentWithConfirmation { document_id };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = requestAboutGraphiteDialogWithLocalizedCommitDate)]
|
||||
pub fn request_about_graphite_dialog_with_localized_commit_date(&self, localized_commit_date: String, localized_commit_year: String) {
|
||||
let message = DialogMessage::RequestAboutGraphiteDialogWithLocalizedCommitDate {
|
||||
localized_commit_date,
|
||||
localized_commit_year,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = requestLicensesThirdPartyDialogWithLicenseText)]
|
||||
pub fn request_licenses_third_party_dialog_with_license_text(&self, license_text: String) {
|
||||
let message = DialogMessage::RequestLicensesThirdPartyDialogWithLicenseText { license_text };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Send new viewport info to the backend
|
||||
#[wasm_bindgen(js_name = updateViewport)]
|
||||
pub fn update_viewport(&self, x: f64, y: f64, width: f64, height: f64, scale: f64) {
|
||||
let message = ViewportMessage::Update { x, y, width, height, scale };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse movement within the screenspace bounds of the viewport
|
||||
#[wasm_bindgen(js_name = onMouseMove)]
|
||||
pub fn on_mouse_move(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
let message = InputPreprocessorMessage::PointerMove { editor_mouse_state, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse scrolling within the screenspace bounds of the viewport
|
||||
#[wasm_bindgen(js_name = onWheelScroll)]
|
||||
pub fn on_wheel_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: f64, wheel_delta_y: f64, wheel_delta_z: f64, modifiers: u8) {
|
||||
let mut editor_mouse_state = EditorMouseState::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");
|
||||
|
||||
let message = InputPreprocessorMessage::WheelScroll { editor_mouse_state, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A mouse button depressed within screenspace the bounds of the viewport
|
||||
#[wasm_bindgen(js_name = onMouseDown)]
|
||||
pub fn on_mouse_down(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
let message = InputPreprocessorMessage::PointerDown { editor_mouse_state, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A mouse button released
|
||||
#[wasm_bindgen(js_name = onMouseUp)]
|
||||
pub fn on_mouse_up(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
let message = InputPreprocessorMessage::PointerUp { editor_mouse_state, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse shaken
|
||||
#[wasm_bindgen(js_name = onMouseShake)]
|
||||
pub fn on_mouse_shake(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
let message = InputPreprocessorMessage::PointerShake { editor_mouse_state, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse double clicked
|
||||
#[wasm_bindgen(js_name = onDoubleClick)]
|
||||
pub fn on_double_click(&self, x: f64, y: f64, mouse_keys: u8, modifiers: u8) {
|
||||
let editor_mouse_state = EditorMouseState::from_keys_and_editor_position(mouse_keys, (x, y).into());
|
||||
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
let message = InputPreprocessorMessage::DoubleClick { editor_mouse_state, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A keyboard button depressed within screenspace the bounds of the viewport
|
||||
#[wasm_bindgen(js_name = onKeyDown)]
|
||||
pub fn on_key_down(&self, name: String, modifiers: u8, key_repeat: bool) {
|
||||
let key = translate_key(&name);
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
trace!("Key down {key:?}, name: {name}, modifiers: {modifiers:?}, key repeat: {key_repeat}");
|
||||
|
||||
let message = InputPreprocessorMessage::KeyDown { key, key_repeat, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A keyboard button released
|
||||
#[wasm_bindgen(js_name = onKeyUp)]
|
||||
pub fn on_key_up(&self, name: String, modifiers: u8, key_repeat: bool) {
|
||||
let key = translate_key(&name);
|
||||
let modifier_keys = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
trace!("Key up {key:?}, name: {name}, modifiers: {modifier_keys:?}, key repeat: {key_repeat}");
|
||||
|
||||
let message = InputPreprocessorMessage::KeyUp { key, key_repeat, modifier_keys };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A text box was committed
|
||||
#[wasm_bindgen(js_name = onChangeText)]
|
||||
pub fn on_change_text(&self, new_text: String, is_left_or_right_click: bool) -> Result<(), JsValue> {
|
||||
let message = TextToolMessage::TextChange { new_text, is_left_or_right_click };
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Dialog got dismissed
|
||||
#[wasm_bindgen(js_name = onDialogDismiss)]
|
||||
pub fn on_dialog_dismiss(&self) {
|
||||
let message = DialogMessage::Dismiss;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A text box was changed
|
||||
#[wasm_bindgen(js_name = updateBounds)]
|
||||
pub fn update_bounds(&self, new_text: String) -> Result<(), JsValue> {
|
||||
let message = TextToolMessage::UpdateBounds { new_text };
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update primary color from sRGB bytes (the wire format at the JS boundary).
|
||||
#[wasm_bindgen(js_name = updatePrimaryColor)]
|
||||
pub fn update_primary_color(&self, color: SRGBA8) {
|
||||
self.dispatch(ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: true,
|
||||
});
|
||||
}
|
||||
|
||||
/// Update secondary color from sRGB bytes (the wire format at the JS boundary).
|
||||
#[wasm_bindgen(js_name = updateSecondaryColor)]
|
||||
pub fn update_secondary_color(&self, color: SRGBA8) {
|
||||
self.dispatch(ToolMessage::SelectWorkingColor {
|
||||
color: Color::from(color),
|
||||
primary: false,
|
||||
});
|
||||
}
|
||||
|
||||
/// Initialize the Rust color picker handler with a starting value (used when the frontend `<ColorPicker />` opens).
|
||||
#[wasm_bindgen(js_name = openColorPicker)]
|
||||
pub fn open_color_picker(&self, initial_value: FillChoiceUI, allow_none: bool, disabled: bool) {
|
||||
let initial_value = FillChoice::from(&initial_value);
|
||||
self.dispatch(ColorPickerMessage::Open { initial_value, allow_none, disabled });
|
||||
}
|
||||
|
||||
/// Tell the Rust color picker handler that the popover is closing.
|
||||
#[wasm_bindgen(js_name = closeColorPicker)]
|
||||
pub fn close_color_picker(&self) {
|
||||
self.dispatch(ColorPickerMessage::Close);
|
||||
}
|
||||
|
||||
/// Update the color of the currently-edited gradient stop, from sRGB bytes (the wire format at the JS boundary).
|
||||
#[wasm_bindgen(js_name = updateGradientStopColor)]
|
||||
pub fn update_gradient_stop_color(&self, color: SRGBA8) {
|
||||
self.dispatch(GradientToolMessage::UpdateStopColor { color: Color::from(color) });
|
||||
}
|
||||
|
||||
/// Start a new undo transaction for gradient stop color editing
|
||||
#[wasm_bindgen(js_name = startGradientStopColorTransaction)]
|
||||
pub fn start_gradient_stop_color_transaction(&self) {
|
||||
self.dispatch(GradientToolMessage::StartTransactionForColorStop);
|
||||
}
|
||||
|
||||
/// Commit the current gradient stop color transaction (called on pointer-up after each drag/click)
|
||||
#[wasm_bindgen(js_name = commitGradientStopColorTransaction)]
|
||||
pub fn commit_gradient_stop_color_transaction(&self) {
|
||||
self.dispatch(GradientToolMessage::CommitTransactionForColorStop);
|
||||
}
|
||||
|
||||
/// Close the gradient stop color picker and commit any pending transaction
|
||||
#[wasm_bindgen(js_name = closeGradientStopColorPicker)]
|
||||
pub fn close_gradient_stop_color_picker(&self) {
|
||||
self.dispatch(GradientToolMessage::CloseStopColorPicker);
|
||||
}
|
||||
|
||||
/// Toggle clipping the alpha of a layer to the alpha of the layer below it in the layer stack
|
||||
#[wasm_bindgen(js_name = clipLayer)]
|
||||
pub fn clip_layer(&self, id: u64) {
|
||||
let id = NodeId(id);
|
||||
let message = DocumentMessage::ClipLayer { id };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Modify the layer selection based on the layer which is clicked while holding down the <kbd>Ctrl</kbd> and/or <kbd>Shift</kbd> modifier keys used for range selection behavior
|
||||
#[wasm_bindgen(js_name = selectLayer)]
|
||||
pub fn select_layer(&self, id: u64, ctrl: bool, shift: bool) {
|
||||
let id = NodeId(id);
|
||||
let message = DocumentMessage::SelectLayer { id, ctrl, shift };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Deselect all layers
|
||||
#[wasm_bindgen(js_name = deselectAllLayers)]
|
||||
pub fn deselect_all_layers(&self) {
|
||||
let message = DocumentMessage::DeselectAllLayers;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Move a layer to within a folder and placed down at the given index.
|
||||
/// If the folder is `None`, it is inserted into the document root.
|
||||
/// If the insert index is `None`, it is inserted at the start of the folder.
|
||||
#[wasm_bindgen(js_name = moveLayerInTree)]
|
||||
pub fn move_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
|
||||
let insert_parent_id = insert_parent_id.map(NodeId);
|
||||
let parent = insert_parent_id.map(LayerNodeIdentifier::new_unchecked).unwrap_or_default();
|
||||
|
||||
let message = DocumentMessage::MoveSelectedLayersTo {
|
||||
parent,
|
||||
insert_index: insert_index.unwrap_or_default(),
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Reorder a draggable Properties panel section to the given index among its peers.
|
||||
#[wasm_bindgen(js_name = reorderPropertiesSection)]
|
||||
pub fn reorder_properties_section(&self, node_id: u64, insert_index: usize) {
|
||||
self.dispatch(DocumentMessage::ReorderPropertiesSection {
|
||||
node_id: NodeId(node_id),
|
||||
insert_index,
|
||||
});
|
||||
}
|
||||
|
||||
/// Duplicate the selected layers, placing the copies within the given folder at the given index.
|
||||
/// If the folder is `None`, they are inserted into the document root.
|
||||
/// If the insert index is `None`, they are inserted at the start of the folder.
|
||||
#[wasm_bindgen(js_name = duplicateLayerInTree)]
|
||||
pub fn duplicate_layer_in_tree(&self, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
|
||||
let message = DocumentMessage::DuplicateSelectedLayersTo {
|
||||
parent: insert_parent_id.map(NodeId).map(LayerNodeIdentifier::new_unchecked).unwrap_or_default(),
|
||||
insert_index: insert_index.unwrap_or_default(),
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Set the name for the layer
|
||||
#[wasm_bindgen(js_name = setLayerName)]
|
||||
pub fn set_layer_name(&self, id: u64, name: String) {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(id));
|
||||
let message = NodeGraphMessage::SetDisplayName {
|
||||
node_id: layer.to_node(),
|
||||
network_path: Vec::new(),
|
||||
alias: name,
|
||||
skip_adding_history_step: false,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
#[wasm_bindgen(js_name = panCanvasAbortPrepare)]
|
||||
pub fn pan_canvas_abort_prepare(&self, x_not_y_axis: bool) {
|
||||
let message = NavigationMessage::CanvasPanAbortPrepare { x_not_y_axis };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen(js_name = panCanvasAbort)]
|
||||
pub fn pan_canvas_abort(&self, x_not_y_axis: bool) {
|
||||
let message = NavigationMessage::CanvasPanAbort { x_not_y_axis };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
#[wasm_bindgen(js_name = panCanvas)]
|
||||
pub fn pan_canvas(&self, delta_x: f64, delta_y: f64) {
|
||||
let message = NavigationMessage::CanvasPan { delta: (delta_x, delta_y).into() };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
#[wasm_bindgen(js_name = panCanvasByFraction)]
|
||||
pub fn pan_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
|
||||
let message = NavigationMessage::CanvasPanByViewportFraction { delta: (delta_x, delta_y).into() };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Merge the selected nodes into a subnetwork
|
||||
#[wasm_bindgen(js_name = mergeSelectedNodes)]
|
||||
pub fn merge_nodes(&self) {
|
||||
let message = NodeGraphMessage::MergeSelectedNodes;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle lock state of all selected layers
|
||||
#[wasm_bindgen(js_name = toggleSelectedLocked)]
|
||||
pub fn toggle_selected_locked(&self) {
|
||||
let message = NodeGraphMessage::ToggleSelectedLocked;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Creates a new document node in the node graph
|
||||
#[wasm_bindgen(js_name = createNode)]
|
||||
pub fn create_node(&self, node_type: JsValue, x: i32, y: i32) {
|
||||
let value: serde_json::Value = serde_wasm_bindgen::from_value(node_type).unwrap();
|
||||
|
||||
let id = NodeId::new();
|
||||
let message = NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(id),
|
||||
node_type: value.into(),
|
||||
xy: Some((x / 24, y / 24)),
|
||||
add_transaction: true,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Respond to selection read
|
||||
#[wasm_bindgen(js_name = readSelection)]
|
||||
pub fn read_selection(&self, content: Option<String>, cut: bool) {
|
||||
let message = ClipboardMessage::ReadSelection { content, cut };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Paste from a serialized JSON representation
|
||||
#[wasm_bindgen(js_name = pasteText)]
|
||||
pub fn paste_text(&self, data: String) {
|
||||
let message = ClipboardMessage::ReadClipboard {
|
||||
content: ClipboardContentRaw::Text(data),
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Pastes an image
|
||||
#[wasm_bindgen(js_name = pasteImage)]
|
||||
pub fn paste_image(
|
||||
&self,
|
||||
name: Option<String>,
|
||||
image_data: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
mouse_x: Option<f64>,
|
||||
mouse_y: Option<f64>,
|
||||
insert_parent_id: Option<u64>,
|
||||
insert_index: Option<usize>,
|
||||
) {
|
||||
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
||||
let image = graphene_std::raster::Image::from_image_data(&image_data, width, height);
|
||||
|
||||
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
||||
let insert_parent_id = NodeId(insert_parent_id);
|
||||
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
||||
Some((parent, insert_index))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let message = PortfolioMessage::InsertImage {
|
||||
name,
|
||||
image,
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Pastes an SVG given its string representation
|
||||
#[wasm_bindgen(js_name = pasteSvg)]
|
||||
pub fn paste_svg(&self, name: Option<String>, svg: String, mouse_x: Option<f64>, mouse_y: Option<f64>, insert_parent_id: Option<u64>, insert_index: Option<usize>) {
|
||||
let mouse = mouse_x.and_then(|x| mouse_y.map(|y| (x, y)));
|
||||
|
||||
let parent_and_insert_index = if let (Some(insert_parent_id), Some(insert_index)) = (insert_parent_id, insert_index) {
|
||||
let insert_parent_id = NodeId(insert_parent_id);
|
||||
let parent = LayerNodeIdentifier::new_unchecked(insert_parent_id);
|
||||
Some((parent, insert_index))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let message = PortfolioMessage::InsertSvg {
|
||||
name,
|
||||
svg,
|
||||
mouse,
|
||||
parent_and_insert_index,
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle visibility of a layer or node given its node ID
|
||||
#[wasm_bindgen(js_name = toggleNodeVisibilityLayerPanel)]
|
||||
pub fn toggle_node_visibility_layer(&self, id: u64) {
|
||||
let node_id = NodeId(id);
|
||||
let message = NodeGraphMessage::ToggleVisibility { node_id, network_path: Vec::new() };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Pin or unpin a node given its node ID
|
||||
#[wasm_bindgen(js_name = setNodePinned)]
|
||||
pub fn set_node_pinned(&self, id: u64, pinned: bool) {
|
||||
self.dispatch(DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned });
|
||||
}
|
||||
|
||||
/// Collapse or expand a node's section in the Properties panel
|
||||
#[wasm_bindgen(js_name = toggleNodePropertiesSectionExpanded)]
|
||||
pub fn toggle_node_properties_section_expanded(&self, id: u64) {
|
||||
self.dispatch(DocumentMessage::ToggleNodePropertiesSectionExpanded { node_id: NodeId(id) });
|
||||
}
|
||||
|
||||
/// Delete a layer or node given its node ID
|
||||
#[wasm_bindgen(js_name = deleteNode)]
|
||||
pub fn delete_node(&self, id: u64) {
|
||||
self.dispatch(DocumentMessage::DeleteNode { node_id: NodeId(id) });
|
||||
}
|
||||
|
||||
/// Toggle lock state of a layer from the layer list
|
||||
#[wasm_bindgen(js_name = toggleLayerLock)]
|
||||
pub fn toggle_layer_lock(&self, node_id: u64) {
|
||||
let message = NodeGraphMessage::ToggleLocked {
|
||||
node_id: NodeId(node_id),
|
||||
network_path: Vec::new(),
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle expansions state of a layer from the layer list
|
||||
#[wasm_bindgen(js_name = toggleLayerExpansion)]
|
||||
pub fn toggle_layer_expansion(&self, tree_path: &[u64], recursive: bool) {
|
||||
let tree_path = tree_path.iter().map(|&id| NodeId(id)).collect();
|
||||
let message = DocumentMessage::ToggleLayerExpansion { tree_path, recursive };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Set the active panel to the most recently clicked panel
|
||||
#[wasm_bindgen(js_name = setActivePanel)]
|
||||
pub fn set_active_panel(&self, panel: String) {
|
||||
let message = DocumentMessage::SetActivePanel { active_panel: panel.into() };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle display type for a layer
|
||||
#[wasm_bindgen(js_name = setToNodeOrLayer)]
|
||||
pub fn set_to_node_or_layer(&self, id: u64, is_layer: bool) {
|
||||
self.dispatch(DocumentMessage::SetToNodeOrLayer { node_id: NodeId(id), is_layer });
|
||||
}
|
||||
|
||||
/// Set the name of an import or export
|
||||
#[wasm_bindgen(js_name = setImportName)]
|
||||
pub fn set_import_name(&self, index: usize, name: String) {
|
||||
let message = NodeGraphMessage::SetImportExportName {
|
||||
name,
|
||||
index: ImportOrExport::Import(index),
|
||||
};
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Set the name of an export
|
||||
#[wasm_bindgen(js_name = setExportName)]
|
||||
pub fn set_export_name(&self, index: usize, name: String) {
|
||||
let message = NodeGraphMessage::SetImportExportName {
|
||||
name,
|
||||
index: ImportOrExport::Export(index),
|
||||
};
|
||||
self.dispatch(message);
|
||||
#[cfg(feature = "native")]
|
||||
#[wasm_bindgen(js_name = loadPersistedState)]
|
||||
pub fn load_persisted_state(&self, _state: JsValue) {
|
||||
log::error!("loadPersistedState is unavailable on desktop; persistence is handled natively");
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
#[cfg(not(feature = "native"))]
|
||||
use crate::EDITOR;
|
||||
#[cfg(not(feature = "native"))]
|
||||
use crate::EDITOR_HAS_CRASHED;
|
||||
use crate::EDITOR_WRAPPER;
|
||||
use crate::editor_wrapper::EditorWrapper;
|
||||
use crate::{EDITOR_HAS_CRASHED, EDITOR_WRAPPER};
|
||||
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;
|
||||
#[cfg(not(feature = "native"))]
|
||||
use editor::messages::prelude::*;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::Image;
|
||||
use js_sys::{Object, Reflect};
|
||||
#[cfg(not(feature = "native"))]
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
use wasm_bindgen::JsCast;
|
||||
@@ -119,18 +123,8 @@ pub(crate) fn async_wake_callback() -> Wake {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn auto_save_all_documents() {
|
||||
// Process no further messages after a crash to avoid spamming the console
|
||||
if EDITOR_HAS_CRASHED.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
wrapper(|wrapper| {
|
||||
wrapper.dispatch(PortfolioMessage::AutoSaveAllDocuments);
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)]) {
|
||||
/// Blits each rasterized image to a canvas registered on `window.imageCanvases`
|
||||
pub(crate) fn render_image_data_to_canvases<'a>(image_data: impl IntoIterator<Item = &'a RasterizedImage>) {
|
||||
let window = match window() {
|
||||
Some(window) => window,
|
||||
None => {
|
||||
@@ -155,11 +149,13 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
|
||||
};
|
||||
let canvases_obj = Object::from(canvases_obj);
|
||||
|
||||
for (placeholder_id, image) in image_data.iter() {
|
||||
for image in image_data {
|
||||
let (placeholder_id, width, height) = (image.id, image.width, image.height);
|
||||
let pixels = image.pixels.as_slice();
|
||||
let canvas_name = placeholder_id.to_string();
|
||||
let js_key = JsValue::from_str(&canvas_name);
|
||||
|
||||
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || image.width == 0 || image.height == 0 {
|
||||
if Reflect::has(&canvases_obj, &js_key).unwrap_or(false) || width == 0 || height == 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -169,8 +165,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
|
||||
.dyn_into::<HtmlCanvasElement>()
|
||||
.expect("Failed to cast element to HtmlCanvasElement");
|
||||
|
||||
canvas.set_width(image.width);
|
||||
canvas.set_height(image.height);
|
||||
canvas.set_width(width);
|
||||
canvas.set_height(height);
|
||||
|
||||
let context: CanvasRenderingContext2d = canvas
|
||||
.get_context("2d")
|
||||
@@ -178,10 +174,8 @@ pub(crate) fn render_image_data_to_canvases(image_data: &[(u64, Image<SRGBA8>)])
|
||||
.expect("2d context was not found")
|
||||
.dyn_into::<CanvasRenderingContext2d>()
|
||||
.expect("Failed to cast context to CanvasRenderingContext2d");
|
||||
// `SRGBA8` is `#[repr(C)]` of four `u8`s, so the data buffer is already the byte format the canvas expects
|
||||
let u8_data: &[u8] = bytemuck::cast_slice(&image.data);
|
||||
let clamped_u8_data = wasm_bindgen::Clamped(u8_data);
|
||||
match ImageData::new_with_u8_clamped_array_and_sh(clamped_u8_data, image.width, image.height) {
|
||||
let clamped_pixels = wasm_bindgen::Clamped(pixels);
|
||||
match ImageData::new_with_u8_clamped_array_and_sh(clamped_pixels, width, height) {
|
||||
Ok(image_data_obj) => {
|
||||
if context.put_image_data(&image_data_obj, 0, 0).is_err() {
|
||||
error!("Failed to put image data on canvas for id: {placeholder_id}");
|
||||
@@ -209,6 +203,7 @@ pub(crate) fn calculate_hash<T: std::hash::Hash>(t: &T) -> u64 {
|
||||
}
|
||||
|
||||
/// Translate a keyboard key from its JS name to its Rust `Key` enum
|
||||
#[cfg(feature = "editor")]
|
||||
pub(crate) fn translate_key(name: &str) -> Key {
|
||||
use Key::*;
|
||||
|
||||
|
||||
+69
-39
@@ -4,11 +4,18 @@
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
pub mod editor_commands;
|
||||
pub mod editor_wrapper;
|
||||
pub mod helpers;
|
||||
pub mod native_communication;
|
||||
mod wasm_value;
|
||||
|
||||
#[cfg(any(feature = "native", not(target_family = "wasm")))]
|
||||
pub use editor_commands::EditorCommand;
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
use crate::helpers::wrapper;
|
||||
#[cfg(feature = "editor")]
|
||||
use editor::messages::prelude::*;
|
||||
use std::panic;
|
||||
use std::sync::Mutex;
|
||||
@@ -24,6 +31,7 @@ pub static LOGGER: WasmLog = WasmLog;
|
||||
thread_local! {
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub static EDITOR: Mutex<Option<editor::application::Editor>> = const { Mutex::new(None) };
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub static MESSAGE_BUFFER: std::cell::RefCell<Vec<Message>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
pub static EDITOR_WRAPPER: Mutex<Option<editor_wrapper::EditorWrapper>> = const { Mutex::new(None) };
|
||||
pub static PANIC_DIALOG_MESSAGE_CALLBACK: std::cell::RefCell<Option<js_sys::Function>> = const { std::cell::RefCell::new(None) };
|
||||
@@ -43,36 +51,41 @@ pub fn init_graphite() {
|
||||
/// When a panic occurs, notify the user and log the error to the JS console before the backend dies
|
||||
pub fn panic_hook(info: &panic::PanicHookInfo) {
|
||||
let info = info.to_string();
|
||||
let backtrace = Error::new("stack").stack().to_string();
|
||||
if backtrace.contains("DynAnyNode") {
|
||||
log::error!("Node graph evaluation panicked {info}");
|
||||
|
||||
// When the graph panics, the node runtime lock may not be released properly
|
||||
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() {
|
||||
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() };
|
||||
// Node graph panics can only originate here when the node graph runs inside this wasm module
|
||||
#[cfg(feature = "editor")]
|
||||
{
|
||||
let backtrace = Error::new("stack").stack().to_string();
|
||||
if backtrace.contains("DynAnyNode") {
|
||||
log::error!("Node graph evaluation panicked {info}");
|
||||
|
||||
// When the graph panics, the node runtime lock may not be released properly
|
||||
if editor::node_graph_executor::NODE_RUNTIME.try_lock().is_none() {
|
||||
unsafe { editor::node_graph_executor::NODE_RUNTIME.force_unlock() };
|
||||
}
|
||||
|
||||
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
|
||||
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
|
||||
wrapper(|wrapper| {
|
||||
let error = r#"
|
||||
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
|
||||
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
|
||||
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
|
||||
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
|
||||
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
|
||||
/text>"#
|
||||
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
|
||||
.to_string();
|
||||
wrapper.send_frontend_message_to_js(FrontendMessage::UpdateDocumentArtwork { svg: error });
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if !NODE_GRAPH_ERROR_DISPLAYED.load(Ordering::SeqCst) {
|
||||
NODE_GRAPH_ERROR_DISPLAYED.store(true, Ordering::SeqCst);
|
||||
wrapper(|wrapper| {
|
||||
let error = r#"
|
||||
<rect x="50%" y="50%" width="600" height="100" transform="translate(-300 -50)" rx="4" fill="var(--color-error-red)" />
|
||||
<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-size="18" fill="var(--color-2-mildblack)">
|
||||
<tspan x="50%" dy="-24" font-weight="bold">The document crashed while being rendered in its current state.</tspan>
|
||||
<tspan x="50%" dy="24">The editor is now unstable! Undo your last action to restore the artwork,</tspan>
|
||||
<tspan x="50%" dy="24">then save your document and restart the editor before continuing work.</tspan>
|
||||
/text>"#
|
||||
// It's a mystery why the `/text>` tag above needs to be missing its `<`, but when it exists it prints the `<` character in the text. However this works with it removed.
|
||||
.to_string();
|
||||
wrapper.send_frontend_message_to_js_rust_proxy(FrontendMessage::UpdateDocumentArtwork { svg: error });
|
||||
});
|
||||
}
|
||||
|
||||
return;
|
||||
} else {
|
||||
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
EDITOR_HAS_CRASHED.store(true, Ordering::SeqCst);
|
||||
|
||||
log::error!("{info}");
|
||||
|
||||
// Prefer using the raw JS callback to avoid mutex lock contention inside the panic hook.
|
||||
@@ -82,30 +95,20 @@ pub fn panic_hook(info: &panic::PanicHookInfo) {
|
||||
}
|
||||
|
||||
fn send_panic_dialog_via_callback(panic_info: String) -> Result<(), String> {
|
||||
let message = FrontendMessage::DisplayDialogPanic { panic_info };
|
||||
let message_type = message.to_discriminant().local_name();
|
||||
let message = PanicDialogMessage::DisplayDialogPanic { panic_info: panic_info.clone() };
|
||||
let Ok(message_data) = serde_wasm_bindgen::to_value(&message) else {
|
||||
log::error!("Failed to serialize crash dialog panic message");
|
||||
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
|
||||
unreachable!("Message variant changed unexpectedly")
|
||||
};
|
||||
return Err(panic_info);
|
||||
};
|
||||
|
||||
PANIC_DIALOG_MESSAGE_CALLBACK.with(|callback| {
|
||||
let callback_ref = callback.borrow();
|
||||
let Some(callback) = callback_ref.as_ref() else {
|
||||
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
|
||||
unreachable!("Message variant changed unexpectedly")
|
||||
};
|
||||
return Err(panic_info);
|
||||
};
|
||||
|
||||
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from(message_type), &message_data) {
|
||||
log::error!("Failed to send crash dialog panic message to JS: {:?}", error);
|
||||
let FrontendMessage::DisplayDialogPanic { panic_info } = message else {
|
||||
unreachable!("Message variant changed unexpectedly")
|
||||
};
|
||||
if let Err(error) = callback.call2(&JsValue::null(), &JsValue::from("DisplayDialogPanic"), &message_data) {
|
||||
log::error!("Failed to send crash dialog panic message to JS: {error:?}");
|
||||
return Err(panic_info);
|
||||
}
|
||||
|
||||
@@ -201,3 +204,30 @@ impl log::Log for WasmLog {
|
||||
|
||||
fn flush(&self) {}
|
||||
}
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
use editor::messages::prelude::FrontendMessage as PanicDialogMessage;
|
||||
|
||||
#[cfg(not(feature = "editor"))]
|
||||
use PanicDialogMessageCopy as PanicDialogMessage;
|
||||
|
||||
#[cfg(any(not(feature = "editor"), test))]
|
||||
#[derive(serde::Serialize)]
|
||||
enum PanicDialogMessageCopy {
|
||||
DisplayDialogPanic {
|
||||
#[serde(rename = "panicInfo")]
|
||||
panic_info: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "editor"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn panic_dialog_copy_matches_editor_shape() {
|
||||
let copy = serde_json::to_value(PanicDialogMessageCopy::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
|
||||
let real = serde_json::to_value(FrontendMessage::DisplayDialogPanic { panic_info: "info".into() }).unwrap();
|
||||
assert_eq!(copy, real);
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,77 @@
|
||||
use crate::editor_wrapper::EditorWrapper;
|
||||
use crate::helpers::wrapper;
|
||||
use editor::messages::prelude::FrontendMessage;
|
||||
//! Messaging with the native process. Serialized `FrontendMessage`s come in and are forwarded to JS,
|
||||
//! `EditorCommand`s go back out. Encoding and decoding both live here so the wire format stays in one place.
|
||||
|
||||
use crate::editor_wrapper::{EditorWrapper, IMAGE_DATA_HASH};
|
||||
use crate::helpers::{calculate_hash, render_image_data_to_canvases, wrapper};
|
||||
use crate::wasm_value::WasmValue;
|
||||
use js_sys::{ArrayBuffer, Uint8Array};
|
||||
use std::sync::atomic::Ordering;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen(js_name = "receiveNativeMessage")]
|
||||
pub fn receive_native_message(buffer: ArrayBuffer) {
|
||||
let buffer = Uint8Array::new(buffer.as_ref()).to_vec();
|
||||
match ron::from_str::<Vec<FrontendMessage>>(str::from_utf8(buffer.as_slice()).unwrap()) {
|
||||
match serde_json::from_slice::<Vec<(String, String)>>(&buffer) {
|
||||
Ok(messages) => {
|
||||
let callback = move |wrapper: &mut EditorWrapper| {
|
||||
for message in messages {
|
||||
wrapper.send_frontend_message_to_js_rust_proxy(message);
|
||||
wrapper(move |wrapper: &mut EditorWrapper| {
|
||||
for (name, data) in messages {
|
||||
match name.as_str() {
|
||||
"UpdateImageData" => {
|
||||
let new_hash = calculate_hash(&data);
|
||||
if IMAGE_DATA_HASH.swap(new_hash, Ordering::Relaxed) == new_hash {
|
||||
continue;
|
||||
}
|
||||
|
||||
match serde_json::from_str::<Vec<RasterizedImage>>(&data) {
|
||||
Ok(image_data) => render_image_data_to_canvases(image_data.iter()),
|
||||
Err(e) => error!("Failed to deserialize image data: {e:?}"),
|
||||
}
|
||||
}
|
||||
_ => match serde_json::from_str::<WasmValue>(&data) {
|
||||
Ok(value) => wrapper.forward_serialized_frontend_message_to_js(&name, value),
|
||||
Err(e) => log::error!("Failed to deserialize frontend message {name}: {e:?}"),
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
wrapper(callback);
|
||||
});
|
||||
}
|
||||
Err(e) => log::error!("Failed to deserialize frontend messages: {e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
pub fn encode_frontend_messages(messages: Vec<editor::messages::prelude::FrontendMessage>) -> Option<Vec<u8>> {
|
||||
use editor::messages::prelude::FrontendMessage;
|
||||
use editor::utility_traits::{AsMessage, ToDiscriminant};
|
||||
|
||||
let messages: Vec<(String, String)> = messages
|
||||
.into_iter()
|
||||
.map(|message| {
|
||||
let name = message.to_discriminant().local_name();
|
||||
let data = match message {
|
||||
FrontendMessage::UpdateImageData { image_data } => serde_json::to_string(&image_data).inspect_err(|e| log::error!("Failed to serialize {name} payload: {e}")).ok()?,
|
||||
message => crate::wasm_value::encode(&message)
|
||||
.inspect_err(|e| log::error!("Failed to serialize FrontendMessage {name}: {e}"))
|
||||
.ok()?,
|
||||
};
|
||||
Some((name, data))
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
|
||||
serde_json::to_vec(&messages).ok()
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
|
||||
pub fn decode_editor_command(data: &[u8]) -> Option<editor::messages::prelude::Message> {
|
||||
match serde_json::from_slice::<crate::EditorCommand>(data) {
|
||||
Ok(command) => Some(command.into()),
|
||||
Err(e) => {
|
||||
log::error!("Failed to deserialize editor command: {e}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn initialize_native_communication() {
|
||||
let global = js_sys::global();
|
||||
|
||||
@@ -44,3 +96,38 @@ pub fn send_message_to_cef(message: String) {
|
||||
// Call it with argument
|
||||
func.call1(&JsValue::NULL, &JsValue::from(buffer)).expect("Function call failed");
|
||||
}
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
pub(crate) use editor::messages::frontend::utility_types::RasterizedImage;
|
||||
|
||||
#[cfg(not(feature = "editor"))]
|
||||
pub(crate) use RasterizedImageCopy as RasterizedImage;
|
||||
|
||||
#[cfg(any(not(feature = "editor"), test))]
|
||||
#[derive(serde::Deserialize)]
|
||||
pub(crate) struct RasterizedImageCopy {
|
||||
pub(crate) id: u64,
|
||||
pub(crate) width: u32,
|
||||
pub(crate) height: u32,
|
||||
pub(crate) pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "editor"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rasterized_image_copy_matches_editor_shape() {
|
||||
let editor_image = RasterizedImage {
|
||||
id: 7,
|
||||
width: 2,
|
||||
height: 1,
|
||||
pixels: serde_bytes::ByteBuf::from(vec![1, 2, 3, 4, 5, 6, 7, 8]),
|
||||
};
|
||||
let json = serde_json::to_string(&vec![editor_image]).unwrap();
|
||||
let decoded: Vec<RasterizedImageCopy> = serde_json::from_str(&json).unwrap();
|
||||
assert_eq!(decoded[0].id, 7);
|
||||
assert_eq!((decoded[0].width, decoded[0].height), (2, 1));
|
||||
assert_eq!(decoded[0].pixels, [1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
//! Serializable stand-in for `JsValue`, used to send `FrontendMessage`s from the native editor process to JS.
|
||||
//! Keeps the types JSON can't represent (`BigInt`, `Uint8Array`, `Map`, `undefined`, `NaN`) so the wasm side
|
||||
//! can reconstruct the same `JsValue`s that `serde_wasm_bindgen` produces on web.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[cfg(feature = "editor")]
|
||||
use serde_json::Error;
|
||||
use wasm_bindgen::JsValue;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub(crate) enum WasmValue {
|
||||
Undefined,
|
||||
Bool(bool),
|
||||
Number(f64),
|
||||
NonFinite(NonFinite),
|
||||
Int(i64),
|
||||
UInt(u64),
|
||||
String(String),
|
||||
Bytes(Vec<u8>),
|
||||
Seq(Vec<WasmValue>),
|
||||
Object(Vec<(String, WasmValue)>),
|
||||
Map(Vec<(WasmValue, WasmValue)>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) enum NonFinite {
|
||||
Nan,
|
||||
PositiveInfinity,
|
||||
NegativeInfinity,
|
||||
}
|
||||
|
||||
impl From<NonFinite> for f64 {
|
||||
fn from(value: NonFinite) -> Self {
|
||||
match value {
|
||||
NonFinite::Nan => f64::NAN,
|
||||
NonFinite::PositiveInfinity => f64::INFINITY,
|
||||
NonFinite::NegativeInfinity => f64::NEG_INFINITY,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WasmValue> for JsValue {
|
||||
fn from(value: WasmValue) -> Self {
|
||||
match value {
|
||||
WasmValue::Undefined => JsValue::UNDEFINED,
|
||||
WasmValue::Bool(value) => JsValue::from_bool(value),
|
||||
WasmValue::Number(value) => JsValue::from_f64(value),
|
||||
WasmValue::NonFinite(value) => JsValue::from_f64(value.into()),
|
||||
WasmValue::Int(value) => JsValue::from(value),
|
||||
WasmValue::UInt(value) => JsValue::from(value),
|
||||
WasmValue::String(value) => JsValue::from_str(&value),
|
||||
WasmValue::Bytes(bytes) => js_sys::Uint8Array::from(bytes.as_slice()).into(),
|
||||
WasmValue::Seq(values) => {
|
||||
let array = js_sys::Array::new();
|
||||
for value in values {
|
||||
array.push(&value.into());
|
||||
}
|
||||
array.into()
|
||||
}
|
||||
WasmValue::Object(fields) => {
|
||||
let object = js_sys::Object::new();
|
||||
for (key, value) in fields {
|
||||
let _ = js_sys::Reflect::set(&object, &JsValue::from_str(&key), &value.into());
|
||||
}
|
||||
object.into()
|
||||
}
|
||||
WasmValue::Map(entries) => {
|
||||
let map = js_sys::Map::new();
|
||||
for (key, value) in entries {
|
||||
map.set(&key.into(), &value.into());
|
||||
}
|
||||
map.into()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
pub(crate) fn encode<T: Serialize + ?Sized>(value: &T) -> Result<String, serde_json::Error> {
|
||||
serde_json::to_string(&ser::to_value(value)?)
|
||||
}
|
||||
|
||||
#[cfg(feature = "editor")]
|
||||
mod ser {
|
||||
use super::*;
|
||||
use serde::ser::{self, Error as _};
|
||||
|
||||
pub(super) fn to_value<T: Serialize + ?Sized>(value: &T) -> Result<WasmValue, Error> {
|
||||
value.serialize(ValueSerializer)
|
||||
}
|
||||
|
||||
struct ValueSerializer;
|
||||
|
||||
impl ser::Serializer for ValueSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
type SerializeSeq = SeqSerializer;
|
||||
type SerializeTuple = SeqSerializer;
|
||||
type SerializeTupleStruct = SeqSerializer;
|
||||
type SerializeTupleVariant = VariantSeqSerializer;
|
||||
type SerializeMap = MapSerializer;
|
||||
type SerializeStruct = ObjectSerializer;
|
||||
type SerializeStructVariant = VariantObjectSerializer;
|
||||
|
||||
fn serialize_bool(self, v: bool) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Bool(v))
|
||||
}
|
||||
|
||||
fn serialize_i8(self, v: i8) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Number(v as f64))
|
||||
}
|
||||
|
||||
fn serialize_i16(self, v: i16) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Number(v as f64))
|
||||
}
|
||||
|
||||
fn serialize_i32(self, v: i32) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Number(v as f64))
|
||||
}
|
||||
|
||||
fn serialize_i64(self, v: i64) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Int(v))
|
||||
}
|
||||
|
||||
fn serialize_i128(self, v: i128) -> Result<WasmValue, Error> {
|
||||
if let Ok(v) = i64::try_from(v) {
|
||||
Ok(WasmValue::Int(v))
|
||||
} else {
|
||||
u64::try_from(v)
|
||||
.map(WasmValue::UInt)
|
||||
.map_err(|_| Error::custom(format!("i128 value {v} exceeds the wire BigInt range")))
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize_u8(self, v: u8) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Number(v as f64))
|
||||
}
|
||||
|
||||
fn serialize_u16(self, v: u16) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Number(v as f64))
|
||||
}
|
||||
|
||||
fn serialize_u32(self, v: u32) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Number(v as f64))
|
||||
}
|
||||
|
||||
fn serialize_u64(self, v: u64) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::UInt(v))
|
||||
}
|
||||
|
||||
fn serialize_u128(self, v: u128) -> Result<WasmValue, Error> {
|
||||
u64::try_from(v)
|
||||
.map(WasmValue::UInt)
|
||||
.map_err(|_| Error::custom(format!("u128 value {v} exceeds the wire BigInt range")))
|
||||
}
|
||||
|
||||
fn serialize_f32(self, v: f32) -> Result<WasmValue, Error> {
|
||||
self.serialize_f64(v as f64)
|
||||
}
|
||||
|
||||
fn serialize_f64(self, v: f64) -> Result<WasmValue, Error> {
|
||||
Ok(if v.is_finite() {
|
||||
WasmValue::Number(v)
|
||||
} else if v.is_nan() {
|
||||
WasmValue::NonFinite(NonFinite::Nan)
|
||||
} else if v > 0. {
|
||||
WasmValue::NonFinite(NonFinite::PositiveInfinity)
|
||||
} else {
|
||||
WasmValue::NonFinite(NonFinite::NegativeInfinity)
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_char(self, v: char) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::String(v.to_string()))
|
||||
}
|
||||
|
||||
fn serialize_str(self, v: &str) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::String(v.to_string()))
|
||||
}
|
||||
|
||||
fn serialize_bytes(self, v: &[u8]) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Bytes(v.to_vec()))
|
||||
}
|
||||
|
||||
fn serialize_none(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Undefined)
|
||||
}
|
||||
|
||||
fn serialize_some<T: Serialize + ?Sized>(self, value: &T) -> Result<WasmValue, Error> {
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_unit(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Undefined)
|
||||
}
|
||||
|
||||
fn serialize_unit_struct(self, _name: &'static str) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Undefined)
|
||||
}
|
||||
|
||||
fn serialize_unit_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::String(variant.to_string()))
|
||||
}
|
||||
|
||||
fn serialize_newtype_struct<T: Serialize + ?Sized>(self, _name: &'static str, value: &T) -> Result<WasmValue, Error> {
|
||||
value.serialize(self)
|
||||
}
|
||||
|
||||
fn serialize_newtype_variant<T: Serialize + ?Sized>(self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Object(vec![(variant.to_string(), value.serialize(ValueSerializer)?)]))
|
||||
}
|
||||
|
||||
fn serialize_seq(self, len: Option<usize>) -> Result<SeqSerializer, Error> {
|
||||
Ok(SeqSerializer(Vec::with_capacity(len.unwrap_or_default())))
|
||||
}
|
||||
|
||||
fn serialize_tuple(self, len: usize) -> Result<SeqSerializer, Error> {
|
||||
self.serialize_seq(Some(len))
|
||||
}
|
||||
|
||||
fn serialize_tuple_struct(self, _name: &'static str, len: usize) -> Result<SeqSerializer, Error> {
|
||||
self.serialize_seq(Some(len))
|
||||
}
|
||||
|
||||
fn serialize_tuple_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantSeqSerializer, Error> {
|
||||
Ok(VariantSeqSerializer {
|
||||
variant,
|
||||
elements: Vec::with_capacity(len),
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_map(self, len: Option<usize>) -> Result<MapSerializer, Error> {
|
||||
Ok(MapSerializer {
|
||||
entries: Vec::with_capacity(len.unwrap_or_default()),
|
||||
pending_key: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn serialize_struct(self, _name: &'static str, len: usize) -> Result<ObjectSerializer, Error> {
|
||||
Ok(ObjectSerializer(Vec::with_capacity(len)))
|
||||
}
|
||||
|
||||
fn serialize_struct_variant(self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize) -> Result<VariantObjectSerializer, Error> {
|
||||
Ok(VariantObjectSerializer {
|
||||
variant,
|
||||
fields: Vec::with_capacity(len),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct SeqSerializer(Vec<WasmValue>);
|
||||
|
||||
impl ser::SerializeSeq for SeqSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||
self.0.push(value.serialize(ValueSerializer)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Seq(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl ser::SerializeTuple for SeqSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_element<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||
ser::SerializeSeq::serialize_element(self, value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
ser::SerializeSeq::end(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl ser::SerializeTupleStruct for SeqSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||
ser::SerializeSeq::serialize_element(self, value)
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
ser::SerializeSeq::end(self)
|
||||
}
|
||||
}
|
||||
|
||||
struct VariantSeqSerializer {
|
||||
variant: &'static str,
|
||||
elements: Vec<WasmValue>,
|
||||
}
|
||||
|
||||
impl ser::SerializeTupleVariant for VariantSeqSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||
self.elements.push(value.serialize(ValueSerializer)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Seq(self.elements))]))
|
||||
}
|
||||
}
|
||||
|
||||
struct MapSerializer {
|
||||
entries: Vec<(WasmValue, WasmValue)>,
|
||||
pending_key: Option<WasmValue>,
|
||||
}
|
||||
|
||||
impl ser::SerializeMap for MapSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_key<T: Serialize + ?Sized>(&mut self, key: &T) -> Result<(), Error> {
|
||||
self.pending_key = Some(key.serialize(ValueSerializer)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn serialize_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
|
||||
let key = self.pending_key.take().ok_or_else(|| Error::custom("Map value serialized without a key"))?;
|
||||
self.entries.push((key, value.serialize(ValueSerializer)?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Map(self.entries))
|
||||
}
|
||||
}
|
||||
|
||||
struct ObjectSerializer(Vec<(String, WasmValue)>);
|
||||
|
||||
impl ser::SerializeStruct for ObjectSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
|
||||
self.0.push((key.to_string(), value.serialize(ValueSerializer)?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Object(self.0))
|
||||
}
|
||||
}
|
||||
|
||||
struct VariantObjectSerializer {
|
||||
variant: &'static str,
|
||||
fields: Vec<(String, WasmValue)>,
|
||||
}
|
||||
|
||||
impl ser::SerializeStructVariant for VariantObjectSerializer {
|
||||
type Ok = WasmValue;
|
||||
type Error = Error;
|
||||
|
||||
fn serialize_field<T: Serialize + ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> {
|
||||
self.fields.push((key.to_string(), value.serialize(ValueSerializer)?));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn end(self) -> Result<WasmValue, Error> {
|
||||
Ok(WasmValue::Object(vec![(self.variant.to_string(), WasmValue::Object(self.fields))]))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::wasm_value::encode;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
enum TestMessage {
|
||||
UnitVariant,
|
||||
StructVariant {
|
||||
#[serde(rename = "nodeId")]
|
||||
node_id: u64,
|
||||
width: u32,
|
||||
scale: f64,
|
||||
min: f64,
|
||||
max: f64,
|
||||
label: Option<String>,
|
||||
widths: std::collections::BTreeMap<u64, u32>,
|
||||
flags: Vec<bool>,
|
||||
bytes: serde_bytes::ByteBuf,
|
||||
},
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mirrors_serde_wasm_bindgen_representations() {
|
||||
assert_eq!(to_value(&TestMessage::UnitVariant).unwrap(), WasmValue::String("unitVariant".into()));
|
||||
|
||||
let message = TestMessage::StructVariant {
|
||||
node_id: u64::MAX,
|
||||
width: 8,
|
||||
scale: f64::NAN,
|
||||
min: f64::NEG_INFINITY,
|
||||
max: f64::INFINITY,
|
||||
label: None,
|
||||
widths: [(42, 7)].into(),
|
||||
flags: vec![true, false],
|
||||
bytes: serde_bytes::ByteBuf::from(vec![0, 255]),
|
||||
};
|
||||
let expected = WasmValue::Object(vec![(
|
||||
"structVariant".into(),
|
||||
WasmValue::Object(vec![
|
||||
("nodeId".into(), WasmValue::UInt(u64::MAX)),
|
||||
("width".into(), WasmValue::Number(8.)),
|
||||
("scale".into(), WasmValue::NonFinite(NonFinite::Nan)),
|
||||
("min".into(), WasmValue::NonFinite(NonFinite::NegativeInfinity)),
|
||||
("max".into(), WasmValue::NonFinite(NonFinite::PositiveInfinity)),
|
||||
("label".into(), WasmValue::Undefined),
|
||||
("widths".into(), WasmValue::Map(vec![(WasmValue::UInt(42), WasmValue::Number(7.))])),
|
||||
("flags".into(), WasmValue::Seq(vec![WasmValue::Bool(true), WasmValue::Bool(false)])),
|
||||
("bytes".into(), WasmValue::Bytes(vec![0, 255])),
|
||||
]),
|
||||
)]);
|
||||
assert_eq!(to_value(&message).unwrap(), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_decode_roundtrip() {
|
||||
let message = TestMessage::StructVariant {
|
||||
node_id: 1,
|
||||
width: 2,
|
||||
scale: f64::NAN,
|
||||
min: f64::NEG_INFINITY,
|
||||
max: 1.5,
|
||||
label: Some("hi".into()),
|
||||
widths: [(3, 4)].into(),
|
||||
flags: vec![true],
|
||||
bytes: serde_bytes::ByteBuf::from(vec![9]),
|
||||
};
|
||||
|
||||
let json: &str = &encode(&message).unwrap();
|
||||
let decoded: WasmValue = serde_json::from_str(json).unwrap();
|
||||
|
||||
assert_eq!(decoded, to_value(&message).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,7 @@ fn transform_network(content: TaggedValue, rotation: TaggedValue) -> ProtoNetwor
|
||||
|
||||
#[test]
|
||||
fn transform_composes_onto_item_wire() {
|
||||
use glam::{DAffine2, DVec2};
|
||||
use glam::DVec2;
|
||||
|
||||
let network = transform_network(TaggedValue::TypeDefault(item!(Vector)), TaggedValue::F64(0.));
|
||||
let output = network.output;
|
||||
@@ -197,7 +197,7 @@ fn transform_composes_onto_item_wire() {
|
||||
let context: Context = None;
|
||||
let result: Option<Item<Vector>> = futures::executor::block_on(tree.eval(output, context));
|
||||
let item = result.expect("A rank-0 chain through Transform should stay rank 0");
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
|
||||
let transform = item.attr_cloned_or_default::<core_types::attr::Transform>();
|
||||
assert_eq!(transform.translation, DVec2::new(5., 0.), "The translation should compose onto the item's transform attribute");
|
||||
}
|
||||
|
||||
@@ -219,8 +219,8 @@ fn transform_broadcasts_item_content_across_a_framed_parameter() {
|
||||
let list = result.expect("The broadcast should produce a List");
|
||||
assert_eq!(list.len(), 2, "One output item per frame slot");
|
||||
|
||||
let first: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 0);
|
||||
let second: DAffine2 = list.attribute_cloned_or_default(core_types::ATTR_TRANSFORM, 1);
|
||||
let first: DAffine2 = list.attr_cloned_or_default::<core_types::attr::Transform>(0);
|
||||
let second: DAffine2 = list.attr_cloned_or_default::<core_types::attr::Transform>(1);
|
||||
assert!((first.matrix2.col(0).y - 0.).abs() < 1e-10, "Slot 0 should be unrotated");
|
||||
assert!((second.matrix2.col(0).y - 1.).abs() < 1e-10, "Slot 1 should be rotated 90 degrees");
|
||||
}
|
||||
@@ -320,7 +320,7 @@ fn value_wires_materialize_as_items_at_resolution() {
|
||||
let context: Context = None;
|
||||
let result: Option<Item<DAffine2>> = futures::executor::block_on(tree.eval(NodeId(5), context));
|
||||
let item = result.expect("A value matrix should flow through Transform as an Item");
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(core_types::ATTR_TRANSFORM);
|
||||
let transform = item.attr_cloned_or_default::<core_types::attr::Transform>();
|
||||
assert_eq!(transform.translation, DVec2::new(7., 0.), "The translation should compose onto the gained transform attribute");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Typed attribute keys.
|
||||
//!
|
||||
//! Each key is a zero-sized marker implementing [`Attr`], which ties the name (the string
|
||||
//! stored in the attribute store) to the Rust value type.
|
||||
//!
|
||||
//! Keys are declared with the [`node_macro::attrs!`] macro: `Name: Type` entries, where
|
||||
//! `namespace { ... }` blocks contribute a `namespace:` name prefix. The key name is
|
||||
//! derived mechanically from the ident (UpperCamel -> snake_case). An optional `= value`
|
||||
//! after the type declares the key's implicit default (see [`Attr::implicit_default`]).
|
||||
|
||||
use crate::Color;
|
||||
use crate::list::NodeIdPath;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub trait Attr {
|
||||
type Value: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static;
|
||||
fn name() -> &'static str;
|
||||
|
||||
/// The value an item without this attribute is considered to have: the value type's `Default`,
|
||||
/// unless the key's `attrs!` declaration overrides it with `= value`.
|
||||
fn implicit_default() -> Self::Value {
|
||||
Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
Transform: DAffine2,
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
BlendMode: crate::blending::BlendMode,
|
||||
/// Item's opacity multiplier, composed multiplicatively through nested groups. Affects content clipped to the item.
|
||||
Opacity: f64 = 1.,
|
||||
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
|
||||
OpacityFill: f64 = 1.,
|
||||
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
ClippingMask: bool,
|
||||
/// Byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
Start: u64,
|
||||
/// Byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
End: u64,
|
||||
/// A regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
|
||||
Name: String,
|
||||
/// A JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||
Type: String,
|
||||
/// Artboard's top-left corner in document coordinates.
|
||||
Location: DVec2,
|
||||
/// Artboard's width and height.
|
||||
Dimensions: DVec2,
|
||||
/// Artboard's background fill.
|
||||
Background: Color,
|
||||
/// Whether an artboard clips content to its bounds.
|
||||
Clip: bool,
|
||||
/// Text item's font size in document-space units.
|
||||
FontSize: f64,
|
||||
/// Text item's line height as a ratio of the font size.
|
||||
LineHeight: f64,
|
||||
/// Text item's extra spacing between letters in document-space units.
|
||||
LetterSpacing: f64,
|
||||
/// Text item's maximum line-wrap width in document-space units.
|
||||
MaxWidth: Option<f64>,
|
||||
/// Text item's maximum block height in document-space units, past which lines are not drawn.
|
||||
MaxHeight: Option<f64>,
|
||||
/// Text item's faux-italic letter tilt angle in degrees.
|
||||
LetterTilt: f64,
|
||||
editor {
|
||||
/// Path from the root network to the layer node owning this item.
|
||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
||||
LayerPath: NodeIdPath,
|
||||
/// Affine mapping the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text'
|
||||
/// node's text frame in this item's local space. Each item carries the frame relative to its own
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
TextFrame: DAffine2,
|
||||
},
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
extern crate log;
|
||||
|
||||
pub mod attr;
|
||||
pub mod bounds;
|
||||
pub mod consts;
|
||||
pub mod context;
|
||||
@@ -16,6 +17,7 @@ pub mod uuid;
|
||||
pub mod value;
|
||||
|
||||
pub use crate as core_types;
|
||||
pub use attr::Attr;
|
||||
pub use blending::*;
|
||||
pub use color::Color;
|
||||
pub use context::*;
|
||||
@@ -23,11 +25,6 @@ pub use ctor;
|
||||
pub use dyn_any::{StaticTypeSized, WasmNotSend, WasmNotSync};
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_SPREAD_METHOD, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use no_std_types::AsU32;
|
||||
pub use no_std_types::blending;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
use crate::attr::{self, Attr};
|
||||
use crate::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use crate::math::quad::Quad;
|
||||
use crate::transform::ApplyTransform;
|
||||
@@ -7,79 +8,6 @@ use glam::DAffine2;
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
|
||||
// =================================================
|
||||
// Standard attribute keys used across the data flow
|
||||
// =================================================
|
||||
|
||||
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
|
||||
pub const ATTR_TRANSFORM: &str = "transform";
|
||||
/// Item's `BlendMode`, controlling how it composites with content beneath it.
|
||||
pub const ATTR_BLEND_MODE: &str = "blend_mode";
|
||||
/// Item's opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Composed multiplicatively through nested groups. Affects content clipped to the item.
|
||||
pub const ATTR_OPACITY: &str = "opacity";
|
||||
/// Item's fill opacity multiplier (`f64`, implicit default `1.`).
|
||||
/// Like opacity but does not affect content clipped to the item.
|
||||
pub const ATTR_OPACITY_FILL: &str = "opacity_fill";
|
||||
/// `bool` for whether an item inherits the alpha of the content beneath it (clipping mask).
|
||||
pub const ATTR_CLIPPING_MASK: &str = "clipping_mask";
|
||||
/// `NodeIdPath` path from the root network to the layer node owning this item.
|
||||
/// Used by editor tools to route clicks/selection back to the originating layer.
|
||||
pub const ATTR_EDITOR_LAYER_PATH: &str = "editor:layer_path";
|
||||
/// `List<Graphic>` snapshot of the upstream content that fed into a destructive merge
|
||||
/// (Boolean Operation, Rasterize, etc.), so the editor can still surface click targets for
|
||||
/// the original child layers after their content has been collapsed.
|
||||
pub const ATTR_EDITOR_MERGED_LAYERS: &str = "editor:merged_layers";
|
||||
/// Optional `Vector` that overrides the item's own geometry for click-target generation.
|
||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
||||
/// by clicking anywhere within their bounds, not just the filled letterform.
|
||||
pub const ATTR_EDITOR_CLICK_TARGET: &str = "editor:click_target";
|
||||
/// `DAffine2` mapping the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text'
|
||||
/// node's text frame in this item's local space. Each item carries the frame relative to its own
|
||||
/// glyph origin so it survives `Index Elements` filtering. The Text tool reads this to position
|
||||
/// its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
pub const ATTR_EDITOR_TEXT_FRAME: &str = "editor:text_frame";
|
||||
/// `u64` byte offset where a regex match begins ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_START: &str = "start";
|
||||
/// `u64` byte offset where a regex match ends ('Regex Find All', 'Regex Capture' text nodes).
|
||||
pub const ATTR_END: &str = "end";
|
||||
/// `String` for a regex named-capture-group's name, or empty for unnamed groups ('Regex Capture' text node).
|
||||
pub const ATTR_NAME: &str = "name";
|
||||
/// `String` for a JSON value's type (`"string"`, `"number"`, `"object"`, etc.) from 'JSON Query All'.
|
||||
pub const ATTR_TYPE: &str = "type";
|
||||
/// Artboard's `DVec2` top-left corner in document coordinates.
|
||||
pub const ATTR_LOCATION: &str = "location";
|
||||
/// Artboard's `DVec2` width and height.
|
||||
pub const ATTR_DIMENSIONS: &str = "dimensions";
|
||||
/// Artboard's `Color` background fill.
|
||||
pub const ATTR_BACKGROUND: &str = "background";
|
||||
/// `bool` for whether an artboard clips content to its bounds.
|
||||
pub const ATTR_CLIP: &str = "clip";
|
||||
/// Gradient's `GradientSpreadMethod` (`Pad`, `Reflect`, or `Repeat`).
|
||||
pub const ATTR_SPREAD_METHOD: &str = "spread_method";
|
||||
/// Gradient's `GradientType` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_TYPE: &str = "gradient_type";
|
||||
/// Vector graphics object's filled area paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_FILL: &str = "fill";
|
||||
/// Vector graphics object's stroke paint, of type List<T> where T is any graphic type.
|
||||
pub const ATTR_STROKE: &str = "stroke";
|
||||
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
|
||||
pub const ATTR_FONT_SIZE: &str = "font_size";
|
||||
/// Text item's font, as a `Resource` of the loaded font file.
|
||||
pub const ATTR_FONT: &str = "font";
|
||||
/// Text item's line height as a ratio of the font size (`f64`, implicit default `1.2`).
|
||||
pub const ATTR_LINE_HEIGHT: &str = "line_height";
|
||||
/// Text item's extra spacing between letters in document-space units (`f64`, implicit default `0.`).
|
||||
pub const ATTR_LETTER_SPACING: &str = "letter_spacing";
|
||||
/// Text item's maximum line-wrap width in document-space units (`Option<f64>`, implicit default `None`).
|
||||
pub const ATTR_MAX_WIDTH: &str = "max_width";
|
||||
/// Text item's maximum block height in document-space units, past which lines are not drawn (`Option<f64>`, implicit default `None`).
|
||||
pub const ATTR_MAX_HEIGHT: &str = "max_height";
|
||||
/// Text item's faux-italic letter tilt angle in degrees (`f64`, implicit default `0.`).
|
||||
pub const ATTR_LETTER_TILT: &str = "letter_tilt";
|
||||
/// Text item's `TextAlign` horizontal alignment of lines within the block.
|
||||
pub const ATTR_TEXT_ALIGN: &str = "text_align";
|
||||
|
||||
// =====================
|
||||
// TYPE: NodeIdPath
|
||||
// =====================
|
||||
@@ -132,17 +60,9 @@ unsafe impl<T: StaticTypeSized> StaticType for Bundle<T> {
|
||||
// Implicit attribute defaults
|
||||
// ===========================
|
||||
|
||||
/// Overrides the type's default value for certain attributes.
|
||||
fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
|
||||
match key {
|
||||
ATTR_OPACITY | ATTR_OPACITY_FILL => Some(Box::new(1_f64)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
|
||||
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`attr::implicit_default_value`]).
|
||||
fn pad_with_implicit_default(key: &str, attribute: &mut Box<dyn AnyAttribute>, count: usize) {
|
||||
match implicit_default_value(key) {
|
||||
match attr::implicit_default_value(key) {
|
||||
Some(default) => attribute.push_repeated(&*default, count),
|
||||
None => {
|
||||
for _ in 0..count {
|
||||
@@ -494,12 +414,18 @@ impl ListDyn {
|
||||
self.len == 0
|
||||
}
|
||||
|
||||
/// Returns a reference to the attribute value at the given key and item index, downcast to `U`, if present and matching.
|
||||
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
/// Returns a reference to the attribute value at the given runtime key and item index, downcast to `U`, if present and matching.
|
||||
/// For keys known at compile time use [`Self::attr`]; this variant is for keys only known at runtime (e.g. the attribute nodes).
|
||||
pub fn attribute_dyn<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
self.attributes
|
||||
.iter()
|
||||
.find_map(|(k, attribute)| if k == key { attribute.get_any(index)?.downcast_ref::<U>() } else { None })
|
||||
}
|
||||
|
||||
/// Returns a reference to the value of the typed attribute at the given item index, if present.
|
||||
pub fn attr<A: Attr>(&self, index: usize) -> Option<&A::Value> {
|
||||
self.attribute_dyn(A::name(), index)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> From<List<T>> for ListDyn {
|
||||
@@ -620,8 +546,8 @@ impl ItemAttributeValues {
|
||||
.find_map(|(existing_key, value)| if existing_key == key { (**value).as_any_mut().downcast_mut::<T>() } else { None })
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the value, inserting a default if it doesn't exist or has the wrong type.
|
||||
pub fn get_or_insert_default_mut<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> &mut T {
|
||||
/// Gets a mutable reference to the value, inserting the provided default if it doesn't exist or has the wrong type.
|
||||
pub fn get_or_insert_with_mut<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str, default: impl FnOnce() -> T) -> &mut T {
|
||||
let needs_insert = match self.0.iter().position(|(existing_key, _)| existing_key == key) {
|
||||
Some(index) => {
|
||||
if (*self.0[index].1).as_any().downcast_ref::<T>().is_some() {
|
||||
@@ -635,7 +561,7 @@ impl ItemAttributeValues {
|
||||
};
|
||||
|
||||
if needs_insert {
|
||||
self.0.push((key.to_string(), Box::new(T::default())));
|
||||
self.0.push((key.to_string(), Box::new(default())));
|
||||
}
|
||||
|
||||
self.get_mut::<T>(key).expect("Attribute was just ensured to exist with correct type")
|
||||
@@ -700,6 +626,35 @@ impl ItemAttributeValues {
|
||||
self.0.push((key.to_string(), value));
|
||||
}
|
||||
}
|
||||
|
||||
// ==================
|
||||
// Typed key variants
|
||||
// ==================
|
||||
|
||||
/// Gets a reference to the value of the typed attribute, if present.
|
||||
pub fn attr<A: Attr>(&self) -> Option<&A::Value> {
|
||||
self.get(A::name())
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the value of the typed attribute, if present.
|
||||
pub fn attr_mut<A: Attr>(&mut self) -> Option<&mut A::Value> {
|
||||
self.get_mut(A::name())
|
||||
}
|
||||
|
||||
/// Gets a mutable reference to the value of the typed attribute, inserting the key's default value if absent.
|
||||
pub fn attr_mut_or_insert_default<A: Attr>(&mut self) -> &mut A::Value {
|
||||
self.get_or_insert_with_mut(A::name(), A::implicit_default)
|
||||
}
|
||||
|
||||
/// Inserts the typed attribute's value, replacing any existing entry.
|
||||
pub fn set_attr<A: Attr>(&mut self, value: A::Value) {
|
||||
self.insert(A::name(), value);
|
||||
}
|
||||
|
||||
/// Removes and returns the value of the typed attribute, if present.
|
||||
pub fn remove_attr<A: Attr>(&mut self) -> Option<A::Value> {
|
||||
self.remove(A::name())
|
||||
}
|
||||
}
|
||||
|
||||
// ==========
|
||||
@@ -1003,9 +958,9 @@ impl<T> List<T> {
|
||||
self.attributes.keys()
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Attribute-oriented iteration
|
||||
// ============================
|
||||
// =================
|
||||
// Element iteration
|
||||
// =================
|
||||
|
||||
/// Returns an iterator over shared references to all element values.
|
||||
pub fn iter_element_values(&self) -> std::slice::Iter<'_, T> {
|
||||
@@ -1017,28 +972,6 @@ impl<T> List<T> {
|
||||
self.element.iter_mut()
|
||||
}
|
||||
|
||||
/// Returns an iterator over shared references to the values of a typed attribute, or `None` if the attribute doesn't exist or has the wrong type.
|
||||
pub fn iter_attribute_values<U: 'static>(&self, key: &str) -> Option<std::slice::Iter<'_, U>> {
|
||||
self.attributes.get_attribute_slice::<U>(key).map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Returns an iterator over mutable references to the values of a typed attribute attribute, or `None` if the attribute doesn't exist or has the wrong type.
|
||||
pub fn iter_attribute_values_mut<U: 'static>(&mut self, key: &str) -> Option<std::slice::IterMut<'_, U>> {
|
||||
self.attributes.get_attribute_slice_mut::<U>(key).map(|s| s.iter_mut())
|
||||
}
|
||||
|
||||
/// Returns an iterator that yields cloned attribute values for the given key, falling back to `U::default()` for each item if the attribute is missing or has the wrong type.
|
||||
pub fn iter_attribute_values_or_default<U: Clone + Default + 'static>(&self, key: &str) -> impl Iterator<Item = U> + '_ {
|
||||
let slice = self.attributes.get_attribute_slice::<U>(key);
|
||||
let len = self.element.len();
|
||||
(0..len).map(move |i| slice.map_or_else(U::default, |s| s[i].clone()))
|
||||
}
|
||||
|
||||
/// Returns a mutable iterator over a typed attribute, creating the attribute with default values if it doesn't exist or has the wrong type.
|
||||
pub fn iter_attribute_values_mut_or_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> std::slice::IterMut<'_, U> {
|
||||
self.attributes.get_or_create_attribute_slice_mut::<U>(key).iter_mut()
|
||||
}
|
||||
|
||||
// ======================
|
||||
// Indexed element access
|
||||
// ======================
|
||||
@@ -1057,26 +990,12 @@ impl<T> List<T> {
|
||||
// Indexed attribute access
|
||||
// ========================
|
||||
|
||||
/// Returns a shared reference to the attribute value at the given item index and key, if it exists and can be downcast to the requested type.
|
||||
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
/// Returns a shared reference to the attribute value at the given item index and runtime key, if it exists and can be downcast to the requested type.
|
||||
/// For keys known at compile time use [`Self::attr`]; this variant is for keys only known at runtime (e.g. the attribute nodes).
|
||||
pub fn attribute_dyn<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
|
||||
self.attributes.get_value(key, index)
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value at the given item index and key, or `U::default()` if absent or of a different type.
|
||||
pub fn attribute_cloned_or_default<U: Clone + Default + 'static>(&self, key: &str, index: usize) -> U {
|
||||
self.attributes.get_value::<U>(key, index).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value at the given item index and key, or the provided default if absent or of a different type.
|
||||
pub fn attribute_cloned_or<U: Clone + 'static>(&self, key: &str, index: usize, default: U) -> U {
|
||||
self.attributes.get_value::<U>(key, index).cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Sets the attribute value at the given item index and key, creating the attribute with defaults if it doesn't exist.
|
||||
pub fn set_attribute<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, index: usize, value: U) {
|
||||
self.attributes.set_value(key, index, value);
|
||||
}
|
||||
|
||||
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
|
||||
/// Falls back to default if the value's type doesn't match an existing attribute.
|
||||
pub fn set_attribute_value_dyn(&mut self, key: impl Into<String>, index: usize, value: AttributeValueDyn) {
|
||||
@@ -1091,17 +1010,6 @@ impl<T> List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the entire attribute for the given key, if present.
|
||||
pub fn remove_attribute(&mut self, key: &str) {
|
||||
self.attributes.remove_attribute(key);
|
||||
}
|
||||
|
||||
/// Runs the given closure on a mutable reference to the attribute value at the given item index,
|
||||
/// creating the attribute with defaults if it doesn't exist, and returns the closure's result.
|
||||
pub fn with_attribute_mut_or_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static, R, F: FnOnce(&mut U) -> R>(&mut self, key: &str, index: usize, f: F) -> R {
|
||||
f(self.attributes.get_or_insert_default_value::<U>(key, index))
|
||||
}
|
||||
|
||||
/// Returns a debug-formatted display string for the attribute at the given item index and key.
|
||||
pub fn attribute_display_value(&self, key: &str, index: usize, overrides: fn(&dyn std::any::Any) -> Option<String>) -> Option<String> {
|
||||
self.attributes.display_value(key, index, overrides)
|
||||
@@ -1112,16 +1020,69 @@ impl<T> List<T> {
|
||||
self.attributes.get_any_value(key, index)
|
||||
}
|
||||
|
||||
// ====================
|
||||
// Split borrow helpers
|
||||
// ====================
|
||||
// ==================
|
||||
// Typed key variants
|
||||
// ==================
|
||||
|
||||
/// Returns disjoint mutable references to the element slice and a typed attribute slice, creating the attribute with defaults if it doesn't exist.
|
||||
/// Returns a shared reference to the value of the typed attribute at the given item index, if present.
|
||||
pub fn attr<A: Attr>(&self, index: usize) -> Option<&A::Value> {
|
||||
self.attributes.get_value(A::name(), index)
|
||||
}
|
||||
|
||||
/// Returns a clone of the value of the typed attribute at the given item index, or the key's default value if absent.
|
||||
pub fn attr_cloned_or_default<A: Attr>(&self, index: usize) -> A::Value {
|
||||
self.attr::<A>(index).cloned().unwrap_or_else(A::implicit_default)
|
||||
}
|
||||
|
||||
/// Returns a clone of the value of the typed attribute at the given item index, or the provided default if absent.
|
||||
pub fn attr_cloned_or<A: Attr>(&self, index: usize, default: A::Value) -> A::Value {
|
||||
self.attr::<A>(index).cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Sets the value of the typed attribute at the given item index, creating the attribute with defaults if it doesn't exist.
|
||||
pub fn set_attr<A: Attr>(&mut self, index: usize, value: A::Value) {
|
||||
self.attributes.set_value(A::name(), index, value);
|
||||
}
|
||||
|
||||
/// Removes the entire typed attribute, if present.
|
||||
pub fn remove_attr<A: Attr>(&mut self) {
|
||||
self.attributes.remove_attribute(A::name());
|
||||
}
|
||||
|
||||
/// Runs the given closure on a mutable reference to the value of the typed attribute at the given item index,
|
||||
/// creating the attribute with defaults if it doesn't exist, and returns the closure's result.
|
||||
pub fn with_attr_mut_or_default<A: Attr, R, F: FnOnce(&mut A::Value) -> R>(&mut self, index: usize, f: F) -> R {
|
||||
f(self.attributes.get_or_insert_default_value::<A::Value>(A::name(), index))
|
||||
}
|
||||
|
||||
/// Returns an iterator over shared references to the values of the typed attribute, or `None` if it doesn't exist.
|
||||
pub fn iter_attr_values<A: Attr>(&self) -> Option<std::slice::Iter<'_, A::Value>> {
|
||||
self.attributes.get_attribute_slice::<A::Value>(A::name()).map(|s| s.iter())
|
||||
}
|
||||
|
||||
/// Returns an iterator over mutable references to the values of the typed attribute, or `None` if it doesn't exist.
|
||||
pub fn iter_attr_values_mut<A: Attr>(&mut self) -> Option<std::slice::IterMut<'_, A::Value>> {
|
||||
self.attributes.get_attribute_slice_mut::<A::Value>(A::name()).map(|s| s.iter_mut())
|
||||
}
|
||||
|
||||
/// Returns an iterator that yields cloned values of the typed attribute, falling back to the key's default value for each item if the attribute is missing.
|
||||
pub fn iter_attr_values_or_default<A: Attr>(&self) -> impl Iterator<Item = A::Value> + '_ {
|
||||
let slice = self.attributes.get_attribute_slice::<A::Value>(A::name());
|
||||
let len = self.element.len();
|
||||
(0..len).map(move |i| slice.map_or_else(A::implicit_default, |s| s[i].clone()))
|
||||
}
|
||||
|
||||
/// Returns a mutable iterator over the typed attribute, creating the attribute with defaults if it doesn't exist.
|
||||
pub fn iter_attr_values_mut_or_default<A: Attr>(&mut self) -> std::slice::IterMut<'_, A::Value> {
|
||||
self.attributes.get_or_create_attribute_slice_mut::<A::Value>(A::name()).iter_mut()
|
||||
}
|
||||
|
||||
/// Returns disjoint mutable references to the element slice and the typed attribute's slice, creating the attribute with defaults if it doesn't exist.
|
||||
/// This enables simultaneous mutable access to elements and a single attribute without borrowing conflicts.
|
||||
pub fn element_and_attribute_slices_mut<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> (&mut [T], &mut [U]) {
|
||||
pub fn element_and_attr_slices_mut<A: Attr>(&mut self) -> (&mut [T], &mut [A::Value]) {
|
||||
let Self { element, attributes } = self;
|
||||
let attribute_position = attributes.find_or_create_attribute::<U>(key);
|
||||
let attribute = (*attributes.attributes[attribute_position].1).as_any_mut().downcast_mut::<Attribute<U>>().unwrap();
|
||||
let attribute_position = attributes.find_or_create_attribute::<A::Value>(A::name());
|
||||
let attribute = (*attributes.attributes[attribute_position].1).as_any_mut().downcast_mut::<Attribute<A::Value>>().unwrap();
|
||||
(element.as_mut_slice(), &mut attribute.0)
|
||||
}
|
||||
|
||||
@@ -1151,7 +1112,7 @@ impl<T: BoundingBox> BoundingBox for List<T> {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
let mut combined_bounds = None;
|
||||
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attr_values_or_default::<crate::attr::Transform>()) {
|
||||
match element.bounding_box(transform * item_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => return RenderBoundingBox::Infinite,
|
||||
@@ -1173,7 +1134,7 @@ impl<T: BoundingBox> BoundingBox for List<T> {
|
||||
let mut combined_bounds = None;
|
||||
let mut any_infinite = false;
|
||||
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attribute_values_or_default::<DAffine2>(ATTR_TRANSFORM)) {
|
||||
for (element, item_transform) in self.iter_element_values().zip(self.iter_attr_values_or_default::<crate::attr::Transform>()) {
|
||||
match element.thumbnail_bounding_box(transform * item_transform, include_stroke) {
|
||||
RenderBoundingBox::None => continue,
|
||||
RenderBoundingBox::Infinite => any_infinite = true,
|
||||
@@ -1245,14 +1206,14 @@ impl<T: PartialEq> PartialEq for List<T> {
|
||||
impl<T> ApplyTransform for List<T> {
|
||||
/// Right-multiplies the modification into each item's transform attribute.
|
||||
fn apply_transform(&mut self, modification: &DAffine2) {
|
||||
for transform in self.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in self.iter_attr_values_mut_or_default::<crate::attr::Transform>() {
|
||||
*transform *= *modification;
|
||||
}
|
||||
}
|
||||
|
||||
/// Left-multiplies the modification into each item's transform attribute.
|
||||
fn left_apply_transform(&mut self, modification: &DAffine2) {
|
||||
for transform in self.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in self.iter_attr_values_mut_or_default::<crate::attr::Transform>() {
|
||||
*transform = *modification * *transform;
|
||||
}
|
||||
}
|
||||
@@ -1349,50 +1310,54 @@ impl<T> Item<T> {
|
||||
&mut self.attributes
|
||||
}
|
||||
|
||||
/// Returns a reference to the attribute value for the given key, if it exists and is of the requested type.
|
||||
pub fn attribute<U: 'static>(&self, key: &str) -> Option<&U> {
|
||||
self.attributes.get(key)
|
||||
// ======================
|
||||
// Typed attribute access
|
||||
// ======================
|
||||
|
||||
/// Returns a reference to the value of the typed attribute, if present.
|
||||
pub fn attr<A: Attr>(&self) -> Option<&A::Value> {
|
||||
self.attributes.attr::<A>()
|
||||
}
|
||||
|
||||
/// Returns the attribute value for the given key, or the provided default if absent or of a different type.
|
||||
pub fn attribute_or<'a, U: 'static>(&'a self, key: &str, default: &'a U) -> &'a U {
|
||||
self.attribute(key).unwrap_or(default)
|
||||
/// Returns a reference to the value of the typed attribute, or the provided default if absent.
|
||||
pub fn attr_or<'a, A: Attr>(&'a self, default: &'a A::Value) -> &'a A::Value {
|
||||
self.attr::<A>().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value for the given key, or the provided default if absent or of a different type.
|
||||
pub fn attribute_cloned_or<U: Clone + 'static>(&self, key: &str, default: U) -> U {
|
||||
self.attribute(key).cloned().unwrap_or(default)
|
||||
/// Returns a clone of the value of the typed attribute, or the provided default if absent.
|
||||
pub fn attr_cloned_or<A: Attr>(&self, default: A::Value) -> A::Value {
|
||||
self.attr::<A>().cloned().unwrap_or(default)
|
||||
}
|
||||
|
||||
/// Returns a clone of the attribute value for the given key, or `U`'s default value if absent or of a different type.
|
||||
pub fn attribute_cloned_or_default<U: Clone + Default + 'static>(&self, key: &str) -> U {
|
||||
self.attribute(key).cloned().unwrap_or_default()
|
||||
/// Returns a clone of the value of the typed attribute, or the key's default value if absent.
|
||||
pub fn attr_cloned_or_default<A: Attr>(&self) -> A::Value {
|
||||
self.attr::<A>().cloned().unwrap_or_else(A::implicit_default)
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the attribute value for the given key, if it exists and is of the requested type.
|
||||
pub fn attribute_mut<U: 'static>(&mut self, key: &str) -> Option<&mut U> {
|
||||
self.attributes.get_mut(key)
|
||||
/// Returns a mutable reference to the value of the typed attribute, if present.
|
||||
pub fn attr_mut<A: Attr>(&mut self) -> Option<&mut A::Value> {
|
||||
self.attributes.attr_mut::<A>()
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the attribute value for the given key, inserting a default value if absent or of a different type.
|
||||
pub fn attribute_mut_or_insert_default<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: &str) -> &mut U {
|
||||
self.attributes.get_or_insert_default_mut(key)
|
||||
/// Returns a mutable reference to the value of the typed attribute, inserting the key's default value if absent.
|
||||
pub fn attr_mut_or_insert_default<A: Attr>(&mut self) -> &mut A::Value {
|
||||
self.attributes.attr_mut_or_insert_default::<A>()
|
||||
}
|
||||
|
||||
/// Sets the attribute value for the given key, replacing any existing entry with the same key.
|
||||
pub fn set_attribute<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(&mut self, key: impl Into<String>, value: U) {
|
||||
self.attributes.insert(key, value);
|
||||
/// Sets the value of the typed attribute, replacing any existing entry.
|
||||
pub fn set_attr<A: Attr>(&mut self, value: A::Value) {
|
||||
self.attributes.set_attr::<A>(value);
|
||||
}
|
||||
|
||||
/// Sets the attribute value for the given key and returns the item, enabling builder-style chaining.
|
||||
pub fn with_attribute<U: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>(mut self, key: impl Into<String>, value: U) -> Self {
|
||||
self.set_attribute(key, value);
|
||||
/// Sets the value of the typed attribute and returns the item, enabling builder-style chaining.
|
||||
pub fn with_attr<A: Attr>(mut self, value: A::Value) -> Self {
|
||||
self.set_attr::<A>(value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Removes and returns the attribute value for the given key, if it exists and is of the requested type.
|
||||
pub fn remove_attribute<U: 'static>(&mut self, key: &str) -> Option<U> {
|
||||
self.attributes.remove(key)
|
||||
/// Removes and returns the value of the typed attribute, if present.
|
||||
pub fn remove_attr<A: Attr>(&mut self) -> Option<A::Value> {
|
||||
self.attributes.remove_attr::<A>()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1417,13 +1382,13 @@ impl<T> From<T> for List<T> {
|
||||
impl<T> ApplyTransform for Item<T> {
|
||||
/// Right-multiplies the modification into the item's transform attribute.
|
||||
fn apply_transform(&mut self, modification: &DAffine2) {
|
||||
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let transform = self.attr_mut_or_insert_default::<crate::attr::Transform>();
|
||||
*transform *= *modification;
|
||||
}
|
||||
|
||||
/// Left-multiplies the modification into the item's transform attribute.
|
||||
fn left_apply_transform(&mut self, modification: &DAffine2) {
|
||||
let transform = self.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let transform = self.attr_mut_or_insert_default::<crate::attr::Transform>();
|
||||
*transform = *modification * *transform;
|
||||
}
|
||||
}
|
||||
@@ -1468,6 +1433,7 @@ impl<T> DoubleEndedIterator for ItemIter<T> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::attr;
|
||||
|
||||
// An item that doesn't set opacity must read as fully opaque even once a sibling introduces the
|
||||
// opacity attribute, otherwise the dense store pads it with f64's `0.` default and it vanishes.
|
||||
@@ -1476,29 +1442,76 @@ mod tests {
|
||||
// Collecting items (the path Boolean Operation takes when merging operands)
|
||||
let mut collected = List::<()>::new();
|
||||
collected.push(Item::new_from_element(()));
|
||||
collected.push(Item::new_from_element(()).with_attribute(ATTR_OPACITY, 1_f64));
|
||||
assert_eq!(collected.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 1.);
|
||||
collected.push(Item::new_from_element(()).with_attr::<attr::Opacity>(1.));
|
||||
assert_eq!(collected.attr::<attr::Opacity>(0), Some(&1.));
|
||||
|
||||
// Extending one list with another
|
||||
let mut base = List::<()>::new();
|
||||
base.push(Item::new_from_element(()));
|
||||
let mut tail = List::<()>::new();
|
||||
tail.push(Item::new_from_element(()).with_attribute(ATTR_OPACITY_FILL, 1_f64));
|
||||
tail.push(Item::new_from_element(()).with_attr::<attr::OpacityFill>(1.));
|
||||
base.extend(tail);
|
||||
assert_eq!(base.attribute_cloned_or_default::<f64>(ATTR_OPACITY_FILL, 0), 1.);
|
||||
assert_eq!(base.attr::<attr::OpacityFill>(0), Some(&1.));
|
||||
|
||||
// Setting one item's opacity leaves the others opaque, not transparent
|
||||
let mut indexed = List::<()>::new();
|
||||
indexed.push(Item::new_from_element(()));
|
||||
indexed.push(Item::new_from_element(()));
|
||||
indexed.set_attribute(ATTR_OPACITY, 1, 0.5_f64);
|
||||
assert_eq!(indexed.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 1.);
|
||||
assert_eq!(indexed.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 1), 0.5);
|
||||
indexed.set_attr::<attr::Opacity>(1, 0.5);
|
||||
assert_eq!(indexed.attr::<attr::Opacity>(0), Some(&1.));
|
||||
assert_eq!(indexed.attr::<attr::Opacity>(1), Some(&0.5));
|
||||
|
||||
// A non-opacity numeric attribute still falls back to its type default
|
||||
// A non-opacity numeric attribute still pads with its type default
|
||||
let mut other = List::<()>::new();
|
||||
other.push(Item::new_from_element(()));
|
||||
other.push(Item::new_from_element(()).with_attribute(ATTR_START, 5_u64));
|
||||
assert_eq!(other.attribute_cloned_or_default::<u64>(ATTR_START, 0), 0);
|
||||
other.push(Item::new_from_element(()).with_attr::<attr::Start>(5));
|
||||
assert_eq!(other.attr::<attr::Start>(0), Some(&0));
|
||||
}
|
||||
|
||||
// The typed keys must resolve to the same names as the string constants, and the typed
|
||||
// and string-keyed accessors must hit the same storage.
|
||||
#[test]
|
||||
fn typed_attribute_keys() {
|
||||
assert_eq!(attr::Transform::name(), "transform");
|
||||
assert_eq!(attr::BlendMode::name(), "blend_mode");
|
||||
assert_eq!(attr::Opacity::name(), "opacity");
|
||||
assert_eq!(attr::OpacityFill::name(), "opacity_fill");
|
||||
assert_eq!(attr::ClippingMask::name(), "clipping_mask");
|
||||
assert_eq!(attr::editor::LayerPath::name(), "editor:layer_path");
|
||||
assert_eq!(attr::editor::TextFrame::name(), "editor:text_frame");
|
||||
assert_eq!(attr::Start::name(), "start");
|
||||
assert_eq!(attr::End::name(), "end");
|
||||
assert_eq!(attr::Name::name(), "name");
|
||||
assert_eq!(attr::Type::name(), "type");
|
||||
assert_eq!(attr::Location::name(), "location");
|
||||
assert_eq!(attr::Dimensions::name(), "dimensions");
|
||||
assert_eq!(attr::Background::name(), "background");
|
||||
assert_eq!(attr::Clip::name(), "clip");
|
||||
assert_eq!(attr::FontSize::name(), "font_size");
|
||||
assert_eq!(attr::LineHeight::name(), "line_height");
|
||||
assert_eq!(attr::LetterSpacing::name(), "letter_spacing");
|
||||
assert_eq!(attr::MaxWidth::name(), "max_width");
|
||||
assert_eq!(attr::MaxHeight::name(), "max_height");
|
||||
assert_eq!(attr::LetterTilt::name(), "letter_tilt");
|
||||
|
||||
// Typed writes are visible through dynamic string reads and vice versa
|
||||
let mut item = Item::new_from_element(());
|
||||
item.set_attr::<attr::Opacity>(0.5);
|
||||
assert_eq!(item.attributes().get::<f64>("opacity"), Some(&0.5));
|
||||
item.attributes_mut().insert("start", 5_u64);
|
||||
assert_eq!(item.attr::<attr::Start>(), Some(&5));
|
||||
|
||||
// A missing attribute reads as the key's declared default
|
||||
let empty = Item::new_from_element(());
|
||||
assert_eq!(empty.attr_cloned_or_default::<attr::Opacity>(), 1.);
|
||||
assert_eq!(empty.attr_cloned_or_default::<attr::Start>(), 0);
|
||||
|
||||
// The generated implicit-default lookup drives dense-store padding
|
||||
let mut list = List::<()>::new();
|
||||
list.push(Item::new_from_element(()));
|
||||
list.push(Item::new_from_element(()));
|
||||
list.set_attr::<attr::Opacity>(1, 0.5);
|
||||
assert_eq!(list.attr_cloned_or_default::<attr::Opacity>(0), 1.);
|
||||
assert_eq!(list.attr_cloned_or_default::<attr::Opacity>(1), 0.5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Typed attribute keys whose value types live in this crate. See `core_types::attr` for the trait and macro.
|
||||
|
||||
use crate::graphic::Graphic;
|
||||
use core_types::list::List;
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Vector graphics object's filled area paint.
|
||||
Fill: List<Graphic>,
|
||||
/// Vector graphics object's stroke paint.
|
||||
Stroke: List<Graphic>,
|
||||
editor {
|
||||
/// Snapshot of the upstream content that fed into a destructive merge (Boolean Operation,
|
||||
/// Rasterize, etc.), so the editor can still surface click targets for the original child
|
||||
/// layers after their content has been collapsed.
|
||||
MergedLayers: List<Graphic>,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attr::Attr;
|
||||
|
||||
// Key names are the stored document format — pinned as literals so a key rename shows up as a breaking change.
|
||||
#[test]
|
||||
fn key_names_are_pinned() {
|
||||
assert_eq!(Fill::name(), "fill");
|
||||
assert_eq!(Stroke::name(), "stroke");
|
||||
assert_eq!(editor::MergedLayers::name(), "editor:merged_layers");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
use core_types::Color;
|
||||
use core_types::attr::{self, Attr};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List, NodeIdPath};
|
||||
use core_types::list::{Item, ItemAttributeValues, List};
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -119,32 +120,32 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
// Whether the parent carries each attribute: a structural fact (column presence), never a value comparison.
|
||||
// Flattening composes a parent attribute onto its children only when the parent has it,
|
||||
// so an absent parent attribute never invents a column the children didn't already have.
|
||||
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
|
||||
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
|
||||
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
|
||||
let parent_has_layer_path = current_graphic_item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).is_some();
|
||||
let parent_has_transform = current_graphic_item.attr::<attr::Transform>().is_some();
|
||||
let parent_has_opacity = current_graphic_item.attr::<attr::Opacity>().is_some();
|
||||
let parent_has_fill = current_graphic_item.attr::<attr::OpacityFill>().is_some();
|
||||
let parent_has_layer_path = current_graphic_item.attr::<attr::editor::LayerPath>().is_some();
|
||||
|
||||
let layer_path: NodeIdPath = current_graphic_item.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH);
|
||||
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
let layer_path = current_graphic_item.attr_cloned_or_default::<attr::editor::LayerPath>();
|
||||
let current_transform = current_graphic_item.attr_cloned_or_default::<attr::Transform>();
|
||||
let current_opacity = current_graphic_item.attr_cloned_or_default::<attr::Opacity>();
|
||||
let current_fill = current_graphic_item.attr_cloned_or_default::<attr::OpacityFill>();
|
||||
|
||||
match current_graphic_item.into_element() {
|
||||
// Compose the parent's transform/opacity/fill onto each child, but only for attributes the parent carries.
|
||||
// A child lacking one is padded with the composition identity (`1.` for opacity/fill, identity for transform), so composing through it is a no-op.
|
||||
Graphic::Graphic(mut sub_list) => {
|
||||
if parent_has_transform {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for v in sub_list.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*v = current_transform * *v;
|
||||
}
|
||||
}
|
||||
if parent_has_opacity {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY) {
|
||||
for v in sub_list.iter_attr_values_mut_or_default::<attr::Opacity>() {
|
||||
*v *= current_opacity;
|
||||
}
|
||||
}
|
||||
if parent_has_fill {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY_FILL) {
|
||||
for v in sub_list.iter_attr_values_mut_or_default::<attr::OpacityFill>() {
|
||||
*v *= current_fill;
|
||||
}
|
||||
}
|
||||
@@ -155,22 +156,22 @@ fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic)
|
||||
other => {
|
||||
if let Some(typed_list) = extract_variant(other) {
|
||||
for mut item in typed_list.into_iter() {
|
||||
// Each `|| item.attribute(...)` keeps an attribute the item itself carries
|
||||
// Each `|| item.attr::<...>()` keeps an attribute the item itself carries
|
||||
// (recomposed with the parent's identity value) even when the parent lacks it
|
||||
if parent_has_transform || item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some() {
|
||||
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
item.set_attribute(ATTR_TRANSFORM, current_transform * item_transform);
|
||||
if parent_has_transform || item.attr::<attr::Transform>().is_some() {
|
||||
let item_transform = item.attr_cloned_or_default::<attr::Transform>();
|
||||
item.set_attr::<attr::Transform>(current_transform * item_transform);
|
||||
}
|
||||
if parent_has_opacity || item.attribute::<f64>(ATTR_OPACITY).is_some() {
|
||||
let item_opacity: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
item.set_attribute(ATTR_OPACITY, current_opacity * item_opacity);
|
||||
if parent_has_opacity || item.attr::<attr::Opacity>().is_some() {
|
||||
let item_opacity = item.attr_cloned_or_default::<attr::Opacity>();
|
||||
item.set_attr::<attr::Opacity>(current_opacity * item_opacity);
|
||||
}
|
||||
if parent_has_fill || item.attribute::<f64>(ATTR_OPACITY_FILL).is_some() {
|
||||
let item_fill: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
item.set_attribute(ATTR_OPACITY_FILL, current_fill * item_fill);
|
||||
if parent_has_fill || item.attr::<attr::OpacityFill>().is_some() {
|
||||
let item_fill = item.attr_cloned_or_default::<attr::OpacityFill>();
|
||||
item.set_attr::<attr::OpacityFill>(current_fill * item_fill);
|
||||
}
|
||||
if parent_has_layer_path {
|
||||
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
item.set_attr::<attr::editor::LayerPath>(layer_path.clone());
|
||||
}
|
||||
|
||||
output.push(item);
|
||||
@@ -192,9 +193,9 @@ pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
|
||||
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||
}
|
||||
|
||||
/// Look up the paint graphics stored under attribute for a vector item, in the canonical `List<Graphic>` form.
|
||||
pub fn graphic_list_at<'a>(list: &'a List<Vector>, index: usize, attribute: &str) -> Option<Cow<'a, List<Graphic>>> {
|
||||
list.attribute::<List<Graphic>>(attribute, index)
|
||||
/// Look up the paint graphics stored under the typed attribute for a vector item, in the canonical `List<Graphic>` form.
|
||||
pub fn graphic_list_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> Option<Cow<'_, List<Graphic>>> {
|
||||
list.attr::<A>(index)
|
||||
.map(Cow::Borrowed)
|
||||
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
|
||||
.filter(|graphic_list| is_paint_present(graphic_list))
|
||||
@@ -202,25 +203,25 @@ pub fn graphic_list_at<'a>(list: &'a List<Vector>, index: usize, attribute: &str
|
||||
|
||||
/// Whether the item carries a non-blank canonical `List<Graphic>` paint attribute,
|
||||
/// checked by borrowing without cloning the renderable list.
|
||||
pub fn has_paint_at(list: &List<Vector>, index: usize, attribute: &str) -> bool {
|
||||
list.attribute::<List<Graphic>>(attribute, index).is_some_and(is_paint_present)
|
||||
pub fn has_paint_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> bool {
|
||||
list.attr::<A>(index).is_some_and(is_paint_present)
|
||||
}
|
||||
|
||||
/// Stores a paint attribute in its canonical `List<Graphic>` form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
|
||||
attributes.insert(key, paint.into_graphic_list());
|
||||
pub fn set_paint_attribute<A: Attr<Value = List<Graphic>>>(attributes: &mut ItemAttributeValues, paint: impl IntoGraphicList) {
|
||||
attributes.set_attr::<A>(paint.into_graphic_list());
|
||||
}
|
||||
|
||||
/// Stores a paint attribute at a list index in its canonical `List<Graphic>` form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
|
||||
list.set_attribute(key, index, paint.into_graphic_list());
|
||||
pub fn set_paint_attribute_at<A: Attr<Value = List<Graphic>>, T>(list: &mut List<T>, index: usize, paint: impl IntoGraphicList) {
|
||||
list.set_attr::<A>(index, paint.into_graphic_list());
|
||||
}
|
||||
|
||||
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
|
||||
/// canonical `List<Graphic>` fill and stroke attributes.
|
||||
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
|
||||
fn bake_list_transform<T>(list: &mut List<T>, transform: DAffine2) {
|
||||
for item_transform in list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for item_transform in list.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*item_transform = transform * *item_transform;
|
||||
}
|
||||
}
|
||||
@@ -240,7 +241,7 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
}
|
||||
}
|
||||
|
||||
for paint_key in [ATTR_FILL, ATTR_STROKE] {
|
||||
for paint_key in [crate::attr::Fill::name(), crate::attr::Stroke::name()] {
|
||||
if let Some(graphics) = attributes.get_mut::<List<Graphic>>(paint_key) {
|
||||
bake_graphic_paint_transform(graphics, transform);
|
||||
}
|
||||
@@ -306,10 +307,10 @@ impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
// Propagate the `editor:layer_path` column (if present) from item 0 onto the wrapper Graphic item so a
|
||||
// subsequent `flatten_graphic_list` doesn't drop the inner Vector's layer stamp
|
||||
let layer_path = self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).cloned();
|
||||
let layer_path = self.attr::<attr::editor::LayerPath>(0).cloned();
|
||||
let mut graphic_list = List::new_from_element(Graphic::Vector(self));
|
||||
if let Some(layer_path) = layer_path {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
graphic_list.set_attr::<attr::editor::LayerPath>(0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
}
|
||||
@@ -341,10 +342,10 @@ impl IntoGraphicList for List<Gradient> {
|
||||
|
||||
impl IntoGraphicList for List<String> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path = self.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).cloned();
|
||||
let layer_path = self.attr::<attr::editor::LayerPath>(0).cloned();
|
||||
let mut graphic_list = List::new_from_element(Graphic::Text(self));
|
||||
if let Some(layer_path) = layer_path {
|
||||
graphic_list.set_attribute(ATTR_EDITOR_LAYER_PATH, 0, layer_path);
|
||||
graphic_list.set_attr::<attr::editor::LayerPath>(0, layer_path);
|
||||
}
|
||||
graphic_list
|
||||
}
|
||||
@@ -416,7 +417,7 @@ impl Graphic {
|
||||
|
||||
pub fn had_clip_enabled(&self) -> bool {
|
||||
fn all_clipped<T>(list: &List<T>) -> bool {
|
||||
list.iter_attribute_values_or_default::<bool>(ATTR_CLIPPING_MASK).all(|clip| clip)
|
||||
list.iter_attr_values_or_default::<attr::ClippingMask>().all(|clip| clip)
|
||||
}
|
||||
|
||||
match self {
|
||||
@@ -435,12 +436,12 @@ impl Graphic {
|
||||
match self {
|
||||
Graphic::Vector(vector) => (0..vector.len()).all(|index| {
|
||||
let Some(element) = vector.element(index) else { return false };
|
||||
let opacity: f64 = vector.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity = vector.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
|
||||
let fill_opaque_or_absent = graphic_list_at(vector, index, ATTR_FILL).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
let fill_opaque_or_absent = graphic_list_at::<crate::attr::Fill>(vector, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
|
||||
let stroke_invisible_or_transparent = element.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|
||||
|| graphic_list_at(vector, index, ATTR_STROKE).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
|| graphic_list_at::<crate::attr::Stroke>(vector, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
|
||||
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
|
||||
}),
|
||||
@@ -453,15 +454,17 @@ impl Graphic {
|
||||
Graphic::None => false,
|
||||
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
|
||||
Graphic::Vector(list) => {
|
||||
let is_paint_opaque_at = |key: &str, index: usize| graphic_list_at(list, index, key).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()));
|
||||
fn is_paint_opaque_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> bool {
|
||||
graphic_list_at::<A>(list, index).is_some_and(|graphic_list| graphic_list.element(0).is_some_and(|graphic| graphic.is_opaque()))
|
||||
}
|
||||
|
||||
!list.is_empty()
|
||||
&& (0..list.len()).all(|i| {
|
||||
let Some(vector) = list.element(i) else { return false };
|
||||
let opacity: f64 = list.attribute_cloned_or(ATTR_OPACITY, i, 1.);
|
||||
let opacity_fill: f64 = list.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
|
||||
let fill_opaque = opacity_fill >= 1. - f64::EPSILON && is_paint_opaque_at(ATTR_FILL, i);
|
||||
let stroke_opaque_or_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_opaque_at(ATTR_STROKE, i);
|
||||
let opacity = list.attr_cloned_or_default::<attr::Opacity>(i);
|
||||
let opacity_fill = list.attr_cloned_or_default::<attr::OpacityFill>(i);
|
||||
let fill_opaque = opacity_fill >= 1. - f64::EPSILON && is_paint_opaque_at::<crate::attr::Fill>(list, i);
|
||||
let stroke_opaque_or_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_opaque_at::<crate::attr::Stroke>(list, i);
|
||||
opacity >= 1. - f64::EPSILON && fill_opaque && stroke_opaque_or_invisible
|
||||
})
|
||||
}
|
||||
@@ -477,16 +480,17 @@ impl Graphic {
|
||||
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||
Graphic::Vector(list) => (0..list.len()).all(|i| {
|
||||
let Some(vector) = list.element(i) else { return false };
|
||||
let is_paint_fully_transparent_at =
|
||||
|key: &str, index: usize| graphic_list_at(list, index, key).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
fn is_paint_fully_transparent_at<A: Attr<Value = List<Graphic>>>(list: &List<Vector>, index: usize) -> bool {
|
||||
graphic_list_at::<A>(list, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()))
|
||||
}
|
||||
|
||||
let opacity: f64 = list.attribute_cloned_or(ATTR_OPACITY, i, 1.);
|
||||
let opacity = list.attr_cloned_or_default::<attr::Opacity>(i);
|
||||
if opacity <= f64::EPSILON {
|
||||
return true;
|
||||
}
|
||||
let opacity_fill: f64 = list.attribute_cloned_or(ATTR_OPACITY_FILL, i, 1.);
|
||||
let fill_invisible = opacity_fill <= f64::EPSILON || is_paint_fully_transparent_at(ATTR_FILL, i);
|
||||
let stroke_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_fully_transparent_at(ATTR_STROKE, i);
|
||||
let opacity_fill = list.attr_cloned_or_default::<attr::OpacityFill>(i);
|
||||
let fill_invisible = opacity_fill <= f64::EPSILON || is_paint_fully_transparent_at::<crate::attr::Fill>(list, i);
|
||||
let stroke_invisible = vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()) || is_paint_fully_transparent_at::<crate::attr::Stroke>(list, i);
|
||||
fill_invisible && stroke_invisible
|
||||
}),
|
||||
Graphic::Color(list) => list.iter_element_values().all(|color| color.a() == 0.),
|
||||
@@ -644,7 +648,7 @@ mod tests {
|
||||
fn flatten_does_not_invent_attributes() {
|
||||
let graphics = List::new_from_element(vector_graphic());
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
for key in [ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH] {
|
||||
for key in [attr::Opacity::name(), attr::OpacityFill::name(), attr::Transform::name(), attr::editor::LayerPath::name()] {
|
||||
assert!(!flattened.attribute_keys().any(|k| k == key), "flatten invented the `{key}` attribute");
|
||||
}
|
||||
}
|
||||
@@ -653,20 +657,19 @@ mod tests {
|
||||
#[test]
|
||||
fn flatten_propagates_present_attributes() {
|
||||
let mut graphics = List::new_from_element(vector_graphic());
|
||||
graphics.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
graphics.set_attr::<attr::Opacity>(0, 0.5);
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
assert_eq!(flattened.attr_cloned_or_default::<attr::Opacity>(0), 0.5);
|
||||
|
||||
let mut group = List::new_from_element(Graphic::Graphic(List::new_from_element(vector_graphic())));
|
||||
group.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
group.set_attr::<attr::Opacity>(0, 0.5);
|
||||
let flattened: List<Vector> = group.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
assert_eq!(flattened.attr_cloned_or_default::<attr::Opacity>(0), 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod graphic_is_opaque_tests {
|
||||
use core_types::ATTR_SPREAD_METHOD;
|
||||
use vector_types::{GradientSpreadMethod, GradientStop};
|
||||
|
||||
use super::*;
|
||||
@@ -678,7 +681,7 @@ mod graphic_is_opaque_tests {
|
||||
|
||||
fn gradient_graphic(gradient: Gradient) -> Graphic {
|
||||
let mut gradient_list = List::new_from_element(gradient);
|
||||
gradient_list.set_attribute(ATTR_SPREAD_METHOD, 0, GradientSpreadMethod::Pad);
|
||||
gradient_list.set_attr::<vector_types::attr::SpreadMethod>(0, GradientSpreadMethod::Pad);
|
||||
Graphic::Gradient(gradient_list)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod artboard;
|
||||
pub mod attr;
|
||||
pub mod graphic;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::generate_uuid;
|
||||
use core_types::{ATTR_GRADIENT_TYPE, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color};
|
||||
use core_types::{Color, attr};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::vector_types::gradient::GradientType;
|
||||
@@ -93,9 +93,9 @@ impl RenderExt for List<Gradient> {
|
||||
let mut stop = String::new();
|
||||
|
||||
let Some(stops) = self.element(0) else { return 0 };
|
||||
let gradient_type: GradientType = self.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let local_gradient_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = self.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
let gradient_type = self.attr_cloned_or_default::<vector_types::attr::GradientType>(0);
|
||||
let local_gradient_transform = self.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let spread_method = self.attr_cloned_or_default::<vector_types::attr::SpreadMethod>(0);
|
||||
|
||||
for (position, color, original_midpoint) in stops.interpolated_samples() {
|
||||
stop.push_str("<stop");
|
||||
|
||||
@@ -1,26 +1,23 @@
|
||||
use crate::render_ext::{PaintTarget, RenderExt};
|
||||
use crate::to_peniko::{BlendModeExt, ToPenikoColor};
|
||||
use core_types::CacheHash;
|
||||
use core_types::attr;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::BoundingBox;
|
||||
use core_types::bounds::RenderBoundingBox;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::consts::DEFAULT_FONT_SIZE;
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, List, NodeIdPath};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::{NodeId, generate_uuid};
|
||||
use core_types::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_FONT,
|
||||
ATTR_FONT_SIZE, ATTR_GRADIENT_TYPE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphene_hash::CacheHashWrapper;
|
||||
use graphene_resource::Resource;
|
||||
use graphic_types::attr as graphic_attr;
|
||||
use graphic_types::graphic::{graphic_list_at, has_paint_at, is_paint_present, set_paint_attribute};
|
||||
use graphic_types::raster_types::{BitmapMut, CPU, GPU, Image, Raster, Texture};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientType};
|
||||
@@ -39,6 +36,8 @@ use std::fmt::Write;
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use text_nodes::attr as text_attr;
|
||||
use vector_types::attr as vector_attr;
|
||||
use vector_types::gradient::GradientSpreadMethod;
|
||||
use vello::*;
|
||||
|
||||
@@ -360,7 +359,7 @@ fn emit_svg_fill_path(
|
||||
attributes.push("d", d);
|
||||
let matrix = format_transform_matrix(element_transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
let defs = &mut attributes.0.svg_defs;
|
||||
let fill_attribute = fill_graphic_list
|
||||
@@ -397,9 +396,9 @@ pub(crate) fn gradient_placement(transform: DAffine2, gradient_type: GradientTyp
|
||||
fn create_peniko_gradient_brush(gradient_list: &List<Gradient>, multiplied_transform: &DAffine2) -> Option<(peniko::Brush, DAffine2)> {
|
||||
let stops = gradient_list.element(0)?;
|
||||
|
||||
let gradient_type: GradientType = gradient_list.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, 0);
|
||||
let gradient_transform: DAffine2 = gradient_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let spread_method: GradientSpreadMethod = gradient_list.attribute_cloned_or_default(ATTR_SPREAD_METHOD, 0);
|
||||
let gradient_type = gradient_list.attr_cloned_or_default::<vector_attr::GradientType>(0);
|
||||
let gradient_transform = gradient_list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let spread_method = gradient_list.attr_cloned_or_default::<vector_attr::SpreadMethod>(0);
|
||||
|
||||
let mut peniko_stops = peniko::ColorStops::new();
|
||||
for (position, color, _) in stops.interpolated_samples() {
|
||||
@@ -457,10 +456,10 @@ pub struct RenderMetadata {
|
||||
pub text_frames: HashMap<NodeId, DAffine2>,
|
||||
pub clip_targets: HashSet<NodeId>,
|
||||
pub vector_data: HashMap<NodeId, Arc<Vector>>,
|
||||
/// Per-layer `ATTR_FILL` row attribute, exposed so message handlers can read it.
|
||||
/// Per-layer `graphic_types::attr::Fill` row attribute, exposed so message handlers can read it.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub fill_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
/// Per-layer `ATTR_STROKE` row attribute, exposed so message handlers can read it.
|
||||
/// Per-layer `graphic_types::attr::Stroke` row attribute, exposed so message handlers can read it.
|
||||
#[cfg_attr(feature = "serde", serde(skip))]
|
||||
pub stroke_attributes: HashMap<NodeId, Arc<List<Graphic>>>,
|
||||
pub backgrounds: Vec<Background>,
|
||||
@@ -581,9 +580,9 @@ impl Render for Graphic {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
let layer_path: List<NodeId> = list.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, 0).0;
|
||||
let layer_path: List<NodeId> = list.attr_cloned_or_default::<attr::editor::LayerPath>(0).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let transform = list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
|
||||
metadata.first_element_source_id.insert(element_id, layer);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
@@ -594,7 +593,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::RasterGPU(list) => {
|
||||
@@ -602,7 +601,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::Color(list) => {
|
||||
@@ -610,7 +609,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::Gradient(list) => {
|
||||
@@ -618,7 +617,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
Graphic::Text(list) => {
|
||||
@@ -626,7 +625,7 @@ impl Render for Graphic {
|
||||
|
||||
// TODO: Find a way to handle more than the first item
|
||||
if !list.is_empty() {
|
||||
metadata.local_transforms.insert(element_id, list.attribute_cloned_or_default(ATTR_TRANSFORM, 0));
|
||||
metadata.local_transforms.insert(element_id, list.attr_cloned_or_default::<attr::Transform>(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -699,10 +698,10 @@ impl Render for Graphic {
|
||||
|
||||
/// Reads the artboard metadata for the item at `index` from a `List<Artboard>`.
|
||||
fn read_artboard_attributes(list: &List<Artboard>, index: usize) -> (DVec2, DVec2, Color, bool) {
|
||||
let location: DVec2 = list.attribute_cloned_or_default(ATTR_LOCATION, index);
|
||||
let dimensions: DVec2 = list.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
|
||||
let background: Color = list.attribute_cloned_or_default(ATTR_BACKGROUND, index);
|
||||
let clip: bool = list.attribute_cloned_or_default(ATTR_CLIP, index);
|
||||
let location = list.attr_cloned_or_default::<attr::Location>(index);
|
||||
let dimensions = list.attr_cloned_or_default::<attr::Dimensions>(index);
|
||||
let background = list.attr_cloned_or_default::<attr::Background>(index);
|
||||
let clip = list.attr_cloned_or_default::<attr::Clip>(index);
|
||||
(location, dimensions, background, clip)
|
||||
}
|
||||
|
||||
@@ -737,7 +736,7 @@ impl Render for List<Artboard> {
|
||||
|attributes| {
|
||||
let matrix = format_transform_matrix(DAffine2::from_translation(location));
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
if clip {
|
||||
@@ -800,7 +799,7 @@ impl Render for List<Artboard> {
|
||||
let Some(content) = self.element(index).map(Artboard::as_graphic_list) else { continue };
|
||||
let (location, dimensions, _background, clip) = read_artboard_attributes(self, index);
|
||||
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let element_id = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = element_id {
|
||||
@@ -823,7 +822,7 @@ impl Render for List<Artboard> {
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let dimensions: DVec2 = self.attribute_cloned_or_default(ATTR_DIMENSIONS, index);
|
||||
let dimensions = self.attr_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.));
|
||||
}
|
||||
@@ -839,10 +838,10 @@ impl Render for List<Graphic> {
|
||||
let mut mask_state = None;
|
||||
|
||||
for index in 0..self.len() {
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
render.parent_tag(
|
||||
@@ -850,7 +849,7 @@ impl Render for List<Graphic> {
|
||||
|attributes| {
|
||||
let matrix = format_transform_matrix(transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -895,11 +894,11 @@ impl Render for List<Graphic> {
|
||||
let mut mask_element_and_transform = None;
|
||||
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let transform = transform * item_transform;
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
let mut layer = false;
|
||||
@@ -971,8 +970,8 @@ impl Render for List<Graphic> {
|
||||
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, element_id: Option<NodeId>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
@@ -992,7 +991,7 @@ impl Render for List<Graphic> {
|
||||
let mut all_upstream_outlines = Vec::new();
|
||||
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
|
||||
let mut new_click_targets = Vec::new();
|
||||
@@ -1019,7 +1018,7 @@ impl Render for List<Graphic> {
|
||||
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
let mut new_click_targets = Vec::new();
|
||||
|
||||
@@ -1035,7 +1034,7 @@ impl Render for List<Graphic> {
|
||||
|
||||
fn add_upstream_outline_targets(&self, outlines: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let element = self.element(index).unwrap();
|
||||
let mut new_outlines = Vec::new();
|
||||
|
||||
@@ -1054,7 +1053,7 @@ impl Render for List<Graphic> {
|
||||
}
|
||||
|
||||
fn new_ids_from_hash(&mut self, _reference: Option<NodeId>) {
|
||||
let (elements, layers) = self.element_and_attribute_slices_mut::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH);
|
||||
let (elements, layers) = self.element_and_attr_slices_mut::<attr::editor::LayerPath>();
|
||||
for (element, layer) in elements.iter_mut().zip(layers.iter()) {
|
||||
element.new_ids_from_hash(layer.0.iter_element_values().next_back().copied());
|
||||
}
|
||||
@@ -1065,10 +1064,10 @@ impl Render for List<Vector> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
let Some(vector) = self.element(index) else { continue };
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
|
||||
// Only consider strokes with non-zero weight, since default strokes with zero weight would prevent assigning the correct stroke transform
|
||||
let has_real_stroke = vector.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
@@ -1097,10 +1096,10 @@ impl Render for List<Vector> {
|
||||
MaskType::Mask
|
||||
};
|
||||
|
||||
let fill_graphic_list = graphic_list_at(self, index, ATTR_FILL);
|
||||
let fill_graphic_list = graphic_list_at::<graphic_attr::Fill>(self, index);
|
||||
let fill_graphic = fill_graphic_list.as_ref().and_then(|l| l.element(0));
|
||||
|
||||
let stroke_graphic_list = graphic_list_at(self, index, ATTR_STROKE);
|
||||
let stroke_graphic_list = graphic_list_at::<graphic_attr::Stroke>(self, index);
|
||||
let stroke_graphic = stroke_graphic_list.as_ref().and_then(|l| l.element(0));
|
||||
|
||||
let path_is_closed = vector.stroke_bezier_paths().all(|path| path.closed());
|
||||
@@ -1135,8 +1134,8 @@ impl Render for List<Vector> {
|
||||
|
||||
// The mask must draw at full alpha so the SVG `<mask>`/`<clipPath>` fully zeroes the path interior.
|
||||
// The wrapping SVG group (above) handles the user-set opacity.
|
||||
let mut mask_item = Item::new_from_element(cloned_vector).with_attribute(ATTR_TRANSFORM, item_transform);
|
||||
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
let mut mask_item = Item::new_from_element(cloned_vector).with_attr::<attr::Transform>(item_transform);
|
||||
set_paint_attribute::<graphic_attr::Fill>(mask_item.attributes_mut(), List::new_from_element(Color::BLACK));
|
||||
let vector_item = List::new_from_item(mask_item);
|
||||
|
||||
(id, mask_type, vector_item)
|
||||
@@ -1164,7 +1163,7 @@ impl Render for List<Vector> {
|
||||
attributes.push("d", path.clone());
|
||||
let matrix = format_transform_matrix(element_transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
let defs = &mut attributes.0.svg_defs;
|
||||
@@ -1281,10 +1280,10 @@ impl Render for List<Vector> {
|
||||
use graphic_types::vector_types::vector;
|
||||
|
||||
let Some(element) = self.element(index) else { continue };
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let multiplied_transform = parent_transform * item_transform;
|
||||
let has_real_stroke = element.stroke.as_ref().filter(|stroke| stroke.weight() > 0.);
|
||||
let set_stroke_transform = has_real_stroke.map(|stroke| stroke.transform).filter(|transform| transform_is_invertible(*transform));
|
||||
@@ -1310,8 +1309,8 @@ impl Render for List<Vector> {
|
||||
}
|
||||
}
|
||||
|
||||
let fill_graphic_list = graphic_list_at(self, index, ATTR_FILL);
|
||||
let stroke_graphic_list = graphic_list_at(self, index, ATTR_STROKE);
|
||||
let fill_graphic_list = graphic_list_at::<graphic_attr::Fill>(self, index);
|
||||
let stroke_graphic_list = graphic_list_at::<graphic_attr::Stroke>(self, index);
|
||||
|
||||
// If we're using opacity or a blend mode, we need to push a layer
|
||||
let blend_mode = match render_params.render_mode {
|
||||
@@ -1484,8 +1483,8 @@ impl Render for List<Vector> {
|
||||
|
||||
// The mask must draw at full alpha so `SrcOut` fully zeroes the path interior.
|
||||
// The outer opacity/blend layer (above) handles the user-set opacity.
|
||||
let mut mask_item = Item::new_from_element(cloned_element).with_attribute(ATTR_TRANSFORM, item_transform);
|
||||
set_paint_attribute(mask_item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
let mut mask_item = Item::new_from_element(cloned_element).with_attr::<attr::Transform>(item_transform);
|
||||
set_paint_attribute::<graphic_attr::Fill>(mask_item.attributes_mut(), List::new_from_element(Color::BLACK));
|
||||
let vector_list = List::new_from_item(mask_item);
|
||||
|
||||
let bounds = element.bounding_box_with_transform(multiplied_transform).unwrap_or(layer_bounds);
|
||||
@@ -1559,7 +1558,7 @@ impl Render for List<Vector> {
|
||||
// Aggregate all items' targets per element_id so multi-item lists (e.g. the "Text to Vector Glyphs" node) produce hit areas for every glyph.
|
||||
// Targets are baked relative to item 0's transform since `Graphic::collect_metadata` records that as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if !self.is_empty() {
|
||||
self.attribute_cloned_or_default(ATTR_TRANSFORM, 0)
|
||||
self.attr_cloned_or_default::<attr::Transform>(0)
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
@@ -1574,8 +1573,8 @@ impl Render for List<Vector> {
|
||||
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
|
||||
if let Some(element_id) = caller_element_id.or(layer) {
|
||||
@@ -1588,7 +1587,7 @@ impl Render for List<Vector> {
|
||||
}
|
||||
|
||||
// Use click-target override if the item provides one (e.g. 'Text' node's per-glyph bboxes)
|
||||
let click_target_vector = self.attribute::<Vector>(ATTR_EDITOR_CLICK_TARGET, index).unwrap_or(source);
|
||||
let click_target_vector = self.attr::<vector_attr::editor::ClickTarget>(index).unwrap_or(source);
|
||||
|
||||
let item_relative_transform = item_zero_inverse * transform;
|
||||
|
||||
@@ -1608,16 +1607,16 @@ impl Render for List<Vector> {
|
||||
if let std::collections::hash_map::Entry::Vacant(e) = metadata.vector_data.entry(element_id) {
|
||||
e.insert(Arc::new(source.clone()));
|
||||
|
||||
if let Some(fill_graphic) = graphic_list_at(self, index, ATTR_FILL) {
|
||||
if let Some(fill_graphic) = graphic_list_at::<graphic_attr::Fill>(self, index) {
|
||||
metadata.fill_attributes.insert(element_id, Arc::new(fill_graphic.into_owned()));
|
||||
}
|
||||
if let Some(stroke_graphic) = graphic_list_at(self, index, ATTR_STROKE) {
|
||||
if let Some(stroke_graphic) = graphic_list_at::<graphic_attr::Stroke>(self, index) {
|
||||
metadata.stroke_attributes.insert(element_id, Arc::new(stroke_graphic.into_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
// Surface `editor:text_frame` for the Text tool's drag cage
|
||||
if let Some(&frame) = self.attribute::<DAffine2>(ATTR_EDITOR_TEXT_FRAME, index) {
|
||||
if let Some(&frame) = self.attr::<attr::editor::TextFrame>(index) {
|
||||
metadata.text_frames.entry(element_id).or_insert(frame);
|
||||
}
|
||||
}
|
||||
@@ -1625,7 +1624,7 @@ impl Render for List<Vector> {
|
||||
// If this item carries a snapshot of upstream graphic content (e.g. it was produced by Boolean Operation,
|
||||
// Combine Paths, Morph, or any other destructive merge), recurse into that snapshot so the editor can
|
||||
// surface the original child layers' click targets.
|
||||
let upstream_nested_layers = self.attribute_cloned_or_default::<List<Graphic>>(ATTR_EDITOR_MERGED_LAYERS, index);
|
||||
let upstream_nested_layers = self.attr_cloned_or_default::<graphic_attr::editor::MergedLayers>(index);
|
||||
if !upstream_nested_layers.is_empty() {
|
||||
let mut upstream_footprint = footprint;
|
||||
upstream_footprint.transform *= transform;
|
||||
@@ -1645,10 +1644,10 @@ impl Render for List<Vector> {
|
||||
fn add_upstream_click_targets(&self, click_targets: &mut Vec<ClickTarget>) {
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
// Use click-target override geometry if the item provides one (e.g. 'Text' node's per-glyph bounding boxes)
|
||||
let vector = self.attribute::<Vector>(ATTR_EDITOR_CLICK_TARGET, index).unwrap_or(source);
|
||||
let vector = self.attr::<vector_attr::editor::ClickTarget>(index).unwrap_or(source);
|
||||
|
||||
extend_targets_from_vector(click_targets, self, index, vector, transform);
|
||||
}
|
||||
@@ -1658,7 +1657,7 @@ impl Render for List<Vector> {
|
||||
// Source geometry only, ignoring `editor:click_target`, so outlines reflect actual letterforms
|
||||
for index in 0..self.len() {
|
||||
let Some(source) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
extend_targets_from_vector(outlines, self, index, source, transform);
|
||||
}
|
||||
@@ -1674,7 +1673,7 @@ impl Render for List<Vector> {
|
||||
/// Build one `CompoundPath` (non-zero fill rule, so holes like the inside of an "O" work
|
||||
/// correctly) plus one `FreePoint` per disconnected anchor, apply the transform, and append.
|
||||
fn extend_targets_from_vector(targets: &mut Vec<ClickTarget>, vector_list: &List<Vector>, index: usize, geometry: &Vector, transform: DAffine2) {
|
||||
let filled = has_paint_at(vector_list, index, ATTR_FILL);
|
||||
let filled = has_paint_at::<graphic_attr::Fill>(vector_list, index);
|
||||
|
||||
let mut subpaths: Vec<Subpath<_>> = geometry.stroke_bezier_paths().collect();
|
||||
let all_subpaths_closed = subpaths.iter().all(|subpath| subpath.closed());
|
||||
@@ -1730,10 +1729,10 @@ impl Render for List<Raster<CPU>> {
|
||||
for index in 0..self.len() {
|
||||
let Some(image) = self.element(index) else { continue };
|
||||
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
|
||||
if image.data.is_empty() {
|
||||
continue;
|
||||
@@ -1752,7 +1751,7 @@ impl Render for List<Raster<CPU>> {
|
||||
let matrix = transform * DAffine2::from_scale(1. / size);
|
||||
let matrix = format_transform_matrix(matrix);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
attributes.push("width", size.x.to_string());
|
||||
@@ -1795,7 +1794,7 @@ impl Render for List<Raster<CPU>> {
|
||||
attributes.push("href", base64_string);
|
||||
let matrix = format_transform_matrix(transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
attributes.push("transform", matrix);
|
||||
}
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -1817,9 +1816,9 @@ impl Render for List<Raster<CPU>> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let blend_mode = blend_mode_attr.to_peniko();
|
||||
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
@@ -1834,7 +1833,7 @@ impl Render for List<Raster<CPU>> {
|
||||
layer = true;
|
||||
}
|
||||
|
||||
let transform_attribute: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform_attribute = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
let outline_transform: DAffine2 = transform * transform_attribute;
|
||||
@@ -1874,7 +1873,7 @@ impl Render for List<Raster<CPU>> {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than one item of the `List<Raster<...>>`
|
||||
if !self.is_empty() {
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(0);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
|
||||
// If this raster carries a snapshot of upstream graphic content (e.g. it was produced by Rasterize,
|
||||
@@ -1883,7 +1882,7 @@ impl Render for List<Raster<CPU>> {
|
||||
// The snapshot was captured before Rasterize shifted its input transforms to align with the rasterization
|
||||
// area, so the children are already in the coordinate space matching `footprint` here — we must NOT
|
||||
// multiply in `transform` (which is the rasterization area, not a layer-stack transform).
|
||||
let upstream_nested_layers = self.attribute_cloned_or_default::<List<Graphic>>(ATTR_EDITOR_MERGED_LAYERS, 0);
|
||||
let upstream_nested_layers = self.attr_cloned_or_default::<graphic_attr::editor::MergedLayers>(0);
|
||||
if !upstream_nested_layers.is_empty() {
|
||||
upstream_nested_layers.collect_metadata(metadata, footprint, None);
|
||||
}
|
||||
@@ -1906,10 +1905,10 @@ impl Render for List<Raster<GPU>> {
|
||||
fn render_to_vello(&self, scene: &mut Scene, transform: DAffine2, context: &mut RenderContext, render_params: &RenderParams) {
|
||||
for index in 0..self.len() {
|
||||
let Some(raster) = self.element(index) else { continue };
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let clip_attr: bool = self.attribute_cloned_or_default(ATTR_CLIPPING_MASK, index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let clip_attr = self.attr_cloned_or_default::<attr::ClippingMask>(index);
|
||||
let blend_mode = match render_params.render_mode {
|
||||
RenderMode::Outline => peniko::Mix::Normal,
|
||||
_ => blend_mode_attr.to_peniko(),
|
||||
@@ -1928,7 +1927,7 @@ impl Render for List<Raster<GPU>> {
|
||||
layer = true;
|
||||
}
|
||||
|
||||
let transform_attribute: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform_attribute = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
if let RenderMode::Outline = render_params.render_mode {
|
||||
let outline_transform = transform * transform_attribute;
|
||||
@@ -1969,7 +1968,7 @@ impl Render for List<Raster<GPU>> {
|
||||
metadata.upstream_footprints.insert(element_id, footprint);
|
||||
// TODO: Find a way to handle more than one item of the `List<Raster<...>>`
|
||||
if !self.is_empty() {
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(0);
|
||||
metadata.local_transforms.insert(element_id, transform);
|
||||
|
||||
// If this raster carries a snapshot of upstream graphic content (e.g. it was produced by Rasterize,
|
||||
@@ -1978,7 +1977,7 @@ impl Render for List<Raster<GPU>> {
|
||||
// The snapshot was captured before Rasterize shifted its input transforms to align with the rasterization
|
||||
// area, so the children are already in the coordinate space matching `footprint` here — we must NOT
|
||||
// multiply in `transform` (which is the rasterization area, not a layer-stack transform).
|
||||
let upstream_nested_layers = self.attribute_cloned_or_default::<List<Graphic>>(ATTR_EDITOR_MERGED_LAYERS, 0);
|
||||
let upstream_nested_layers = self.attr_cloned_or_default::<graphic_attr::editor::MergedLayers>(0);
|
||||
if !upstream_nested_layers.is_empty() {
|
||||
upstream_nested_layers.collect_metadata(metadata, footprint, None);
|
||||
}
|
||||
@@ -2000,9 +1999,9 @@ impl Render for List<Raster<GPU>> {
|
||||
impl Render for List<Color> {
|
||||
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
|
||||
for (index, color) in self.iter_element_values().enumerate() {
|
||||
let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
render.leaf_tag("polyline", |attributes| {
|
||||
// Stand-in for an infinite background. Chrome's SVG renderer keeps internal coordinates in f32 and loses
|
||||
// precision past ~2^24 (~16.7 million), causing tile-boundary artifacts that pop in and out during panning.
|
||||
@@ -2031,9 +2030,9 @@ impl Render for List<Color> {
|
||||
use vello::peniko;
|
||||
|
||||
for (index, color) in self.iter_element_values().enumerate() {
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let blend_mode = blend_mode_attr.to_peniko();
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
@@ -2071,12 +2070,12 @@ impl Render for List<Gradient> {
|
||||
|
||||
for index in 0..self.len() {
|
||||
let Some(gradient) = self.element(index) else { continue };
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let spread_method: GradientSpreadMethod = self.attribute_cloned_or_default(ATTR_SPREAD_METHOD, index);
|
||||
let gradient_type: GradientType = self.attribute_cloned_or_default(ATTR_GRADIENT_TYPE, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let spread_method = self.attr_cloned_or_default::<vector_attr::SpreadMethod>(index);
|
||||
let gradient_type = self.attr_cloned_or_default::<vector_attr::GradientType>(index);
|
||||
let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" };
|
||||
render.leaf_tag(tag, |attributes| {
|
||||
if let Some((min, size)) = thumbnail_rect {
|
||||
@@ -2160,13 +2159,13 @@ impl Render for List<Gradient> {
|
||||
for (((index, gradient), spread_method), gradient_type) in self
|
||||
.iter_element_values()
|
||||
.enumerate()
|
||||
.zip(self.iter_attribute_values_or_default::<GradientSpreadMethod>(ATTR_SPREAD_METHOD))
|
||||
.zip(self.iter_attribute_values_or_default::<GradientType>(ATTR_GRADIENT_TYPE))
|
||||
.zip(self.iter_attr_values_or_default::<vector_attr::SpreadMethod>())
|
||||
.zip(self.iter_attr_values_or_default::<vector_attr::GradientType>())
|
||||
{
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let gradient_transform = parent_transform * transform;
|
||||
|
||||
let blend_mode = blend_mode_attr.to_peniko();
|
||||
@@ -2314,16 +2313,16 @@ fn draw_glyph_run_to_bezpaths(glyph_run: &parley::GlyphRun<'_, ()>, x_offset: f3
|
||||
fn text_item_size_and_transform(list: &List<String>, index: usize) -> Option<(DVec2, DAffine2)> {
|
||||
let text = list.element(index)?;
|
||||
let font: Resource = {
|
||||
let f: Resource = list.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
let f = list.attr_cloned_or_default::<text_attr::Font>(index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = list.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = list.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = list.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = list.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = list.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let align: text_nodes::TextAlign = list.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let transform: DAffine2 = list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let font_size = list.attr_cloned_or::<attr::FontSize>(index, DEFAULT_FONT_SIZE);
|
||||
let line_height = list.attr_cloned_or::<attr::LineHeight>(index, 1.2);
|
||||
let letter_spacing = list.attr_cloned_or_default::<attr::LetterSpacing>(index);
|
||||
let max_width = list.attr_cloned_or_default::<attr::MaxWidth>(index);
|
||||
let max_height = list.attr_cloned_or_default::<attr::MaxHeight>(index);
|
||||
let align = list.attr_cloned_or_default::<text_attr::TextAlign>(index);
|
||||
let transform = list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
font_size,
|
||||
@@ -2375,7 +2374,7 @@ pub fn graphic_list_bounding_box(list: &List<Graphic>, transform: DAffine2) -> R
|
||||
let mut any_infinite = false;
|
||||
|
||||
for index in 0..list.len() {
|
||||
let item_transform = transform * list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
|
||||
let item_transform = transform * list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let Some(graphic) = list.element(index) else { continue };
|
||||
let bounds = match graphic {
|
||||
Graphic::Text(text_list) => text_list_bounding_box(text_list, item_transform),
|
||||
@@ -2409,21 +2408,21 @@ impl Render for List<String> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let font: Resource = {
|
||||
let f: Resource = self.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
let f = self.attr_cloned_or_default::<text_attr::Font>(index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = self.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = self.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = self.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = self.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = self.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let letter_tilt: f64 = self.attribute_cloned_or(ATTR_LETTER_TILT, index, 0.);
|
||||
let align: text_nodes::TextAlign = self.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let font_size = self.attr_cloned_or::<attr::FontSize>(index, DEFAULT_FONT_SIZE);
|
||||
let line_height = self.attr_cloned_or::<attr::LineHeight>(index, 1.2);
|
||||
let letter_spacing = self.attr_cloned_or_default::<attr::LetterSpacing>(index);
|
||||
let max_width = self.attr_cloned_or_default::<attr::MaxWidth>(index);
|
||||
let max_height = self.attr_cloned_or_default::<attr::MaxHeight>(index);
|
||||
let letter_tilt = self.attr_cloned_or_default::<attr::LetterTilt>(index);
|
||||
let align = self.attr_cloned_or_default::<text_attr::TextAlign>(index);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
@@ -2494,21 +2493,21 @@ impl Render for List<String> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let item_transform: DAffine2 = self.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let item_transform = self.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let font: Resource = {
|
||||
let f: Resource = self.attribute_cloned_or_default(ATTR_FONT, index);
|
||||
let f = self.attr_cloned_or_default::<text_attr::Font>(index);
|
||||
if f.is_empty() { text_nodes::FALLBACK_FONT_RESOURCE.clone() } else { f }
|
||||
};
|
||||
let font_size: f64 = self.attribute_cloned_or(ATTR_FONT_SIZE, index, DEFAULT_FONT_SIZE);
|
||||
let line_height: f64 = self.attribute_cloned_or(ATTR_LINE_HEIGHT, index, 1.2);
|
||||
let letter_spacing: f64 = self.attribute_cloned_or(ATTR_LETTER_SPACING, index, 0.);
|
||||
let max_width: Option<f64> = self.attribute_cloned_or(ATTR_MAX_WIDTH, index, None);
|
||||
let max_height: Option<f64> = self.attribute_cloned_or(ATTR_MAX_HEIGHT, index, None);
|
||||
let letter_tilt: f64 = self.attribute_cloned_or(ATTR_LETTER_TILT, index, 0.);
|
||||
let align: text_nodes::TextAlign = self.attribute_cloned_or_default(ATTR_TEXT_ALIGN, index);
|
||||
let blend_mode_attr: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE, index);
|
||||
let opacity_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
let opacity_fill_attr: f64 = self.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
let font_size = self.attr_cloned_or::<attr::FontSize>(index, DEFAULT_FONT_SIZE);
|
||||
let line_height = self.attr_cloned_or::<attr::LineHeight>(index, 1.2);
|
||||
let letter_spacing = self.attr_cloned_or_default::<attr::LetterSpacing>(index);
|
||||
let max_width = self.attr_cloned_or_default::<attr::MaxWidth>(index);
|
||||
let max_height = self.attr_cloned_or_default::<attr::MaxHeight>(index);
|
||||
let letter_tilt = self.attr_cloned_or_default::<attr::LetterTilt>(index);
|
||||
let align = self.attr_cloned_or_default::<text_attr::TextAlign>(index);
|
||||
let blend_mode_attr = self.attr_cloned_or_default::<attr::BlendMode>(index);
|
||||
let opacity_attr = self.attr_cloned_or_default::<attr::Opacity>(index);
|
||||
let opacity_fill_attr = self.attr_cloned_or_default::<attr::OpacityFill>(index);
|
||||
let opacity = (opacity_attr * if render_params.for_mask { 1. } else { opacity_fill_attr }) as f32;
|
||||
|
||||
let typesetting = text_nodes::TypesettingConfig {
|
||||
@@ -2559,7 +2558,7 @@ impl Render for List<String> {
|
||||
fn collect_metadata(&self, metadata: &mut RenderMetadata, footprint: Footprint, caller_element_id: Option<NodeId>) {
|
||||
// Click targets are baked relative to item 0's transform, which `Graphic::collect_metadata` records as `local_transforms[element_id]`.
|
||||
let item_zero_transform: DAffine2 = if !self.is_empty() {
|
||||
self.attribute_cloned_or_default(ATTR_TRANSFORM, 0)
|
||||
self.attr_cloned_or_default::<attr::Transform>(0)
|
||||
} else {
|
||||
DAffine2::IDENTITY
|
||||
};
|
||||
@@ -2572,7 +2571,7 @@ impl Render for List<String> {
|
||||
let mut accumulated_click_targets: HashMap<NodeId, Vec<Arc<ClickTarget>>> = HashMap::new();
|
||||
|
||||
for index in 0..self.len() {
|
||||
let layer_path: List<NodeId> = self.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let layer_path: List<NodeId> = self.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let layer = layer_path.iter_element_values().next_back().copied();
|
||||
let Some(element_id) = caller_element_id.or(layer) else { continue };
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Typed attribute keys whose value types live in this crate. See `core_types::attr` for the trait and macro.
|
||||
|
||||
use crate::gradient::GradientSpreadMethod;
|
||||
use crate::vector::Vector;
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Gradient's spread method (`Pad`, `Reflect`, or `Repeat`).
|
||||
SpreadMethod: GradientSpreadMethod,
|
||||
/// Gradient's type (`Linear` or `Radial`).
|
||||
GradientType: crate::gradient::GradientType,
|
||||
editor {
|
||||
/// Vector that overrides the item's own geometry for click-target generation.
|
||||
/// Used by the 'Text' node for per-glyph bounding-box rectangles so glyphs are selectable
|
||||
/// by clicking anywhere within their bounds, not just the filled letterform.
|
||||
ClickTarget: Vector,
|
||||
},
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attr::Attr;
|
||||
|
||||
// Key names are the stored document format — pinned as literals so a key rename shows up as a breaking change.
|
||||
#[test]
|
||||
fn key_names_are_pinned() {
|
||||
assert_eq!(SpreadMethod::name(), "spread_method");
|
||||
assert_eq!(GradientType::name(), "gradient_type");
|
||||
assert_eq!(editor::ClickTarget::name(), "editor:click_target");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
#[macro_use]
|
||||
extern crate log;
|
||||
|
||||
pub mod attr;
|
||||
pub mod gradient;
|
||||
pub mod math;
|
||||
pub mod subpath;
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
use crate::crate_ident::CrateIdent;
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::quote;
|
||||
use syn::parse::ParseStream;
|
||||
use syn::{Attribute, Expr, Ident, Token, Type, braced, token};
|
||||
|
||||
/// Implementation of the `attrs!` macro declaring typed attribute keys.
|
||||
///
|
||||
/// Grammar: `Name: Type`, comma-separated; `namespace { ... }` blocks nest and contribute a
|
||||
/// `namespace:` prefix to the key name, which is otherwise derived mechanically from the key
|
||||
/// ident (UpperCamel → snake_case). An optional `= value` after the type declares the key's
|
||||
/// implicit default, overriding the value type's `Default` for items lacking the attribute.
|
||||
pub fn attrs_impl(input: TokenStream) -> syn::Result<TokenStream> {
|
||||
let entries: Entries = syn::parse2(input)?;
|
||||
let crate_ident = CrateIdent::default();
|
||||
let core = crate_ident.gcore()?;
|
||||
|
||||
let items = entries.0.iter().map(|entry| generate_entry(entry, core, "")).collect::<syn::Result<Vec<_>>>()?;
|
||||
let lookup = generate_implicit_default_lookup(&entries.0, core);
|
||||
|
||||
Ok(quote! {
|
||||
#(#items)*
|
||||
#lookup
|
||||
})
|
||||
}
|
||||
|
||||
struct Entries(Vec<Entry>);
|
||||
|
||||
enum Entry {
|
||||
Key {
|
||||
docs: Vec<Attribute>,
|
||||
ident: Ident,
|
||||
ty: Box<Type>,
|
||||
default: Option<Box<Expr>>,
|
||||
},
|
||||
Namespace {
|
||||
docs: Vec<Attribute>,
|
||||
ident: Ident,
|
||||
entries: Vec<Entry>,
|
||||
},
|
||||
}
|
||||
|
||||
impl syn::parse::Parse for Entries {
|
||||
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||
Ok(Self(parse_entries(input)?))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_entries(input: ParseStream) -> syn::Result<Vec<Entry>> {
|
||||
let mut entries = Vec::new();
|
||||
while !input.is_empty() {
|
||||
let docs = input.call(Attribute::parse_outer)?;
|
||||
let ident: Ident = input.parse()?;
|
||||
if input.peek(token::Brace) {
|
||||
let content;
|
||||
braced!(content in input);
|
||||
entries.push(Entry::Namespace {
|
||||
docs,
|
||||
ident,
|
||||
entries: parse_entries(&content)?,
|
||||
});
|
||||
} else {
|
||||
input.parse::<Token![:]>()?;
|
||||
let ty = Box::new(input.parse::<Type>()?);
|
||||
let default = if input.peek(Token![=]) {
|
||||
input.parse::<Token![=]>()?;
|
||||
Some(Box::new(input.parse::<Expr>()?))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
entries.push(Entry::Key { docs, ident, ty, default });
|
||||
}
|
||||
if !input.is_empty() {
|
||||
input.parse::<Token![,]>()?;
|
||||
}
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn generate_entry(entry: &Entry, core: &TokenStream, prefix: &str) -> syn::Result<TokenStream> {
|
||||
match entry {
|
||||
Entry::Key { docs, ident, ty, default } => {
|
||||
let name = key_name(ident, prefix);
|
||||
let implicit_default = default.as_ref().map(|value| {
|
||||
quote! {
|
||||
fn implicit_default() -> Self::Value {
|
||||
#value
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(quote! {
|
||||
#(#docs)*
|
||||
pub struct #ident;
|
||||
impl #core::attr::Attr for #ident {
|
||||
type Value = #ty;
|
||||
fn name() -> &'static str {
|
||||
#name
|
||||
}
|
||||
#implicit_default
|
||||
}
|
||||
})
|
||||
}
|
||||
Entry::Namespace { docs, ident, entries } => {
|
||||
let child_prefix = child_prefix(ident, prefix);
|
||||
let items = entries.iter().map(|entry| generate_entry(entry, core, &child_prefix)).collect::<syn::Result<Vec<_>>>()?;
|
||||
Ok(quote! {
|
||||
#(#docs)*
|
||||
pub mod #ident {
|
||||
use super::*;
|
||||
#(#items)*
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a string-keyed lookup of the boxed implicit defaults for erased attribute code paths,
|
||||
/// or nothing if no key in this invocation declares a `= value` default.
|
||||
fn generate_implicit_default_lookup(entries: &[Entry], core: &TokenStream) -> Option<TokenStream> {
|
||||
let mut defaulted_keys = Vec::new();
|
||||
collect_defaulted_key_paths(entries, &TokenStream::new(), &mut defaulted_keys);
|
||||
|
||||
if defaulted_keys.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(quote! {
|
||||
/// The boxed implicit default for the key named `key`, if that key declares one with `= value` in `attrs!`.
|
||||
pub fn implicit_default_value(key: &str) -> ::std::option::Option<::std::boxed::Box<dyn #core::list::AnyAttributeValue>> {
|
||||
#(
|
||||
if key == <#defaulted_keys as #core::attr::Attr>::name() {
|
||||
return ::std::option::Option::Some(::std::boxed::Box::new(<#defaulted_keys as #core::attr::Attr>::implicit_default()));
|
||||
}
|
||||
)*
|
||||
::std::option::Option::None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Walks the entry tree collecting module-qualified paths (like `namespace::Key`) of keys that declare a default.
|
||||
fn collect_defaulted_key_paths(entries: &[Entry], module_path: &TokenStream, paths: &mut Vec<TokenStream>) {
|
||||
for entry in entries {
|
||||
match entry {
|
||||
Entry::Key { ident, default: Some(_), .. } => paths.push(quote!(#module_path #ident)),
|
||||
Entry::Key { .. } => {}
|
||||
Entry::Namespace { ident, entries, .. } => collect_defaulted_key_paths(entries, "e!(#module_path #ident::), paths),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_name(ident: &Ident, prefix: &str) -> String {
|
||||
let snake = snake_case(&ident.to_string());
|
||||
if prefix.is_empty() { snake } else { format!("{prefix}:{snake}") }
|
||||
}
|
||||
|
||||
fn child_prefix(ident: &Ident, prefix: &str) -> String {
|
||||
if prefix.is_empty() { ident.to_string() } else { format!("{prefix}:{ident}") }
|
||||
}
|
||||
|
||||
fn snake_case(name: &str) -> String {
|
||||
let mut result = String::with_capacity(name.len() + 4);
|
||||
for (i, c) in name.chars().enumerate() {
|
||||
if c.is_uppercase() {
|
||||
if i > 0 {
|
||||
result.push('_');
|
||||
}
|
||||
result.extend(c.to_lowercase());
|
||||
} else {
|
||||
result.push(c);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
@@ -3,6 +3,7 @@ use proc_macro::TokenStream;
|
||||
use proc_macro_error2::proc_macro_error;
|
||||
use syn::GenericParam;
|
||||
|
||||
mod attrs;
|
||||
mod buffer_struct;
|
||||
mod codegen;
|
||||
mod crate_ident;
|
||||
@@ -33,6 +34,13 @@ pub fn derive_choice_type(input_item: TokenStream) -> TokenStream {
|
||||
derive_choice_type::derive_choice_type_impl(input_item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Declares typed attribute keys implementing the `Attr` trait, plus a wire-name lookup for their
|
||||
/// implicit defaults. See `core_types::attr` for the trait and syntax.
|
||||
#[proc_macro]
|
||||
pub fn attrs(input: TokenStream) -> TokenStream {
|
||||
attrs::attrs_impl(input.into()).unwrap_or_else(|err| err.to_compile_error()).into()
|
||||
}
|
||||
|
||||
/// Derive a struct to implement `ShaderStruct`, see that for docs.
|
||||
#[proc_macro_derive(BufferStruct)]
|
||||
pub fn derive_buffer_struct(input_item: TokenStream) -> TokenStream {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use core_types::attr;
|
||||
use core_types::list::Item;
|
||||
use core_types::registry::types::Percentage;
|
||||
use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL, BlendMode, Color, Ctx};
|
||||
use core_types::{BlendMode, Color, Ctx};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
@@ -19,7 +20,7 @@ fn blend_mode<T>(
|
||||
let mut content = content;
|
||||
let blend_mode = *blend_mode.element();
|
||||
|
||||
content.set_attribute(ATTR_BLEND_MODE, blend_mode);
|
||||
content.set_attr::<attr::BlendMode>(blend_mode);
|
||||
content
|
||||
}
|
||||
|
||||
@@ -54,13 +55,13 @@ fn opacity<T>(
|
||||
let (has_opacity, opacity, has_fill, fill) = (*has_opacity.element(), *opacity.element(), *has_fill.element(), *fill.element());
|
||||
|
||||
if has_opacity {
|
||||
let multiplied = content.attribute_cloned_or(ATTR_OPACITY, 1.) * (opacity / 100.);
|
||||
content.set_attribute(ATTR_OPACITY, multiplied);
|
||||
let multiplied = content.attr_cloned_or_default::<attr::Opacity>() * (opacity / 100.);
|
||||
content.set_attr::<attr::Opacity>(multiplied);
|
||||
}
|
||||
|
||||
if has_fill {
|
||||
let multiplied = content.attribute_cloned_or(ATTR_OPACITY_FILL, 1.) * (fill / 100.);
|
||||
content.set_attribute(ATTR_OPACITY_FILL, multiplied);
|
||||
let multiplied = content.attr_cloned_or_default::<attr::OpacityFill>() * (fill / 100.);
|
||||
content.set_attr::<attr::OpacityFill>(multiplied);
|
||||
}
|
||||
|
||||
content
|
||||
@@ -79,6 +80,6 @@ fn clipping_mask<T>(
|
||||
let mut content = content;
|
||||
let clip = *clip.element();
|
||||
|
||||
content.set_attribute(ATTR_CLIPPING_MASK, clip);
|
||||
content.set_attr::<attr::ClippingMask>(clip);
|
||||
content
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::brush_cache::BrushCache;
|
||||
use crate::brush_stroke::{BrushStyle, BrushTrace};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::attr;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::color::{Alpha, Color, Pixel, Sample};
|
||||
@@ -91,7 +91,7 @@ where
|
||||
return target;
|
||||
}
|
||||
|
||||
let (elements, transforms) = target.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
|
||||
let (elements, transforms) = target.element_and_attr_slices_mut::<attr::Transform>();
|
||||
for (element, transform_attribute) in elements.iter_mut().zip(transforms.iter()) {
|
||||
let target_width = element.width;
|
||||
let target_height = element.height;
|
||||
@@ -281,7 +281,7 @@ async fn brush(
|
||||
let has_erase_or_restore_strokes = trace.iter_element_values().any(|s| matches!(s.style.blend_mode, BlendMode::Erase | BlendMode::Restore));
|
||||
if has_erase_or_restore_strokes {
|
||||
let opaque_image = Image::new(bbox.size().x as u32, bbox.size().y as u32, Color::WHITE);
|
||||
let mut erase_restore_mask = Item::new_from_element(Raster::new_cpu(opaque_image)).with_attribute(ATTR_TRANSFORM, background_bounds);
|
||||
let mut erase_restore_mask = Item::new_from_element(Raster::new_cpu(opaque_image)).with_attr::<attr::Transform>(background_bounds);
|
||||
|
||||
for stroke in trace.into_iter().map(|row| row.into_element()) {
|
||||
let mut brush_texture = cache.get_cached_brush(&stroke.style);
|
||||
@@ -315,10 +315,10 @@ async fn brush(
|
||||
|
||||
// The paint operation changes only the raster and its bounds, so set just the resulting transform; blending, opacity,
|
||||
// clipping, and layer-path attributes carry through from the input `background` rather than being invented here.
|
||||
let transform: DAffine2 = actual_image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform = actual_image.attr_cloned_or_default::<attr::Transform>();
|
||||
|
||||
*result_item.element_mut() = actual_image.into_element();
|
||||
result_item.set_attribute(ATTR_TRANSFORM, transform);
|
||||
result_item.set_attr::<attr::Transform>(transform);
|
||||
|
||||
result_item
|
||||
}
|
||||
@@ -328,8 +328,8 @@ pub fn blend_image_closure(foreground: Item<Raster<CPU>>, mut background: Item<R
|
||||
let background_size = DVec2::new(background.element().width as f64, background.element().height as f64);
|
||||
|
||||
// Transforms a point from the background image to the foreground image
|
||||
let foreground_transform: DAffine2 = foreground.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let background_transform: DAffine2 = background.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let foreground_transform = foreground.attr_cloned_or_default::<attr::Transform>();
|
||||
let background_transform = background.attr_cloned_or_default::<attr::Transform>();
|
||||
let background_to_foreground = DAffine2::from_scale(foreground_size) * foreground_transform.inverse() * background_transform * DAffine2::from_scale(1. / background_size);
|
||||
|
||||
// Footprint of the foreground image (0, 0)..(1, 1) in the background image space
|
||||
@@ -360,7 +360,7 @@ pub fn blend_stamp_closure(foreground: BrushStampGenerator<Color>, mut backgroun
|
||||
let background_size = DVec2::new(background.element().width as f64, background.element().height as f64);
|
||||
|
||||
// Transforms a point from the background image to the foreground image
|
||||
let background_transform: DAffine2 = background.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let background_transform = background.attr_cloned_or_default::<attr::Transform>();
|
||||
let background_to_foreground = background_transform * DAffine2::from_scale(1. / background_size);
|
||||
|
||||
// Footprint of the foreground image (0, 0)..(1, 1) in the background image space
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::brush_stroke::BrushStroke;
|
||||
use crate::brush_stroke::BrushStyle;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::attr;
|
||||
use core_types::graphene_hash::CacheHashWrapper;
|
||||
use core_types::list::Item;
|
||||
use raster_types::CPU;
|
||||
@@ -51,7 +51,7 @@ impl BrushCacheImpl {
|
||||
|
||||
// Check if the first non-blended stroke is an extension of the last one.
|
||||
// Transform is set to ZERO (not the default IDENTITY) as a sentinel to mark this item as uninitialized.
|
||||
let mut first_stroke_texture = Item::new_from_element(Raster::<CPU>::default()).with_attribute(ATTR_TRANSFORM, glam::DAffine2::ZERO);
|
||||
let mut first_stroke_texture = Item::new_from_element(Raster::<CPU>::default()).with_attr::<attr::Transform>(glam::DAffine2::ZERO);
|
||||
let mut first_stroke_point_skip = 0;
|
||||
let strokes = input[num_blended_strokes..].to_vec();
|
||||
if !strokes.is_empty() && self.prev_input.len() > num_blended_strokes {
|
||||
|
||||
@@ -6,7 +6,7 @@ use glam::{DVec2, IVec2, UVec2};
|
||||
/// Obtains the X or Y component of a vec2.
|
||||
///
|
||||
/// The inverse of this node is **Combine Vec2**, which composes a vec2 from its X and Y components.
|
||||
#[node_macro::node(name("Extract XY"), category("Math: Vector"))]
|
||||
#[node_macro::node(name("Extract XY"), category("Math: Vec2"))]
|
||||
fn extract_xy<T: Into<DVec2>>(_: impl Ctx, #[implementations(DVec2, IVec2, UVec2)] vector: Item<T>, axis: Item<XY>) -> Item<f64> {
|
||||
let vector = vector.into_element();
|
||||
let axis = axis.into_element();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use core_types::attr;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::TransformMut;
|
||||
use core_types::{ATTR_BACKGROUND, ATTR_CLIP, ATTR_DIMENSIONS, ATTR_LOCATION, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use core_types::{CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -53,8 +54,8 @@ pub async fn create_artboard<T: IntoGraphicList>(
|
||||
|
||||
// Name is not stored here, it's resolved live from the parent layer's display name
|
||||
Item::new_from_element(Artboard::new(content))
|
||||
.with_attribute(ATTR_LOCATION, normalized_location)
|
||||
.with_attribute(ATTR_DIMENSIONS, normalized_dimensions)
|
||||
.with_attribute(ATTR_BACKGROUND, background)
|
||||
.with_attribute(ATTR_CLIP, clip)
|
||||
.with_attr::<attr::Location>(normalized_location)
|
||||
.with_attr::<attr::Dimensions>(normalized_dimensions)
|
||||
.with_attr::<attr::Background>(background)
|
||||
.with_attr::<attr::Clip>(clip)
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
use core_types::attr;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
|
||||
use core_types::registry::types::{Angle, SeedValue, SignedInteger};
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use core_types::{AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{Graphic, IntoGraphicList};
|
||||
use graphic_types::{Artboard, Vector};
|
||||
@@ -489,7 +490,7 @@ async fn mirror<T: BoundingBox + 'n + Send + Clone>(
|
||||
let normal = DVec2::from_angle(angle.to_radians());
|
||||
|
||||
// The mirror reference may be based on the bounding box if an explicit reference point is chosen
|
||||
let item_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let item_transform = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let RenderBoundingBox::Rectangle(bounding_box) = content.element().bounding_box(item_transform, false) else {
|
||||
return List::new_from_item(content);
|
||||
};
|
||||
@@ -521,7 +522,7 @@ async fn mirror<T: BoundingBox + 'n + Send + Clone>(
|
||||
|
||||
// Add the mirrored copy with the reflection composed onto its transform
|
||||
let mut mirrored = content;
|
||||
mirrored.set_attribute(ATTR_TRANSFORM, reflected_transform * item_transform);
|
||||
mirrored.set_attr::<attr::Transform>(reflected_transform * item_transform);
|
||||
result_list.push(mirrored);
|
||||
|
||||
result_list
|
||||
@@ -600,7 +601,7 @@ fn read_attribute_vector(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Vector>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<Vector>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
@@ -618,10 +619,10 @@ fn read_attribute_number(
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let value = content
|
||||
.attribute::<f64>(&name, index)
|
||||
.attribute_dyn::<f64>(&name, index)
|
||||
.copied()
|
||||
.or_else(|| content.attribute::<u64>(&name, index).map(|v| *v as f64))
|
||||
.or_else(|| content.attribute::<u32>(&name, index).map(|v| *v as f64));
|
||||
.or_else(|| content.attribute_dyn::<u64>(&name, index).map(|v| *v as f64))
|
||||
.or_else(|| content.attribute_dyn::<u32>(&name, index).map(|v| *v as f64));
|
||||
let Some(value) = value else { continue };
|
||||
result.push(Item::new_from_element(value));
|
||||
}
|
||||
@@ -639,7 +640,7 @@ fn read_attribute_bool(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<bool>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<bool>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
@@ -656,7 +657,7 @@ fn read_attribute_string(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<String>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<String>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
@@ -673,7 +674,7 @@ fn read_attribute_transform(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<DAffine2>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<DAffine2>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
@@ -690,7 +691,7 @@ fn read_attribute_color(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Color>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<Color>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
@@ -707,7 +708,7 @@ fn read_attribute_blend_mode(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<BlendMode>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<BlendMode>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
@@ -724,7 +725,7 @@ fn read_attribute_gradient_type(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<GradientType>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<GradientType>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
@@ -741,7 +742,7 @@ fn read_attribute_spread_method(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<GradientSpreadMethod>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<GradientSpreadMethod>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(*value));
|
||||
}
|
||||
result
|
||||
@@ -758,7 +759,7 @@ fn read_attribute_gradient_stops(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Gradient>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<Gradient>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
@@ -775,7 +776,7 @@ fn read_attribute_artboard(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Artboard>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<Artboard>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
@@ -792,7 +793,7 @@ fn read_attribute_raster(
|
||||
let name = name.into_element();
|
||||
let mut result = List::with_capacity(content.len());
|
||||
for index in 0..content.len() {
|
||||
let Some(value) = content.attribute::<Raster<CPU>>(&name, index) else { continue };
|
||||
let Some(value) = content.attribute_dyn::<Raster<CPU>>(&name, index) else { continue };
|
||||
result.push(Item::new_from_element(value.clone()));
|
||||
}
|
||||
result
|
||||
@@ -869,7 +870,7 @@ pub async fn legacy_layer_extend<T: 'n + Send + Clone>(
|
||||
|
||||
let mut base = base;
|
||||
for mut row in new.into_iter() {
|
||||
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
row.set_attr::<attr::editor::LayerPath>(layer_path.clone());
|
||||
base.push(row);
|
||||
}
|
||||
|
||||
@@ -926,7 +927,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
|
||||
for index in 0..current_graphic_list.len() {
|
||||
let Some(current_element) = current_graphic_list.element(index) else { continue };
|
||||
let current_element = current_element.clone();
|
||||
let current_transform: DAffine2 = current_graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let current_transform = current_graphic_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
|
||||
let recurse = fully_flatten || recursion_depth == 0;
|
||||
|
||||
@@ -934,7 +935,7 @@ pub async fn flatten_graphic(_: impl Ctx, content: List<Graphic>, fully_flatten:
|
||||
// If we're allowed to recurse, flatten any graphics we encounter
|
||||
Graphic::Graphic(mut current_element) if recurse => {
|
||||
// Apply the parent graphic's transform to all child elements
|
||||
for graphic_transform in current_element.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for graphic_transform in current_element.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*graphic_transform = current_transform * *graphic_transform;
|
||||
}
|
||||
|
||||
@@ -974,15 +975,15 @@ pub async fn flatten_vector<T: IntoGraphicList>(_: impl Ctx, #[implementations(L
|
||||
// already holds the original transforms; pre-compensate by item 0's inverse so the renderer's
|
||||
// `upstream_footprint *= item_0_transform` recursion cancels out and leaves the originals intact.
|
||||
let mut graphic_list = graphic_list;
|
||||
let item_0_transform: DAffine2 = output.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let item_0_transform = output.attr_cloned_or_default::<attr::Transform>(0);
|
||||
if item_0_transform.matrix2.determinant().abs() > f64::EPSILON {
|
||||
let inverse = item_0_transform.inverse();
|
||||
for transform in graphic_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in graphic_list.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*transform = inverse * *transform;
|
||||
}
|
||||
}
|
||||
|
||||
output.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, graphic_list);
|
||||
output.set_attr::<graphic_types::attr::editor::MergedLayers>(0, graphic_list);
|
||||
}
|
||||
|
||||
output
|
||||
|
||||
@@ -10,9 +10,9 @@ use core_types::list::List;
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::ops::Convert;
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, WasmNotSend};
|
||||
use core_types::{Color, Ctx};
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{WasmNotSend, attr};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
pub use graph_craft::document::value::RenderOutputType;
|
||||
@@ -243,7 +243,7 @@ where
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
for transform in data.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in data.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*transform = DAffine2::from_translation(-aabb.start) * *transform;
|
||||
}
|
||||
data.render_svg(&mut render, &render_params);
|
||||
@@ -270,8 +270,8 @@ where
|
||||
let image = Image::from_image_data(&rasterized.data().0, resolution.x as u32, resolution.y as u32);
|
||||
List::new_from_item(
|
||||
Item::new_from_element(Raster::new_cpu(image))
|
||||
.with_attribute(ATTR_TRANSFORM, footprint.transform)
|
||||
.with_attribute(ATTR_EDITOR_MERGED_LAYERS, upstream_graphic_list),
|
||||
.with_attr::<attr::Transform>(footprint.transform)
|
||||
.with_attr::<graphic_types::attr::editor::MergedLayers>(upstream_graphic_list),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use core_types::Ctx;
|
||||
use core_types::consts::{DEFAULT_FONT_SIZE, DEFAULT_LINE_HEIGHT};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_TEXT_ALIGN, Ctx};
|
||||
use graph_craft::application_io::resource::Resource;
|
||||
use graphic_types::Vector;
|
||||
pub use text_nodes::*;
|
||||
@@ -69,28 +69,28 @@ fn text(
|
||||
let mut item = Item::new_from_element(text);
|
||||
|
||||
if font != Resource::default() {
|
||||
item.set_attribute(ATTR_FONT, font);
|
||||
item.set_attr::<attr::Font>(font);
|
||||
}
|
||||
if (size - DEFAULT_FONT_SIZE).abs() > f64::EPSILON {
|
||||
item.set_attribute(ATTR_FONT_SIZE, size);
|
||||
item.set_attr::<core_types::attr::FontSize>(size);
|
||||
}
|
||||
if (line_height - DEFAULT_LINE_HEIGHT).abs() > f64::EPSILON {
|
||||
item.set_attribute(ATTR_LINE_HEIGHT, line_height);
|
||||
item.set_attr::<core_types::attr::LineHeight>(line_height);
|
||||
}
|
||||
if letter_spacing != 0. {
|
||||
item.set_attribute(ATTR_LETTER_SPACING, letter_spacing);
|
||||
item.set_attr::<core_types::attr::LetterSpacing>(letter_spacing);
|
||||
}
|
||||
if letter_tilt != 0. {
|
||||
item.set_attribute(ATTR_LETTER_TILT, letter_tilt);
|
||||
item.set_attr::<core_types::attr::LetterTilt>(letter_tilt);
|
||||
}
|
||||
if has_max_width {
|
||||
item.set_attribute(ATTR_MAX_WIDTH, Some(max_width));
|
||||
item.set_attr::<core_types::attr::MaxWidth>(Some(max_width));
|
||||
}
|
||||
if has_max_height {
|
||||
item.set_attribute(ATTR_MAX_HEIGHT, Some(max_height));
|
||||
item.set_attr::<core_types::attr::MaxHeight>(Some(max_height));
|
||||
}
|
||||
if align != TextAlign::default() {
|
||||
item.set_attribute(ATTR_TEXT_ALIGN, align);
|
||||
item.set_attr::<attr::TextAlign>(align);
|
||||
}
|
||||
|
||||
item
|
||||
|
||||
+691
-159
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,8 @@
|
||||
use core_types::list::{ATTR_FILL, Item, ItemAttributeValues, List};
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, Color, Ctx,
|
||||
};
|
||||
use core_types::attr::{self, Attr};
|
||||
use core_types::list::{Item, ItemAttributeValues, List};
|
||||
use core_types::{Color, Ctx};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::graphic::{bake_paint_transforms, set_paint_attribute};
|
||||
use graphic_types::vector_types::gradient::{GradientSpreadMethod, GradientType};
|
||||
use graphic_types::vector_types::subpath::{ManipulatorGroup, Subpath};
|
||||
use graphic_types::vector_types::vector::PointId;
|
||||
use graphic_types::vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
|
||||
@@ -43,8 +41,8 @@ async fn boolean_operation<I: graphic_types::IntoGraphicList>(
|
||||
|
||||
// Replace the transformation matrix with a mutation of the vector points themselves
|
||||
if result_vector_list.element_mut(0).is_some() {
|
||||
let transform: DAffine2 = result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
result_vector_list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::IDENTITY);
|
||||
let transform = result_vector_list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
result_vector_list.set_attr::<attr::Transform>(0, DAffine2::IDENTITY);
|
||||
|
||||
let result_vector = result_vector_list.element_mut(0).unwrap();
|
||||
Vector::transform(result_vector, transform);
|
||||
@@ -52,10 +50,10 @@ async fn boolean_operation<I: graphic_types::IntoGraphicList>(
|
||||
|
||||
// Snapshot the input layers as the `editor:merged_layers` attribute so the renderer can recurse into them
|
||||
// for editor click-target preservation.
|
||||
result_vector_list.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, content.clone());
|
||||
result_vector_list.set_attr::<graphic_types::attr::editor::MergedLayers>(0, content.clone());
|
||||
|
||||
// Clean up the boolean operation result by merging duplicated points
|
||||
let merge_transform: DAffine2 = result_vector_list.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let merge_transform = result_vector_list.attr_cloned_or_default::<attr::Transform>(0);
|
||||
result_vector_list.element_mut(0).unwrap().merge_by_distance_spatial(merge_transform, 0.0001);
|
||||
}
|
||||
|
||||
@@ -139,9 +137,9 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
|
||||
};
|
||||
let mut row = if let Some(index) = copy_from_index {
|
||||
let mut attributes = vector.clone_item_attributes(index);
|
||||
let copy_from_transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let copy_from_transform = vector.attr_cloned_or_default::<attr::Transform>(index);
|
||||
// The boolean op bakes input transforms into the output geometry, so the result item carries no transform of its own
|
||||
attributes.insert(ATTR_TRANSFORM, DAffine2::IDENTITY);
|
||||
attributes.set_attr::<attr::Transform>(DAffine2::IDENTITY);
|
||||
|
||||
bake_paint_transforms(&mut attributes, copy_from_transform);
|
||||
|
||||
@@ -157,7 +155,7 @@ fn boolean_operation_on_vector_list(vector: &List<Vector>, boolean_operation: Bo
|
||||
|
||||
for index in 0..vector.len() {
|
||||
let element = vector.element(index).unwrap();
|
||||
paths.push(to_bez_path(element, vector.attribute_cloned_or_default(ATTR_TRANSFORM, index)));
|
||||
paths.push(to_bez_path(element, vector.attr_cloned_or_default::<attr::Transform>(index)));
|
||||
}
|
||||
|
||||
let top = match Topology::<WindingNumber>::from_paths(paths.iter().enumerate().map(|(idx, path)| (path, (idx, paths.len()))), EPSILON) {
|
||||
@@ -185,18 +183,18 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
Graphic::None => Vec::new(),
|
||||
Graphic::Vector(vector) => {
|
||||
// Apply the parent graphic's transform to each element of the `List<Vector>`
|
||||
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let parent_transform = graphic_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
vector
|
||||
.into_iter()
|
||||
.map(|mut sub_vector| {
|
||||
let current_transform: DAffine2 = sub_vector.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
*sub_vector.attribute_mut_or_insert_default(ATTR_TRANSFORM) = parent_transform * current_transform;
|
||||
let current_transform = sub_vector.attr_cloned_or_default::<attr::Transform>();
|
||||
*sub_vector.attr_mut_or_insert_default::<attr::Transform>() = parent_transform * current_transform;
|
||||
sub_vector
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
Graphic::RasterCPU(image) => {
|
||||
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let parent_transform = graphic_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let make_item = |transform: DAffine2, source_attributes: &ItemAttributeValues| {
|
||||
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
|
||||
subpath.apply_transform(transform);
|
||||
@@ -204,10 +202,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
let element = Vector::from_subpath(subpath);
|
||||
|
||||
let mut item = Item::new_from_element(element);
|
||||
for key in [ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH] {
|
||||
for key in [
|
||||
attr::BlendMode::name(),
|
||||
attr::Opacity::name(),
|
||||
attr::OpacityFill::name(),
|
||||
attr::ClippingMask::name(),
|
||||
attr::editor::LayerPath::name(),
|
||||
] {
|
||||
item.attributes_mut().insert_cloned_from(source_attributes, key);
|
||||
}
|
||||
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
set_paint_attribute::<graphic_types::attr::Fill>(item.attributes_mut(), List::new_from_element(Color::BLACK));
|
||||
item
|
||||
};
|
||||
|
||||
@@ -216,14 +220,14 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
// back to the originating raster layer
|
||||
(0..image.len())
|
||||
.map(|i| {
|
||||
let row_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM, i);
|
||||
let row_transform = image.attr_cloned_or_default::<attr::Transform>(i);
|
||||
let source_attributes = image.clone_item_attributes(i);
|
||||
make_item(parent_transform * row_transform, &source_attributes)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
Graphic::RasterGPU(image) => {
|
||||
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let parent_transform = graphic_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let make_item = |transform: DAffine2, source_attributes: &ItemAttributeValues| {
|
||||
let mut subpath = Subpath::new_rectangle(DVec2::ZERO, DVec2::ONE);
|
||||
subpath.apply_transform(transform);
|
||||
@@ -231,10 +235,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
let element = Vector::from_subpath(subpath);
|
||||
|
||||
let mut item = Item::new_from_element(element);
|
||||
for key in [ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH] {
|
||||
for key in [
|
||||
attr::BlendMode::name(),
|
||||
attr::Opacity::name(),
|
||||
attr::OpacityFill::name(),
|
||||
attr::ClippingMask::name(),
|
||||
attr::editor::LayerPath::name(),
|
||||
] {
|
||||
item.attributes_mut().insert_cloned_from(source_attributes, key);
|
||||
}
|
||||
set_paint_attribute(item.attributes_mut(), ATTR_FILL, List::new_from_element(Color::BLACK));
|
||||
set_paint_attribute::<graphic_types::attr::Fill>(item.attributes_mut(), List::new_from_element(Color::BLACK));
|
||||
item
|
||||
};
|
||||
|
||||
@@ -243,16 +253,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
// back to the originating raster layer
|
||||
(0..image.len())
|
||||
.map(|i| {
|
||||
let row_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM, i);
|
||||
let row_transform = image.attr_cloned_or_default::<attr::Transform>(i);
|
||||
let source_attributes = image.clone_item_attributes(i);
|
||||
make_item(parent_transform * row_transform, &source_attributes)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
Graphic::Graphic(mut graphic) => {
|
||||
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let parent_transform = graphic_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
// Apply the parent graphic's transform to each element of the inner `List`
|
||||
for transform in graphic.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in graphic.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*transform = parent_transform * *transform;
|
||||
}
|
||||
|
||||
@@ -266,7 +276,7 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
let (color, mut attributes) = row.into_parts();
|
||||
set_paint_attribute(&mut attributes, ATTR_FILL, List::new_from_element(color));
|
||||
set_paint_attribute::<graphic_types::attr::Fill>(&mut attributes, List::new_from_element(color));
|
||||
|
||||
let mut element = Vector::default();
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
@@ -280,16 +290,16 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
let (stops, mut attributes) = row.into_parts();
|
||||
|
||||
let mut gradient_paint = List::new_from_element(stops);
|
||||
if let Some(transform) = attributes.remove::<DAffine2>(ATTR_TRANSFORM) {
|
||||
gradient_paint.set_attribute(ATTR_TRANSFORM, 0, transform);
|
||||
if let Some(transform) = attributes.remove_attr::<attr::Transform>() {
|
||||
gradient_paint.set_attr::<attr::Transform>(0, transform);
|
||||
}
|
||||
if let Some(gradient_type) = attributes.remove::<GradientType>(ATTR_GRADIENT_TYPE) {
|
||||
gradient_paint.set_attribute(ATTR_GRADIENT_TYPE, 0, gradient_type);
|
||||
if let Some(gradient_type) = attributes.remove_attr::<vector_types::attr::GradientType>() {
|
||||
gradient_paint.set_attr::<vector_types::attr::GradientType>(0, gradient_type);
|
||||
}
|
||||
if let Some(spread_method) = attributes.remove::<GradientSpreadMethod>(ATTR_SPREAD_METHOD) {
|
||||
gradient_paint.set_attribute(ATTR_SPREAD_METHOD, 0, spread_method);
|
||||
if let Some(spread_method) = attributes.remove_attr::<vector_types::attr::SpreadMethod>() {
|
||||
gradient_paint.set_attr::<vector_types::attr::SpreadMethod>(0, spread_method);
|
||||
}
|
||||
set_paint_attribute(&mut attributes, ATTR_FILL, gradient_paint);
|
||||
set_paint_attribute::<graphic_types::attr::Fill>(&mut attributes, gradient_paint);
|
||||
|
||||
let mut element = Vector::default();
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
@@ -299,12 +309,12 @@ fn flatten_vector(graphic_list: &List<Graphic>) -> List<Vector> {
|
||||
.collect::<Vec<_>>(),
|
||||
Graphic::Text(text) => {
|
||||
// Shape the glyphs into vectors (each item's own transform is applied), then compose the parent's transform like the other arms
|
||||
let parent_transform: DAffine2 = graphic_list.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let parent_transform = graphic_list.attr_cloned_or_default::<attr::Transform>(index);
|
||||
text_nodes::shape_text_list(&text, false)
|
||||
.into_iter()
|
||||
.map(|mut sub_vector| {
|
||||
let current_transform: DAffine2 = sub_vector.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
*sub_vector.attribute_mut_or_insert_default(ATTR_TRANSFORM) = parent_transform * current_transform;
|
||||
let current_transform = sub_vector.attr_cloned_or_default::<attr::Transform>();
|
||||
*sub_vector.attr_mut_or_insert_default::<attr::Transform>() = parent_transform * current_transform;
|
||||
sub_vector
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::attr;
|
||||
use core_types::color::Color;
|
||||
use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut};
|
||||
use core_types::context::{Ctx, ExtractFootprint};
|
||||
@@ -32,7 +32,7 @@ impl From<std::io::Error> for Error {
|
||||
|
||||
#[node_macro::node(category("Debug"))]
|
||||
pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Item<Raster<CPU>>) -> Item<Raster<CPU>> {
|
||||
let image_frame_transform: DAffine2 = image_frame.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let image_frame_transform = image_frame.attr_cloned_or_default::<attr::Transform>();
|
||||
|
||||
let footprint = ctx.footprint();
|
||||
let viewport_bounds = footprint.viewport_bounds_in_local_space();
|
||||
@@ -86,7 +86,7 @@ pub fn sample_image(ctx: impl ExtractFootprint + Clone + Send, image_frame: Item
|
||||
// we need to adjust the offset if we truncate the offset calculation
|
||||
|
||||
let new_transform = image_frame_transform * DAffine2::from_translation(offset) * DAffine2::from_scale(size);
|
||||
attributes.insert(ATTR_TRANSFORM, new_transform);
|
||||
attributes.set_attr::<attr::Transform>(new_transform);
|
||||
|
||||
Item::from_parts(Raster::new_cpu(image), attributes)
|
||||
}
|
||||
@@ -163,7 +163,7 @@ pub fn mask(
|
||||
|
||||
let mut row = image;
|
||||
let image_size = DVec2::new(row.element().width as f64, row.element().height as f64);
|
||||
let stencil_transform: DAffine2 = stencil.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let stencil_transform = stencil.attr_cloned_or_default::<attr::Transform>();
|
||||
let mask_size = stencil_transform.scale_magnitudes();
|
||||
|
||||
if mask_size == DVec2::ZERO {
|
||||
@@ -171,7 +171,7 @@ pub fn mask(
|
||||
}
|
||||
|
||||
// Transforms a point from the background image to the foreground image
|
||||
let transform_attribute: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute = row.attr_cloned_or_default::<attr::Transform>();
|
||||
let bg_to_fg = transform_attribute * DAffine2::from_scale(1. / image_size);
|
||||
let stencil_transform_inverse = stencil_transform.inverse();
|
||||
|
||||
@@ -196,7 +196,7 @@ pub fn mask(
|
||||
pub fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Item<DAffine2>) -> Item<Raster<CPU>> {
|
||||
let bounds = *bounds.element();
|
||||
|
||||
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let image_transform = image.attr_cloned_or_default::<attr::Transform>();
|
||||
let image_aabb = Bbox::unit().affine_transform(image_transform).to_axis_aligned_bbox();
|
||||
let bounds_aabb = Bbox::unit().affine_transform(bounds.transform()).to_axis_aligned_bbox();
|
||||
if image_aabb.contains(bounds_aabb.start) && image_aabb.contains(bounds_aabb.end) {
|
||||
@@ -232,7 +232,7 @@ pub fn extend_image_to_bounds(_: impl Ctx, image: Item<Raster<CPU>>, bounds: Ite
|
||||
// let layer_to_new_texture_space = (DAffine2::from_scale(1. / new_scale) * DAffine2::from_translation(new_start) * layer_to_image_space).inverse();
|
||||
let new_texture_to_layer_space = image_transform * DAffine2::from_scale(1. / orig_image_scale) * DAffine2::from_translation(new_start) * DAffine2::from_scale(new_scale);
|
||||
|
||||
attributes.insert(ATTR_TRANSFORM, new_texture_to_layer_space);
|
||||
attributes.set_attr::<attr::Transform>(new_texture_to_layer_space);
|
||||
Item::from_parts(Raster::new_cpu(new_image), attributes)
|
||||
}
|
||||
|
||||
@@ -244,7 +244,7 @@ pub fn empty_image(_: impl Ctx, transform: Item<DAffine2>, color: Item<Color>) -
|
||||
|
||||
let image = Image::new(width, height, color.into_element());
|
||||
|
||||
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)
|
||||
Item::new_from_element(Raster::new_cpu(image)).with_attr::<attr::Transform>(transform)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
@@ -376,7 +376,7 @@ pub fn noise_pattern(
|
||||
}
|
||||
}
|
||||
|
||||
return Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform);
|
||||
return Item::new_from_element(Raster::new_cpu(image)).with_attr::<attr::Transform>(transform);
|
||||
}
|
||||
};
|
||||
noise.set_noise_type(Some(noise_type));
|
||||
@@ -434,7 +434,7 @@ pub fn noise_pattern(
|
||||
}
|
||||
}
|
||||
|
||||
Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)
|
||||
Item::new_from_element(Raster::new_cpu(image)).with_attr::<attr::Transform>(transform)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Pattern"))]
|
||||
@@ -478,7 +478,7 @@ pub fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Item<Raster<CPU>> {
|
||||
data,
|
||||
..Default::default()
|
||||
}))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size))
|
||||
.with_attr::<attr::Transform>(DAffine2::from_translation(offset) * DAffine2::from_scale(size))
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use crate::gcore::Context;
|
||||
use core::f64::consts::TAU;
|
||||
use core_types::attr;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::{Angle, PixelSize};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl};
|
||||
use core_types::{CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, OwnedContextImpl};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
@@ -102,10 +103,10 @@ pub async fn repeat_array<T: Send + Clone + 'static>(
|
||||
for row_index in 0..generated_content.len() {
|
||||
let Some(mut row) = generated_content.clone_item(row_index) else { continue };
|
||||
|
||||
let local_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let local_transform = row.attr_cloned_or_default::<attr::Transform>();
|
||||
let local_translation = DAffine2::from_translation(local_transform.translation);
|
||||
let local_matrix = DAffine2::from_mat2(local_transform.matrix2);
|
||||
*row.attribute_mut_or_insert_default(ATTR_TRANSFORM) = local_translation * transform * local_matrix;
|
||||
*row.attr_mut_or_insert_default::<attr::Transform>() = local_translation * transform * local_matrix;
|
||||
|
||||
result_list.push(row);
|
||||
}
|
||||
@@ -158,10 +159,10 @@ async fn repeat_radial<T: Send + Clone + 'static>(
|
||||
for row_index in 0..generated_content.len() {
|
||||
let Some(mut row) = generated_content.clone_item(row_index) else { continue };
|
||||
|
||||
let local_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let local_transform = row.attr_cloned_or_default::<attr::Transform>();
|
||||
let local_translation = DAffine2::from_translation(local_transform.translation);
|
||||
let local_matrix = DAffine2::from_mat2(local_transform.matrix2);
|
||||
*row.attribute_mut_or_insert_default(ATTR_TRANSFORM) = local_translation * transform * local_matrix;
|
||||
*row.attr_mut_or_insert_default::<attr::Transform>() = local_translation * transform * local_matrix;
|
||||
|
||||
result_list.push(row);
|
||||
}
|
||||
@@ -200,7 +201,7 @@ async fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
|
||||
for points_index in 0..points.len() {
|
||||
let Some(points_element) = points.element(points_index) else { continue };
|
||||
let transform: DAffine2 = points.attribute_cloned_or_default(ATTR_TRANSFORM, points_index);
|
||||
let transform = points.attr_cloned_or_default::<attr::Transform>(points_index);
|
||||
|
||||
let mut iteration = async |index, point| {
|
||||
let transformed_point = transform.transform_point2(point);
|
||||
@@ -209,7 +210,7 @@ async fn repeat_on_points<T: Send + Clone + 'static>(
|
||||
let generated_content = content.eval(new_ctx.into_context()).await;
|
||||
|
||||
for mut generated_row in generated_content.into_iter() {
|
||||
generated_row.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM).translation = transformed_point;
|
||||
generated_row.attr_mut_or_insert_default::<attr::Transform>().translation = transformed_point;
|
||||
result_list.push(generated_row);
|
||||
}
|
||||
};
|
||||
@@ -301,7 +302,7 @@ mod test {
|
||||
let bounds = generated
|
||||
.element(index)
|
||||
.unwrap()
|
||||
.bounding_box_with_transform(generated.attribute_cloned_or_default(ATTR_TRANSFORM, index))
|
||||
.bounding_box_with_transform(generated.attr_cloned_or_default::<attr::Transform>(index))
|
||||
.unwrap();
|
||||
assert!(position.abs_diff_eq((bounds[0] + bounds[1]) / 2., 1e-10));
|
||||
assert_eq!((bounds[1] - bounds[0]).x, position.y);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Typed attribute keys whose value types live in this crate. See `core_types::attr` for the trait and macro.
|
||||
|
||||
use graphene_resource::Resource;
|
||||
|
||||
node_macro::attrs! {
|
||||
/// Text item's font, as a resource of the loaded font file.
|
||||
Font: Resource,
|
||||
/// Text item's horizontal alignment of lines within the block.
|
||||
TextAlign: crate::TextAlign,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::attr::Attr;
|
||||
|
||||
// Key names are the stored document format — pinned as literals so a key rename shows up as a breaking change.
|
||||
#[test]
|
||||
fn key_names_are_pinned() {
|
||||
assert_eq!(Font::name(), "font");
|
||||
assert_eq!(TextAlign::name(), "text_align");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_TYPE, Ctx};
|
||||
use core_types::{Ctx, attr};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::unescape_string;
|
||||
@@ -265,7 +265,7 @@ fn query_json_all(
|
||||
let mut results = Vec::new();
|
||||
resolve_all(&value, &segments, !*unquote_strings.element(), &mut results);
|
||||
|
||||
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attribute(ATTR_TYPE, ty.to_string())).collect()
|
||||
results.into_iter().map(|(text, ty)| Item::new_from_element(text).with_attr::<attr::Type>(ty.to_string())).collect()
|
||||
}
|
||||
|
||||
/// A parsed segment of a JSON access path.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod attr;
|
||||
pub mod fallback;
|
||||
mod font;
|
||||
pub mod json;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use core_types::attr;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_TEXT_FRAME, ATTR_TRANSFORM};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use parley::GlyphRun;
|
||||
use skrifa::GlyphId;
|
||||
@@ -15,13 +15,13 @@ pub struct PathBuilder {
|
||||
origin: DVec2,
|
||||
glyph_subpaths: Vec<Subpath<PointId>>,
|
||||
pub vector_list: List<Vector>,
|
||||
/// Per-glyph AABBs collected in single-item mode, published as `ATTR_EDITOR_CLICK_TARGET` in `finalize()`.
|
||||
/// Per-glyph AABBs collected in single-item mode, published as `vector_types::attr::editor::ClickTarget` in `finalize()`.
|
||||
merged_click_target_bboxes: Vec<[DVec2; 2]>,
|
||||
/// Per-glyph baselines, parallel to `merged_click_target_bboxes`. Groups glyphs by line for the widening pass.
|
||||
merged_click_target_baselines: Vec<f64>,
|
||||
/// Per-glyph AABBs in glyph-local space (multi-item mode), widened in `finalize()` to fill gaps.
|
||||
per_glyph_bboxes: Vec<Option<[DVec2; 2]>>,
|
||||
/// Text frame size, stamped per item as `ATTR_EDITOR_TEXT_FRAME` relative to each item's origin.
|
||||
/// Text frame size, stamped per item as `attr::editor::TextFrame` relative to each item's origin.
|
||||
text_frame_size: DVec2,
|
||||
/// First glyph's baseline offset (pre-height-filter). Used for the empty placeholder item so
|
||||
/// `local_transforms` stays stable when all glyphs are clipped during a resize drag.
|
||||
@@ -85,8 +85,8 @@ impl PathBuilder {
|
||||
let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -glyph_offset);
|
||||
|
||||
let item = Item::new_from_element(Vector::from_subpaths(core::mem::take(&mut self.glyph_subpaths), false))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(glyph_offset))
|
||||
.with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local);
|
||||
.with_attr::<attr::Transform>(DAffine2::from_translation(glyph_offset))
|
||||
.with_attr::<attr::editor::TextFrame>(frame_in_item_local);
|
||||
self.vector_list.push(item);
|
||||
|
||||
// Defer click target creation to `finalize()` where adjacent AABBs get widened
|
||||
@@ -170,8 +170,8 @@ impl PathBuilder {
|
||||
if self.vector_list.is_empty() {
|
||||
let frame_in_item_local = DAffine2::from_scale_angle_translation(self.text_frame_size, 0., -self.first_glyph_offset);
|
||||
let item = Item::new_from_element(Vector::default())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(self.first_glyph_offset))
|
||||
.with_attribute(ATTR_EDITOR_TEXT_FRAME, frame_in_item_local);
|
||||
.with_attr::<attr::Transform>(DAffine2::from_translation(self.first_glyph_offset))
|
||||
.with_attr::<attr::editor::TextFrame>(frame_in_item_local);
|
||||
self.vector_list.push(item);
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ impl PathBuilder {
|
||||
.enumerate()
|
||||
.filter_map(|(index, bbox)| {
|
||||
let bbox = (*bbox)?;
|
||||
let offset = self.vector_list.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index).translation;
|
||||
let offset = self.vector_list.attr_cloned_or_default::<attr::Transform>(index).translation;
|
||||
Some((index, offset, [bbox[0] + offset, bbox[1] + offset]))
|
||||
})
|
||||
.collect();
|
||||
@@ -197,7 +197,7 @@ impl PathBuilder {
|
||||
for (entry, widened) in entries.iter().zip(layer_bboxes.iter()) {
|
||||
let glyph_local = [widened[0] - entry.1, widened[1] - entry.1];
|
||||
let rect = Subpath::new_rectangle(glyph_local[0], glyph_local[1]);
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, entry.0, Vector::from_subpaths([rect], false));
|
||||
self.vector_list.set_attr::<vector_types::attr::editor::ClickTarget>(entry.0, Vector::from_subpaths([rect], false));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,14 +207,14 @@ impl PathBuilder {
|
||||
widen_horizontal_gaps(&mut bboxes, &self.merged_click_target_baselines);
|
||||
|
||||
let widened_subpaths: Vec<_> = bboxes.iter().map(|[min, max]| Subpath::new_rectangle(*min, *max)).collect();
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_CLICK_TARGET, 0, Vector::from_subpaths(widened_subpaths, false));
|
||||
self.vector_list.set_attr::<vector_types::attr::editor::ClickTarget>(0, Vector::from_subpaths(widened_subpaths, false));
|
||||
}
|
||||
|
||||
// Fill in text frame for items that don't have one yet (single-item mode, where item 0 = identity)
|
||||
let frame = DAffine2::from_scale(self.text_frame_size);
|
||||
for index in 0..self.vector_list.len() {
|
||||
if self.vector_list.attribute::<DAffine2>(ATTR_EDITOR_TEXT_FRAME, index).is_none() {
|
||||
self.vector_list.set_attribute(ATTR_EDITOR_TEXT_FRAME, index, frame);
|
||||
if self.vector_list.attr::<attr::editor::TextFrame>(index).is_none() {
|
||||
self.vector_list.set_attr::<attr::editor::TextFrame>(index, frame);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::registry::types::SignedInteger;
|
||||
use core_types::{ATTR_END, ATTR_NAME, ATTR_START, Ctx};
|
||||
use core_types::{Ctx, attr};
|
||||
|
||||
/// Checks whether the string contains a match for the given regular expression pattern. Optionally restricts the match to only the start and/or end of the string.
|
||||
#[node_macro::node(category("Text: Regex"))]
|
||||
@@ -159,10 +159,7 @@ fn regex_find(
|
||||
let start = captured.map_or(0_u64, |m| m.start() as u64);
|
||||
let end = captured.map_or(0_u64, |m| m.end() as u64);
|
||||
let name = capture_names.get(i).cloned().flatten().unwrap_or_default();
|
||||
Item::new_from_element(text)
|
||||
.with_attribute(ATTR_START, start)
|
||||
.with_attribute(ATTR_END, end)
|
||||
.with_attribute(ATTR_NAME, name)
|
||||
Item::new_from_element(text).with_attr::<attr::Start>(start).with_attr::<attr::End>(end).with_attr::<attr::Name>(name)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -208,8 +205,8 @@ fn regex_find_all(
|
||||
.filter_map(|m| m.ok())
|
||||
.map(|m| {
|
||||
Item::new_from_element(m.as_str().to_string())
|
||||
.with_attribute(ATTR_START, m.start() as u64)
|
||||
.with_attribute(ATTR_END, m.end() as u64)
|
||||
.with_attr::<attr::Start>(m.start() as u64)
|
||||
.with_attr::<attr::End>(m.end() as u64)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
use super::TypesettingConfig;
|
||||
use super::text_context::TextContext;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_EDITOR_LAYER_PATH, ATTR_FONT, ATTR_FONT_SIZE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL,
|
||||
ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
};
|
||||
use core_types::attr;
|
||||
use core_types::list::{Item, List};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_resource::Resource;
|
||||
use vector_types::Vector;
|
||||
@@ -33,45 +29,45 @@ pub fn shape_text_item(item: &Item<String>, separate_glyphs: bool) -> List<Vecto
|
||||
|
||||
// Use fallback font when none is explicitly attached.
|
||||
let font: Resource = {
|
||||
let font: Resource = item.attribute_cloned_or_default(ATTR_FONT);
|
||||
let font: Resource = item.attr_cloned_or_default::<crate::attr::Font>();
|
||||
if font.is_empty() { super::FALLBACK_FONT_RESOURCE.clone() } else { font }
|
||||
};
|
||||
|
||||
let defaults = TypesettingConfig::default();
|
||||
let typesetting = TypesettingConfig {
|
||||
font_size: item.attribute_cloned_or(ATTR_FONT_SIZE, defaults.font_size),
|
||||
line_height_ratio: item.attribute_cloned_or(ATTR_LINE_HEIGHT, defaults.line_height_ratio),
|
||||
letter_spacing: item.attribute_cloned_or(ATTR_LETTER_SPACING, defaults.letter_spacing),
|
||||
letter_tilt: item.attribute_cloned_or(ATTR_LETTER_TILT, defaults.letter_tilt),
|
||||
max_width: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_WIDTH, defaults.max_width),
|
||||
max_height: item.attribute_cloned_or::<Option<f64>>(ATTR_MAX_HEIGHT, defaults.max_height),
|
||||
align: item.attribute_cloned_or(ATTR_TEXT_ALIGN, defaults.align),
|
||||
font_size: item.attr_cloned_or::<attr::FontSize>(defaults.font_size),
|
||||
line_height_ratio: item.attr_cloned_or::<attr::LineHeight>(defaults.line_height_ratio),
|
||||
letter_spacing: item.attr_cloned_or::<attr::LetterSpacing>(defaults.letter_spacing),
|
||||
letter_tilt: item.attr_cloned_or::<attr::LetterTilt>(defaults.letter_tilt),
|
||||
max_width: item.attr_cloned_or::<attr::MaxWidth>(defaults.max_width),
|
||||
max_height: item.attr_cloned_or::<attr::MaxHeight>(defaults.max_height),
|
||||
align: item.attr_cloned_or::<crate::attr::TextAlign>(defaults.align),
|
||||
};
|
||||
|
||||
let vectors = to_path(text, &font, typesetting, separate_glyphs);
|
||||
let transform = item.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let layer_path = item.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||
let blend_mode = item.attribute::<BlendMode>(ATTR_BLEND_MODE).copied();
|
||||
let opacity = item.attribute::<f64>(ATTR_OPACITY).copied();
|
||||
let opacity_fill = item.attribute::<f64>(ATTR_OPACITY_FILL).copied();
|
||||
let transform = item.attr_cloned_or_default::<attr::Transform>();
|
||||
let layer_path = item.attr::<attr::editor::LayerPath>().cloned();
|
||||
let blend_mode = item.attr::<attr::BlendMode>().copied();
|
||||
let opacity = item.attr::<attr::Opacity>().copied();
|
||||
let opacity_fill = item.attr::<attr::OpacityFill>().copied();
|
||||
|
||||
let mut result = List::new();
|
||||
for mut produced in vectors.into_iter() {
|
||||
if transform != DAffine2::IDENTITY {
|
||||
let local = produced.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
produced.set_attribute(ATTR_TRANSFORM, transform * local);
|
||||
let local = produced.attr_cloned_or_default::<attr::Transform>();
|
||||
produced.set_attr::<attr::Transform>(transform * local);
|
||||
}
|
||||
if let Some(layer_path) = &layer_path {
|
||||
produced.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
produced.set_attr::<attr::editor::LayerPath>(layer_path.clone());
|
||||
}
|
||||
if let Some(blend_mode) = blend_mode {
|
||||
produced.set_attribute(ATTR_BLEND_MODE, blend_mode);
|
||||
produced.set_attr::<attr::BlendMode>(blend_mode);
|
||||
}
|
||||
if let Some(opacity) = opacity {
|
||||
produced.set_attribute(ATTR_OPACITY, opacity);
|
||||
produced.set_attr::<attr::Opacity>(opacity);
|
||||
}
|
||||
if let Some(opacity_fill) = opacity_fill {
|
||||
produced.set_attribute(ATTR_OPACITY_FILL, opacity_fill);
|
||||
produced.set_attr::<attr::OpacityFill>(opacity_fill);
|
||||
}
|
||||
result.push(produced);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
use core::f64;
|
||||
use core_types::attr;
|
||||
use core_types::color::Color;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::{ApplyTransform, ScaleType, Transform};
|
||||
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl};
|
||||
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, InjectFootprint, ModifyFootprint, OwnedContextImpl};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::raster_types::{CPU, GPU, Raster};
|
||||
use graphic_types::{Artboard, Graphic, Vector};
|
||||
@@ -106,7 +107,7 @@ fn reset_transform<T>(
|
||||
let mut content = content;
|
||||
let (reset_translation, reset_rotation, reset_scale) = (*reset_translation.element(), *reset_rotation.element(), *reset_scale.element());
|
||||
|
||||
let item_transform = content.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let item_transform = content.attr_mut_or_insert_default::<attr::Transform>();
|
||||
|
||||
if reset_translation {
|
||||
item_transform.translation = DVec2::ZERO;
|
||||
@@ -147,14 +148,14 @@ fn replace_transform<T>(
|
||||
let mut content = content;
|
||||
let transform = *transform.element();
|
||||
|
||||
content.set_attribute(ATTR_TRANSFORM, transform.transform());
|
||||
content.set_attr::<attr::Transform>(transform.transform());
|
||||
content
|
||||
}
|
||||
|
||||
/// Obtains the transform of the input content.
|
||||
#[node_macro::node(category("Math: Transform"), path(core_types::vector))]
|
||||
fn extract_transform<T: 'n + Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
|
||||
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
|
||||
Item::new_from_element(content.attr_cloned_or_default::<attr::Transform>())
|
||||
}
|
||||
|
||||
/// Produces the inverse of the input transform, which is the transform that undoes the effect of the original transform.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transform::BakeTransform;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_TRANSFORM, Ctx};
|
||||
use core_types::{Ctx, attr};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
use vector_types::vector::VectorModification;
|
||||
@@ -13,7 +13,7 @@ async fn path_modify(_ctx: impl Ctx, vector: Item<Vector>, modification: Item<Bo
|
||||
modification.into_element().apply(vector.element_mut());
|
||||
|
||||
// Drop the stale click-target override so hit testing uses the geometry the user is now editing
|
||||
vector.remove_attribute::<Vector>(ATTR_EDITOR_CLICK_TARGET);
|
||||
vector.remove_attr::<vector_types::attr::editor::ClickTarget>();
|
||||
|
||||
// Set the path to the encapsulating subgraph (drop our own trailing entry from `node_path`),
|
||||
// matching the `path_of_subgraph` proto so editor tools can route data back to the parent layer.
|
||||
@@ -22,9 +22,9 @@ async fn path_modify(_ctx: impl Ctx, vector: Item<Vector>, modification: Item<Bo
|
||||
let len = node_path.len();
|
||||
node_path.into_iter().take(len.saturating_sub(1)).collect()
|
||||
};
|
||||
let existing = vector.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH).0;
|
||||
let existing = vector.attr_cloned_or_default::<attr::editor::LayerPath>().0;
|
||||
let layer_path = if existing.is_empty() { subgraph_path } else { existing };
|
||||
vector.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path));
|
||||
vector.set_attr::<attr::editor::LayerPath>(NodeIdPath(layer_path));
|
||||
|
||||
vector
|
||||
}
|
||||
@@ -33,7 +33,7 @@ async fn path_modify(_ctx: impl Ctx, vector: Item<Vector>, modification: Item<Bo
|
||||
#[node_macro::node(category("Vector"))]
|
||||
async fn bake_transform<T: BakeTransform + 'n + Send + 'static>(_ctx: impl Ctx, #[implementations(Vector, DAffine2, DVec2)] content: Item<T>) -> Item<T> {
|
||||
let mut content = content;
|
||||
if let Some(transform) = content.remove_attribute::<DAffine2>(ATTR_TRANSFORM) {
|
||||
if let Some(transform) = content.remove_attr::<attr::Transform>() {
|
||||
content.element_mut().bake_transform(&transform);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
use core::cmp::Ordering;
|
||||
use core::f64::consts::{PI, TAU};
|
||||
use core::hash::{Hash, Hasher};
|
||||
use core_types::attr::{self, Attr};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::list::{ATTR_FILL, ATTR_STROKE, Item, ItemAttributeValues, List, ListDyn, NodeIdPath};
|
||||
use core_types::list::{Item, ItemAttributeValues, List, ListDyn};
|
||||
use core_types::registry::types::{Angle, Length, Multiplier, Percentage, PixelLength, Progression, SeedValue};
|
||||
use core_types::transform::{Footprint, Transform};
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{
|
||||
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_TYPE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_SPREAD_METHOD, ATTR_TRANSFORM, CloneVarArgs,
|
||||
Color, Context, Ctx, ExtractAll, OwnedContextImpl,
|
||||
};
|
||||
use core_types::{CloneVarArgs, Color, Context, Ctx, ExtractAll, OwnedContextImpl};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::Vector;
|
||||
use graphic_types::graphic::{bake_paint_transforms, graphic_list_at, has_paint_at, is_paint_present, set_paint_attribute_at};
|
||||
@@ -73,32 +71,32 @@ impl VectorListIterMut for List<Vector> {
|
||||
trait VectorItemMut {
|
||||
fn for_each_vector_mut(&mut self, f: impl FnMut(&mut Vector, DAffine2));
|
||||
|
||||
fn set_vector_paint(&mut self, key: &str, paint: List<Graphic>);
|
||||
fn set_vector_paint<A: Attr<Value = List<Graphic>>>(&mut self, paint: List<Graphic>);
|
||||
}
|
||||
|
||||
impl VectorItemMut for Item<Vector> {
|
||||
fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, DAffine2)) {
|
||||
let transform = self.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM);
|
||||
let transform = self.attr_cloned_or_default::<attr::Transform>();
|
||||
f(self.element_mut(), transform);
|
||||
}
|
||||
|
||||
fn set_vector_paint(&mut self, key: &str, paint: List<Graphic>) {
|
||||
self.set_attribute(key, paint);
|
||||
fn set_vector_paint<A: Attr<Value = List<Graphic>>>(&mut self, paint: List<Graphic>) {
|
||||
self.set_attr::<A>(paint);
|
||||
}
|
||||
}
|
||||
|
||||
impl VectorItemMut for Item<Graphic> {
|
||||
fn for_each_vector_mut(&mut self, mut f: impl FnMut(&mut Vector, DAffine2)) {
|
||||
let Some(vector_list) = self.element_mut().as_vector_mut() else { return };
|
||||
let (elements, transforms) = vector_list.element_and_attribute_slices_mut::<DAffine2>(ATTR_TRANSFORM);
|
||||
let (elements, transforms) = vector_list.element_and_attr_slices_mut::<attr::Transform>();
|
||||
for (vector, transform) in elements.iter_mut().zip(transforms.iter()) {
|
||||
f(vector, *transform);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_vector_paint(&mut self, key: &str, paint: List<Graphic>) {
|
||||
fn set_vector_paint<A: Attr<Value = List<Graphic>>>(&mut self, paint: List<Graphic>) {
|
||||
let Some(vector_list) = self.element_mut().as_vector_mut() else { return };
|
||||
for slot in vector_list.iter_attribute_values_mut_or_default::<List<Graphic>>(key) {
|
||||
for slot in vector_list.iter_attr_values_mut_or_default::<A>() {
|
||||
*slot = paint.clone();
|
||||
}
|
||||
}
|
||||
@@ -161,10 +159,10 @@ where
|
||||
let paint = List::new_from_element(color).into_graphic_list();
|
||||
|
||||
if fill {
|
||||
set_paint_attribute_at(vector_list, index, ATTR_FILL, paint.clone());
|
||||
set_paint_attribute_at::<graphic_types::attr::Fill, _>(vector_list, index, paint.clone());
|
||||
}
|
||||
if stroke && vector_list.element(index).is_some_and(|vector| vector.stroke.is_some()) {
|
||||
set_paint_attribute_at(vector_list, index, ATTR_STROKE, paint.clone());
|
||||
set_paint_attribute_at::<graphic_types::attr::Stroke, _>(vector_list, index, paint.clone());
|
||||
}
|
||||
|
||||
i += 1;
|
||||
@@ -208,19 +206,19 @@ where
|
||||
for graphic in fill.iter_element_values_mut() {
|
||||
let Graphic::Gradient(gradient) = graphic else { continue };
|
||||
|
||||
if gradient.iter_attribute_values::<GradientType>(ATTR_GRADIENT_TYPE).is_none() {
|
||||
for value in gradient.iter_attribute_values_mut_or_default::<GradientType>(ATTR_GRADIENT_TYPE) {
|
||||
if gradient.iter_attr_values::<vector_types::attr::GradientType>().is_none() {
|
||||
for value in gradient.iter_attr_values_mut_or_default::<vector_types::attr::GradientType>() {
|
||||
*value = _gradient_type;
|
||||
}
|
||||
}
|
||||
|
||||
if gradient.iter_attribute_values::<GradientSpreadMethod>(ATTR_SPREAD_METHOD).is_none() {
|
||||
for value in gradient.iter_attribute_values_mut_or_default::<GradientSpreadMethod>(ATTR_SPREAD_METHOD) {
|
||||
if gradient.iter_attr_values::<vector_types::attr::SpreadMethod>().is_none() {
|
||||
for value in gradient.iter_attr_values_mut_or_default::<vector_types::attr::SpreadMethod>() {
|
||||
*value = _spread_method;
|
||||
}
|
||||
}
|
||||
|
||||
if gradient.iter_attribute_values::<DAffine2>(ATTR_TRANSFORM).is_none() {
|
||||
if gradient.iter_attr_values::<attr::Transform>().is_none() {
|
||||
// Without an explicit placement, derive one covering the paint target's bounding box (the CSS `auto` behavior)
|
||||
let transform = if _has_transform {
|
||||
_transform
|
||||
@@ -246,13 +244,13 @@ where
|
||||
initial_gradient_transform_for_bounding_box([min, max])
|
||||
};
|
||||
|
||||
for value in gradient.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for value in gradient.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*value = transform;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
content.set_vector_paint(ATTR_FILL, fill);
|
||||
content.set_vector_paint::<graphic_types::attr::Fill>(fill);
|
||||
content
|
||||
}
|
||||
|
||||
@@ -326,7 +324,7 @@ where
|
||||
});
|
||||
|
||||
let paint = paint.into_graphic_list();
|
||||
content.set_vector_paint(ATTR_STROKE, paint);
|
||||
content.set_vector_paint::<graphic_types::attr::Stroke>(paint);
|
||||
content
|
||||
}
|
||||
|
||||
@@ -388,7 +386,7 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
let do_scale = random_scale_difference.abs() > 1e-6;
|
||||
let do_rotation = random_rotation.abs() > 1e-6;
|
||||
|
||||
let points_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let points_transform: DAffine2 = row.attr_cloned_or_default::<attr::Transform>();
|
||||
for &point in row.element().point_domain.positions() {
|
||||
let translation = points_transform.transform_point2(point);
|
||||
|
||||
@@ -417,8 +415,8 @@ async fn copy_to_points<I: 'n + Send + Clone>(
|
||||
|
||||
for row_index in 0..content.len() {
|
||||
let Some(mut row) = content.clone_item(row_index) else { continue };
|
||||
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
row.set_attribute(ATTR_TRANSFORM, transform * row_transform);
|
||||
let row_transform: DAffine2 = row.attr_cloned_or_default::<attr::Transform>();
|
||||
row.set_attr::<attr::Transform>(transform * row_transform);
|
||||
|
||||
result_list.push(row);
|
||||
}
|
||||
@@ -446,7 +444,7 @@ async fn round_corners(
|
||||
min_angle_threshold: Item<Angle>,
|
||||
) -> Item<Vector> {
|
||||
let (radius, roundness, edge_length_limit, min_angle_threshold) = (*radius.element(), *roundness.element(), *edge_length_limit.element(), *min_angle_threshold.element());
|
||||
let source_transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let source_transform: DAffine2 = source.attr_cloned_or_default::<attr::Transform>();
|
||||
let source_transform_inverse = source_transform.inverse();
|
||||
let (source, attributes) = source.into_parts();
|
||||
|
||||
@@ -550,7 +548,7 @@ pub fn merge_by_distance(
|
||||
|
||||
match algorithm {
|
||||
MergeByDistanceAlgorithm::Spatial => {
|
||||
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
content.element_mut().merge_by_distance_spatial(transform, distance);
|
||||
}
|
||||
MergeByDistanceAlgorithm::Topological => content.element_mut().merge_by_distance_topological(distance),
|
||||
@@ -767,12 +765,12 @@ async fn extrude(_: impl Ctx, source: Item<Vector>, direction: Item<DVec2>, join
|
||||
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn box_warp(_: impl Ctx, content: Item<Vector>, #[expose] rectangle: Item<Vector>) -> Item<Vector> {
|
||||
let target_transform: DAffine2 = rectangle.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let target_transform: DAffine2 = rectangle.attr_cloned_or_default::<attr::Transform>();
|
||||
let target = rectangle.into_element();
|
||||
|
||||
let mut row = content;
|
||||
{
|
||||
let transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = row.attr_cloned_or_default::<attr::Transform>();
|
||||
let vector = std::mem::take(row.element_mut());
|
||||
|
||||
// Get the bounding box of the source vector geometry
|
||||
@@ -832,7 +830,7 @@ async fn box_warp(_: impl Ctx, content: Item<Vector>, #[expose] rectangle: Item<
|
||||
|
||||
// Reset the transform since we've applied it directly to the points
|
||||
*row.element_mut() = result;
|
||||
row.set_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY);
|
||||
row.set_attr::<attr::Transform>(DAffine2::IDENTITY);
|
||||
}
|
||||
row
|
||||
}
|
||||
@@ -942,8 +940,8 @@ where
|
||||
RowsOrColumns::Rows => DVec2::new(strip.along_position, strip.cross_position),
|
||||
RowsOrColumns::Columns => DVec2::new(strip.cross_position, strip.along_position),
|
||||
};
|
||||
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
row.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(target_position - top_left) * row_transform);
|
||||
let row_transform: DAffine2 = row.attr_cloned_or_default::<attr::Transform>();
|
||||
row.set_attr::<attr::Transform>(DAffine2::from_translation(target_position - top_left) * row_transform);
|
||||
|
||||
strip.along_position += along + separation;
|
||||
} else {
|
||||
@@ -954,8 +952,8 @@ where
|
||||
RowsOrColumns::Rows => DVec2::new(0., new_cross),
|
||||
RowsOrColumns::Columns => DVec2::new(new_cross, 0.),
|
||||
};
|
||||
let row_transform: DAffine2 = row.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
row.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(target_position - top_left) * row_transform);
|
||||
let row_transform: DAffine2 = row.attr_cloned_or_default::<attr::Transform>();
|
||||
row.set_attr::<attr::Transform>(DAffine2::from_translation(target_position - top_left) * row_transform);
|
||||
|
||||
strips.push(Strip {
|
||||
along_position: along + separation,
|
||||
@@ -986,7 +984,7 @@ async fn auto_tangents(
|
||||
) -> Item<Vector> {
|
||||
let (spread, preserve_existing) = (*spread.element(), *preserve_existing.element());
|
||||
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = source.attr_cloned_or_default::<attr::Transform>();
|
||||
let (source, attributes) = source.into_parts();
|
||||
|
||||
let mut result = Vector {
|
||||
@@ -1146,7 +1144,7 @@ async fn bounding_box(_: impl Ctx, content: Item<Vector>) -> Item<Vector> {
|
||||
async fn dimensions(_: impl Ctx, content: Item<Vector>) -> Item<DVec2> {
|
||||
let dimensions = content
|
||||
.element()
|
||||
.bounding_box_with_transform(content.attribute_cloned_or_default(ATTR_TRANSFORM))
|
||||
.bounding_box_with_transform(content.attr_cloned_or_default::<attr::Transform>())
|
||||
.map(|[top_left, bottom_right]| bottom_right - top_left)
|
||||
.unwrap_or_default();
|
||||
|
||||
@@ -1358,7 +1356,7 @@ async fn offset_path(_: impl Ctx, content: Item<Vector>, distance: Item<f64>, jo
|
||||
let mut content = content;
|
||||
let (distance, join, miter_limit) = (*distance.element(), *join.element(), *miter_limit.element());
|
||||
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let transform = Affine::new(transform_attribute.to_cols_array());
|
||||
let vector = std::mem::take(content.element_mut());
|
||||
|
||||
@@ -1406,7 +1404,7 @@ where
|
||||
let flattened: List<Vector> = graphic_list.clone().into_flattened_list();
|
||||
|
||||
// A fill exists when the canonical attribute carries paint
|
||||
let has_fills: Vec<bool> = (0..flattened.len()).map(|index| has_paint_at(&flattened, index, ATTR_FILL)).collect();
|
||||
let has_fills: Vec<bool> = (0..flattened.len()).map(|index| has_paint_at::<graphic_types::attr::Fill>(&flattened, index)).collect();
|
||||
|
||||
let mut output: List<Vector> = flattened
|
||||
.into_iter()
|
||||
@@ -1466,14 +1464,14 @@ where
|
||||
vector.stroke = None;
|
||||
let mut fill_attributes = attributes.clone();
|
||||
// No stroke remains on the fill row
|
||||
fill_attributes.remove::<List<Graphic>>(ATTR_STROKE);
|
||||
fill_attributes.remove_attr::<graphic_types::attr::Stroke>();
|
||||
Item::from_parts(vector, fill_attributes)
|
||||
});
|
||||
|
||||
let mut stroke_attributes = attributes;
|
||||
// Drop the original fill and use the stroke paint to fill the outlined stroke
|
||||
stroke_attributes.remove::<List<Graphic>>(ATTR_FILL);
|
||||
stroke_attributes.rename(ATTR_STROKE, ATTR_FILL);
|
||||
stroke_attributes.remove_attr::<graphic_types::attr::Fill>();
|
||||
stroke_attributes.rename(graphic_types::attr::Stroke::name(), graphic_types::attr::Fill::name());
|
||||
|
||||
let stroke_row = Item::from_parts(solidified_stroke, stroke_attributes);
|
||||
|
||||
@@ -1492,15 +1490,15 @@ where
|
||||
// already holds the original transforms; pre-compensate by row 0's inverse so the renderer's
|
||||
// `upstream_footprint *= row_0_transform` recursion cancels out and leaves the originals intact.
|
||||
let mut graphic_list = graphic_list;
|
||||
let row_0_transform: DAffine2 = output.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
let row_0_transform: DAffine2 = output.attr_cloned_or_default::<attr::Transform>(0);
|
||||
if row_0_transform.matrix2.determinant().abs() > f64::EPSILON {
|
||||
let inverse = row_0_transform.inverse();
|
||||
for transform in graphic_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in graphic_list.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*transform = inverse * *transform;
|
||||
}
|
||||
}
|
||||
|
||||
output.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, graphic_list);
|
||||
output.set_attr::<graphic_types::attr::editor::MergedLayers>(0, graphic_list);
|
||||
}
|
||||
|
||||
output
|
||||
@@ -1574,14 +1572,14 @@ pub async fn combine_paths<T: IntoGraphicList>(_: impl Ctx, #[implementations(Li
|
||||
// Concatenate every vector element's subpaths into the single output compound path
|
||||
for index in 0..flattened.len() {
|
||||
let Some(element) = flattened.element(index) else { continue };
|
||||
let layer_path: List<NodeId> = flattened.attribute_cloned_or_default::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, index).0;
|
||||
let layer_path: List<NodeId> = flattened.attr_cloned_or_default::<attr::editor::LayerPath>(index).0;
|
||||
let node_id = layer_path.iter_element_values().next_back().map(|node_id| node_id.0).unwrap_or_default();
|
||||
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(index, node_id).hash(&mut hasher);
|
||||
let collision_hash_seed = hasher.finish();
|
||||
|
||||
let source_transform = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let source_transform = flattened.attr_cloned_or_default::<attr::Transform>(index);
|
||||
output.concat(element, source_transform, collision_hash_seed);
|
||||
|
||||
// TODO: Make this instead use the first encountered stroke
|
||||
@@ -1595,10 +1593,10 @@ pub async fn combine_paths<T: IntoGraphicList>(_: impl Ctx, #[implementations(Li
|
||||
let source_attributes = flattened.clone_item_attributes(primary);
|
||||
let mut attributes = ItemAttributeValues::new();
|
||||
|
||||
attributes.insert_cloned_from(&source_attributes, ATTR_FILL);
|
||||
attributes.insert_cloned_from(&source_attributes, ATTR_STROKE);
|
||||
attributes.insert_cloned_from(&source_attributes, graphic_types::attr::Fill::name());
|
||||
attributes.insert_cloned_from(&source_attributes, graphic_types::attr::Stroke::name());
|
||||
// Adopt the last input item's layer (if any) so the editor can also bucket clicks under a contributing child layer
|
||||
attributes.insert_cloned_from(&source_attributes, ATTR_EDITOR_LAYER_PATH);
|
||||
attributes.insert_cloned_from(&source_attributes, attr::editor::LayerPath::name());
|
||||
bake_paint_transforms(&mut attributes, source_transform);
|
||||
|
||||
let output = std::mem::take(output_list.element_mut(0).unwrap());
|
||||
@@ -1608,7 +1606,7 @@ pub async fn combine_paths<T: IntoGraphicList>(_: impl Ctx, #[implementations(Li
|
||||
// Preserve a reference to the original upstream `List<Graphic>` so the renderer can recurse into it
|
||||
// when collecting metadata, exposing the original child layers' click targets to editor tools.
|
||||
// This is the same mechanism Boolean Operation uses to keep its inputs editable after the merge.
|
||||
output_list.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, graphic_list);
|
||||
output_list.set_attr::<graphic_types::attr::editor::MergedLayers>(0, graphic_list);
|
||||
|
||||
output_list.into_iter().next().unwrap_or_default()
|
||||
}
|
||||
@@ -1654,12 +1652,12 @@ async fn sample_polyline(
|
||||
stroke: std::mem::take(&mut content.element_mut().stroke),
|
||||
};
|
||||
// Transfer the stroke transform from the input vector content to the result.
|
||||
result.set_stroke_transform(content.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
result.set_stroke_transform(content.attr_cloned_or_default::<attr::Transform>());
|
||||
|
||||
for local_bezpath in content.element().stroke_bezpath_iter() {
|
||||
// Apply the transform to compute sample locations in world space (for correct distance-based spacing)
|
||||
let mut world_bezpath = local_bezpath.clone();
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
world_bezpath.apply_affine(Affine::new(transform_attribute.to_cols_array()));
|
||||
|
||||
// Per-segment perimeter lengths (transform-baked) for distance-based spacing
|
||||
@@ -1718,7 +1716,7 @@ async fn simplify(
|
||||
|
||||
let options = SimplifyOptions::default();
|
||||
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let transform = Affine::new(transform_attribute.to_cols_array());
|
||||
let inverse_transform = transform.inverse();
|
||||
|
||||
@@ -1812,7 +1810,7 @@ async fn decimate(
|
||||
points.iter().enumerate().filter(|(i, _)| keep[*i]).map(|(_, p)| *p).collect()
|
||||
}
|
||||
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let transform = Affine::new(transform_attribute.to_cols_array());
|
||||
let inverse_transform = transform.inverse();
|
||||
|
||||
@@ -1992,7 +1990,7 @@ async fn position_on_path(
|
||||
let (progression, reverse, parameterized_distance) = (progression.into_element(), reverse.into_element(), parameterized_distance.into_element());
|
||||
let euclidian = !parameterized_distance;
|
||||
|
||||
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let mut bezpaths: Vec<_> = content.element().stroke_bezpath_iter().map(|bezpath| (bezpath, transform)).collect();
|
||||
let bezpath_count = bezpaths.len() as f64;
|
||||
let progression = progression.clamp(0., bezpath_count);
|
||||
@@ -2031,7 +2029,7 @@ async fn tangent_on_path(
|
||||
let (progression, reverse, parameterized_distance, radians) = (progression.into_element(), reverse.into_element(), parameterized_distance.into_element(), radians.into_element());
|
||||
let euclidian = !parameterized_distance;
|
||||
|
||||
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let mut bezpaths: Vec<_> = content.element().stroke_bezpath_iter().map(|bezpath| (bezpath, transform)).collect();
|
||||
let bezpath_count = bezpaths.len() as f64;
|
||||
let progression = progression.clamp(0., bezpath_count);
|
||||
@@ -2222,7 +2220,7 @@ async fn jitter_points(
|
||||
let (max_distance, seed, along_normals) = (*max_distance.element(), *seed.element(), *along_normals.element());
|
||||
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(seed.into());
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2);
|
||||
|
||||
let deltas: Vec<_> = (0..content.element().point_domain.positions().len())
|
||||
@@ -2247,7 +2245,7 @@ async fn jitter_points(
|
||||
})
|
||||
.collect();
|
||||
|
||||
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
apply_point_deltas(content.element_mut(), &deltas, transform);
|
||||
|
||||
content
|
||||
@@ -2267,7 +2265,7 @@ async fn offset_points(
|
||||
) -> Item<Vector> {
|
||||
let mut content = content;
|
||||
let distance = *distance.element();
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
let inverse_linear = inverse_linear_or_repair(transform_attribute.matrix2);
|
||||
|
||||
let deltas: Vec<_> = (0..content.element().point_domain.positions().len())
|
||||
@@ -2285,7 +2283,7 @@ async fn offset_points(
|
||||
})
|
||||
.collect();
|
||||
|
||||
let transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>();
|
||||
apply_point_deltas(content.element_mut(), &deltas, transform);
|
||||
|
||||
content
|
||||
@@ -2409,8 +2407,8 @@ async fn morph<I: IntoGraphicList>(
|
||||
}
|
||||
|
||||
fn lerp_gradient_transform(gradient_list_a: &List<Gradient>, gradient_list_b: &List<Gradient>, time: f64) -> DAffine2 {
|
||||
let transform_a = gradient_list_a.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
|
||||
let transform_b = gradient_list_b.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0);
|
||||
let transform_a = gradient_list_a.attr_cloned_or_default::<attr::Transform>(0);
|
||||
let transform_b = gradient_list_b.attr_cloned_or_default::<attr::Transform>(0);
|
||||
|
||||
let start_a = transform_a.translation;
|
||||
let end_a = transform_a.translation + transform_a.matrix2.x_axis;
|
||||
@@ -2470,7 +2468,7 @@ async fn morph<I: IntoGraphicList>(
|
||||
let metadata_source = if time < 0.5 { gradient_list_a } else { gradient_list_b };
|
||||
|
||||
let mut gradient_list = metadata_source.clone();
|
||||
gradient_list.set_attribute(ATTR_TRANSFORM, 0, lerp_gradient_transform(gradient_list_a, gradient_list_b, time));
|
||||
gradient_list.set_attr::<attr::Transform>(0, lerp_gradient_transform(gradient_list_a, gradient_list_b, time));
|
||||
|
||||
gradient_with_stops(gradient_list, stops)
|
||||
}),
|
||||
@@ -2499,7 +2497,7 @@ async fn morph<I: IntoGraphicList>(
|
||||
let default_polyline = || {
|
||||
let mut default_path = BezPath::new();
|
||||
for index in 0..content.len() {
|
||||
let transform_attribute: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let transform_attribute: DAffine2 = content.attr_cloned_or_default::<attr::Transform>(index);
|
||||
let origin = transform_attribute.translation;
|
||||
let point = kurbo::Point::new(origin.x, origin.y);
|
||||
if index == 0 {
|
||||
@@ -2513,7 +2511,7 @@ async fn morph<I: IntoGraphicList>(
|
||||
|
||||
let control_bezpaths: Vec<BezPath> = {
|
||||
// User-provided path: collect all subpaths with the path's transform applied
|
||||
let path_transform: DAffine2 = path.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let path_transform: DAffine2 = path.attr_cloned_or_default::<attr::Transform>();
|
||||
let paths: Vec<BezPath> = path
|
||||
.element()
|
||||
.stroke_bezpath_iter()
|
||||
@@ -2585,8 +2583,8 @@ async fn morph<I: IntoGraphicList>(
|
||||
if content.element(source_index).is_none() || content.element(target_index).is_none() {
|
||||
return 0.;
|
||||
}
|
||||
let source_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, source_index);
|
||||
let target_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, target_index);
|
||||
let source_transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>(source_index);
|
||||
let target_transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>(target_index);
|
||||
let (s_angle, s_scale, s_skew) = source_transform.decompose_rotation_scale_skew();
|
||||
let (t_angle, t_scale, t_skew) = target_transform.decompose_rotation_scale_skew();
|
||||
|
||||
@@ -2658,14 +2656,14 @@ async fn morph<I: IntoGraphicList>(
|
||||
};
|
||||
|
||||
// Lerp blending attributes: opacity/fill interpolate, blend_mode/clip step at the midpoint
|
||||
let source_blend_mode: BlendMode = content.attribute_cloned_or_default(ATTR_BLEND_MODE, source_index);
|
||||
let target_blend_mode: BlendMode = content.attribute_cloned_or_default(ATTR_BLEND_MODE, target_index);
|
||||
let source_opacity: f64 = content.attribute_cloned_or(ATTR_OPACITY, source_index, 1.);
|
||||
let target_opacity: f64 = content.attribute_cloned_or(ATTR_OPACITY, target_index, 1.);
|
||||
let source_fill: f64 = content.attribute_cloned_or(ATTR_OPACITY_FILL, source_index, 1.);
|
||||
let target_fill: f64 = content.attribute_cloned_or(ATTR_OPACITY_FILL, target_index, 1.);
|
||||
let source_clip: bool = content.attribute_cloned_or_default(ATTR_CLIPPING_MASK, source_index);
|
||||
let target_clip: bool = content.attribute_cloned_or_default(ATTR_CLIPPING_MASK, target_index);
|
||||
let source_blend_mode: BlendMode = content.attr_cloned_or_default::<attr::BlendMode>(source_index);
|
||||
let target_blend_mode: BlendMode = content.attr_cloned_or_default::<attr::BlendMode>(target_index);
|
||||
let source_opacity: f64 = content.attr_cloned_or_default::<attr::Opacity>(source_index);
|
||||
let target_opacity: f64 = content.attr_cloned_or_default::<attr::Opacity>(target_index);
|
||||
let source_fill: f64 = content.attr_cloned_or_default::<attr::OpacityFill>(source_index);
|
||||
let target_fill: f64 = content.attr_cloned_or_default::<attr::OpacityFill>(target_index);
|
||||
let source_clip: bool = content.attr_cloned_or_default::<attr::ClippingMask>(source_index);
|
||||
let target_clip: bool = content.attr_cloned_or_default::<attr::ClippingMask>(target_index);
|
||||
|
||||
let lerped_blend_mode = if time < 0.5 { source_blend_mode } else { target_blend_mode };
|
||||
let lerped_opacity = source_opacity + (target_opacity - source_opacity) * time;
|
||||
@@ -2687,8 +2685,8 @@ async fn morph<I: IntoGraphicList>(
|
||||
// This decomposition must match the one used in Stroke::lerp so the renderer's stroke_transform.inverse()
|
||||
// correctly cancels the element transform, keeping the stroke uniform when Stroke is after Transform.
|
||||
let lerped_transform = {
|
||||
let source_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, source_index);
|
||||
let target_transform: DAffine2 = content.attribute_cloned_or_default(ATTR_TRANSFORM, target_index);
|
||||
let source_transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>(source_index);
|
||||
let target_transform: DAffine2 = content.attr_cloned_or_default::<attr::Transform>(target_index);
|
||||
let (s_angle, s_scale, s_skew) = source_transform.decompose_rotation_scale_skew();
|
||||
let (t_angle, t_scale, t_skew) = target_transform.decompose_rotation_scale_skew();
|
||||
|
||||
@@ -2717,7 +2715,7 @@ async fn morph<I: IntoGraphicList>(
|
||||
// in which case we skip pre-compensation to avoid propagating NaN through merged_layers transforms.
|
||||
if lerped_transform.matrix2.determinant().abs() > f64::EPSILON {
|
||||
let lerped_inverse = lerped_transform.inverse();
|
||||
for transform in graphic_list_content.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
for transform in graphic_list_content.iter_attr_values_mut_or_default::<attr::Transform>() {
|
||||
*transform = lerped_inverse * *transform;
|
||||
}
|
||||
}
|
||||
@@ -2729,8 +2727,8 @@ async fn morph<I: IntoGraphicList>(
|
||||
let endpoint_element = content.element(endpoint_index).unwrap();
|
||||
|
||||
let mut attributes = content.clone_item_attributes(endpoint_index);
|
||||
attributes.insert(ATTR_TRANSFORM, lerped_transform);
|
||||
attributes.insert(ATTR_EDITOR_MERGED_LAYERS, graphic_list_content);
|
||||
attributes.set_attr::<attr::Transform>(lerped_transform);
|
||||
attributes.set_attr::<graphic_types::attr::editor::MergedLayers>(graphic_list_content);
|
||||
|
||||
return Item::from_parts(endpoint_element.clone(), attributes);
|
||||
}
|
||||
@@ -2756,13 +2754,13 @@ async fn morph<I: IntoGraphicList>(
|
||||
let mut vector = Vector { stroke, ..Default::default() };
|
||||
|
||||
let fill_paint = {
|
||||
let source = graphic_list_at(&content, source_index, ATTR_FILL);
|
||||
let target = graphic_list_at(&content, target_index, ATTR_FILL);
|
||||
let source = graphic_list_at::<graphic_types::attr::Fill>(&content, source_index);
|
||||
let target = graphic_list_at::<graphic_types::attr::Fill>(&content, target_index);
|
||||
lerp_graphic(source.as_deref(), target.as_deref(), time)
|
||||
};
|
||||
let stroke_paint = {
|
||||
let source = graphic_list_at(&content, source_index, ATTR_STROKE);
|
||||
let target = graphic_list_at(&content, target_index, ATTR_STROKE);
|
||||
let source = graphic_list_at::<graphic_types::attr::Stroke>(&content, source_index);
|
||||
let target = graphic_list_at::<graphic_types::attr::Stroke>(&content, target_index);
|
||||
lerp_graphic(source.as_deref(), target.as_deref(), time)
|
||||
};
|
||||
|
||||
@@ -2913,31 +2911,31 @@ async fn morph<I: IntoGraphicList>(
|
||||
// the click-target identity (so the editor can route clicks back to one of the contributing layers)
|
||||
let primary_index = if time < 0.5 { source_index } else { target_index };
|
||||
let mut item = Item::new_from_element(vector);
|
||||
item.set_attribute(ATTR_TRANSFORM, lerped_transform);
|
||||
item.set_attr::<attr::Transform>(lerped_transform);
|
||||
|
||||
// Propagate each blending/layer column only when the input carries it, so attribute presence stays determined by the graph rather than by runtime values
|
||||
if content.attribute::<BlendMode>(ATTR_BLEND_MODE, source_index).is_some() {
|
||||
item.set_attribute(ATTR_BLEND_MODE, lerped_blend_mode);
|
||||
if content.attr::<attr::BlendMode>(source_index).is_some() {
|
||||
item.set_attr::<attr::BlendMode>(lerped_blend_mode);
|
||||
}
|
||||
if content.attribute::<f64>(ATTR_OPACITY, source_index).is_some() {
|
||||
item.set_attribute(ATTR_OPACITY, lerped_opacity);
|
||||
if content.attr::<attr::Opacity>(source_index).is_some() {
|
||||
item.set_attr::<attr::Opacity>(lerped_opacity);
|
||||
}
|
||||
if content.attribute::<f64>(ATTR_OPACITY_FILL, source_index).is_some() {
|
||||
item.set_attribute(ATTR_OPACITY_FILL, lerped_fill);
|
||||
if content.attr::<attr::OpacityFill>(source_index).is_some() {
|
||||
item.set_attr::<attr::OpacityFill>(lerped_fill);
|
||||
}
|
||||
if content.attribute::<bool>(ATTR_CLIPPING_MASK, source_index).is_some() {
|
||||
item.set_attribute(ATTR_CLIPPING_MASK, lerped_clip);
|
||||
if content.attr::<attr::ClippingMask>(source_index).is_some() {
|
||||
item.set_attr::<attr::ClippingMask>(lerped_clip);
|
||||
}
|
||||
if let Some(layer_path) = content.attribute::<NodeIdPath>(ATTR_EDITOR_LAYER_PATH, primary_index) {
|
||||
item.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.clone());
|
||||
if let Some(layer_path) = content.attr::<attr::editor::LayerPath>(primary_index) {
|
||||
item.set_attr::<attr::editor::LayerPath>(layer_path.clone());
|
||||
}
|
||||
item.set_attribute(ATTR_EDITOR_MERGED_LAYERS, graphic_list_content);
|
||||
item.set_attr::<graphic_types::attr::editor::MergedLayers>(graphic_list_content);
|
||||
|
||||
if let Some(fill) = fill_paint {
|
||||
item.set_attribute(ATTR_FILL, fill);
|
||||
item.set_attr::<graphic_types::attr::Fill>(fill);
|
||||
}
|
||||
if let Some(stroke) = stroke_paint {
|
||||
item.set_attribute(ATTR_STROKE, stroke);
|
||||
item.set_attr::<graphic_types::attr::Stroke>(stroke);
|
||||
}
|
||||
|
||||
item
|
||||
@@ -3217,7 +3215,7 @@ fn bevel_algorithm(mut vector: Vector, transform: DAffine2, distance: f64) -> Ve
|
||||
fn bevel(_: impl Ctx, source: Item<Vector>, #[default(10.)] distance: Item<Length>) -> Item<Vector> {
|
||||
let distance = *distance.element();
|
||||
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = source.attr_cloned_or_default::<attr::Transform>();
|
||||
let (element, attributes) = source.into_parts();
|
||||
|
||||
Item::from_parts(bevel_algorithm(element, transform, distance), attributes)
|
||||
@@ -3233,7 +3231,7 @@ fn close_path(_: impl Ctx, source: Item<Vector>) -> Item<Vector> {
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
fn point_inside(_: impl Ctx, source: Item<Vector>, point: Item<DVec2>) -> Item<bool> {
|
||||
let point = point.into_element();
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = source.attr_cloned_or_default::<attr::Transform>();
|
||||
let inside = source.element().check_point_inside_shape(transform, point);
|
||||
|
||||
Item::new_from_element(inside)
|
||||
@@ -3292,7 +3290,7 @@ async fn index_points(
|
||||
|
||||
#[node_macro::node(category("Vector: Measure"), path(core_types::vector))]
|
||||
async fn path_length(_: impl Ctx, source: Item<Vector>) -> Item<f64> {
|
||||
let transform: DAffine2 = source.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = source.attr_cloned_or_default::<attr::Transform>();
|
||||
let length = source
|
||||
.element()
|
||||
.stroke_bezpath_iter()
|
||||
@@ -3310,7 +3308,7 @@ async fn area(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<Cont
|
||||
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
|
||||
let vector = content.eval(new_ctx).await;
|
||||
|
||||
let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = vector.attr_cloned_or_default::<attr::Transform>();
|
||||
let area_scale = transform.matrix2.determinant().abs();
|
||||
let area = vector.element().stroke_bezpath_iter().map(|subpath| subpath.area() * area_scale).sum::<f64>();
|
||||
|
||||
@@ -3323,7 +3321,7 @@ async fn centroid(ctx: impl Ctx + CloneVarArgs + ExtractAll, content: impl Node<
|
||||
let new_ctx = OwnedContextImpl::from(ctx).with_footprint(Footprint::default()).into_context();
|
||||
let vector = content.eval(new_ctx).await;
|
||||
|
||||
let transform: DAffine2 = vector.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let transform: DAffine2 = vector.attr_cloned_or_default::<attr::Transform>();
|
||||
let position = element_centroid(vector.element(), transform, centroid_type);
|
||||
|
||||
Item::new_from_element(position)
|
||||
@@ -3390,7 +3388,7 @@ mod test {
|
||||
fn create_vector_item(bezpath: BezPath, transform: DAffine2) -> Item<Vector> {
|
||||
let mut row = Vector::default();
|
||||
row.append_bezpath(bezpath);
|
||||
Item::new_from_element(row).with_attribute(ATTR_TRANSFORM, transform)
|
||||
Item::new_from_element(row).with_attr::<attr::Transform>(transform)
|
||||
}
|
||||
|
||||
fn item<T>(value: T) -> Item<T> {
|
||||
@@ -3559,7 +3557,7 @@ mod test {
|
||||
// Test a rectangular path with non-zero rotation
|
||||
let square = Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
|
||||
let mut square = List::new_from_element(square);
|
||||
square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
|
||||
square.with_attr_mut_or_default::<attr::Transform, _, _>(0, |t| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
|
||||
let bounding_box = BoundingBoxNodeMapped { content: FutureWrapperNode(square) }.eval(Footprint::default()).await;
|
||||
let bounding_box = bounding_box.element(0).unwrap();
|
||||
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
|
||||
@@ -3692,7 +3690,7 @@ mod test {
|
||||
async fn morph() {
|
||||
let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
|
||||
let mut second_rectangle = rectangles.clone_item(0).unwrap();
|
||||
*second_rectangle.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into());
|
||||
*second_rectangle.attr_mut_or_insert_default::<attr::Transform>() *= DAffine2::from_translation((-100., -100.).into());
|
||||
rectangles.push(second_rectangle);
|
||||
|
||||
let morphed = super::morph(
|
||||
@@ -3712,7 +3710,7 @@ mod test {
|
||||
vec![DVec2::new(0., 0.), DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]
|
||||
);
|
||||
// The interpolated transform carries the midpoint translation (approximate due to arc-length parameterization)
|
||||
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
|
||||
assert!((morphed.attr_cloned_or_default::<attr::Transform>(0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -3724,11 +3722,11 @@ mod test {
|
||||
};
|
||||
|
||||
let item_a = Item::new_from_element(rect())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::IDENTITY)
|
||||
.with_attribute(ATTR_FILL, List::new_from_element(Color::RED).into_graphic_list());
|
||||
.with_attr::<attr::Transform>(DAffine2::IDENTITY)
|
||||
.with_attr::<graphic_types::attr::Fill>(List::new_from_element(Color::RED).into_graphic_list());
|
||||
let item_b = Item::new_from_element(rect())
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation((-100., -100.).into()))
|
||||
.with_attribute(ATTR_FILL, List::new_from_element(Color::BLUE).into_graphic_list());
|
||||
.with_attr::<attr::Transform>(DAffine2::from_translation((-100., -100.).into()))
|
||||
.with_attr::<graphic_types::attr::Fill>(List::new_from_element(Color::BLUE).into_graphic_list());
|
||||
|
||||
let mut content = List::new_from_item(item_a);
|
||||
content.push(item_b);
|
||||
@@ -3744,7 +3742,7 @@ mod test {
|
||||
.await;
|
||||
let morphed = List::new_from_item(morphed);
|
||||
|
||||
let fill = graphic_list_at(&morphed, 0, ATTR_FILL).expect("Morph should keep the fill paint at the midpoint");
|
||||
let fill = graphic_list_at::<graphic_types::attr::Fill>(&morphed, 0).expect("Morph should keep the fill paint at the midpoint");
|
||||
|
||||
// Interpolated color between red and blue should have >0 value on both R and B
|
||||
let Some(Graphic::Color(colors)) = fill.element(0) else {
|
||||
@@ -3825,7 +3823,7 @@ mod test {
|
||||
source.push(curve.as_path_el());
|
||||
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.));
|
||||
let vector_item = Item::new_from_element(Vector::from_bezpath(source)).with_attribute(ATTR_TRANSFORM, transform);
|
||||
let vector_item = Item::new_from_element(Vector::from_bezpath(source)).with_attr::<attr::Transform>(transform);
|
||||
|
||||
let beveled = super::bevel((), vector_item, Item::new_from_element(2_f64.sqrt() * 100.));
|
||||
let beveled = beveled.element();
|
||||
|
||||
@@ -23,6 +23,7 @@ serde-discriminant = []
|
||||
proc-macro2 = { workspace = true }
|
||||
syn = { workspace = true }
|
||||
quote = { workspace = true }
|
||||
convert_case = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
use convert_case::{Case, Casing};
|
||||
use proc_macro2::TokenStream;
|
||||
use quote::{quote, quote_spanned};
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{Error, FnArg, Ident, Item, ItemFn, ItemMod, ItemUse, Pat, Visibility};
|
||||
|
||||
pub fn editor_commands_impl(attr: TokenStream, module: ItemMod) -> syn::Result<TokenStream> {
|
||||
if !attr.is_empty() {
|
||||
return Err(Error::new(attr.span(), "#[editor_commands] takes no arguments"));
|
||||
}
|
||||
for attr in &module.attrs {
|
||||
if !attr.path().is_ident("doc") {
|
||||
return Err(Error::new(attr.span(), "the #[editor_commands] module may not have other attributes"));
|
||||
}
|
||||
}
|
||||
let Some((_, items)) = module.content else {
|
||||
return Err(Error::new(module.mod_token.span, "#[editor_commands] requires a module with an inline body"));
|
||||
};
|
||||
|
||||
let mut imports: Vec<ItemUse> = Vec::new();
|
||||
let mut functions: Vec<ItemFn> = Vec::new();
|
||||
for item in items {
|
||||
match item {
|
||||
Item::Use(import) => imports.push(import),
|
||||
Item::Fn(function) => functions.push(function),
|
||||
other => return Err(Error::new(other.span(), "only `use` imports and command functions may appear in an #[editor_commands] module")),
|
||||
}
|
||||
}
|
||||
|
||||
let mut variants = TokenStream::new();
|
||||
let mut stubs = TokenStream::new();
|
||||
let mut arms = TokenStream::new();
|
||||
|
||||
for function in &functions {
|
||||
for attr in &function.attrs {
|
||||
if !attr.path().is_ident("doc") {
|
||||
return Err(Error::new(
|
||||
attr.span(),
|
||||
"command functions may not have attributes; anything that doesn't fit the `fn name(args…) -> Message` contract belongs in a plain impl block",
|
||||
));
|
||||
}
|
||||
}
|
||||
if !matches!(function.vis, Visibility::Inherited) {
|
||||
return Err(Error::new(
|
||||
function.span(),
|
||||
"command functions have no visibility modifier; the macro generates the public JS-facing stub",
|
||||
));
|
||||
}
|
||||
|
||||
let signature = &function.sig;
|
||||
if let Some(receiver) = signature.receiver() {
|
||||
return Err(Error::new(receiver.span(), "command functions take no `self`; they are pure `args… -> Message` translations"));
|
||||
}
|
||||
if !signature.generics.params.is_empty() || signature.asyncness.is_some() || signature.unsafety.is_some() {
|
||||
return Err(Error::new(signature.span(), "command functions must be plain non-generic, non-async, safe functions"));
|
||||
}
|
||||
|
||||
let docs = &function.attrs;
|
||||
let fn_name = &signature.ident;
|
||||
let variant = Ident::new(&fn_name.to_string().to_case(Case::Pascal), fn_name.span());
|
||||
let js_name = Ident::new(&fn_name.to_string().to_case(Case::Camel), fn_name.span());
|
||||
|
||||
let mut param_names = Vec::new();
|
||||
let mut param_types = Vec::new();
|
||||
for parameter in &signature.inputs {
|
||||
let FnArg::Typed(pat_type) = parameter else { unreachable!("receiver is rejected above") };
|
||||
let Pat::Ident(pat_ident) = &*pat_type.pat else {
|
||||
return Err(Error::new(pat_type.span(), "command parameters must be plain identifiers"));
|
||||
};
|
||||
param_names.push(&pat_ident.ident);
|
||||
param_types.push(&*pat_type.ty);
|
||||
}
|
||||
|
||||
let return_type = &signature.output;
|
||||
let body = &function.block;
|
||||
|
||||
let span = fn_name.span();
|
||||
variants.extend(quote_spanned! {span=>
|
||||
#(#docs)*
|
||||
#variant { #(#param_names: #param_types,)* },
|
||||
});
|
||||
stubs.extend(quote_spanned! {span=>
|
||||
#(#docs)*
|
||||
#[cfg(not(feature = "native"))]
|
||||
#[wasm_bindgen(js_name = #js_name)]
|
||||
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
|
||||
self.dispatch((move || #return_type #body)())
|
||||
}
|
||||
#(#docs)*
|
||||
#[cfg(feature = "native")]
|
||||
#[wasm_bindgen(js_name = #js_name)]
|
||||
pub fn #fn_name(&self, #(#param_names: #param_types,)*) {
|
||||
self.send(EditorCommand::#variant { #(#param_names,)* })
|
||||
}
|
||||
});
|
||||
arms.extend(quote_spanned! {span=>
|
||||
EditorCommand::#variant { #(#param_names,)* } => #body,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(quote! {
|
||||
#(
|
||||
#[cfg(feature = "editor")]
|
||||
#imports
|
||||
)*
|
||||
|
||||
#[cfg(any(feature = "native", not(target_family = "wasm")))]
|
||||
#[derive(serde::Serialize, serde::Deserialize)]
|
||||
pub enum EditorCommand {
|
||||
#variants
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "editor", any(feature = "native", not(target_family = "wasm"))))]
|
||||
impl From<EditorCommand> for Message {
|
||||
fn from(command: EditorCommand) -> Self {
|
||||
match command {
|
||||
#arms
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[wasm_bindgen]
|
||||
impl EditorWrapper {
|
||||
#stubs
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
mod as_message;
|
||||
mod combined_message_attrs;
|
||||
mod discriminant;
|
||||
mod editor_commands;
|
||||
mod extract_fields;
|
||||
mod helper_structs;
|
||||
mod helpers;
|
||||
@@ -15,6 +16,7 @@ mod widget_builder;
|
||||
use crate::as_message::derive_as_message_impl;
|
||||
use crate::combined_message_attrs::combined_message_attrs_impl;
|
||||
use crate::discriminant::derive_discriminant_impl;
|
||||
use crate::editor_commands::editor_commands_impl;
|
||||
use crate::extract_fields::derive_extract_field_impl;
|
||||
use crate::helper_structs::AttrInnerSingleString;
|
||||
use crate::hierarchical_tree::generate_hierarchical_tree;
|
||||
@@ -302,6 +304,12 @@ pub fn message_handler_data(attr: TokenStream, input_item: TokenStream) -> Token
|
||||
TokenStream::from(message_handler_data_attr_impl(attr.into(), input_item.into()).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[proc_macro_attribute]
|
||||
pub fn editor_commands(attr: TokenStream, input_item: TokenStream) -> TokenStream {
|
||||
let module = syn::parse_macro_input!(input_item as syn::ItemMod);
|
||||
TokenStream::from(editor_commands_impl(attr.into(), module).unwrap_or_else(|err| err.to_compile_error()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -8,7 +8,15 @@ use std::path::Path;
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
const EXCLUDED_DIRECTORIES: &[&str] = &["target", ".git", "frontend/node_modules", "frontend/dist", "frontend/wrapper/pkg", "tools"];
|
||||
const EXCLUDED_DIRECTORIES: &[&str] = &[
|
||||
"target",
|
||||
".git",
|
||||
"frontend/node_modules",
|
||||
"frontend/dist",
|
||||
"frontend/wrapper/pkg",
|
||||
"frontend/wrapper/pkg-native",
|
||||
"tools",
|
||||
];
|
||||
const INCLUDED_EXTENSIONS: &[&str] = &["rs"];
|
||||
|
||||
const DEBOUNCE: Duration = Duration::from_millis(500);
|
||||
|
||||
@@ -10,8 +10,12 @@ pub fn frontend_dir() -> PathBuf {
|
||||
workspace_dir().join("frontend")
|
||||
}
|
||||
|
||||
fn wasm_glue_path() -> PathBuf {
|
||||
frontend_dir().join("wrapper").join("pkg").join(format!("{OUT_NAME}.js"))
|
||||
fn pkg_dir(native: bool) -> PathBuf {
|
||||
frontend_dir().join("wrapper").join(if native { "pkg-native" } else { "pkg" })
|
||||
}
|
||||
|
||||
fn wasm_glue_path(native: bool) -> PathBuf {
|
||||
pkg_dir(native).join(format!("{OUT_NAME}.js"))
|
||||
}
|
||||
|
||||
pub fn setup() -> Result<(), Error> {
|
||||
@@ -50,15 +54,15 @@ pub fn build_wasm(release: bool, native: bool) -> Result<(), Error> {
|
||||
|
||||
pub fn build_wasm_steps(release: bool, native: bool) -> Vec<Expression> {
|
||||
let wasm_artifact = target_dir().join(WASM_TARGET).join(if release { "release" } else { "debug" }).join(format!("{OUT_NAME}.wasm"));
|
||||
let pkg_dir = frontend_dir().join("wrapper").join("pkg");
|
||||
let pkg_dir = pkg_dir(native);
|
||||
|
||||
let mut steps = vec![
|
||||
cmd!("cargo", "build", "--lib", "--package", WRAPPER_CRATE, "--target", WASM_TARGET)
|
||||
.arg_if(release, "--release")
|
||||
.args_if(native, ["--no-default-features", "--features", "native"])
|
||||
.dir(workspace_dir())
|
||||
.before_spawn(|_| {
|
||||
if is_build_corrupted() {
|
||||
.before_spawn(move |_| {
|
||||
if is_build_corrupted(wasm_glue_path(native)) {
|
||||
clean_wasm();
|
||||
}
|
||||
Ok(())
|
||||
@@ -90,8 +94,8 @@ pub fn clean_wasm() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
pub fn is_build_corrupted() -> bool {
|
||||
let Ok(js) = std::fs::read_to_string(wasm_glue_path()) else {
|
||||
pub fn is_build_corrupted(path: PathBuf) -> bool {
|
||||
let Ok(js) = std::fs::read_to_string(&path) else {
|
||||
return false;
|
||||
};
|
||||
js.contains("from \"env\"") || js.contains("from 'env'")
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn category_description(category: &str) -> &str {
|
||||
"Math: Numeric" => "Nodes in this category perform discontinuous numeric operations such as rounding, clamping, mapping, and randomization.",
|
||||
"Math: Transform" => "Nodes in this category perform transformations on graphical elements and calculations involving transformation matrices.",
|
||||
"Math: Trig" => "Nodes in this category perform trigonometric operations such as sine, cosine, tangent, and their inverses.",
|
||||
"Math: Vector" => "Nodes in this category perform operations involving `vec2` values (points or arrows in 2D space) such as the dot product, normalization, and distance calculations.",
|
||||
"Math: Vec2" => "Nodes in this category perform operations involving `vec2` values (points or arrows in 2D space) such as the dot product, normalization, and distance calculations.",
|
||||
"Raster: Adjustment" => "Nodes in this category perform per-pixel color adjustments on raster graphics, such as brightness and contrast modifications.",
|
||||
"Raster: Channels" => "Nodes in this category enable channel-specific manipulation of the RGB and alpha channels of raster graphics.",
|
||||
"Raster: Filter" => "Nodes in this category apply filtering effects to raster graphics such as blurs and sharpening.",
|
||||
|
||||
Reference in new issue
Block a user