2023-07-21 22:36:25 +00:00
|
|
|
#![allow(clippy::await_holding_refcell_ref)]
|
|
|
|
use async_trait::async_trait;
|
|
|
|
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
|
|
|
use std::{cell::RefCell, rc::Rc};
|
|
|
|
|
|
|
|
use crate::{query::Query, DesktopContext};
|
2022-12-30 06:08:25 +00:00
|
|
|
|
2023-07-21 22:36:25 +00:00
|
|
|
/// Reprents the desktop-target's provider of evaluators.
|
|
|
|
pub struct DesktopEvalProvider {
|
2024-01-05 02:19:28 +00:00
|
|
|
pub(crate) desktop_ctx: DesktopContext,
|
2022-12-30 07:56:10 +00:00
|
|
|
}
|
|
|
|
|
2024-01-05 02:19:28 +00:00
|
|
|
impl DesktopEvalProvider {
|
|
|
|
pub fn new(desktop_ctx: DesktopContext) -> Self {
|
|
|
|
Self { desktop_ctx }
|
|
|
|
}
|
2023-07-21 22:36:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl EvalProvider for DesktopEvalProvider {
|
|
|
|
fn new_evaluator(&self, js: String) -> Result<Rc<dyn Evaluator>, EvalError> {
|
|
|
|
Ok(Rc::new(DesktopEvaluator::new(self.desktop_ctx.clone(), js)))
|
2022-12-30 07:56:10 +00:00
|
|
|
}
|
2022-12-30 06:08:25 +00:00
|
|
|
}
|
|
|
|
|
2024-01-06 00:01:05 +00:00
|
|
|
/// Represents a desktop-target's JavaScript evaluator.
|
|
|
|
pub(crate) struct DesktopEvaluator {
|
2023-07-21 22:36:25 +00:00
|
|
|
query: Rc<RefCell<Query<serde_json::Value>>>,
|
|
|
|
}
|
2022-12-30 06:08:25 +00:00
|
|
|
|
2023-07-21 22:36:25 +00:00
|
|
|
impl DesktopEvaluator {
|
|
|
|
/// Creates a new evaluator for desktop-based targets.
|
|
|
|
pub fn new(desktop_ctx: DesktopContext, js: String) -> Self {
|
|
|
|
let ctx = desktop_ctx.clone();
|
|
|
|
let query = desktop_ctx.query.new_query(&js, ctx);
|
2022-12-30 06:08:25 +00:00
|
|
|
|
2023-07-21 22:36:25 +00:00
|
|
|
Self {
|
|
|
|
query: Rc::new(RefCell::new(query)),
|
|
|
|
}
|
2022-12-30 06:08:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-21 22:36:25 +00:00
|
|
|
#[async_trait(?Send)]
|
|
|
|
impl Evaluator for DesktopEvaluator {
|
|
|
|
async fn join(&self) -> Result<serde_json::Value, EvalError> {
|
|
|
|
self.query
|
|
|
|
.borrow_mut()
|
|
|
|
.result()
|
|
|
|
.await
|
|
|
|
.map_err(|e| EvalError::Communication(e.to_string()))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Sends a message to the evaluated JavaScript.
|
|
|
|
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
|
|
|
if let Err(e) = self.query.borrow_mut().send(data) {
|
|
|
|
return Err(EvalError::Communication(e.to_string()));
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
2022-12-30 06:08:25 +00:00
|
|
|
|
2023-07-21 22:36:25 +00:00
|
|
|
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
|
|
|
async fn recv(&self) -> Result<serde_json::Value, EvalError> {
|
|
|
|
self.query
|
|
|
|
.borrow_mut()
|
|
|
|
.recv()
|
|
|
|
.await
|
|
|
|
.map_err(|e| EvalError::Communication(e.to_string()))
|
|
|
|
}
|
2022-12-30 06:08:25 +00:00
|
|
|
}
|