Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] Add Deno ops tests #27

Merged
merged 6 commits into from
Mar 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 24 additions & 24 deletions modules/astrodon-tauri/src/deno_runtime/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ use uuid::Uuid;

use crate::events_manager::EventsManager;
use crate::messages::CloseWindowMessage;
use crate::messages::RunWindowMessage;
use crate::messages::SentToWindowMessage;
use crate::messages::WindowConfig;
use crate::AstrodonMessage;

/**
Expand All @@ -25,9 +25,9 @@ pub fn new(sender: Sender<AstrodonMessage>, events_manager: EventsManager) -> Ex
Extension::builder()
.ops(vec![
("runWindow", op_async(run_window)),
("closeWindow", op_async(close_window)),
("sendToWindow", op_async(send_to_window)),
("listenEvent", op_async(listen_event)),
("closeWindow", op_async(close_window)),
])
.state(move |s| {
s.put(sender.clone());
Expand All @@ -37,6 +37,27 @@ pub fn new(sender: Sender<AstrodonMessage>, events_manager: EventsManager) -> Ex
.build()
}

/**
* Close a webview window
*/
async fn close_window(
state: Rc<RefCell<OpState>>,
args: CloseWindowMessage,
_: (),
) -> Result<(), AnyError> {
let sender: Sender<AstrodonMessage> = {
let state = state.borrow();
state
.try_borrow::<Sender<AstrodonMessage>>()
.unwrap()
.clone()
};

sender.send(AstrodonMessage::CloseWindow(args)).await?;

Ok(())
}

