mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90d953f199 | ||
|
|
adba81a906 | ||
|
|
c9cec90437 | ||
|
|
a47695090d | ||
|
|
47845ec5a6 | ||
|
|
f88896a887 |
No files matched your search
+14
-17
@@ -1,30 +1,27 @@
|
||||
{ pkgs, ... }:
|
||||
|
||||
let
|
||||
version = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
hashes = {
|
||||
aarch64-linux = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
x86_64-linux = "sha256-OPGMBJmvvLiLdBDniBQwx7LmTGGI59AcesJdILSeqcs=";
|
||||
};
|
||||
version = "149.7827.0";
|
||||
upstream = "149.0.5+g6770623+chromium-149.0.7827.197";
|
||||
|
||||
selectSystem =
|
||||
attrs:
|
||||
attrs.${pkgs.stdenv.hostPlatform.system}
|
||||
or (throw "Unsupported system ${pkgs.stdenv.hostPlatform.system}");
|
||||
|
||||
src = pkgs.fetchurl {
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${version}_${
|
||||
selectSystem {
|
||||
aarch64-linux = "linuxarm64";
|
||||
x86_64-linux = "linux64";
|
||||
}
|
||||
}_minimal.tar.bz2";
|
||||
hash = selectSystem hashes;
|
||||
src = selectSystem {
|
||||
x86_64-linux = pkgs.fetchurl {
|
||||
url = "https://github.com/timon-schelling/graphite-cef/releases/download/v${version}/graphite_cef_x86-64_linux.tar.xz";
|
||||
hash = "sha256-CtvS/+NUh5ilnunt4AsWaZfWPiCsdEtz6+TLADT1Gqk=";
|
||||
};
|
||||
aarch64-linux = pkgs.fetchurl {
|
||||
url = "https://cef-builds.spotifycdn.com/cef_binary_${upstream}_linuxarm64_minimal.tar.bz2";
|
||||
hash = "sha256-cBAvcvs1rAg5EKJkCt81RZYupCWpUNIC/nLt3PJow7Q=";
|
||||
};
|
||||
};
|
||||
in
|
||||
pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
version = builtins.head (builtins.split "\\+" version);
|
||||
inherit src;
|
||||
pkgs.cef-binary.overrideAttrs (_: {
|
||||
inherit src version;
|
||||
postInstall = ''
|
||||
rm -r $out/* $out/.* || true
|
||||
strip ./Release/*.so*
|
||||
@@ -38,7 +35,7 @@ pkgs.cef-binary.overrideAttrs (finalAttrs: {
|
||||
echo '${
|
||||
builtins.toJSON {
|
||||
type = "minimal";
|
||||
name = builtins.baseNameOf finalAttrs.src.url;
|
||||
name = "cef_binary_${upstream}";
|
||||
sha1 = "";
|
||||
}
|
||||
}' > $out/archive.json
|
||||
|
||||
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 {
|
||||
|
||||
@@ -183,23 +183,6 @@ pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
|
||||
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
|
||||
pub const AUTO_SAVE_TIMEOUT_SECONDS: u64 = 1;
|
||||
|
||||
// PLOTTER
|
||||
/// Address of the pen plotter print server, hard-coded for the conference booth LAN where it won't change.
|
||||
pub const PLOTTER_SERVER_ADDRESS: &str = "http://192.168.77.10:4747";
|
||||
/// Drawable area of letter paper in the plotter, in inches (portrait). The artwork's bounding box (the artboard is
|
||||
/// dropped) is scaled to fit, rotated to landscape when wider than tall.
|
||||
pub const PLOTTER_PAPER_SIZE_INCHES: (f64, f64) = (7.5, 10.);
|
||||
/// Fixed per-job overhead in seconds before the pen starts moving. Derived directly from timed plots: two versions of
|
||||
/// the same artwork plotted separately (3:24 + 12:17) minus both overlaid in a single job (15:23) leaves the setup
|
||||
/// time counted one extra time, giving 18 seconds.
|
||||
pub const PLOTTER_SETUP_SECONDS: f64 = 18.;
|
||||
/// Pen-down drawing speed in inches per second. Fitted (with the pen lift time below) to timed plots of the same
|
||||
/// artwork with solid strokes (349 in, 20 lifts, 3:24) and dash-baked strokes (176 in, 818 lifts, 12:17).
|
||||
pub const PLOTTER_PEN_SPEED_INCHES_PER_SECOND: f64 = 2.047;
|
||||
/// Seconds per pen lift/reposition/lower cycle, once per subpath. This also covers pen-up travel, which is not
|
||||
/// modeled by distance because the print server reorders paths to minimize it. Fitted alongside the pen speed above.
|
||||
pub const PLOTTER_PEN_LIFT_SECONDS: f64 = 0.774;
|
||||
|
||||
// INPUT
|
||||
pub const DOUBLE_CLICK_MILLISECONDS: u64 = 500;
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ pub enum DialogMessage {
|
||||
NewDocumentDialog(NewDocumentDialogMessage),
|
||||
#[child]
|
||||
PreferencesDialog(PreferencesDialogMessage),
|
||||
#[child]
|
||||
SendToPlotterDialog(SendToPlotterDialogMessage),
|
||||
|
||||
// Messages
|
||||
Dismiss,
|
||||
@@ -24,9 +22,6 @@ pub enum DialogMessage {
|
||||
title: String,
|
||||
description: String,
|
||||
},
|
||||
DisplaySendToPlotterSuccess {
|
||||
job_name: String,
|
||||
},
|
||||
RequestAboutGraphiteDialog,
|
||||
RequestAboutGraphiteDialogWithLocalizedCommitDate {
|
||||
localized_commit_date: String,
|
||||
@@ -42,7 +37,6 @@ pub enum DialogMessage {
|
||||
},
|
||||
RequestNewDocumentDialog,
|
||||
RequestPreferencesDialog,
|
||||
RequestSendToPlotterDialog,
|
||||
RequestConfirmRestartDialog {
|
||||
preferences_requiring_restart: Vec<String>,
|
||||
},
|
||||
|
||||
@@ -4,7 +4,6 @@ use crate::messages::dialog::simple_dialogs::{ConfirmRestartDialog, LicensesThir
|
||||
use crate::messages::frontend::utility_types::ExportBounds;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct DialogMessageContext<'a> {
|
||||
@@ -19,7 +18,6 @@ pub struct DialogMessageHandler {
|
||||
export_dialog: ExportDialogMessageHandler,
|
||||
new_document_dialog: NewDocumentDialogMessageHandler,
|
||||
preferences_dialog: PreferencesDialogMessageHandler,
|
||||
send_to_plotter_dialog: SendToPlotterDialogMessageHandler,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
@@ -31,7 +29,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
DialogMessage::ExportDialog(message) => self.export_dialog.process_message(message, responses, ExportDialogMessageContext { portfolio }),
|
||||
DialogMessage::NewDocumentDialog(message) => self.new_document_dialog.process_message(message, responses, ()),
|
||||
DialogMessage::PreferencesDialog(message) => self.preferences_dialog.process_message(message, responses, PreferencesDialogMessageContext { preferences }),
|
||||
DialogMessage::SendToPlotterDialog(message) => self.send_to_plotter_dialog.process_message(message, responses, SendToPlotterDialogMessageContext { portfolio }),
|
||||
|
||||
DialogMessage::Dismiss => {
|
||||
if let Some(message) = self.on_dismiss.take() {
|
||||
@@ -63,11 +60,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
let dialog = simple_dialogs::ErrorDialog { title, description };
|
||||
dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
DialogMessage::DisplaySendToPlotterSuccess { job_name } => {
|
||||
self.on_dismiss = None;
|
||||
let dialog = simple_dialogs::SendToPlotterSuccessDialog { job_name };
|
||||
dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
DialogMessage::RequestAboutGraphiteDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
responses.add(FrontendMessage::TriggerAboutGraphiteLocalizedCommitDate {
|
||||
@@ -144,23 +136,6 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
self.on_dismiss = Some(PreferencesDialogMessage::Confirm.into());
|
||||
self.preferences_dialog.send_dialog_to_frontend(responses, preferences);
|
||||
}
|
||||
DialogMessage::RequestSendToPlotterDialog => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
if let Some(document) = portfolio.active_document() {
|
||||
// Switch the viewport to outline mode so the artwork previews as the pen plotter will draw it
|
||||
responses.add(DocumentMessage::SetRenderMode { render_mode: RenderMode::Outline });
|
||||
|
||||
// Kick off a render of the plotter SVG purely to measure it for the time estimate shown in the dialog
|
||||
responses.add(PortfolioMessage::SubmitPlotterExport {
|
||||
job_name: document.name.clone(),
|
||||
estimate_only: true,
|
||||
});
|
||||
|
||||
self.send_to_plotter_dialog.job_name = document.name.clone();
|
||||
self.send_to_plotter_dialog.estimate = crate::messages::dialog::send_to_plotter_dialog::PlotTimeEstimate::Pending;
|
||||
self.send_to_plotter_dialog.send_dialog_to_frontend(responses);
|
||||
}
|
||||
}
|
||||
DialogMessage::RequestConfirmRestartDialog { preferences_requiring_restart } => {
|
||||
self.on_dismiss = Some(DialogMessage::Close.into());
|
||||
let dialog = ConfirmRestartDialog { preferences_requiring_restart };
|
||||
@@ -174,6 +149,5 @@ impl MessageHandler<DialogMessage, DialogMessageContext<'_>> for DialogMessageHa
|
||||
RequestExportDialog,
|
||||
RequestNewDocumentDialog,
|
||||
RequestPreferencesDialog,
|
||||
RequestSendToPlotterDialog,
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,6 @@ mod dialog_message_handler;
|
||||
pub mod export_dialog;
|
||||
pub mod new_document_dialog;
|
||||
pub mod preferences_dialog;
|
||||
pub mod send_to_plotter_dialog;
|
||||
pub mod simple_dialogs;
|
||||
|
||||
#[doc(inline)]
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
mod send_to_plotter_dialog_message;
|
||||
mod send_to_plotter_dialog_message_handler;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use send_to_plotter_dialog_message::{SendToPlotterDialogMessage, SendToPlotterDialogMessageDiscriminant};
|
||||
#[doc(inline)]
|
||||
pub use send_to_plotter_dialog_message_handler::{PlotTimeEstimate, SendToPlotterDialogMessageContext, SendToPlotterDialogMessageHandler, estimated_plot_seconds};
|
||||
@@ -1,10 +0,0 @@
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
#[impl_message(Message, DialogMessage, SendToPlotterDialog)]
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum SendToPlotterDialogMessage {
|
||||
JobName { name: String },
|
||||
UpdateTimeEstimate { seconds: Option<f64> },
|
||||
|
||||
Submit,
|
||||
}
|
||||
-153
@@ -1,153 +0,0 @@
|
||||
use crate::consts::{PLOTTER_PAPER_SIZE_INCHES, PLOTTER_PEN_LIFT_SECONDS, PLOTTER_PEN_SPEED_INCHES_PER_SECOND, PLOTTER_SETUP_SECONDS};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
use graphene_std::renderer::plot_statistics::PlotStatistics;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct SendToPlotterDialogMessageContext<'a> {
|
||||
pub portfolio: &'a PortfolioMessageHandler,
|
||||
}
|
||||
|
||||
/// How long the plotter is expected to take on the current document, shown in the dialog.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub enum PlotTimeEstimate {
|
||||
/// The estimate render is still in flight.
|
||||
#[default]
|
||||
Pending,
|
||||
/// The estimate could not be computed.
|
||||
Unavailable,
|
||||
/// Estimated plot duration in seconds.
|
||||
Seconds(f64),
|
||||
}
|
||||
|
||||
/// A dialog to send the current document to the pen plotter print server as an SVG.
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
pub struct SendToPlotterDialogMessageHandler {
|
||||
pub job_name: String,
|
||||
pub estimate: PlotTimeEstimate,
|
||||
}
|
||||
|
||||
#[message_handler_data]
|
||||
impl MessageHandler<SendToPlotterDialogMessage, SendToPlotterDialogMessageContext<'_>> for SendToPlotterDialogMessageHandler {
|
||||
fn process_message(&mut self, message: SendToPlotterDialogMessage, responses: &mut VecDeque<Message>, context: SendToPlotterDialogMessageContext) {
|
||||
let SendToPlotterDialogMessageContext { portfolio } = context;
|
||||
|
||||
match message {
|
||||
SendToPlotterDialogMessage::JobName { name } => self.job_name = name,
|
||||
|
||||
SendToPlotterDialogMessage::UpdateTimeEstimate { seconds } => {
|
||||
self.estimate = match seconds {
|
||||
Some(seconds) => PlotTimeEstimate::Seconds(seconds),
|
||||
None => PlotTimeEstimate::Unavailable,
|
||||
};
|
||||
|
||||
// Refresh only the dialog content, since re-displaying the whole dialog would reopen it if the user has already closed it
|
||||
self.send_layout(responses, LayoutTarget::DialogColumn1);
|
||||
return;
|
||||
}
|
||||
|
||||
SendToPlotterDialogMessage::Submit => {
|
||||
// Fall back to the document name so the attendant can still tell jobs apart if the field was cleared
|
||||
let job_name = if self.job_name.trim().is_empty() {
|
||||
portfolio.active_document().map(|document| document.name.clone()).unwrap_or_default()
|
||||
} else {
|
||||
self.job_name.clone()
|
||||
};
|
||||
|
||||
responses.add_front(PortfolioMessage::SubmitPlotterExport { job_name, estimate_only: false });
|
||||
}
|
||||
}
|
||||
|
||||
self.send_dialog_to_frontend(responses);
|
||||
}
|
||||
|
||||
advertise_actions!(SendToPlotterDialogUpdate;
|
||||
);
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for SendToPlotterDialogMessageHandler {
|
||||
const ICON: &'static str = "File";
|
||||
const TITLE: &'static str = "Send to Plotter";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![
|
||||
TextButton::new("Send")
|
||||
.emphasized(true)
|
||||
.on_update(|_| {
|
||||
DialogMessage::CloseAndThen {
|
||||
followups: vec![SendToPlotterDialogMessage::Submit.into()],
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
TextButton::new("Cancel").on_update(|_| FrontendMessage::DialogClose.into()).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for SendToPlotterDialogMessageHandler {
|
||||
fn layout(&self) -> Layout {
|
||||
let job_name = vec![
|
||||
TextLabel::new("Job Name").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextInput::new(&self.job_name)
|
||||
.on_update(|text_input: &TextInput| SendToPlotterDialogMessage::JobName { name: text_input.value.clone() }.into())
|
||||
.min_width(200)
|
||||
.widget_instance(),
|
||||
];
|
||||
|
||||
let estimate_text = match self.estimate {
|
||||
PlotTimeEstimate::Pending => "Estimating…".to_string(),
|
||||
PlotTimeEstimate::Unavailable => "Unknown".to_string(),
|
||||
PlotTimeEstimate::Seconds(seconds) => format_plot_duration(seconds),
|
||||
};
|
||||
let estimated_time = vec![
|
||||
TextLabel::new("Estimated Time").table_align(true).min_width(100).widget_instance(),
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
TextLabel::new(estimate_text).widget_instance(),
|
||||
];
|
||||
|
||||
Layout(vec![LayoutGroup::row(job_name), LayoutGroup::row(estimated_time)])
|
||||
}
|
||||
}
|
||||
|
||||
/// Estimates how long the plotter will take to draw the given SVG, in seconds.
|
||||
///
|
||||
/// The artwork's bounding box is scaled to fit the paper (rotated to landscape when wider than tall), then timed as a
|
||||
/// fixed setup cost, pen-down drawing at a constant speed, and a fixed cost per pen lift (which also covers pen-up
|
||||
/// travel, since the print server reorders paths to minimize it). The pen draws every path as its outline, so total
|
||||
/// path length approximates the pen-down distance regardless of fills. Intricate fine detail like text tends to run
|
||||
/// over this estimate because the machine cannot reach full speed on tiny curves.
|
||||
pub fn estimated_plot_seconds(statistics: &PlotStatistics) -> f64 {
|
||||
let (paper_width, paper_height) = if statistics.width > statistics.height {
|
||||
(PLOTTER_PAPER_SIZE_INCHES.1, PLOTTER_PAPER_SIZE_INCHES.0)
|
||||
} else {
|
||||
PLOTTER_PAPER_SIZE_INCHES
|
||||
};
|
||||
let scale = if statistics.width > 0. && statistics.height > 0. {
|
||||
(paper_width / statistics.width).min(paper_height / statistics.height)
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
|
||||
let pen_down_inches = statistics.pen_down_distance * scale;
|
||||
|
||||
PLOTTER_SETUP_SECONDS + pen_down_inches / PLOTTER_PEN_SPEED_INCHES_PER_SECOND + statistics.pen_lift_count as f64 * PLOTTER_PEN_LIFT_SECONDS
|
||||
}
|
||||
|
||||
/// Formats an estimated duration like "About 3 min 20 sec", rounded to the nearest 5 seconds.
|
||||
fn format_plot_duration(seconds: f64) -> String {
|
||||
let total = (((seconds / 5.).round() * 5.).max(5.)) as u64;
|
||||
let minutes = total / 60;
|
||||
let seconds = total % 60;
|
||||
|
||||
if minutes == 0 {
|
||||
format!("About {seconds} sec")
|
||||
} else if seconds == 0 {
|
||||
format!("About {minutes} min")
|
||||
} else {
|
||||
format!("About {minutes} min {seconds} sec")
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ mod failed_to_load_documents_dialog;
|
||||
mod failed_to_open_document_dialog;
|
||||
mod licenses_dialog;
|
||||
mod licenses_third_party_dialog;
|
||||
mod send_to_plotter_success_dialog;
|
||||
|
||||
pub use about_graphite_dialog::AboutGraphiteDialog;
|
||||
pub use close_all_documents_dialog::CloseAllDocumentsDialog;
|
||||
@@ -21,4 +20,3 @@ pub use failed_to_load_documents_dialog::FailedToLoadDocumentsDialog;
|
||||
pub use failed_to_open_document_dialog::FailedToOpenDocumentDialog;
|
||||
pub use licenses_dialog::LicensesDialog;
|
||||
pub use licenses_third_party_dialog::LicensesThirdPartyDialog;
|
||||
pub use send_to_plotter_success_dialog::SendToPlotterSuccessDialog;
|
||||
@@ -1,34 +0,0 @@
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::prelude::*;
|
||||
|
||||
/// A dialog to confirm that a job was successfully queued on the pen plotter print server.
|
||||
pub struct SendToPlotterSuccessDialog {
|
||||
pub job_name: String,
|
||||
}
|
||||
|
||||
impl DialogLayoutHolder for SendToPlotterSuccessDialog {
|
||||
const ICON: &'static str = "CheckboxChecked";
|
||||
const TITLE: &'static str = "Send to Plotter";
|
||||
|
||||
fn layout_buttons(&self) -> Layout {
|
||||
let widgets = vec![TextButton::new("OK").emphasized(true).on_update(|_| FrontendMessage::DialogClose.into()).widget_instance()];
|
||||
|
||||
Layout(vec![LayoutGroup::row(widgets)])
|
||||
}
|
||||
}
|
||||
|
||||
impl LayoutHolder for SendToPlotterSuccessDialog {
|
||||
fn layout(&self) -> Layout {
|
||||
Layout(vec![
|
||||
LayoutGroup::row(vec![TextLabel::new("Sent to the plotter queue").bold(true).widget_instance()]),
|
||||
LayoutGroup::row(vec![
|
||||
TextLabel::new(format!(
|
||||
"The job \"{}\" was added to the queue.\nA booth attendant will start the plot from the dashboard.",
|
||||
self.job_name
|
||||
))
|
||||
.multiline(true)
|
||||
.widget_instance(),
|
||||
]),
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -106,11 +105,6 @@ pub enum FrontendMessage {
|
||||
mime: String,
|
||||
size: (f64, f64),
|
||||
},
|
||||
TriggerSendToPlotter {
|
||||
name: String,
|
||||
svg: String,
|
||||
address: String,
|
||||
},
|
||||
TriggerFetchAndOpenDocument {
|
||||
name: String,
|
||||
filename: String,
|
||||
@@ -240,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,
|
||||
}
|
||||
@@ -453,7 +453,6 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
|
||||
// DialogMessage
|
||||
entry!(KeyDown(KeyE); modifiers=[Accel], action_dispatch=DialogMessage::RequestExportDialog),
|
||||
entry!(KeyDown(KeyN); modifiers=[Accel], action_dispatch=DialogMessage::RequestNewDocumentDialog),
|
||||
entry!(KeyDown(KeyP); modifiers=[Accel], action_dispatch=DialogMessage::RequestSendToPlotterDialog),
|
||||
entry!(KeyDown(Comma); modifiers=[Accel], action_dispatch=DialogMessage::RequestPreferencesDialog),
|
||||
//
|
||||
// DebugMessage
|
||||
|
||||
@@ -172,12 +172,6 @@ impl LayoutHolder for MenuBarMessageHandler {
|
||||
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestExportDialog))
|
||||
.on_commit(|_| DialogMessage::RequestExportDialog.into())
|
||||
.disabled(no_active_document),
|
||||
MenuListEntry::new("Send to Plotter…")
|
||||
.label("Send to Plotter…")
|
||||
.icon("FileExport")
|
||||
.tooltip_shortcut(action_shortcut!(DialogMessageDiscriminant::RequestSendToPlotterDialog))
|
||||
.on_commit(|_| DialogMessage::RequestSendToPlotterDialog.into())
|
||||
.disabled(no_active_document),
|
||||
],
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
vec![preferences],
|
||||
|
||||
@@ -1323,8 +1323,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
DocumentMessage::SetRenderMode { render_mode } => {
|
||||
self.render_mode = render_mode;
|
||||
responses.add_front(NodeGraphMessage::RunDocumentGraph);
|
||||
// Keep the document bar's render mode radio buttons in sync when the mode is set programmatically
|
||||
responses.add(PortfolioMessage::UpdateDocumentWidgets);
|
||||
}
|
||||
DocumentMessage::AddTransaction => {
|
||||
// Reverse order since they are added to the front
|
||||
|
||||
@@ -197,10 +197,6 @@ pub enum PortfolioMessage {
|
||||
artboard_name: Option<String>,
|
||||
artboard_count: usize,
|
||||
},
|
||||
SubmitPlotterExport {
|
||||
job_name: String,
|
||||
estimate_only: bool,
|
||||
},
|
||||
SubmitActiveGraphRender,
|
||||
SubmitGraphRender {
|
||||
document_id: DocumentId,
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::application::{Editor, generate_uuid};
|
||||
use crate::consts::{DEFAULT_DOCUMENT_NAME, FILE_EXTENSION, GDD_FILE_EXTENSION};
|
||||
use crate::messages::animation::TimingInformation;
|
||||
use crate::messages::dialog::simple_dialogs;
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, ExportBounds, FileType, PersistedState};
|
||||
use crate::messages::frontend::utility_types::{DocumentInfo, PersistedState};
|
||||
use crate::messages::input_mapper::utility_types::input_keyboard::Key;
|
||||
use crate::messages::input_mapper::utility_types::macros::{action_shortcut, action_shortcut_manual};
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
@@ -1461,32 +1461,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
||||
});
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitPlotterExport { job_name, estimate_only } => {
|
||||
let document_id = self.active_document_id.expect("Tried to render non-existent document");
|
||||
let document = self.documents.get_mut(&document_id).expect("Tried to render non-existent document");
|
||||
let export_config = ExportConfig {
|
||||
name: job_name,
|
||||
file_type: FileType::Svg,
|
||||
scale_factor: 1.,
|
||||
bounds: ExportBounds::AllArtwork,
|
||||
for_plotter: true,
|
||||
plotter_estimate_only: estimate_only,
|
||||
..Default::default()
|
||||
};
|
||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
||||
|
||||
if let Err(description) = result {
|
||||
// A failed estimate render (e.g. an empty document) just marks the estimate as unavailable
|
||||
if estimate_only {
|
||||
responses.add(DialogMessage::SendToPlotterDialog(SendToPlotterDialogMessage::UpdateTimeEstimate { seconds: None }));
|
||||
} else {
|
||||
responses.add(DialogMessage::DisplayDialogError {
|
||||
title: "Unable to send to the plotter".to_string(),
|
||||
description,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitActiveGraphRender => {
|
||||
if let Some(document_id) = self.active_document_id {
|
||||
responses.add(PortfolioMessage::SubmitGraphRender { document_id, ignore_hash: false });
|
||||
|
||||
@@ -14,7 +14,6 @@ pub use crate::messages::defer::{DeferMessage, DeferMessageDiscriminant, DeferMe
|
||||
pub use crate::messages::dialog::export_dialog::{ExportDialogMessage, ExportDialogMessageContext, ExportDialogMessageDiscriminant, ExportDialogMessageHandler};
|
||||
pub use crate::messages::dialog::new_document_dialog::{NewDocumentDialogMessage, NewDocumentDialogMessageDiscriminant, NewDocumentDialogMessageHandler};
|
||||
pub use crate::messages::dialog::preferences_dialog::{PreferencesDialogMessage, PreferencesDialogMessageContext, PreferencesDialogMessageDiscriminant, PreferencesDialogMessageHandler};
|
||||
pub use crate::messages::dialog::send_to_plotter_dialog::{SendToPlotterDialogMessage, SendToPlotterDialogMessageContext, SendToPlotterDialogMessageDiscriminant, SendToPlotterDialogMessageHandler};
|
||||
pub use crate::messages::dialog::{DialogMessage, DialogMessageContext, DialogMessageDiscriminant, DialogMessageHandler};
|
||||
pub use crate::messages::frontend::{FrontendMessage, FrontendMessageDiscriminant};
|
||||
pub use crate::messages::future::{FutureMessage, FutureMessageContext, FutureMessageDiscriminant, FutureMessageHandler, MessageFuture, MessageSpawner, Wake};
|
||||
|
||||
@@ -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};
|
||||
@@ -196,8 +196,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
hide_artboard_background: false,
|
||||
bake_stroke_dashes: false,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -269,8 +267,6 @@ impl NodeGraphExecutor {
|
||||
render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: true,
|
||||
hide_artboard_background: false,
|
||||
bake_stroke_dashes: false,
|
||||
};
|
||||
|
||||
// Execute the node graph
|
||||
@@ -319,25 +315,15 @@ impl NodeGraphExecutor {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The plotter flow switches the viewport to Outline mode as a preview, so pin its export to the normal render
|
||||
// mode for a deterministic serialization regardless of what the viewport is showing
|
||||
let render_mode = if export_config.for_plotter {
|
||||
graphene_std::vector::style::RenderMode::Normal
|
||||
} else {
|
||||
document.render_mode
|
||||
};
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport,
|
||||
scale: export_config.scale_factor,
|
||||
time: Default::default(),
|
||||
pointer: DVec2::ZERO,
|
||||
export_format,
|
||||
render_mode,
|
||||
render_mode: document.render_mode,
|
||||
for_export: true,
|
||||
for_eyedropper: false,
|
||||
hide_artboard_background: export_config.for_plotter,
|
||||
bake_stroke_dashes: export_config.for_plotter,
|
||||
};
|
||||
export_config.size = resolution;
|
||||
|
||||
@@ -582,8 +568,6 @@ impl NodeGraphExecutor {
|
||||
render_mode: document.render_mode,
|
||||
for_export: false,
|
||||
for_eyedropper: false,
|
||||
hide_artboard_background: false,
|
||||
bake_stroke_dashes: false,
|
||||
};
|
||||
let execution_id = self.queue_execution(render_config);
|
||||
self.futures.push_back((
|
||||
@@ -678,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 });
|
||||
@@ -749,8 +729,6 @@ impl NodeGraphExecutor {
|
||||
size,
|
||||
artboard_name,
|
||||
artboard_count,
|
||||
for_plotter,
|
||||
plotter_estimate_only,
|
||||
..
|
||||
} = export_config;
|
||||
|
||||
@@ -771,18 +749,7 @@ impl NodeGraphExecutor {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => {
|
||||
if plotter_estimate_only {
|
||||
// Measure the SVG the plotter would receive and report the time estimate back to the dialog
|
||||
let seconds =
|
||||
graphene_std::renderer::plot_statistics::svg_plot_statistics(&svg).map(|statistics| crate::messages::dialog::send_to_plotter_dialog::estimated_plot_seconds(&statistics));
|
||||
responses.add(DialogMessage::SendToPlotterDialog(SendToPlotterDialogMessage::UpdateTimeEstimate { seconds }));
|
||||
} else if for_plotter {
|
||||
responses.add(FrontendMessage::TriggerSendToPlotter {
|
||||
name: base_name,
|
||||
svg,
|
||||
address: crate::consts::PLOTTER_SERVER_ADDRESS.to_string(),
|
||||
});
|
||||
} else if file_type == FileType::Svg {
|
||||
if file_type == FileType::Svg {
|
||||
responses.add(FrontendMessage::TriggerSaveFile {
|
||||
name,
|
||||
folder,
|
||||
|
||||
@@ -91,10 +91,6 @@ pub struct ExportConfig {
|
||||
pub size: UVec2,
|
||||
pub artboard_name: Option<String>,
|
||||
pub artboard_count: usize,
|
||||
/// Send the exported SVG to the pen plotter print server instead of saving it as a file.
|
||||
pub for_plotter: bool,
|
||||
/// Only measure the plotter SVG for a time estimate instead of sending it to the print server.
|
||||
pub plotter_estimate_only: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -29,9 +29,6 @@ const initialState: PortfolioStoreState = {
|
||||
|
||||
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
|
||||
|
||||
// Prevents double-submitting a plotter job while one upload is still in flight
|
||||
let plotterUploadInFlight = false;
|
||||
|
||||
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
|
||||
const store: Writable<PortfolioStoreState> = import.meta.hot?.data?.store || writable<PortfolioStoreState>(initialState);
|
||||
if (import.meta.hot) import.meta.hot.data.store = store;
|
||||
@@ -132,34 +129,6 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
|
||||
}
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("TriggerSendToPlotter", async (data) => {
|
||||
const { name, svg, address } = data;
|
||||
|
||||
if (plotterUploadInFlight) return;
|
||||
plotterUploadInFlight = true;
|
||||
|
||||
try {
|
||||
// POST the SVG to the print server's job queue endpoint, with the job name in the query string
|
||||
const endpoint = `${address}/api/jobs?name=${encodeURIComponent(name)}`;
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(endpoint, { method: "POST", headers: { "content-type": "image/svg+xml" }, body: svg });
|
||||
} catch {
|
||||
editor.errorDialog("Send to Plotter failed", `Could not reach the print server. Is it running at ${address} and connected to the same network?`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.status === 201) {
|
||||
editor.sendToPlotterSuccessDialog(name);
|
||||
} else {
|
||||
const serverError = (await response.json().catch(() => undefined))?.error;
|
||||
editor.errorDialog("Send to Plotter failed", `The print server rejected the job${serverError ? `: ${serverError}` : ` (HTTP ${response.status})`}.`);
|
||||
}
|
||||
} finally {
|
||||
plotterUploadInFlight = false;
|
||||
}
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateWorkspacePanelLayout", (data) => {
|
||||
update((state) => {
|
||||
state.panelLayout = data.panelLayout;
|
||||
@@ -227,7 +196,6 @@ export function destroyPortfolioStore() {
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSaveDocument");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSaveFile");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerExportImage");
|
||||
subscriptions.unsubscribeFrontendMessage("TriggerSendToPlotter");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateWorkspacePanelLayout");
|
||||
subscriptions.unsubscribeLayoutUpdate("WelcomeScreenButtons");
|
||||
subscriptions.unsubscribeLayoutUpdate("PropertiesPanel");
|
||||
|
||||
@@ -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,689 @@
|
||||
//! 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::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: Any, x: i32, y: i32) -> Message {
|
||||
let id = NodeId::new();
|
||||
NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(id),
|
||||
node_type: node_type.cast(),
|
||||
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,101 +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);
|
||||
}
|
||||
|
||||
/// Displays a dialog confirming that a job was successfully queued on the pen plotter print server
|
||||
#[wasm_bindgen(js_name = sendToPlotterSuccessDialog)]
|
||||
pub fn send_to_plotter_success_dialog(&self, job_name: String) {
|
||||
let message = DialogMessage::DisplaySendToPlotterSuccess { job_name };
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Answer whether or not the editor has crashed
|
||||
#[wasm_bindgen(js_name = hasCrashed)]
|
||||
pub fn has_crashed(&self) -> bool {
|
||||
@@ -337,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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,10 +83,6 @@ pub struct RenderConfig {
|
||||
pub export_format: ExportFormat,
|
||||
pub for_export: bool,
|
||||
pub for_eyedropper: bool,
|
||||
/// Skip rendering artboard background rectangles, used for pen plotter output.
|
||||
pub hide_artboard_background: bool,
|
||||
/// Cut dashed strokes into their visible dash segments so the path geometry itself carries the dash pattern, used for pen plotter output.
|
||||
pub bake_stroke_dashes: bool,
|
||||
}
|
||||
|
||||
impl RenderConfig {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod convert_usvg_path;
|
||||
pub mod plot_statistics;
|
||||
pub mod render_ext;
|
||||
mod renderer;
|
||||
pub mod to_peniko;
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
use kurbo::{BezPath, ParamCurveArclen, PathEl, PathSeg, Point, Rect, Shape};
|
||||
|
||||
/// Pen movement totals for plotting an SVG document with a pen plotter, which draws every path as its outline.
|
||||
/// Distances are in SVG user units; scale by the paper fit before converting to wall-clock time.
|
||||
///
|
||||
/// Pen-up travel between subpaths is deliberately not measured: the print server reorders paths (and rotates the
|
||||
/// start points of closed ones) to minimize travel, so document-order travel distance is meaningless. Its cost is
|
||||
/// captured as part of the constant time per pen lift instead.
|
||||
pub struct PlotStatistics {
|
||||
/// Total distance drawn with the pen down, following every path's geometry.
|
||||
pub pen_down_distance: f64,
|
||||
/// Number of pen lift/reposition/lower cycles (one per subpath).
|
||||
pub pen_lift_count: usize,
|
||||
/// Width of the artwork's bounding box, which the print server scales to fit the paper (the document size is ignored).
|
||||
pub width: f64,
|
||||
/// Height of the artwork's bounding box.
|
||||
pub height: f64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MeasureState {
|
||||
pen_down_distance: f64,
|
||||
pen_lift_count: usize,
|
||||
bounds: Option<Rect>,
|
||||
}
|
||||
|
||||
/// Measures the pen plotter movement statistics of an SVG document by walking every path in document order.
|
||||
/// Returns `None` if the SVG cannot be parsed or contains no path geometry.
|
||||
pub fn svg_plot_statistics(svg: &str) -> Option<PlotStatistics> {
|
||||
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).ok()?;
|
||||
|
||||
let mut state = MeasureState::default();
|
||||
accumulate_group(tree.root(), &mut state);
|
||||
|
||||
let bounds = state.bounds?;
|
||||
Some(PlotStatistics {
|
||||
pen_down_distance: state.pen_down_distance,
|
||||
pen_lift_count: state.pen_lift_count,
|
||||
width: bounds.width(),
|
||||
height: bounds.height(),
|
||||
})
|
||||
}
|
||||
|
||||
fn accumulate_group(group: &usvg::Group, state: &mut MeasureState) {
|
||||
for node in group.children() {
|
||||
match node {
|
||||
usvg::Node::Group(group) => accumulate_group(group, state),
|
||||
usvg::Node::Path(path) => accumulate_bezpath(&usvg_path_to_bezpath(path), state),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn accumulate_bezpath(bezpath: &BezPath, state: &mut MeasureState) {
|
||||
const ARC_LENGTH_ACCURACY: f64 = 0.1;
|
||||
|
||||
if bezpath.elements().is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
for segment in bezpath.segments() {
|
||||
state.pen_down_distance += match segment {
|
||||
PathSeg::Line(line) => line.p0.distance(line.p1),
|
||||
segment => segment.arclen(ARC_LENGTH_ACCURACY),
|
||||
};
|
||||
}
|
||||
|
||||
state.pen_lift_count += bezpath.elements().iter().filter(|element| matches!(element, PathEl::MoveTo(_))).count();
|
||||
|
||||
let bounds = bezpath.bounding_box();
|
||||
if !bounds.is_nan() {
|
||||
state.bounds = Some(state.bounds.map_or(bounds, |existing| existing.union(bounds)));
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a usvg path into a kurbo path with its absolute transform applied.
|
||||
fn usvg_path_to_bezpath(path: &usvg::Path) -> BezPath {
|
||||
let transform = path.abs_transform();
|
||||
let to_point = |point: &usvg::tiny_skia_path::Point| {
|
||||
let (x, y) = (point.x as f64, point.y as f64);
|
||||
Point::new(
|
||||
transform.sx as f64 * x + transform.kx as f64 * y + transform.tx as f64,
|
||||
transform.ky as f64 * x + transform.sy as f64 * y + transform.ty as f64,
|
||||
)
|
||||
};
|
||||
|
||||
let mut bezpath = BezPath::new();
|
||||
let mut points = path.data().points().iter();
|
||||
|
||||
for verb in path.data().verbs() {
|
||||
match verb {
|
||||
usvg::tiny_skia_path::PathVerb::Move => {
|
||||
let Some(point) = points.next().map(to_point) else { continue };
|
||||
bezpath.move_to(point);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Line => {
|
||||
let Some(end) = points.next().map(to_point) else { continue };
|
||||
bezpath.line_to(end);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Quad => {
|
||||
let Some(handle) = points.next().map(to_point) else { continue };
|
||||
let Some(end) = points.next().map(to_point) else { continue };
|
||||
bezpath.quad_to(handle, end);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Cubic => {
|
||||
let Some(first_handle) = points.next().map(to_point) else { continue };
|
||||
let Some(second_handle) = points.next().map(to_point) else { continue };
|
||||
let Some(end) = points.next().map(to_point) else { continue };
|
||||
bezpath.curve_to(first_handle, second_handle, end);
|
||||
}
|
||||
usvg::tiny_skia_path::PathVerb::Close => bezpath.close_path(),
|
||||
}
|
||||
}
|
||||
|
||||
bezpath
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn measures_lines_squares_and_bounds() {
|
||||
// A 30x30 square (120 units drawn, 1 lift) followed by a vertical line (100 units drawn, 1 lift),
|
||||
// with an artwork bounding box spanning (10,10) to (40,150)
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 200" width="100" height="200">
|
||||
<path d="M10,10 L40,10 L40,40 L10,40 Z" fill="black" />
|
||||
<path d="M10,50 L10,150" stroke="black" fill="none" />
|
||||
</svg>"##;
|
||||
|
||||
let statistics = svg_plot_statistics(svg).unwrap();
|
||||
|
||||
assert_eq!(statistics.pen_lift_count, 2);
|
||||
assert!((statistics.pen_down_distance - 220.).abs() < 1e-6, "pen down was {}", statistics.pen_down_distance);
|
||||
assert!((statistics.width - 30.).abs() < 1e-6, "width was {}", statistics.width);
|
||||
assert!((statistics.height - 140.).abs() < 1e-6, "height was {}", statistics.height);
|
||||
}
|
||||
}
|
||||
@@ -179,11 +179,10 @@ impl RenderExt for Stroke {
|
||||
|
||||
let default_weight = if self.align != StrokeAlign::Center && render_params.aligned_strokes { 1. / 2. } else { 1. };
|
||||
|
||||
// Set to None if the value is the SVG default. When dashes are baked into the path geometry, the dash attributes must be
|
||||
// omitted so the pattern isn't applied a second time to the already-cut dash segments.
|
||||
// Set to None if the value is the SVG default
|
||||
let weight = (self.weight != default_weight).then_some(self.weight);
|
||||
let dash_array = (!self.dash_lengths.is_empty() && !render_params.bake_stroke_dashes).then_some(self.dash_lengths());
|
||||
let dash_offset = (self.dash_offset != 0. && !render_params.bake_stroke_dashes).then_some(self.dash_offset);
|
||||
let dash_array = (!self.dash_lengths.is_empty()).then_some(self.dash_lengths());
|
||||
let dash_offset = (self.dash_offset != 0.).then_some(self.dash_offset);
|
||||
let stroke_cap = (self.cap != StrokeCap::Butt).then_some(self.cap);
|
||||
let stroke_join = (self.join != StrokeJoin::Miter).then_some(self.join);
|
||||
let stroke_join_miter_limit = (self.join_miter_limit != 4.).then_some(self.join_miter_limit);
|
||||
|
||||
@@ -230,10 +230,6 @@ pub struct RenderParams {
|
||||
pub artboard_background: Option<Color>,
|
||||
/// Viewport zoom level (document-space scale). Used to compute constant viewport-pixel stroke widths in Outline mode.
|
||||
pub viewport_zoom: f64,
|
||||
/// Skip rendering artboard background rectangles, used for pen plotter output where a background would be traced as a giant filled contour.
|
||||
pub hide_artboard_background: bool,
|
||||
/// Cut dashed strokes into their visible dash segments so the path geometry itself carries the dash pattern, used for pen plotter output where `stroke-dasharray` would be ignored.
|
||||
pub bake_stroke_dashes: bool,
|
||||
}
|
||||
|
||||
impl RenderParams {
|
||||
@@ -722,18 +718,16 @@ impl Render for List<Artboard> {
|
||||
let height = dimensions.y.abs();
|
||||
|
||||
// Background
|
||||
if !render_params.hide_artboard_background {
|
||||
render.leaf_tag("rect", |attributes| {
|
||||
attributes.push("fill", format!("#{}", SRGBA8::from(background).to_rgb_hex()));
|
||||
if background.a() < 1. {
|
||||
attributes.push("fill-opacity", ((background.a() * 1000.).round() / 1000.).to_string());
|
||||
}
|
||||
attributes.push("x", x.to_string());
|
||||
attributes.push("y", y.to_string());
|
||||
attributes.push("width", width.to_string());
|
||||
attributes.push("height", height.to_string());
|
||||
});
|
||||
}
|
||||
render.leaf_tag("rect", |attributes| {
|
||||
attributes.push("fill", format!("#{}", SRGBA8::from(background).to_rgb_hex()));
|
||||
if background.a() < 1. {
|
||||
attributes.push("fill-opacity", ((background.a() * 1000.).round() / 1000.).to_string());
|
||||
}
|
||||
attributes.push("x", x.to_string());
|
||||
attributes.push("y", y.to_string());
|
||||
attributes.push("width", width.to_string());
|
||||
attributes.push("height", height.to_string());
|
||||
});
|
||||
|
||||
// Artwork
|
||||
render.parent_tag(
|
||||
@@ -781,12 +775,10 @@ impl Render for List<Artboard> {
|
||||
|
||||
let artboard_transform = kurbo::Affine::new(transform.to_cols_array());
|
||||
|
||||
if !render_params.hide_artboard_background {
|
||||
let color = SRGBA8::from(background).to_peniko_color();
|
||||
scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., artboard_transform, &rect);
|
||||
scene.fill(peniko::Fill::NonZero, artboard_transform, color, None, &rect);
|
||||
scene.pop_layer();
|
||||
}
|
||||
let color = SRGBA8::from(background).to_peniko_color();
|
||||
scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., artboard_transform, &rect);
|
||||
scene.fill(peniko::Fill::NonZero, artboard_transform, color, None, &rect);
|
||||
scene.pop_layer();
|
||||
|
||||
if clip {
|
||||
scene.push_clip_layer(peniko::Fill::NonZero, kurbo::Affine::new(transform.to_cols_array()), &rect);
|
||||
@@ -1122,33 +1114,7 @@ impl Render for List<Vector> {
|
||||
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
|
||||
let use_face_fill = vector.use_face_fill();
|
||||
|
||||
// When baking dashes, cut each stroked path into its visible dash segments so the geometry itself carries the dash
|
||||
// pattern, letting consumers that ignore `stroke-dasharray` (like a pen plotter) still draw the dashes.
|
||||
let baked_dash_path = (render_params.bake_stroke_dashes && stroke_graphic.is_some_and(|graphic| !graphic.is_fully_transparent()))
|
||||
.then_some(vector.stroke.as_ref())
|
||||
.flatten()
|
||||
.filter(|stroke| stroke.has_renderable_stroke() && !stroke.dash_lengths.is_empty())
|
||||
.and_then(|stroke| {
|
||||
let dash_pattern: Vec<f64> = stroke.dash_lengths.iter().map(|length| length.max(0.)).collect();
|
||||
if dash_pattern.iter().sum::<f64>() <= 0. {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut dashed_path = String::new();
|
||||
for mut bezpath in vector.stroke_bezpath_iter() {
|
||||
bezpath.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
|
||||
let dashed_bezpath: BezPath = kurbo::dash(bezpath.iter(), stroke.dash_offset, &dash_pattern).collect();
|
||||
dashed_path.push_str(dashed_bezpath.to_svg().as_str());
|
||||
}
|
||||
Some(dashed_path)
|
||||
});
|
||||
|
||||
// When dashes are baked, the fill is dropped entirely rather than emitted as a separate path: the pen plotter
|
||||
// draws every path as its outline, and a fill's contour is the same uncut geometry the dashes were cut from,
|
||||
// so it would be drawn as a solid line right over the dashes.
|
||||
let emit_separate_fill = needs_separate_alignment_fill && baked_dash_path.is_none();
|
||||
|
||||
if emit_separate_fill && !wants_stroke_below {
|
||||
if needs_separate_alignment_fill && !wants_stroke_below {
|
||||
emit_svg_fill_path(
|
||||
render,
|
||||
path.clone(),
|
||||
@@ -1176,8 +1142,7 @@ impl Render for List<Vector> {
|
||||
(id, mask_type, vector_item)
|
||||
});
|
||||
|
||||
// Face fills are dropped when dashes are baked for the same reason as above: their boundaries retrace the dashed edges
|
||||
if use_face_fill && baked_dash_path.is_none() {
|
||||
if use_face_fill {
|
||||
for mut face_path in vector.construct_faces().filter(|face| face.area() >= 0.) {
|
||||
face_path.apply_affine(Affine::new(applied_stroke_transform.to_cols_array()));
|
||||
let face_d = face_path.to_svg();
|
||||
@@ -1196,7 +1161,7 @@ impl Render for List<Vector> {
|
||||
}
|
||||
|
||||
render.leaf_tag("path", |attributes| {
|
||||
attributes.push("d", baked_dash_path.clone().unwrap_or_else(|| path.clone()));
|
||||
attributes.push("d", path.clone());
|
||||
let matrix = format_transform_matrix(element_transform);
|
||||
if !matrix.is_empty() {
|
||||
attributes.push(ATTR_TRANSFORM, matrix);
|
||||
@@ -1264,7 +1229,7 @@ impl Render for List<Vector> {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let fill_attribute = if needs_separate_alignment_fill || use_face_fill || baked_dash_path.is_some() {
|
||||
let fill_attribute = if needs_separate_alignment_fill || use_face_fill {
|
||||
r#" fill="none""#.to_string()
|
||||
} else {
|
||||
fill_graphic_list
|
||||
@@ -1296,7 +1261,7 @@ impl Render for List<Vector> {
|
||||
});
|
||||
|
||||
// When splitting passes and stroke is below, draw the fill after the stroke.
|
||||
if emit_separate_fill && wants_stroke_below {
|
||||
if needs_separate_alignment_fill && wants_stroke_below {
|
||||
emit_svg_fill_path(
|
||||
render,
|
||||
path.clone(),
|
||||
@@ -1508,16 +1473,7 @@ impl Render for List<Vector> {
|
||||
// Render the path
|
||||
match render_params.render_mode {
|
||||
RenderMode::Outline => {
|
||||
let (mut outline_stroke, outline_color_peniko) = get_outline_styles(render_params);
|
||||
|
||||
// Show the stroke's dash pattern in the outline preview so dashed strokes read the same as they will be plotted
|
||||
if let Some(stroke) = stroke.filter(|stroke| stroke.has_renderable_stroke()) {
|
||||
let dash_pattern: kurbo::Dashes = stroke.dash_lengths.iter().map(|length| length.max(0.)).collect();
|
||||
if dash_pattern.iter().sum::<f64>() > 0. {
|
||||
outline_stroke.dash_pattern = dash_pattern;
|
||||
outline_stroke.dash_offset = stroke.dash_offset;
|
||||
}
|
||||
}
|
||||
let (outline_stroke, outline_color_peniko) = get_outline_styles(render_params);
|
||||
|
||||
scene.stroke(&outline_stroke, kurbo::Affine::new(element_transform.to_cols_array()), outline_color_peniko, None, &path);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,5 @@
|
||||
pub mod bezpath_algorithms;
|
||||
mod contants;
|
||||
pub mod convex_hull;
|
||||
pub mod intersection;
|
||||
pub mod merge_by_distance;
|
||||
pub mod offset_subpath;
|
||||
|
||||
@@ -49,7 +49,7 @@ impl ContextBuilder {
|
||||
let mut adapters = enumerate_sorted(&instance, self.backends).await;
|
||||
|
||||
if let Some(index) = self.selection
|
||||
&& index >= adapters.len()
|
||||
&& index < adapters.len()
|
||||
{
|
||||
let selected_adapter = adapters.remove(index);
|
||||
adapters.insert(0, selected_adapter);
|
||||
|
||||
@@ -7,7 +7,6 @@ use core_types::{Ctx, ExtractFootprint};
|
||||
use glam::{Affine2, UVec2, Vec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graphic_types::raster_types::Texture;
|
||||
use graphic_types::vector_types::vector::style::RenderMode;
|
||||
use rendering::{RenderParams, SvgRender, SvgRenderOutput};
|
||||
use std::fmt::Write;
|
||||
use wgpu::util::DeviceExt;
|
||||
@@ -34,9 +33,6 @@ async fn render_background<'a: 'n>(
|
||||
let mut render_params = render_params.clone();
|
||||
render_params.footprint = *footprint;
|
||||
|
||||
// Outline mode previews the artwork as it would be drawn on paper, so transparency shows as solid white instead of the checkerboard
|
||||
let solid_white_background = render_params.render_mode == RenderMode::Outline;
|
||||
|
||||
let data = match foreground_data {
|
||||
RenderOutputType::Texture(foreground_texture) => {
|
||||
let doc_to_screen = render_params.footprint.transform.as_affine2();
|
||||
@@ -47,7 +43,6 @@ async fn render_background<'a: 'n>(
|
||||
backgrounds: &metadata.backgrounds,
|
||||
document_to_screen: doc_to_screen,
|
||||
zoom: render_params.viewport_zoom.to_f32(),
|
||||
solid_white: solid_white_background,
|
||||
})
|
||||
.await;
|
||||
|
||||
@@ -63,17 +58,6 @@ async fn render_background<'a: 'n>(
|
||||
|
||||
if render_params.viewport_zoom > 0. {
|
||||
let draw_checkerboard = |render: &mut SvgRender, rect: vello::kurbo::Rect, pattern_origin: glam::DVec2, checker_id_prefix: &str| {
|
||||
if solid_white_background {
|
||||
render.leaf_tag("rect", |attributes| {
|
||||
attributes.push("x", rect.x0.to_string());
|
||||
attributes.push("y", rect.y0.to_string());
|
||||
attributes.push("width", rect.width().to_string());
|
||||
attributes.push("height", rect.height().to_string());
|
||||
attributes.push("fill", "#ffffff".to_string());
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let checker_id = format!("{checker_id_prefix}-{}", generate_uuid());
|
||||
let cell_size = 8. / render_params.viewport_zoom;
|
||||
let pattern_size = cell_size * 2.;
|
||||
@@ -164,8 +148,6 @@ pub struct CompositeBackgroundArgs<'a> {
|
||||
backgrounds: &'a [rendering::Background],
|
||||
document_to_screen: Affine2,
|
||||
zoom: f32,
|
||||
/// Draw solid white instead of the transparency checkerboard, used in Outline mode.
|
||||
solid_white: bool,
|
||||
}
|
||||
|
||||
impl AsyncWgpuPipeline for CompositeBackground {
|
||||
@@ -357,7 +339,6 @@ impl AsyncWgpuPipeline for CompositeBackground {
|
||||
backgrounds,
|
||||
document_to_screen,
|
||||
zoom,
|
||||
solid_white,
|
||||
} = args;
|
||||
|
||||
let foreground_size = foreground.size();
|
||||
@@ -381,7 +362,7 @@ impl AsyncWgpuPipeline for CompositeBackground {
|
||||
let checker_draws = if backgrounds.is_empty() {
|
||||
vec![(
|
||||
3,
|
||||
self.create_checker_bind_group(device, CompositeUniforms::fullscreen(viewport_size, screen_to_document, checker_size_doc, solid_white)),
|
||||
self.create_checker_bind_group(device, CompositeUniforms::fullscreen(viewport_size, screen_to_document, checker_size_doc)),
|
||||
)]
|
||||
} else {
|
||||
backgrounds
|
||||
@@ -397,7 +378,7 @@ impl AsyncWgpuPipeline for CompositeBackground {
|
||||
return None;
|
||||
}
|
||||
|
||||
let uniforms = CompositeUniforms::rect(min, max, document_to_screen, viewport_size, checker_size_doc, solid_white);
|
||||
let uniforms = CompositeUniforms::rect(min, max, document_to_screen, viewport_size, checker_size_doc);
|
||||
Some((6, self.create_checker_bind_group(device, uniforms)))
|
||||
})
|
||||
.collect()
|
||||
@@ -493,19 +474,19 @@ struct CompositeUniforms {
|
||||
viewport_size: [f32; 2],
|
||||
pattern_origin: [f32; 2],
|
||||
checker_size: f32,
|
||||
solid_white: f32,
|
||||
_pad: f32,
|
||||
}
|
||||
|
||||
impl CompositeUniforms {
|
||||
fn fullscreen(viewport_size: Vec2, screen_to_document: Affine2, checker_size_doc: f32, solid_white: bool) -> Self {
|
||||
Self::new(screen_to_document, Vec2::ZERO, Vec2::ZERO, viewport_size, Vec2::ZERO, checker_size_doc, solid_white)
|
||||
fn fullscreen(viewport_size: Vec2, screen_to_document: Affine2, checker_size_doc: f32) -> Self {
|
||||
Self::new(screen_to_document, Vec2::ZERO, Vec2::ZERO, viewport_size, Vec2::ZERO, checker_size_doc)
|
||||
}
|
||||
|
||||
fn rect(rect_min: Vec2, rect_max: Vec2, document_to_screen: Affine2, viewport_size: Vec2, checker_size_doc: f32, solid_white: bool) -> Self {
|
||||
Self::new(document_to_screen, rect_min, rect_max, viewport_size, rect_min, checker_size_doc, solid_white)
|
||||
fn rect(rect_min: Vec2, rect_max: Vec2, document_to_screen: Affine2, viewport_size: Vec2, checker_size_doc: f32) -> Self {
|
||||
Self::new(document_to_screen, rect_min, rect_max, viewport_size, rect_min, checker_size_doc)
|
||||
}
|
||||
|
||||
fn new(transform: Affine2, rect_min: Vec2, rect_max: Vec2, viewport_size: Vec2, pattern_origin: Vec2, checker_size: f32, solid_white: bool) -> Self {
|
||||
fn new(transform: Affine2, rect_min: Vec2, rect_max: Vec2, viewport_size: Vec2, pattern_origin: Vec2, checker_size: f32) -> Self {
|
||||
Self {
|
||||
transform_x: transform.matrix2.x_axis.to_array(),
|
||||
transform_y: transform.matrix2.y_axis.to_array(),
|
||||
@@ -515,7 +496,7 @@ impl CompositeUniforms {
|
||||
viewport_size: viewport_size.to_array(),
|
||||
pattern_origin: pattern_origin.to_array(),
|
||||
checker_size,
|
||||
solid_white: if solid_white { 1. } else { 0. },
|
||||
_pad: 0.,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ struct CompositeUniforms {
|
||||
viewport_size: vec2<f32>,
|
||||
pattern_origin: vec2<f32>,
|
||||
checker_size: f32,
|
||||
solid_white: f32,
|
||||
_pad: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
@@ -44,10 +44,7 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let tile = floor((in.document_position - uniforms.pattern_origin) / uniforms.checker_size);
|
||||
let parity = i32(tile.x + tile.y) & 1;
|
||||
var luminance = select(1.0, 0.8, parity == 1);
|
||||
if uniforms.solid_white != 0.0 {
|
||||
luminance = 1.0;
|
||||
}
|
||||
let luminance = select(1.0, 0.8, parity == 1);
|
||||
|
||||
let fw = fwidthFine(in.document_position);
|
||||
let coverage_max = 1.0 - smoothstep(uniforms.rect_max - fw, uniforms.rect_max, in.document_position);
|
||||
|
||||
@@ -7,7 +7,7 @@ struct CompositeUniforms {
|
||||
viewport_size: vec2<f32>,
|
||||
pattern_origin: vec2<f32>,
|
||||
checker_size: f32,
|
||||
solid_white: f32,
|
||||
_pad: f32,
|
||||
};
|
||||
|
||||
@group(0) @binding(0)
|
||||
@@ -40,9 +40,6 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
|
||||
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
let tile = floor((in.document_position - uniforms.pattern_origin) / uniforms.checker_size);
|
||||
let parity = i32(tile.x + tile.y) & 1;
|
||||
var luminance = vec3<f32>(select(1.0, 0.8, parity == 1));
|
||||
if uniforms.solid_white != 0.0 {
|
||||
luminance = vec3<f32>(1.0);
|
||||
}
|
||||
let luminance = vec3<f32>(select(1.0, 0.8, parity == 1));
|
||||
return vec4<f32>(luminance, 1.0);
|
||||
}
|
||||
@@ -174,8 +174,6 @@ async fn create_context<'a: 'n>(
|
||||
render_output_type,
|
||||
scale: render_config.scale,
|
||||
viewport_zoom: logical_viewport.scale_magnitudes().x,
|
||||
hide_artboard_background: render_config.hide_artboard_background,
|
||||
bake_stroke_dashes: render_config.bake_stroke_dashes,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
|
||||
@@ -24,13 +24,12 @@ use std::collections::{HashMap, HashSet};
|
||||
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
|
||||
use vector_types::subpath::{BezierHandles, ManipulatorGroup};
|
||||
use vector_types::vector::algorithms::bezpath_algorithms::{self, TValue, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath, tangent_on_bezpath};
|
||||
use vector_types::vector::algorithms::convex_hull::convex_hull_of_geometry;
|
||||
use vector_types::vector::algorithms::merge_by_distance::MergeByDistanceExt;
|
||||
use vector_types::vector::algorithms::offset_subpath::offset_bezpath;
|
||||
use vector_types::vector::algorithms::spline::{solve_spline_first_handle_closed, solve_spline_first_handle_open};
|
||||
use vector_types::vector::misc::{
|
||||
CentroidType, ExtrudeJoiningAlgorithm, HandleId, InterpolationDistribution, MergeByDistanceAlgorithm, PointSpacingType, RowsOrColumns, bezpath_from_manipulator_groups,
|
||||
bezpath_to_manipulator_groups, dvec2_to_point, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
||||
bezpath_to_manipulator_groups, handles_to_segment, is_linear, point_to_dvec2, segment_to_handles,
|
||||
};
|
||||
use vector_types::vector::style::{DashPattern, Gradient, PaintOrder, Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use vector_types::vector::{FillId, PointId, RegionId, SegmentDomain, SegmentId, StrokeId, VectorExt};
|
||||
@@ -560,67 +559,6 @@ pub fn merge_by_distance(
|
||||
content
|
||||
}
|
||||
|
||||
/// Wraps all of the input geometry in its convex hull: the shape a taut rubber band would form when stretched around it.
|
||||
///
|
||||
/// Convex portions of curved segments are kept exactly as they are, and the boundary departs from a curve only where it must, continuing along a straight bridging line that leaves and rejoins the curves at perfect tangents. The anchor points, floating points, and subpaths (open or closed) of all the input shapes are wrapped together into one combined hull.
|
||||
#[node_macro::node(category("Vector: Modifier"), path(core_types::vector))]
|
||||
async fn convex_hull<I: IntoGraphicList>(
|
||||
_: impl Ctx,
|
||||
/// The `List` of vector paths to wrap in the convex hull. Nested `List`s are automatically flattened.
|
||||
#[implementations(List<Graphic>, List<Vector>)]
|
||||
content: I,
|
||||
) -> List<Vector> {
|
||||
let content = content.into_graphic_list();
|
||||
let flattened: List<Vector> = content.clone().into_flattened_list();
|
||||
|
||||
// Gather the world-space segments and floating anchor points of every input item
|
||||
let mut segments = Vec::new();
|
||||
let mut loose_points = Vec::new();
|
||||
for index in 0..flattened.len() {
|
||||
let Some(element) = flattened.element(index) else { continue };
|
||||
let transform: DAffine2 = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let affine = Affine::new(transform.to_cols_array());
|
||||
|
||||
for bezpath in element.stroke_bezpath_iter() {
|
||||
segments.extend(bezpath.segments().map(|segment| affine * segment));
|
||||
}
|
||||
|
||||
// Anchor points not connected to any segment still participate in the hull
|
||||
let connected_points: HashSet<usize> = element.segment_domain.start_point().iter().chain(element.segment_domain.end_point()).copied().collect();
|
||||
for (point_index, &position) in element.point_domain.positions().iter().enumerate() {
|
||||
if !connected_points.contains(&point_index) {
|
||||
loose_points.push(dvec2_to_point(transform.transform_point2(position)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let hull = convex_hull_of_geometry(&segments, &loose_points);
|
||||
|
||||
// Carry over the attributes and stroke of the last input item, matching the Boolean Operation node
|
||||
let Some(last_index) = flattened.len().checked_sub(1) else { return List::new() };
|
||||
let mut attributes = flattened.clone_item_attributes(last_index);
|
||||
let last_transform: DAffine2 = flattened.attribute_cloned_or_default(ATTR_TRANSFORM, last_index);
|
||||
|
||||
// The hull geometry is built in world space, so the result item carries no transform of its own
|
||||
attributes.insert(ATTR_TRANSFORM, DAffine2::IDENTITY);
|
||||
bake_paint_transforms(&mut attributes, last_transform);
|
||||
|
||||
let mut element = Vector {
|
||||
stroke: flattened.element(last_index).map(|vector| vector.stroke.clone()).unwrap_or_default(),
|
||||
..Default::default()
|
||||
};
|
||||
element.append_bezpath(hull);
|
||||
element.set_stroke_transform(DAffine2::IDENTITY);
|
||||
|
||||
let mut result = List::new();
|
||||
result.push(Item::from_parts(element, attributes));
|
||||
|
||||
// Snapshot the input layers so the renderer can recurse into them for editor click-target preservation
|
||||
result.set_attribute(ATTR_EDITOR_MERGED_LAYERS, 0, content);
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub mod extrude_algorithms {
|
||||
use glam::DVec2;
|
||||
use kurbo::{ParamCurve, ParamCurveDeriv};
|
||||
@@ -3673,33 +3611,6 @@ mod test {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn convex_hull_wraps_multiple_items_and_floating_points() {
|
||||
// Two squares far apart, each placed by its own transform, plus a free-floating anchor point far above
|
||||
let square = Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY);
|
||||
let mut content = List::new();
|
||||
content.push(create_vector_item(square.clone(), DAffine2::IDENTITY));
|
||||
content.push(create_vector_item(square, DAffine2::from_translation(DVec2::new(100., 0.))));
|
||||
|
||||
let mut floating = Vector::default();
|
||||
floating.point_domain.push(PointId::generate(), DVec2::new(50., 200.));
|
||||
content.push(Item::new_from_element(floating));
|
||||
|
||||
let hull = super::convex_hull(Footprint::default(), content).await;
|
||||
let element = hull.element(0).unwrap();
|
||||
|
||||
// The hull is the pentagon spanning both squares' outer corners and the floating point
|
||||
let positions = element.point_domain.positions();
|
||||
assert_eq!(positions.len(), 5, "expected a pentagon, got anchors at {positions:?}");
|
||||
for expected in [DVec2::new(0., 0.), DVec2::new(110., 0.), DVec2::new(110., 10.), DVec2::new(50., 200.), DVec2::new(0., 10.)] {
|
||||
assert!(positions.iter().any(|position| position.distance(expected) < 1e-6), "expected a hull anchor near {expected}");
|
||||
}
|
||||
|
||||
// The hull geometry is emitted in world space with no residual transform
|
||||
let transform: DAffine2 = hull.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
|
||||
assert_eq!(transform, DAffine2::IDENTITY);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sample_polyline() {
|
||||
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
# Spec: "Send to Plotter" — upload the current document as SVG to a LAN print server
|
||||
|
||||
## What this is
|
||||
|
||||
We are running a conference booth where visitors draw vector artwork in Graphite at demo
|
||||
stations, and their drawing gets physically plotted with a pen on letter paper by a Cricut
|
||||
machine as a takeaway. A small HTTP print server (a separate, already-finished project) drives
|
||||
the Cricut; it accepts SVG jobs over the LAN and manages a queue with a live dashboard.
|
||||
|
||||
The missing piece, and the task for you, is on the Graphite side: an in-app action that exports
|
||||
the current document as SVG and POSTs it to that print server. Today we have to save an SVG file
|
||||
and manually upload it via the dashboard; visitors should instead be able to click one thing
|
||||
inside Graphite.
|
||||
|
||||
## Booth context (why the design looks like this)
|
||||
|
||||
- Four Windows 11 demo stations run Graphite. The booth LAN is an isolated switch with **no
|
||||
internet**: static IPs on `192.168.77.0/24` (stations are `.10`, `.20`, `.30`, `.40`), blank
|
||||
gateway. Because there is no internet, each station runs Graphite from a **local dev server**
|
||||
(`npm start`, i.e. an `http://localhost` origin), not from the production website.
|
||||
- The print server runs on the station connected to the Cricut, listening on port `4747`. At
|
||||
the booth it is expected at `http://192.168.77.10:4747`, but the host may change, so the
|
||||
endpoint URL must be user-configurable and persisted. For development, the natural default is
|
||||
`http://localhost:4747`.
|
||||
- Sending a job is safe and non-destructive: the queue is human-gated twice (a booth attendant
|
||||
resumes the paused queue from the dashboard, and each plot additionally waits for a physical
|
||||
Go button press on the machine). Graphite only needs to fire the upload and report success or
|
||||
failure; queue management, previews, and status all already exist on the server's dashboard.
|
||||
|
||||
## The endpoint
|
||||
|
||||
`POST http://<host>:4747/api/jobs`
|
||||
|
||||
Two accepted body forms; **use the raw form** (simplest):
|
||||
|
||||
1. **Raw SVG body** — any `content-type` that is not `application/json` (use
|
||||
`image/svg+xml`). The job name is taken from the `?name=` query parameter.
|
||||
2. JSON body (`content-type: application/json`): `{ "svg": "<svg …>", "name": "…", "options": { … } }`.
|
||||
|
||||
Example of the raw form:
|
||||
|
||||
```
|
||||
POST http://192.168.77.10:4747/api/jobs?name=Alices%20drawing
|
||||
content-type: image/svg+xml
|
||||
|
||||
<svg xmlns="http://www.w3.org/2000/svg" …>…</svg>
|
||||
```
|
||||
|
||||
Server behavior:
|
||||
|
||||
- **Success**: `201` with JSON `{ "id": "<job id>", "name": "<name>", "status": "queued" }`.
|
||||
- **Validation failure**: `400` with JSON `{ "error": "request body must contain an <svg>" }`
|
||||
(the body must match `/<svg[\s>]/i`). Other errors return `500` with `{ "error": "…" }`.
|
||||
- **Body limit**: 25 MB.
|
||||
- **CORS**: fully open. Every response carries `access-control-allow-origin: *`, and `OPTIONS`
|
||||
preflights are answered with `access-control-allow-methods: GET,POST,DELETE,OPTIONS` and
|
||||
`access-control-allow-headers: content-type` (plus `access-control-allow-private-network:
|
||||
true` for Chrome's private-network-access preflight). A plain browser `fetch` works.
|
||||
- If a `name` is omitted the server invents one; still, always send the document name so the
|
||||
attendant can tell jobs apart on the dashboard.
|
||||
- Do **not** send job options from Graphite (paper size, rotation, etc. exist as query
|
||||
parameters, but the booth-wide defaults are configured on the server; the client staying
|
||||
dumb is a feature).
|
||||
|
||||
## What the plotter does with the SVG (sets expectations for the export)
|
||||
|
||||
- The artwork is auto-scaled to fit 7.5×10" (letter paper minus margin) preserving aspect
|
||||
ratio, and auto-rotated to portrait when clearly landscape. Absolute units and document size
|
||||
in the SVG are irrelevant; only the aspect ratio and the shapes matter.
|
||||
- Everything is drawn with a **pen**: every path renders as its outline. Fills are not filled
|
||||
in; a filled shape plots as its contour.
|
||||
- The server already strips Graphite's artboard background: an exported artboard produces a
|
||||
background `<rect>` immediately before a `<g clip-path="url(#artboard-…)">` group, and the
|
||||
server removes exactly that rect. So exporting a document with an artboard is fine as-is.
|
||||
Known limitation: a solid background drawn as anything else (a giant `<polyline>`, a path)
|
||||
is NOT stripped and would be plotted, but that is a server concern, not yours.
|
||||
- Use the same SVG serialization as the existing file export (File > Export); the server is
|
||||
known to handle that output. Do not invent a new export path.
|
||||
|
||||
## What to build in Graphite
|
||||
|
||||
1. A menu action (e.g. **File > Send to Plotter…**, near Export) that opens a small dialog:
|
||||
- **Server address** text field, persisted across sessions (default `http://localhost:4747`).
|
||||
Accept a bare `host:port` or full origin; normalize to `<origin>/api/jobs` internally.
|
||||
- **Job name** text field, defaulting to the document name.
|
||||
- A **Send** button.
|
||||
2. On send: export the current document to an SVG string exactly as File > Export SVG would
|
||||
(whole document / all artboards, default settings), then
|
||||
`fetch(endpoint, { method: 'POST', headers: { 'content-type': 'image/svg+xml' }, body: svg })`
|
||||
with the name in the query string.
|
||||
3. Feedback:
|
||||
- Success (`201`): a brief confirmation (e.g. a toast/dialog: "Sent to plotter queue as
|
||||
'<name>'").
|
||||
- Failure: show the reason. Distinguish "could not reach the server" (network error —
|
||||
wrong address, server not running) from a server-reported error (`400`/`500` JSON
|
||||
`error` field). Booth attendants are non-experts under time pressure; the message should
|
||||
say what to check ("Is the print server running at <address>?").
|
||||
- A pending state on the button while in flight; sends should not be double-fireable.
|
||||
4. Non-goals: no queue status display, no job management, no auth, no retry logic, no
|
||||
settings beyond the address field. The server dashboard covers all of that.
|
||||
|
||||
## Testing without the plotter
|
||||
|
||||
The print server is a zero-dependency Node ≥ 20 project; run `node bin/cricut-print-server.mjs
|
||||
serve` from its repo and it listens on `:4747` even with no Cricut hardware or Design Space
|
||||
running — submitted jobs simply sit in the paused queue, visible with previews at
|
||||
`http://127.0.0.1:4747/`. That is the ideal end-to-end check: send from Graphite, see the job
|
||||
card appear with the right name and a correct preview.
|
||||
|
||||
If you don't have that repo, a sufficient mock is:
|
||||
|
||||
```js
|
||||
require('node:http').createServer((req, res) => {
|
||||
let b = '';
|
||||
req.on('data', (c) => (b += c));
|
||||
req.on('end', () => {
|
||||
const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type', 'access-control-allow-methods': 'GET,POST,DELETE,OPTIONS', 'access-control-allow-private-network': 'true' };
|
||||
if (req.method === 'OPTIONS') { res.writeHead(204, cors); return res.end(); }
|
||||
const ok = /<svg[\s>]/i.test(b);
|
||||
res.writeHead(ok ? 201 : 400, { ...cors, 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify(ok ? { id: 'test1', name: new URL(req.url, 'http://x').searchParams.get('name'), status: 'queued' } : { error: 'request body must contain an <svg>' }));
|
||||
console.log(req.method, req.url, b.length, 'bytes');
|
||||
});
|
||||
}).listen(4747);
|
||||
```
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Mixed content**: a Graphite instance served over HTTPS (the production site) cannot
|
||||
`fetch` an `http://` LAN address — the browser blocks it silently-ish. This is fine for the
|
||||
booth (stations run `http://localhost` dev builds, and localhost is a secure context allowed
|
||||
to reach private hosts), but don't be confused if a test from the production site fails;
|
||||
consider mentioning it in the failure message if `location.protocol === 'https:'` and the
|
||||
target is `http:`.
|
||||
- **Chrome private network access**: Chrome sends a special preflight when a page reaches into
|
||||
a private network. The server answers it (`access-control-allow-private-network: true`), so
|
||||
this should just work; noted here in case a future Chrome version tightens behavior.
|
||||
- The SVG can be large (procedural documents); it is sent as one POST body, well under the
|
||||
25 MB limit in practice. No chunking or compression needed.
|
||||
@@ -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'")
|
||||
|
||||
Reference in new issue
Block a user