Dispatcher::handle_message does not need Result anymore (#365)

* Dispatcher::handle_message does not need Result anymore (1)

Callers can get rid of result handling, too.

* Dispatcher::handle_message does not need Result anymore (2)

* Dispatcher::handle_message does not need Result anymore (3) cargo fmt
This commit is contained in:
phimuemue
2021-08-30 21:41:58 -07:00
committed by Keavon Chambers
parent 16a7877a23
commit 2ef9038667
4 changed files with 91 additions and 100 deletions
+35 -40
View File
@@ -1,4 +1,4 @@
use crate::{message_prelude::*, EditorError}; use crate::message_prelude::*;
pub use crate::document::DocumentsMessageHandler; pub use crate::document::DocumentsMessageHandler;
pub use crate::input::{InputMapper, InputPreprocessor}; pub use crate::input::{InputMapper, InputPreprocessor};
@@ -26,7 +26,7 @@ const GROUP_MESSAGES: &[MessageDiscriminant] = &[
]; ];
impl Dispatcher { impl Dispatcher {
pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Result<(), EditorError> { pub fn handle_message<T: Into<Message>>(&mut self, message: T) {
self.messages.push_back(message.into()); self.messages.push_back(message.into());
use Message::*; use Message::*;
@@ -50,7 +50,6 @@ impl Dispatcher {
} }
} }
} }
Ok(())
} }
pub fn collect_actions(&self) -> ActionList { pub fn collect_actions(&self) -> ActionList {
@@ -126,8 +125,8 @@ mod test {
let mut editor = create_editor_with_three_layers(); let mut editor = create_editor_with_three_layers();
let document_before_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_before_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
editor.handle_message(DocumentsMessage::Copy).unwrap(); editor.handle_message(DocumentsMessage::Copy);
editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 }).unwrap(); editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 });
let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
let layers_before_copy = document_before_copy.root.as_folder().unwrap().layers(); let layers_before_copy = document_before_copy.root.as_folder().unwrap().layers();
@@ -158,9 +157,9 @@ mod test {
let document_before_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_before_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
let shape_id = document_before_copy.root.as_folder().unwrap().layer_ids[1]; let shape_id = document_before_copy.root.as_folder().unwrap().layer_ids[1];
editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![shape_id]])).unwrap(); editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![shape_id]]));
editor.handle_message(DocumentsMessage::Copy).unwrap(); editor.handle_message(DocumentsMessage::Copy);
editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 }).unwrap(); editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 });
let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
@@ -192,40 +191,36 @@ mod test {
const LINE_INDEX: usize = 0; const LINE_INDEX: usize = 0;
const PEN_INDEX: usize = 1; const PEN_INDEX: usize = 1;
editor.handle_message(DocumentMessage::CreateFolder(vec![])).unwrap(); editor.handle_message(DocumentMessage::CreateFolder(vec![]));
let document_before_added_shapes = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_before_added_shapes = editor.dispatcher.documents_message_handler.active_document().document.clone();
let folder_id = document_before_added_shapes.root.as_folder().unwrap().layer_ids[FOLDER_INDEX]; let folder_id = document_before_added_shapes.root.as_folder().unwrap().layer_ids[FOLDER_INDEX];
// TODO: This adding of a Line and Pen should be rewritten using the corresponding functions in EditorTestUtils. // TODO: This adding of a Line and Pen should be rewritten using the corresponding functions in EditorTestUtils.
// This has not been done yet as the line and pen tool are not yet able to add layers to the currently selected folder // This has not been done yet as the line and pen tool are not yet able to add layers to the currently selected folder
editor editor.handle_message(Operation::AddLine {
.handle_message(Operation::AddLine { path: vec![folder_id, LINE_INDEX as u64],
path: vec![folder_id, LINE_INDEX as u64], insert_index: 0,
insert_index: 0, transform: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
transform: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], style: Default::default(),
style: Default::default(), });
})
.unwrap();
editor editor.handle_message(Operation::AddPen {
.handle_message(Operation::AddPen { path: vec![folder_id, PEN_INDEX as u64],
path: vec![folder_id, PEN_INDEX as u64], insert_index: 0,
insert_index: 0, transform: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
transform: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], style: Default::default(),
style: Default::default(), points: vec![(10.0, 20.0), (30.0, 40.0)],
points: vec![(10.0, 20.0), (30.0, 40.0)], });
})
.unwrap();
editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![folder_id]])).unwrap(); editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![folder_id]]));
let document_before_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_before_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
editor.handle_message(DocumentsMessage::Copy).unwrap(); editor.handle_message(DocumentsMessage::Copy);
editor.handle_message(DocumentMessage::DeleteSelectedLayers).unwrap(); editor.handle_message(DocumentMessage::DeleteSelectedLayers);
editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 }).unwrap(); editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 });
editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 }).unwrap(); editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 });
let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
@@ -282,12 +277,12 @@ mod test {
let rect_id = document_before_copy.root.as_folder().unwrap().layer_ids[RECT_INDEX]; let rect_id = document_before_copy.root.as_folder().unwrap().layer_ids[RECT_INDEX];
let ellipse_id = document_before_copy.root.as_folder().unwrap().layer_ids[ELLIPSE_INDEX]; let ellipse_id = document_before_copy.root.as_folder().unwrap().layer_ids[ELLIPSE_INDEX];
editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![rect_id], vec![ellipse_id]])).unwrap(); editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![rect_id], vec![ellipse_id]]));
editor.handle_message(DocumentsMessage::Copy).unwrap(); editor.handle_message(DocumentsMessage::Copy);
editor.handle_message(DocumentMessage::DeleteSelectedLayers).unwrap(); editor.handle_message(DocumentMessage::DeleteSelectedLayers);
editor.draw_rect(0., 800., 12., 200.); editor.draw_rect(0., 800., 12., 200.);
editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 }).unwrap(); editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 });
editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 }).unwrap(); editor.handle_message(DocumentsMessage::PasteIntoFolder { path: vec![], insert_index: -1 });
let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone(); let document_after_copy = editor.dispatcher.documents_message_handler.active_document().document.clone();
@@ -316,17 +311,17 @@ mod test {
let verify_order = |handler: &mut DocumentMessageHandler| (handler.all_layers_sorted(), handler.non_selected_layers_sorted(), handler.selected_layers_sorted()); let verify_order = |handler: &mut DocumentMessageHandler| (handler.all_layers_sorted(), handler.non_selected_layers_sorted(), handler.selected_layers_sorted());
editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![0], vec![2]])).unwrap(); editor.handle_message(DocumentMessage::SetSelectedLayers(vec![vec![0], vec![2]]));
editor.handle_message(DocumentMessage::ReorderSelectedLayers(1)).unwrap(); editor.handle_message(DocumentMessage::ReorderSelectedLayers(1));
let (all, non_selected, selected) = verify_order(&mut editor.dispatcher.documents_message_handler.active_document_mut()); let (all, non_selected, selected) = verify_order(&mut editor.dispatcher.documents_message_handler.active_document_mut());
assert_eq!(all, non_selected.into_iter().chain(selected.into_iter()).collect::<Vec<_>>()); assert_eq!(all, non_selected.into_iter().chain(selected.into_iter()).collect::<Vec<_>>());
editor.handle_message(DocumentMessage::ReorderSelectedLayers(-1)).unwrap(); editor.handle_message(DocumentMessage::ReorderSelectedLayers(-1));
let (all, non_selected, selected) = verify_order(&mut editor.dispatcher.documents_message_handler.active_document_mut()); let (all, non_selected, selected) = verify_order(&mut editor.dispatcher.documents_message_handler.active_document_mut());
assert_eq!(all, selected.into_iter().chain(non_selected.into_iter()).collect::<Vec<_>>()); assert_eq!(all, selected.into_iter().chain(non_selected.into_iter()).collect::<Vec<_>>());
editor.handle_message(DocumentMessage::ReorderSelectedLayers(i32::MAX)).unwrap(); editor.handle_message(DocumentMessage::ReorderSelectedLayers(i32::MAX));
let (all, non_selected, selected) = verify_order(&mut editor.dispatcher.documents_message_handler.active_document_mut()); let (all, non_selected, selected) = verify_order(&mut editor.dispatcher.documents_message_handler.active_document_mut());
assert_eq!(all, non_selected.into_iter().chain(selected.into_iter()).collect::<Vec<_>>()); assert_eq!(all, non_selected.into_iter().chain(selected.into_iter()).collect::<Vec<_>>());
} }
+5 -6
View File
@@ -39,12 +39,11 @@ impl Editor {
Self { dispatcher: Dispatcher::new() } Self { dispatcher: Dispatcher::new() }
} }
pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Result<Vec<FrontendMessage>, EditorError> { pub fn handle_message<T: Into<Message>>(&mut self, message: T) -> Vec<FrontendMessage> {
self.dispatcher.handle_message(message).map(|_| { self.dispatcher.handle_message(message);
let mut responses = Vec::new(); let mut responses = Vec::new();
std::mem::swap(&mut responses, &mut self.dispatcher.responses); std::mem::swap(&mut responses, &mut self.dispatcher.responses);
responses responses
})
} }
} }
+4 -4
View File
@@ -62,7 +62,7 @@ impl EditorTestUtils for Editor {
} }
fn mouseup(&mut self, state: EditorMouseState) { fn mouseup(&mut self, state: EditorMouseState) {
self.handle_message(InputPreprocessorMessage::MouseUp(state, ModifierKeys::default())).unwrap(); self.handle_message(InputPreprocessorMessage::MouseUp(state, ModifierKeys::default()));
} }
fn lmb_mousedown(&mut self, x: f64, y: f64) { fn lmb_mousedown(&mut self, x: f64, y: f64) {
@@ -74,14 +74,14 @@ impl EditorTestUtils for Editor {
} }
fn input(&mut self, message: InputPreprocessorMessage) { fn input(&mut self, message: InputPreprocessorMessage) {
self.handle_message(Message::InputPreprocessor(message)).unwrap(); self.handle_message(Message::InputPreprocessor(message));
} }
fn select_tool(&mut self, typ: ToolType) { fn select_tool(&mut self, typ: ToolType) {
self.handle_message(Message::Tool(ToolMessage::ActivateTool(typ))).unwrap(); self.handle_message(Message::Tool(ToolMessage::ActivateTool(typ)));
} }
fn select_primary_color(&mut self, color: Color) { fn select_primary_color(&mut self, color: Color) {
self.handle_message(Message::Tool(ToolMessage::SelectPrimaryColor(color))).unwrap(); self.handle_message(Message::Tool(ToolMessage::SelectPrimaryColor(color)));
} }
} }
+47 -50
View File
@@ -13,19 +13,16 @@ fn convert_error(err: editor::EditorError) -> JsValue {
Error::new(&err.to_string()).into() Error::new(&err.to_string()).into()
} }
fn dispatch<T: Into<Message>>(message: T) -> Result<(), JsValue> { fn dispatch<T: Into<Message>>(message: T) {
let result = crate::EDITOR_STATE.with(|state| state.borrow_mut().handle_message(message.into())); let messages = crate::EDITOR_STATE.with(|state| state.borrow_mut().handle_message(message.into()));
if let Ok(messages) = result { crate::handle_responses(messages);
crate::handle_responses(messages);
}
Ok(())
} }
/// Modify the currently selected tool in the document state store /// Modify the currently selected tool in the document state store
#[wasm_bindgen] #[wasm_bindgen]
pub fn select_tool(tool: String) -> Result<(), JsValue> { pub fn select_tool(tool: String) -> Result<(), JsValue> {
match translate_tool(&tool) { match translate_tool(&tool) {
Some(tool) => dispatch(ToolMessage::ActivateTool(tool)), Some(tool) => Ok(dispatch(ToolMessage::ActivateTool(tool))),
None => Err(Error::new(&format!("Couldn't select {} because it was not recognized as a valid tool", tool)).into()), None => Err(Error::new(&format!("Couldn't select {} because it was not recognized as a valid tool", tool)).into()),
} }
} }
@@ -35,7 +32,7 @@ pub fn select_tool(tool: String) -> Result<(), JsValue> {
pub fn set_tool_options(tool: String, options: &JsValue) -> Result<(), JsValue> { pub fn set_tool_options(tool: String, options: &JsValue) -> Result<(), JsValue> {
match options.into_serde::<ToolOptions>() { match options.into_serde::<ToolOptions>() {
Ok(options) => match translate_tool(&tool) { Ok(options) => match translate_tool(&tool) {
Some(tool) => dispatch(ToolMessage::SetToolOptions(tool, options)), Some(tool) => Ok(dispatch(ToolMessage::SetToolOptions(tool, options))),
None => Err(Error::new(&format!("Couldn't set options for {} because it was not recognized as a valid tool", tool)).into()), 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()), Err(err) => Err(Error::new(&format!("Invalid JSON for ToolOptions: {}", err)).into()),
@@ -56,65 +53,65 @@ pub fn send_tool_message(tool: String, message: &JsValue) -> Result<(), JsValue>
None => Err(Error::new(&format!("Couldn't send message for {} because it was not recognized as a valid tool", 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 { match tool_message {
Ok(tool_message) => dispatch(tool_message), Ok(tool_message) => Ok(dispatch(tool_message)),
Err(err) => Err(err), Err(err) => Err(err),
} }
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn select_document(document: usize) -> Result<(), JsValue> { pub fn select_document(document: usize) {
dispatch(DocumentsMessage::SelectDocument(document)) dispatch(DocumentsMessage::SelectDocument(document))
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn get_open_documents_list() -> Result<(), JsValue> { pub fn get_open_documents_list() {
dispatch(DocumentsMessage::GetOpenDocumentsList) dispatch(DocumentsMessage::GetOpenDocumentsList)
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn new_document() -> Result<(), JsValue> { pub fn new_document() {
dispatch(DocumentsMessage::NewDocument) dispatch(DocumentsMessage::NewDocument)
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn open_document() -> Result<(), JsValue> { pub fn open_document() {
dispatch(DocumentsMessage::OpenDocument) dispatch(DocumentsMessage::OpenDocument)
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn open_document_file(name: String, content: String) -> Result<(), JsValue> { pub fn open_document_file(name: String, content: String) {
dispatch(DocumentsMessage::OpenDocumentFile(name, content)) dispatch(DocumentsMessage::OpenDocumentFile(name, content))
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn save_document() -> Result<(), JsValue> { pub fn save_document() {
dispatch(DocumentMessage::SaveDocument) dispatch(DocumentMessage::SaveDocument)
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn close_document(document: usize) -> Result<(), JsValue> { pub fn close_document(document: usize) {
dispatch(DocumentsMessage::CloseDocument(document)) dispatch(DocumentsMessage::CloseDocument(document))
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn close_all_documents() -> Result<(), JsValue> { pub fn close_all_documents() {
dispatch(DocumentsMessage::CloseAllDocuments) dispatch(DocumentsMessage::CloseAllDocuments)
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn close_active_document_with_confirmation() -> Result<(), JsValue> { pub fn close_active_document_with_confirmation() {
dispatch(DocumentsMessage::CloseActiveDocumentWithConfirmation) dispatch(DocumentsMessage::CloseActiveDocumentWithConfirmation)
} }
#[wasm_bindgen] #[wasm_bindgen]
pub fn close_all_documents_with_confirmation() -> Result<(), JsValue> { pub fn close_all_documents_with_confirmation() {
dispatch(DocumentsMessage::CloseAllDocumentsWithConfirmation) dispatch(DocumentsMessage::CloseAllDocumentsWithConfirmation)
} }
/// Send new bounds when document panel viewports get resized or moved within the editor /// Send new bounds when document panel viewports get resized or moved within the editor
/// [left, top, right, bottom]... /// [left, top, right, bottom]...
#[wasm_bindgen] #[wasm_bindgen]
pub fn bounds_of_viewports(bounds_of_viewports: &[f64]) -> Result<(), JsValue> { pub fn bounds_of_viewports(bounds_of_viewports: &[f64]) {
let chunked: Vec<_> = bounds_of_viewports.chunks(4).map(ViewportBounds::from_slice).collect(); let chunked: Vec<_> = bounds_of_viewports.chunks(4).map(ViewportBounds::from_slice).collect();
let ev = InputPreprocessorMessage::BoundsOfViewports(chunked); let ev = InputPreprocessorMessage::BoundsOfViewports(chunked);
dispatch(ev) dispatch(ev)
@@ -122,7 +119,7 @@ pub fn bounds_of_viewports(bounds_of_viewports: &[f64]) -> Result<(), JsValue> {
/// Mouse movement within the screenspace bounds of the viewport /// Mouse movement within the screenspace bounds of the viewport
#[wasm_bindgen] #[wasm_bindgen]
pub fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Result<(), JsValue> { 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 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 modifier_keys = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys");
@@ -133,7 +130,7 @@ pub fn on_mouse_move(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Result<()
/// Mouse scrolling within the screenspace bounds of the viewport /// Mouse scrolling within the screenspace bounds of the viewport
#[wasm_bindgen] #[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) -> Result<(), JsValue> { 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()); 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); editor_mouse_state.scroll_delta = ScrollDelta::new(wheel_delta_x, wheel_delta_y, wheel_delta_z);
@@ -145,7 +142,7 @@ pub fn on_mouse_scroll(x: f64, y: f64, mouse_keys: u8, wheel_delta_x: i32, wheel
/// A mouse button depressed within screenspace the bounds of the viewport /// A mouse button depressed within screenspace the bounds of the viewport
#[wasm_bindgen] #[wasm_bindgen]
pub fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Result<(), JsValue> { 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 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 modifier_keys = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys");
@@ -156,7 +153,7 @@ pub fn on_mouse_down(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Result<()
/// A mouse button released /// A mouse button released
#[wasm_bindgen] #[wasm_bindgen]
pub fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Result<(), JsValue> { 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 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 modifier_keys = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys");
@@ -167,7 +164,7 @@ pub fn on_mouse_up(x: f64, y: f64, mouse_keys: u8, modifiers: u8) -> Result<(),
/// A keyboard button depressed within screenspace the bounds of the viewport /// A keyboard button depressed within screenspace the bounds of the viewport
#[wasm_bindgen] #[wasm_bindgen]
pub fn on_key_down(name: String, modifiers: u8) -> Result<(), JsValue> { pub fn on_key_down(name: String, modifiers: u8) {
let key = translate_key(&name); let key = translate_key(&name);
let mods = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys"); let mods = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys");
log::trace!("Key down {:?}, name: {}, modifiers: {:?}", key, name, mods); log::trace!("Key down {:?}, name: {}, modifiers: {:?}", key, name, mods);
@@ -177,7 +174,7 @@ pub fn on_key_down(name: String, modifiers: u8) -> Result<(), JsValue> {
/// A keyboard button released /// A keyboard button released
#[wasm_bindgen] #[wasm_bindgen]
pub fn on_key_up(name: String, modifiers: u8) -> Result<(), JsValue> { pub fn on_key_up(name: String, modifiers: u8) {
let key = translate_key(&name); let key = translate_key(&name);
let mods = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys"); let mods = ModifierKeys::from_bits(modifiers).expect("invalid modifier keys");
log::trace!("Key up {:?}, name: {}, modifiers: {:?}", key, name, mods); log::trace!("Key up {:?}, name: {}, modifiers: {:?}", key, name, mods);
@@ -187,55 +184,55 @@ pub fn on_key_up(name: String, modifiers: u8) -> Result<(), JsValue> {
/// Update primary color /// Update primary color
#[wasm_bindgen] #[wasm_bindgen]
pub fn update_primary_color(primary_color: Color) -> Result<(), JsValue> { pub fn update_primary_color(primary_color: Color) {
dispatch(ToolMessage::SelectPrimaryColor(primary_color.inner())) dispatch(ToolMessage::SelectPrimaryColor(primary_color.inner()))
} }
/// Update secondary color /// Update secondary color
#[wasm_bindgen] #[wasm_bindgen]
pub fn update_secondary_color(secondary_color: Color) -> Result<(), JsValue> { pub fn update_secondary_color(secondary_color: Color) {
dispatch(ToolMessage::SelectSecondaryColor(secondary_color.inner())) dispatch(ToolMessage::SelectSecondaryColor(secondary_color.inner()))
} }
/// Swap primary and secondary color /// Swap primary and secondary color
#[wasm_bindgen] #[wasm_bindgen]
pub fn swap_colors() -> Result<(), JsValue> { pub fn swap_colors() {
dispatch(ToolMessage::SwapColors) dispatch(ToolMessage::SwapColors)
} }
/// Reset primary and secondary colors to their defaults /// Reset primary and secondary colors to their defaults
#[wasm_bindgen] #[wasm_bindgen]
pub fn reset_colors() -> Result<(), JsValue> { pub fn reset_colors() {
dispatch(ToolMessage::ResetColors) dispatch(ToolMessage::ResetColors)
} }
/// Undo history one step /// Undo history one step
#[wasm_bindgen] #[wasm_bindgen]
pub fn undo() -> Result<(), JsValue> { pub fn undo() {
dispatch(DocumentMessage::Undo) dispatch(DocumentMessage::Undo)
} }
/// Redo history one step /// Redo history one step
#[wasm_bindgen] #[wasm_bindgen]
pub fn redo() -> Result<(), JsValue> { pub fn redo() {
dispatch(DocumentMessage::Redo) dispatch(DocumentMessage::Redo)
} }
/// Select all layers /// Select all layers
#[wasm_bindgen] #[wasm_bindgen]
pub fn select_all_layers() -> Result<(), JsValue> { pub fn select_all_layers() {
dispatch(DocumentMessage::SelectAllLayers) dispatch(DocumentMessage::SelectAllLayers)
} }
/// Deselect all layers /// Deselect all layers
#[wasm_bindgen] #[wasm_bindgen]
pub fn deselect_all_layers() -> Result<(), JsValue> { pub fn deselect_all_layers() {
dispatch(DocumentMessage::DeselectAllLayers) dispatch(DocumentMessage::DeselectAllLayers)
} }
/// Reorder selected layer /// Reorder selected layer
#[wasm_bindgen] #[wasm_bindgen]
pub fn reorder_selected_layers(delta: i32) -> Result<(), JsValue> { pub fn reorder_selected_layers(delta: i32) {
dispatch(DocumentMessage::ReorderSelectedLayers(delta)) dispatch(DocumentMessage::ReorderSelectedLayers(delta))
} }
@@ -262,96 +259,96 @@ pub fn set_blend_mode_for_selected_layers(blend_mode_svg_style_name: String) ->
_ => return Err(convert_error(EditorError::Misc("UnknownBlendMode".to_string()))), _ => return Err(convert_error(EditorError::Misc("UnknownBlendMode".to_string()))),
}; };
dispatch(DocumentMessage::SetBlendModeForSelectedLayers(blend_mode)) Ok(dispatch(DocumentMessage::SetBlendModeForSelectedLayers(blend_mode)))
} }
/// Set the opacity for the selected layers /// Set the opacity for the selected layers
#[wasm_bindgen] #[wasm_bindgen]
pub fn set_opacity_for_selected_layers(opacity_percent: f64) -> Result<(), JsValue> { pub fn set_opacity_for_selected_layers(opacity_percent: f64) {
dispatch(DocumentMessage::SetOpacityForSelectedLayers(opacity_percent / 100.)) dispatch(DocumentMessage::SetOpacityForSelectedLayers(opacity_percent / 100.))
} }
/// Export the document /// Export the document
#[wasm_bindgen] #[wasm_bindgen]
pub fn export_document() -> Result<(), JsValue> { pub fn export_document() {
dispatch(DocumentMessage::ExportDocument) dispatch(DocumentMessage::ExportDocument)
} }
/// Sets the zoom to the value /// Sets the zoom to the value
#[wasm_bindgen] #[wasm_bindgen]
pub fn set_canvas_zoom(new_zoom: f64) -> Result<(), JsValue> { pub fn set_canvas_zoom(new_zoom: f64) {
let ev = MovementMessage::SetCanvasZoom(new_zoom); let ev = MovementMessage::SetCanvasZoom(new_zoom);
dispatch(ev) dispatch(ev)
} }
/// Zoom in to the next step /// Zoom in to the next step
#[wasm_bindgen] #[wasm_bindgen]
pub fn increase_canvas_zoom() -> Result<(), JsValue> { pub fn increase_canvas_zoom() {
let ev = MovementMessage::IncreaseCanvasZoom; let ev = MovementMessage::IncreaseCanvasZoom;
dispatch(ev) dispatch(ev)
} }
/// Zoom out to the next step /// Zoom out to the next step
#[wasm_bindgen] #[wasm_bindgen]
pub fn decrease_canvas_zoom() -> Result<(), JsValue> { pub fn decrease_canvas_zoom() {
let ev = MovementMessage::DecreaseCanvasZoom; let ev = MovementMessage::DecreaseCanvasZoom;
dispatch(ev) dispatch(ev)
} }
/// Sets the rotation to the new value (in radians) /// Sets the rotation to the new value (in radians)
#[wasm_bindgen] #[wasm_bindgen]
pub fn set_rotation(new_radians: f64) -> Result<(), JsValue> { pub fn set_rotation(new_radians: f64) {
let ev = MovementMessage::SetCanvasRotation(new_radians); let ev = MovementMessage::SetCanvasRotation(new_radians);
dispatch(ev) dispatch(ev)
} }
/// Translates document (in viewport coords) /// Translates document (in viewport coords)
#[wasm_bindgen] #[wasm_bindgen]
pub fn translate_canvas(delta_x: f64, delta_y: f64) -> Result<(), JsValue> { pub fn translate_canvas(delta_x: f64, delta_y: f64) {
let ev = MovementMessage::TranslateCanvas((delta_x, delta_y).into()); let ev = MovementMessage::TranslateCanvas((delta_x, delta_y).into());
dispatch(ev) dispatch(ev)
} }
/// Translates document (in viewport coords) /// Translates document (in viewport coords)
#[wasm_bindgen] #[wasm_bindgen]
pub fn translate_canvas_by_fraction(delta_x: f64, delta_y: f64) -> Result<(), JsValue> { pub fn translate_canvas_by_fraction(delta_x: f64, delta_y: f64) {
let ev = MovementMessage::TranslateCanvasByViewportFraction((delta_x, delta_y).into()); let ev = MovementMessage::TranslateCanvasByViewportFraction((delta_x, delta_y).into());
dispatch(ev) dispatch(ev)
} }
/// Update the list of selected layers. The layer paths have to be stored in one array and are separated by LayerId::MAX /// Update the list of selected layers. The layer paths have to be stored in one array and are separated by LayerId::MAX
#[wasm_bindgen] #[wasm_bindgen]
pub fn select_layers(paths: Vec<LayerId>) -> Result<(), JsValue> { pub fn select_layers(paths: Vec<LayerId>) {
let paths = paths.split(|id| *id == LayerId::MAX).map(|path| path.to_vec()).collect(); let paths = paths.split(|id| *id == LayerId::MAX).map(|path| path.to_vec()).collect();
dispatch(DocumentMessage::SetSelectedLayers(paths)) dispatch(DocumentMessage::SetSelectedLayers(paths))
} }
/// Toggle visibility of a layer from the layer list /// Toggle visibility of a layer from the layer list
#[wasm_bindgen] #[wasm_bindgen]
pub fn toggle_layer_visibility(path: Vec<LayerId>) -> Result<(), JsValue> { pub fn toggle_layer_visibility(path: Vec<LayerId>) {
dispatch(DocumentMessage::ToggleLayerVisibility(path)) dispatch(DocumentMessage::ToggleLayerVisibility(path))
} }
/// Toggle expansions state of a layer from the layer list /// Toggle expansions state of a layer from the layer list
#[wasm_bindgen] #[wasm_bindgen]
pub fn toggle_layer_expansion(path: Vec<LayerId>) -> Result<(), JsValue> { pub fn toggle_layer_expansion(path: Vec<LayerId>) {
dispatch(DocumentMessage::ToggleLayerExpansion(path)) dispatch(DocumentMessage::ToggleLayerExpansion(path))
} }
/// Renames a layer from the layer list /// Renames a layer from the layer list
#[wasm_bindgen] #[wasm_bindgen]
pub fn rename_layer(path: Vec<LayerId>, new_name: String) -> Result<(), JsValue> { pub fn rename_layer(path: Vec<LayerId>, new_name: String) {
dispatch(DocumentMessage::RenameLayer(path, new_name)) dispatch(DocumentMessage::RenameLayer(path, new_name))
} }
/// Deletes a layer from the layer list /// Deletes a layer from the layer list
#[wasm_bindgen] #[wasm_bindgen]
pub fn delete_layer(path: Vec<LayerId>) -> Result<(), JsValue> { pub fn delete_layer(path: Vec<LayerId>) {
dispatch(DocumentMessage::DeleteLayer(path)) dispatch(DocumentMessage::DeleteLayer(path))
} }
/// Requests the backend to add a layer to the layer list /// Requests the backend to add a layer to the layer list
#[wasm_bindgen] #[wasm_bindgen]
pub fn add_folder(path: Vec<LayerId>) -> Result<(), JsValue> { pub fn add_folder(path: Vec<LayerId>) {
dispatch(DocumentMessage::CreateFolder(path)) dispatch(DocumentMessage::CreateFolder(path))
} }