mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-19 10:58:04 +08:00
Rework wasm initialization and reduce global state (#379)
* wasm: do the async initialization only once This allows the rest of the app to access wasm synchronously. This allows removing of a global. * provide the wasm via vue provide/inject. There's still code directly accessing the wasm. That will be changed later. * MenuBarInput: use injected wasm instead of the global instance * Let the App handle event listeners * move stateful modules into state/ * state/fullscreen: create per instance * App: load the initial document list on mount. This got lost a few commits ago. Now it's back. * state/dialog: create per instance * util/input: remove dependency on global dialog instance * state/documents: create per instance * reponse-handler: move into EditorWasm * comingSoon: move into dialog * wasm: allow instantiating multiple editors * input handlers: do not look at canvases outside the mounted App * input: listen on the container instead of the window when possible * - removed proxy from wasm-loader - integrated with js-dispatcher - state functions to classes - integrated some upstream changes * fix errors caused by merge * Getting closer: - added global state to track all instances - fix fullscreen close trigger - wasm-loader is statefull - panic across instanes * - fix outline while using editor - removed circular import rule - added editorInstance to js message constructor * - changed input handler to a class - still need a better way of handeling it in App.vue * - fixed single instance of inputManager to weakmap * - fix no-explicit-any in a few places - removed global state from input.ts * simplified two long lines * removed global state * removed $data from App * add mut self to functions in api.rs * Update Workspace.vue remove outdated import * fixed missing import * Changes throughout code review; note this causes some bugs to be fixed in a later commit * PR review round 1 * - fix coming soon bugs - changed folder structure * moved declaration to .d.ts * - changed from classes to functions - moved decs back to app.vue * removed need to export js function to rust * changed folder structure * fixed indentation breaking multiline strings * Fix eslint rule to whitelist @/../ * Simplify strip-indents implementation * replace type assertions with better annotations or proper runtime checks * Small tweaks and code rearranging improvements after second code review pass * maybe fix mouse events * Add back preventDefault for mouse scroll * code review round 2 * Comment improvements * -removed runtime checks - fixed layers not showing * - extened proxy to cover classes - stopped multiple panics from logging - Stop wasm-bindgen from mut ref counting our struct * cleaned up messageConstructors exports * Fix input and fullscreen regressions Co-authored-by: Max Fisher <maxmfishernj@gmail.com> Co-authored-by: mfish33 <32677537+mfish33@users.noreply.github.com> Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
committed by
GitHub
parent
37be856884
commit
448e72fe02
@@ -2,427 +2,446 @@
|
||||
// It serves as a thin wrapper over the editor backend API that relies
|
||||
// on the dispatcher messaging system and more complex Rust data types.
|
||||
|
||||
use crate::dispatch;
|
||||
use std::cell::{Cell, UnsafeCell};
|
||||
|
||||
use crate::helpers::Error;
|
||||
use crate::type_translators::{translate_blend_mode, translate_key, translate_tool_type};
|
||||
use crate::EDITOR_HAS_CRASHED;
|
||||
use editor::consts::FILE_SAVE_SUFFIX;
|
||||
use editor::input::input_preprocessor::ModifierKeys;
|
||||
use editor::input::mouse::{EditorMouseState, ScrollDelta, ViewportBounds};
|
||||
use editor::message_prelude::*;
|
||||
use editor::misc::EditorError;
|
||||
use editor::tool::{tool_options::ToolOptions, tools, ToolType};
|
||||
use editor::Color;
|
||||
use editor::LayerId;
|
||||
use editor::{message_prelude::*, Color};
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
/// Intentionally panic for testing purposes
|
||||
// To avoid wasm-bindgen from checking mutable reference issues using WasmRefCell
|
||||
// we must make all methods take a non mutable reference to self. Not doing this creates
|
||||
// an issue when rust calls into JS which calls back to rust in the same call stack.
|
||||
#[wasm_bindgen]
|
||||
pub fn intentional_panic() {
|
||||
panic!();
|
||||
pub struct Editor {
|
||||
editor: UnsafeCell<editor::Editor>,
|
||||
instance_received_crashed: Cell<bool>,
|
||||
handle_response: js_sys::Function,
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
impl Editor {
|
||||
#[wasm_bindgen(constructor)]
|
||||
pub fn new(handle_response: js_sys::Function) -> Editor {
|
||||
Editor {
|
||||
editor: UnsafeCell::new(editor::Editor::new()),
|
||||
instance_received_crashed: Cell::new(false),
|
||||
handle_response,
|
||||
}
|
||||
}
|
||||
|
||||
// Sends a message to the dispatcher in the Editor Backend
|
||||
fn dispatch<T: Into<Message>>(&self, message: T) {
|
||||
// Process no further messages after a crash to avoid spamming the console
|
||||
let has_crashed = EDITOR_HAS_CRASHED.with(|crash_state| crash_state.borrow().clone());
|
||||
if let Some(message) = has_crashed {
|
||||
if !self.instance_received_crashed.get() {
|
||||
self.handle_response(message);
|
||||
self.instance_received_crashed.set(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let editor = unsafe { self.editor.get().as_mut().unwrap() };
|
||||
// Dispatch the message and receive a vector of FrontendMessage responses
|
||||
let responses = editor.handle_message(message.into());
|
||||
for response in responses.into_iter() {
|
||||
// Send each FrontendMessage to the JavaScript frontend
|
||||
self.handle_response(response);
|
||||
}
|
||||
}
|
||||
|
||||
// Sends a FrontendMessage to JavaScript
|
||||
fn handle_response(&self, message: FrontendMessage) {
|
||||
let message_type = message.to_discriminant().local_name();
|
||||
let message_data = JsValue::from_serde(&message).expect("Failed to serialize FrontendMessage");
|
||||
|
||||
let js_return_value = self.handle_response.call2(&JsValue::null(), &JsValue::from(message_type), &message_data);
|
||||
|
||||
if let Err(error) = js_return_value {
|
||||
log::error!(
|
||||
"While handling FrontendMessage \"{:?}\", JavaScript threw an error: {:?}",
|
||||
message.to_discriminant().local_name(),
|
||||
error,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Modify the currently selected tool in the document state store
|
||||
pub fn select_tool(&self, tool: String) -> Result<(), JsValue> {
|
||||
match translate_tool_type(&tool) {
|
||||
Some(tool) => {
|
||||
let message = ToolMessage::ActivateTool(tool);
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(Error::new(&format!("Couldn't select {} because it was not recognized as a valid tool", tool)).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the options for a given tool
|
||||
pub fn set_tool_options(&self, tool: String, options: &JsValue) -> Result<(), JsValue> {
|
||||
match options.into_serde::<ToolOptions>() {
|
||||
Ok(options) => match translate_tool_type(&tool) {
|
||||
Some(tool) => {
|
||||
let message = ToolMessage::SetToolOptions(tool, options);
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(Error::new(&format!("Couldn't set options for {} because it was not recognized as a valid tool", tool)).into()),
|
||||
},
|
||||
Err(err) => Err(Error::new(&format!("Invalid JSON for ToolOptions: {}", err)).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a message to a given tool
|
||||
pub fn send_tool_message(&self, tool: String, message: &JsValue) -> Result<(), JsValue> {
|
||||
let tool_message = match translate_tool_type(&tool) {
|
||||
Some(tool) => match tool {
|
||||
ToolType::Select => match message.into_serde::<tools::select::SelectMessage>() {
|
||||
Ok(select_message) => Ok(ToolMessage::Select(select_message)),
|
||||
Err(err) => Err(Error::new(&format!("Invalid message for {}: {}", tool, err)).into()),
|
||||
},
|
||||
_ => Err(Error::new(&format!("Tool message sending not implemented for {}", tool)).into()),
|
||||
},
|
||||
None => Err(Error::new(&format!("Couldn't send message for {} because it was not recognized as a valid tool", tool)).into()),
|
||||
};
|
||||
|
||||
match tool_message {
|
||||
Ok(message) => {
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn select_document(&self, document: usize) {
|
||||
let message = DocumentsMessage::SelectDocument(document);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn get_open_documents_list(&self) {
|
||||
let message = DocumentsMessage::UpdateOpenDocumentsList;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn new_document(&self) {
|
||||
let message = DocumentsMessage::NewDocument;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn open_document(&self) {
|
||||
let message = DocumentsMessage::OpenDocument;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn open_document_file(&self, name: String, content: String) {
|
||||
let message = DocumentsMessage::OpenDocumentFile(name, content);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn save_document(&self) {
|
||||
let message = DocumentMessage::SaveDocument;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn close_document(&self, document: usize) {
|
||||
let message = DocumentsMessage::CloseDocument(document);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn close_all_documents(&self) {
|
||||
let message = DocumentsMessage::CloseAllDocuments;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn close_active_document_with_confirmation(&self) {
|
||||
let message = DocumentsMessage::CloseActiveDocumentWithConfirmation;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
pub fn close_all_documents_with_confirmation(&self) {
|
||||
let message = DocumentsMessage::CloseAllDocumentsWithConfirmation;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn request_about_graphite_dialog(&self) {
|
||||
let message = DocumentsMessage::RequestAboutGraphiteDialog;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Send new bounds when document panel viewports get resized or moved within the editor
|
||||
/// [left, top, right, bottom]...
|
||||
#[wasm_bindgen]
|
||||
pub fn bounds_of_viewports(&self, bounds_of_viewports: &[f64]) {
|
||||
let chunked: Vec<_> = bounds_of_viewports.chunks(4).map(ViewportBounds::from_slice).collect();
|
||||
|
||||
let message = InputPreprocessorMessage::BoundsOfViewports(chunked);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse movement within the screenspace bounds of the viewport
|
||||
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::MouseMove(editor_mouse_state, modifier_keys);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse scrolling within the screenspace bounds of the viewport
|
||||
pub fn on_mouse_scroll(&self, x: f64, y: f64, mouse_keys: u8, wheel_delta_x: i32, wheel_delta_y: i32, wheel_delta_z: i32, 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::MouseScroll(editor_mouse_state, modifier_keys);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A mouse button depressed within screenspace the bounds of the viewport
|
||||
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::MouseDown(editor_mouse_state, modifier_keys);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A mouse button released
|
||||
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::MouseUp(editor_mouse_state, modifier_keys);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A keyboard button depressed within screenspace the bounds of the viewport
|
||||
pub fn on_key_down(&self, name: String, modifiers: u8) {
|
||||
let key = translate_key(&name);
|
||||
let modifiers = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
log::trace!("Key down {:?}, name: {}, modifiers: {:?}", key, name, modifiers);
|
||||
|
||||
let message = InputPreprocessorMessage::KeyDown(key, modifiers);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// A keyboard button released
|
||||
pub fn on_key_up(&self, name: String, modifiers: u8) {
|
||||
let key = translate_key(&name);
|
||||
let modifiers = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
log::trace!("Key up {:?}, name: {}, modifiers: {:?}", key, name, modifiers);
|
||||
|
||||
let message = InputPreprocessorMessage::KeyUp(key, modifiers);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Update primary color
|
||||
pub fn update_primary_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let primary_color = match Color::from_rgbaf32(red, green, blue, alpha) {
|
||||
Some(color) => color,
|
||||
None => return Err(Error::new("Invalid color").into()),
|
||||
};
|
||||
|
||||
let message = ToolMessage::SelectPrimaryColor(primary_color);
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update secondary color
|
||||
pub fn update_secondary_color(&self, red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let secondary_color = match Color::from_rgbaf32(red, green, blue, alpha) {
|
||||
Some(color) => color,
|
||||
None => return Err(Error::new("Invalid color").into()),
|
||||
};
|
||||
|
||||
let message = ToolMessage::SelectSecondaryColor(secondary_color);
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Swap primary and secondary color
|
||||
pub fn swap_colors(&self) {
|
||||
let message = ToolMessage::SwapColors;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Reset primary and secondary colors to their defaults
|
||||
pub fn reset_colors(&self) {
|
||||
let message = ToolMessage::ResetColors;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Undo history one step
|
||||
pub fn undo(&self) {
|
||||
let message = DocumentMessage::Undo;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Redo history one step
|
||||
pub fn redo(&self) {
|
||||
let message = DocumentMessage::Redo;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Select all layers
|
||||
pub fn select_all_layers(&self) {
|
||||
let message = DocumentMessage::SelectAllLayers;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Deselect all layers
|
||||
pub fn deselect_all_layers(&self) {
|
||||
let message = DocumentMessage::DeselectAllLayers;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Reorder selected layer
|
||||
pub fn reorder_selected_layers(&self, delta: i32) {
|
||||
let message = DocumentMessage::ReorderSelectedLayers(delta);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Set the blend mode for the selected layers
|
||||
pub fn set_blend_mode_for_selected_layers(&self, blend_mode_svg_style_name: String) -> Result<(), JsValue> {
|
||||
let blend_mode = translate_blend_mode(blend_mode_svg_style_name.as_str());
|
||||
|
||||
match blend_mode {
|
||||
Some(mode) => {
|
||||
let message = DocumentMessage::SetBlendModeForSelectedLayers(mode);
|
||||
self.dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(Error::new(&EditorError::Misc("UnknownBlendMode".to_string()).to_string()).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the opacity for the selected layers
|
||||
pub fn set_opacity_for_selected_layers(&self, opacity_percent: f64) {
|
||||
let message = DocumentMessage::SetOpacityForSelectedLayers(opacity_percent / 100.);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Export the document
|
||||
pub fn export_document(&self) {
|
||||
let message = DocumentMessage::ExportDocument;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Set snapping disabled / enabled
|
||||
pub fn set_snapping(&self, new_status: bool) {
|
||||
let message = DocumentMessage::SetSnapping(new_status);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Sets the zoom to the value
|
||||
pub fn set_canvas_zoom(&self, new_zoom: f64) {
|
||||
let message = MovementMessage::SetCanvasZoom(new_zoom);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Zoom in to the next step
|
||||
pub fn increase_canvas_zoom(&self) {
|
||||
let message = MovementMessage::IncreaseCanvasZoom;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Zoom out to the next step
|
||||
pub fn decrease_canvas_zoom(&self) {
|
||||
let message = MovementMessage::DecreaseCanvasZoom;
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Sets the rotation to the new value (in radians)
|
||||
pub fn set_rotation(&self, new_radians: f64) {
|
||||
let message = MovementMessage::SetCanvasRotation(new_radians);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
pub fn translate_canvas(&self, delta_x: f64, delta_y: f64) {
|
||||
let message = MovementMessage::TranslateCanvas((delta_x, delta_y).into());
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
pub fn translate_canvas_by_fraction(&self, delta_x: f64, delta_y: f64) {
|
||||
let message = MovementMessage::TranslateCanvasByViewportFraction((delta_x, delta_y).into());
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Update the list of selected layers. The layer paths have to be stored in one array and are separated by LayerId::MAX
|
||||
pub fn select_layers(&self, paths: Vec<LayerId>) {
|
||||
let paths = paths.split(|id| *id == LayerId::MAX).map(|path| path.to_vec()).collect();
|
||||
|
||||
let message = DocumentMessage::SetSelectedLayers(paths);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle visibility of a layer from the layer list
|
||||
pub fn toggle_layer_visibility(&self, path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::ToggleLayerVisibility(path);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle expansions state of a layer from the layer list
|
||||
pub fn toggle_layer_expansion(&self, path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::ToggleLayerExpansion(path);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Renames a layer from the layer list
|
||||
pub fn rename_layer(&self, path: Vec<LayerId>, new_name: String) {
|
||||
let message = DocumentMessage::RenameLayer(path, new_name);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Deletes a layer from the layer list
|
||||
pub fn delete_layer(&self, path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::DeleteLayer(path);
|
||||
self.dispatch(message);
|
||||
}
|
||||
|
||||
/// Requests the backend to add a layer to the layer list
|
||||
pub fn add_folder(&self, path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::CreateFolder(path);
|
||||
self.dispatch(message);
|
||||
}
|
||||
}
|
||||
|
||||
/// Access a handle to WASM memory
|
||||
#[wasm_bindgen]
|
||||
pub fn wasm_memory() -> JsValue {
|
||||
wasm_bindgen::memory()
|
||||
}
|
||||
|
||||
/// Modify the currently selected tool in the document state store
|
||||
/// Intentionally panic for debugging purposes
|
||||
#[wasm_bindgen]
|
||||
pub fn select_tool(tool: String) -> Result<(), JsValue> {
|
||||
match translate_tool_type(&tool) {
|
||||
Some(tool) => {
|
||||
let message = ToolMessage::ActivateTool(tool);
|
||||
dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(Error::new(&format!("Couldn't select {} because it was not recognized as a valid tool", tool)).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the options for a given tool
|
||||
#[wasm_bindgen]
|
||||
pub fn set_tool_options(tool: String, options: &JsValue) -> Result<(), JsValue> {
|
||||
match options.into_serde::<ToolOptions>() {
|
||||
Ok(options) => match translate_tool_type(&tool) {
|
||||
Some(tool) => {
|
||||
let message = ToolMessage::SetToolOptions(tool, options);
|
||||
dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(Error::new(&format!("Couldn't set options for {} because it was not recognized as a valid tool", tool)).into()),
|
||||
},
|
||||
Err(err) => Err(Error::new(&format!("Invalid JSON for ToolOptions: {}", err)).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a message to a given tool
|
||||
#[wasm_bindgen]
|
||||
pub fn send_tool_message(tool: String, message: &JsValue) -> Result<(), JsValue> {
|
||||
let tool_message = match translate_tool_type(&tool) {
|
||||
Some(tool) => match tool {
|
||||
ToolType::Select => match message.into_serde::<tools::select::SelectMessage>() {
|
||||
Ok(select_message) => Ok(ToolMessage::Select(select_message)),
|
||||
Err(err) => Err(Error::new(&format!("Invalid message for {}: {}", tool, err)).into()),
|
||||
},
|
||||
_ => Err(Error::new(&format!("Tool message sending not implemented for {}", tool)).into()),
|
||||
},
|
||||
None => Err(Error::new(&format!("Couldn't send message for {} because it was not recognized as a valid tool", tool)).into()),
|
||||
};
|
||||
|
||||
match tool_message {
|
||||
Ok(message) => {
|
||||
dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn select_document(document: usize) {
|
||||
let message = DocumentsMessage::SelectDocument(document);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn get_open_documents_list() {
|
||||
let message = DocumentsMessage::UpdateOpenDocumentsList;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn new_document() {
|
||||
let message = DocumentsMessage::NewDocument;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn open_document() {
|
||||
let message = DocumentsMessage::OpenDocument;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn open_document_file(name: String, content: String) {
|
||||
let message = DocumentsMessage::OpenDocumentFile(name, content);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn save_document() {
|
||||
let message = DocumentMessage::SaveDocument;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn close_document(document: usize) {
|
||||
let message = DocumentsMessage::CloseDocument(document);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn close_all_documents() {
|
||||
let message = DocumentsMessage::CloseAllDocuments;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn close_active_document_with_confirmation() {
|
||||
let message = DocumentsMessage::CloseActiveDocumentWithConfirmation;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn close_all_documents_with_confirmation() {
|
||||
let message = DocumentsMessage::CloseAllDocumentsWithConfirmation;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn request_about_graphite_dialog() {
|
||||
let message = DocumentsMessage::RequestAboutGraphiteDialog;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Send new bounds when document panel viewports get resized or moved within the editor
|
||||
/// [left, top, right, bottom]...
|
||||
#[wasm_bindgen]
|
||||
pub fn bounds_of_viewports(bounds_of_viewports: &[f64]) {
|
||||
let chunked: Vec<_> = bounds_of_viewports.chunks(4).map(ViewportBounds::from_slice).collect();
|
||||
|
||||
let message = InputPreprocessorMessage::BoundsOfViewports(chunked);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse movement within the screenspace bounds of the viewport
|
||||
#[wasm_bindgen]
|
||||
pub fn on_mouse_move(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::MouseMove(editor_mouse_state, modifier_keys);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Mouse scrolling within the screenspace bounds of the viewport
|
||||
#[wasm_bindgen]
|
||||
pub fn on_mouse_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: i32, wheel_delta_y: i32, wheel_delta_z: i32, 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::MouseScroll(editor_mouse_state, modifier_keys);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// A mouse button depressed within screenspace the bounds of the viewport
|
||||
#[wasm_bindgen]
|
||||
pub fn on_mouse_down(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::MouseDown(editor_mouse_state, modifier_keys);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// A mouse button released
|
||||
#[wasm_bindgen]
|
||||
pub fn on_mouse_up(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::MouseUp(editor_mouse_state, modifier_keys);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// A keyboard button depressed within screenspace the bounds of the viewport
|
||||
#[wasm_bindgen]
|
||||
pub fn on_key_down(name: String, modifiers: u8) {
|
||||
let key = translate_key(&name);
|
||||
let modifiers = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
log::trace!("Key down {:?}, name: {}, modifiers: {:?}", key, name, modifiers);
|
||||
|
||||
let message = InputPreprocessorMessage::KeyDown(key, modifiers);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// A keyboard button released
|
||||
#[wasm_bindgen]
|
||||
pub fn on_key_up(name: String, modifiers: u8) {
|
||||
let key = translate_key(&name);
|
||||
let modifiers = ModifierKeys::from_bits(modifiers).expect("Invalid modifier keys");
|
||||
|
||||
log::trace!("Key up {:?}, name: {}, modifiers: {:?}", key, name, modifiers);
|
||||
|
||||
let message = InputPreprocessorMessage::KeyUp(key, modifiers);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Update primary color
|
||||
#[wasm_bindgen]
|
||||
pub fn update_primary_color(red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let primary_color = match Color::from_rgbaf32(red, green, blue, alpha) {
|
||||
Some(color) => color,
|
||||
None => return Err(Error::new("Invalid color").into()),
|
||||
};
|
||||
|
||||
let message = ToolMessage::SelectPrimaryColor(primary_color);
|
||||
dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update secondary color
|
||||
#[wasm_bindgen]
|
||||
pub fn update_secondary_color(red: f32, green: f32, blue: f32, alpha: f32) -> Result<(), JsValue> {
|
||||
let secondary_color = match Color::from_rgbaf32(red, green, blue, alpha) {
|
||||
Some(color) => color,
|
||||
None => return Err(Error::new("Invalid color").into()),
|
||||
};
|
||||
|
||||
let message = ToolMessage::SelectSecondaryColor(secondary_color);
|
||||
dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Swap primary and secondary color
|
||||
#[wasm_bindgen]
|
||||
pub fn swap_colors() {
|
||||
let message = ToolMessage::SwapColors;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Reset primary and secondary colors to their defaults
|
||||
#[wasm_bindgen]
|
||||
pub fn reset_colors() {
|
||||
let message = ToolMessage::ResetColors;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Undo history one step
|
||||
#[wasm_bindgen]
|
||||
pub fn undo() {
|
||||
let message = DocumentMessage::Undo;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Redo history one step
|
||||
#[wasm_bindgen]
|
||||
pub fn redo() {
|
||||
let message = DocumentMessage::Redo;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Select all layers
|
||||
#[wasm_bindgen]
|
||||
pub fn select_all_layers() {
|
||||
let message = DocumentMessage::SelectAllLayers;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Deselect all layers
|
||||
#[wasm_bindgen]
|
||||
pub fn deselect_all_layers() {
|
||||
let message = DocumentMessage::DeselectAllLayers;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Reorder selected layer
|
||||
#[wasm_bindgen]
|
||||
pub fn reorder_selected_layers(delta: i32) {
|
||||
let message = DocumentMessage::ReorderSelectedLayers(delta);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Set the blend mode for the selected layers
|
||||
#[wasm_bindgen]
|
||||
pub fn set_blend_mode_for_selected_layers(blend_mode_svg_style_name: String) -> Result<(), JsValue> {
|
||||
let blend_mode = translate_blend_mode(blend_mode_svg_style_name.as_str());
|
||||
|
||||
match blend_mode {
|
||||
Some(mode) => {
|
||||
let message = DocumentMessage::SetBlendModeForSelectedLayers(mode);
|
||||
dispatch(message);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
None => Err(Error::new(&EditorError::Misc("UnknownBlendMode".to_string()).to_string()).into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the opacity for the selected layers
|
||||
#[wasm_bindgen]
|
||||
pub fn set_opacity_for_selected_layers(opacity_percent: f64) {
|
||||
let message = DocumentMessage::SetOpacityForSelectedLayers(opacity_percent / 100.);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Export the document
|
||||
#[wasm_bindgen]
|
||||
pub fn export_document() {
|
||||
let message = DocumentMessage::ExportDocument;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Set snapping disabled / enabled
|
||||
#[wasm_bindgen]
|
||||
pub fn set_snapping(new_status: bool) {
|
||||
let message = DocumentMessage::SetSnapping(new_status);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Sets the zoom to the value
|
||||
#[wasm_bindgen]
|
||||
pub fn set_canvas_zoom(new_zoom: f64) {
|
||||
let message = MovementMessage::SetCanvasZoom(new_zoom);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Zoom in to the next step
|
||||
#[wasm_bindgen]
|
||||
pub fn increase_canvas_zoom() {
|
||||
let message = MovementMessage::IncreaseCanvasZoom;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Zoom out to the next step
|
||||
#[wasm_bindgen]
|
||||
pub fn decrease_canvas_zoom() {
|
||||
let message = MovementMessage::DecreaseCanvasZoom;
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Sets the rotation to the new value (in radians)
|
||||
#[wasm_bindgen]
|
||||
pub fn set_rotation(new_radians: f64) {
|
||||
let message = MovementMessage::SetCanvasRotation(new_radians);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
#[wasm_bindgen]
|
||||
pub fn translate_canvas(delta_x: f64, delta_y: f64) {
|
||||
let message = MovementMessage::TranslateCanvas((delta_x, delta_y).into());
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Translates document (in viewport coords)
|
||||
#[wasm_bindgen]
|
||||
pub fn translate_canvas_by_fraction(delta_x: f64, delta_y: f64) {
|
||||
let message = MovementMessage::TranslateCanvasByViewportFraction((delta_x, delta_y).into());
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Update the list of selected layers. The layer paths have to be stored in one array and are separated by LayerId::MAX
|
||||
#[wasm_bindgen]
|
||||
pub fn select_layers(paths: Vec<LayerId>) {
|
||||
let paths = paths.split(|id| *id == LayerId::MAX).map(|path| path.to_vec()).collect();
|
||||
|
||||
let message = DocumentMessage::SetSelectedLayers(paths);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle visibility of a layer from the layer list
|
||||
#[wasm_bindgen]
|
||||
pub fn toggle_layer_visibility(path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::ToggleLayerVisibility(path);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Toggle expansions state of a layer from the layer list
|
||||
#[wasm_bindgen]
|
||||
pub fn toggle_layer_expansion(path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::ToggleLayerExpansion(path);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Renames a layer from the layer list
|
||||
#[wasm_bindgen]
|
||||
pub fn rename_layer(path: Vec<LayerId>, new_name: String) {
|
||||
let message = DocumentMessage::RenameLayer(path, new_name);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Deletes a layer from the layer list
|
||||
#[wasm_bindgen]
|
||||
pub fn delete_layer(path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::DeleteLayer(path);
|
||||
dispatch(message);
|
||||
}
|
||||
|
||||
/// Requests the backend to add a layer to the layer list
|
||||
#[wasm_bindgen]
|
||||
pub fn add_folder(path: Vec<LayerId>) {
|
||||
let message = DocumentMessage::CreateFolder(path);
|
||||
dispatch(message);
|
||||
pub fn intentional_panic() {
|
||||
panic!();
|
||||
}
|
||||
|
||||
/// Get the constant FILE_SAVE_SUFFIX
|
||||
|
||||
@@ -3,17 +3,15 @@ mod helpers;
|
||||
pub mod logging;
|
||||
pub mod type_translators;
|
||||
|
||||
use editor::{message_prelude::*, Editor};
|
||||
use editor::message_prelude::FrontendMessage;
|
||||
use logging::WasmLog;
|
||||
use std::cell::RefCell;
|
||||
use std::panic;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
// Set up the persistent editor backend state (the thread_local macro provides a way to initialize static variables with non-constant functions)
|
||||
thread_local! { pub static EDITOR_STATE: RefCell<Editor> = RefCell::new(Editor::new()); }
|
||||
// Set up the persistent editor backend state
|
||||
static LOGGER: WasmLog = WasmLog;
|
||||
static EDITOR_HAS_CRASHED: AtomicBool = AtomicBool::new(false);
|
||||
thread_local! { pub static EDITOR_HAS_CRASHED: RefCell<Option<FrontendMessage>> = RefCell::new(None); }
|
||||
|
||||
// Initialize the backend
|
||||
#[wasm_bindgen(start)]
|
||||
@@ -30,44 +28,5 @@ fn panic_hook(info: &panic::PanicInfo) {
|
||||
let title = "The editor crashed — sorry about that".to_string();
|
||||
let description = "An internal error occurred. Reload the editor to continue. Please report this by filing an issue on GitHub.".to_string();
|
||||
|
||||
handle_response(FrontendMessage::DisplayPanic { panic_info, title, description });
|
||||
|
||||
EDITOR_HAS_CRASHED.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
|
||||
// Sends a message to the dispatcher in the Editor Backend
|
||||
fn dispatch<T: Into<Message>>(message: T) {
|
||||
// Process no further messages after a crash to avoid spamming the console
|
||||
if EDITOR_HAS_CRASHED.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Dispatch the message and receive a vector of FrontendMessage responses
|
||||
let responses = EDITOR_STATE.with(|state| state.try_borrow_mut().ok().map(|mut state| state.handle_message(message.into())));
|
||||
for response in responses.unwrap_or_default().into_iter() {
|
||||
// Send each FrontendMessage to the JavaScript frontend
|
||||
handle_response(response);
|
||||
}
|
||||
}
|
||||
|
||||
// Sends a FrontendMessage to JavaScript
|
||||
fn handle_response(message: FrontendMessage) {
|
||||
let message_type = message.to_discriminant().local_name();
|
||||
let message_data = JsValue::from_serde(&message).expect("Failed to serialize FrontendMessage");
|
||||
|
||||
let js_return_value = handleJsMessage(message_type, message_data);
|
||||
if let Err(error) = js_return_value {
|
||||
log::error!(
|
||||
"While handling FrontendMessage \"{:?}\", JavaScript threw an error: {:?}",
|
||||
message.to_discriminant().local_name(),
|
||||
error,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// The JavaScript function to call into with each FrontendMessage
|
||||
#[wasm_bindgen(module = "/../src/utilities/js-message-dispatcher-binding.ts")]
|
||||
extern "C" {
|
||||
#[wasm_bindgen(catch)]
|
||||
fn handleJsMessage(responseType: String, responseData: JsValue) -> Result<(), JsValue>;
|
||||
EDITOR_HAS_CRASHED.with(|crash_status| crash_status.borrow_mut().replace(FrontendMessage::DisplayPanic { panic_info, title, description }));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user