#[derive(Serialize, Deserialize, Debug)]
struct EventListen {
name: String,
Expand Down Expand Up @@ -75,7 +96,7 @@ async fn listen_event(
*/
async fn run_window(
state: Rc<RefCell<OpState>>,
args: RunWindowMessage,
args: WindowConfig,
_: (),
) -> Result<(), AnyError> {
let sender: Sender<AstrodonMessage> = {
Expand Down Expand Up @@ -114,24 +135,3 @@ async fn send_to_window(

Ok(())
}

/**
* Close a webview window
*/
async fn close_window(
state: Rc<RefCell<OpState>>,
args: CloseWindowMessage,
_: (),
) -> Result<(), AnyError> {
let sender: Sender<AstrodonMessage> = {
let state = state.borrow();
state
.try_borrow::<Sender<AstrodonMessage>>()
.unwrap()
.clone()
};

sender.send(AstrodonMessage::CloseWindow(args)).await?;

Ok(())
}
7 changes: 4 additions & 3 deletions modules/astrodon-tauri/src/deno_runtime/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,17 +98,18 @@ impl DenoRuntime {
.await
.unwrap_or_else(error_handler);

worker.dispatch_load_event(&located_script_name!())
worker
.dispatch_load_event(&located_script_name!())
.unwrap_or_else(error_handler);

worker
.run_event_loop(true)
.await
.unwrap_or_else(error_handler);

worker.dispatch_load_event(&located_script_name!())
worker
.dispatch_load_event(&located_script_name!())
.unwrap_or_else(error_handler);

}
}

Expand Down
8 changes: 4 additions & 4 deletions modules/astrodon-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ use tokio::sync::mpsc;

pub use deno_core;

mod deno_runtime;
mod events_manager;
mod messages;
mod metadata;
pub mod deno_runtime;
pub mod events_manager;
pub mod messages;
pub mod metadata;
mod wry_runtime;

pub use metadata::{AppInfo, Metadata};
Expand Down
30 changes: 12 additions & 18 deletions modules/astrodon-tauri/src/messages.rs
Original file line number Diff line number Diff line change
@@ -1,46 +1,40 @@
use serde::{Deserialize, Serialize};

#[derive(Debug)]
#[derive(Debug, PartialEq)]
pub enum AstrodonMessage {
SentToWindow(SentToWindowMessage),
RunWindow(RunWindowMessage),
RunWindow(WindowConfig),
CloseWindow(CloseWindowMessage),
SentToDeno(String, String),
}

#[derive(Debug)]
pub enum WryEvent {
RunScript(String, String),
NewWindow(RunWindowMessage),
NewWindow(WindowConfig),
CloseWindow(CloseWindowMessage),
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct CloseWindowMessage {
pub id: String,
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
#[serde(tag = "_type")]
pub enum WindowContent {
Url { url: String },
Html { html: String },
}

#[derive(Serialize, Deserialize, Debug)]
pub struct RunWindowMessage {
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct WindowConfig {
pub id: String,
pub title: String,
pub content: WindowContent,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct CloseWindowMessage {
pub id: String
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum IpcMessage {
SendEvent { name: String, content: String },
}

#[derive(Serialize, Deserialize, Debug)]
#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct SentToWindowMessage {
pub id: String,
pub event: String,
Expand Down
4 changes: 2 additions & 2 deletions modules/astrodon-tauri/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
/**
* Information primarily used for deno_installer (tauri-bundler)
*/
#[derive(Serialize, Deserialize, Clone, Debug)]
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct AppInfo {
pub name: String,
pub id: String,
Expand All @@ -21,7 +21,7 @@ pub struct AppInfo {
}

// Inspired by https://github.com/denoland/deno/blob/8b2989c417db9090913f1cb6074ae961f4c14d5e/cli/standalone.rs#L46
#[derive(Serialize, Deserialize, Clone, Debug)]
#[derive(Serialize, Deserialize, Clone)]
pub struct Metadata {
pub entrypoint: ModuleSpecifier,
pub info: AppInfo,
Expand Down
34 changes: 19 additions & 15 deletions modules/astrodon-tauri/src/wry_runtime.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use deno_core::{futures::executor::block_on, serde_json};
use deno_core::serde_json;
use directories::ProjectDirs;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use tokio::sync::mpsc::Receiver;
use tokio::sync::mpsc::Sender;
Expand All @@ -14,7 +16,7 @@ use wry::{

use crate::events_manager::EventsManager;
use crate::{
messages::{IpcMessage, WindowContent, WryEvent},
messages::{WindowContent, WryEvent},
AppInfo, AstrodonMessage, Metadata,
};

Expand All @@ -33,7 +35,7 @@ impl WryRuntime {

let proxy = event_loop.create_proxy();

// custom event loop - this basically process and forwards events to the wry event loop
// Handle messages emitted from the Deno runtime
tokio::task::spawn(async move {
loop {
match self.deno_receiver.recv().await.unwrap() {
Expand Down Expand Up @@ -99,23 +101,16 @@ impl WryRuntime {
}
}
Event::UserEvent(WryEvent::NewWindow(msg)) => {
let new_window = block_on(create_new_window(
let new_window = create_new_window(
msg.title,
msg.content,
event_loop,
self.deno_sender.clone(),
&mut web_context,
));
);
custom_id_mapper.insert(msg.id, new_window.0);
webviews.insert(new_window.0, new_window.1);
}
Event::UserEvent(WryEvent::CloseWindow(msg)) => {
let id = custom_id_mapper.get(&msg.id);
if let Some(window_id) = id {
webviews.remove(&window_id);
custom_id_mapper.remove(&msg.id);
}
}
_ => (),
}
});
Expand All @@ -130,7 +125,13 @@ fn get_web_context(info: AppInfo) -> WebContext {
WebContext::new(Some(bundle_path.config_dir().to_path_buf()))
}

async fn create_new_window(
#[derive(Serialize, Deserialize)]
#[serde(tag = "type")]
enum IpcMessage {
SendEvent { name: String, content: String },
}

fn create_new_window(
title: String,
content: WindowContent,
event_loop: &EventLoopWindowTarget<WryEvent>,
Expand All @@ -145,17 +146,20 @@ async fn create_new_window(
let window_id = window.id();

let handler = move |_: &Window, req: String| {
let message: IpcMessage = serde_json::from_str(&req).unwrap();
let message = serde_json::from_str(&req);

let snd = snd.clone();

// Handle the events emitted from the webview
match message {
IpcMessage::SendEvent { name, content } => {
Ok(IpcMessage::SendEvent { name, content }) => {
tokio::spawn(async move {
snd.send(AstrodonMessage::SentToDeno(name, content))
.await
.unwrap();
});
}
Err(_) => {}
}
};

Expand Down
26 changes: 26 additions & 0 deletions modules/astrodon-tauri/tests/deno_ops.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Wait for the trigger event to be fired
await Deno.core.opAsync("listenEvent", { name: "to-deno" });

// Send response to Rust
await Deno.core.opAsync("sendToWindow", {
id: "window-id",
event: "to-rust",
content: JSON.stringify({
"astrodon": "nice"
})
})

// Create window
await Deno.core.opAsync("runWindow", {
id: "window-id",
title: "Astrodon",
content: {
_type: "Url",
url: "https://github.com/astrodon/astrodon",
}
});

// Close window
await Deno.core.opAsync("closeWindow", {
id: "window-id",
})