make eval copy
This commit is contained in:
1 parent
894a79d3df
commit
a789d6a64e
13 files changed
+191
-107
No files matched your search
Generated
+5
@@ -2529,6 +2529,7 @@ dependencies = [
|
|||||||
"exitcode",
|
"exitcode",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"generational-box",
|
||||||
"global-hotkey",
|
"global-hotkey",
|
||||||
"infer 0.11.0",
|
"infer 0.11.0",
|
||||||
"muda",
|
"muda",
|
||||||
@@ -2662,6 +2663,7 @@ dependencies = [
|
|||||||
"enumset",
|
"enumset",
|
||||||
"euclid",
|
"euclid",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
|
"generational-box",
|
||||||
"keyboard-types",
|
"keyboard-types",
|
||||||
"rfd",
|
"rfd",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -2725,6 +2727,7 @@ dependencies = [
|
|||||||
"dioxus-interpreter-js",
|
"dioxus-interpreter-js",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"generational-box",
|
||||||
"minify-js",
|
"minify-js",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"pretty_env_logger",
|
"pretty_env_logger",
|
||||||
@@ -2912,6 +2915,7 @@ dependencies = [
|
|||||||
"dioxus-signals",
|
"dioxus-signals",
|
||||||
"fern",
|
"fern",
|
||||||
"fs_extra",
|
"fs_extra",
|
||||||
|
"generational-box",
|
||||||
"http 0.2.11",
|
"http 0.2.11",
|
||||||
"lru 0.10.1",
|
"lru 0.10.1",
|
||||||
"rustc-hash",
|
"rustc-hash",
|
||||||
@@ -2962,6 +2966,7 @@ dependencies = [
|
|||||||
"dioxus-web",
|
"dioxus-web",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"generational-box",
|
||||||
"gloo-dialogs",
|
"gloo-dialogs",
|
||||||
"gloo-timers",
|
"gloo-timers",
|
||||||
"js-sys",
|
"js-sys",
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ dioxus-html = { workspace = true, features = [
|
|||||||
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
|
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
|
||||||
dioxus-hot-reload = { workspace = true, optional = true }
|
dioxus-hot-reload = { workspace = true, optional = true }
|
||||||
dioxus-cli-config = { workspace = true }
|
dioxus-cli-config = { workspace = true }
|
||||||
|
generational-box = { workspace = true }
|
||||||
|
|
||||||
serde = "1.0.136"
|
serde = "1.0.136"
|
||||||
serde_json = "1.0.79"
|
serde_json = "1.0.79"
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
#![allow(clippy::await_holding_refcell_ref)]
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
||||||
use std::{cell::RefCell, rc::Rc};
|
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
|
||||||
|
|
||||||
use crate::{query::Query, DesktopContext};
|
use crate::{query::Query, DesktopContext};
|
||||||
|
|
||||||
@@ -17,55 +15,57 @@ impl DesktopEvalProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EvalProvider for DesktopEvalProvider {
|
impl EvalProvider for DesktopEvalProvider {
|
||||||
fn new_evaluator(&self, js: String) -> Result<Box<dyn Evaluator>, EvalError> {
|
fn new_evaluator(&self, js: String) -> Result<GenerationalBox<Box<dyn Evaluator>>, EvalError> {
|
||||||
Ok(Box::new(DesktopEvaluator::new(
|
Ok(DesktopEvaluator::create(self.desktop_ctx.clone(), js))
|
||||||
self.desktop_ctx.clone(),
|
|
||||||
js,
|
|
||||||
)))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents a desktop-target's JavaScript evaluator.
|
/// Represents a desktop-target's JavaScript evaluator.
|
||||||
pub(crate) struct DesktopEvaluator {
|
pub(crate) struct DesktopEvaluator {
|
||||||
query: Rc<RefCell<Query<serde_json::Value>>>,
|
query: Query<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DesktopEvaluator {
|
impl DesktopEvaluator {
|
||||||
/// Creates a new evaluator for desktop-based targets.
|
/// Creates a new evaluator for desktop-based targets.
|
||||||
pub fn new(desktop_ctx: DesktopContext, js: String) -> Self {
|
pub fn create(desktop_ctx: DesktopContext, js: String) -> GenerationalBox<Box<dyn Evaluator>> {
|
||||||
let ctx = desktop_ctx.clone();
|
let ctx = desktop_ctx.clone();
|
||||||
let query = desktop_ctx.query.new_query(&js, ctx);
|
let query = desktop_ctx.query.new_query(&js, ctx);
|
||||||
|
|
||||||
Self {
|
// We create a generational box that is owned by the query slot so that when we drop the query slot, the generational box is also dropped.
|
||||||
query: Rc::new(RefCell::new(query)),
|
let owner = UnsyncStorage::owner();
|
||||||
}
|
let query_id = query.id;
|
||||||
|
let query = owner.insert(Box::new(DesktopEvaluator { query }) as Box<dyn Evaluator>);
|
||||||
|
desktop_ctx.query.active_requests.slab.borrow_mut()[query_id].owner = Some(owner);
|
||||||
|
|
||||||
|
query
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl Evaluator for DesktopEvaluator {
|
impl Evaluator for DesktopEvaluator {
|
||||||
async fn join(&self) -> Result<serde_json::Value, EvalError> {
|
fn poll_join(
|
||||||
|
&mut self,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
self.query
|
self.query
|
||||||
.borrow_mut()
|
.poll_result(cx)
|
||||||
.result()
|
|
||||||
.await
|
|
||||||
.map_err(|e| EvalError::Communication(e.to_string()))
|
.map_err(|e| EvalError::Communication(e.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends a message to the evaluated JavaScript.
|
/// Sends a message to the evaluated JavaScript.
|
||||||
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
||||||
if let Err(e) = self.query.borrow_mut().send(data) {
|
if let Err(e) = self.query.send(data) {
|
||||||
return Err(EvalError::Communication(e.to_string()));
|
return Err(EvalError::Communication(e.to_string()));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
||||||
async fn recv(&mut self) -> Result<serde_json::Value, EvalError> {
|
fn poll_recv(
|
||||||
|
&mut self,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
self.query
|
self.query
|
||||||
.borrow_mut()
|
.poll_recv(cx)
|
||||||
.recv()
|
|
||||||
.await
|
|
||||||
.map_err(|e| EvalError::Communication(e.to_string()))
|
.map_err(|e| EvalError::Communication(e.to_string()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
use std::{cell::RefCell, rc::Rc};
|
use std::{cell::RefCell, rc::Rc};
|
||||||
|
|
||||||
use crate::DesktopContext;
|
use crate::DesktopContext;
|
||||||
use futures_util::StreamExt;
|
use futures_util::{FutureExt, StreamExt};
|
||||||
|
use generational_box::Owner;
|
||||||
use serde::{de::DeserializeOwned, Deserialize};
|
use serde::{de::DeserializeOwned, Deserialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use slab::Slab;
|
use slab::Slab;
|
||||||
@@ -43,8 +44,8 @@ let dioxus = {
|
|||||||
|
|
||||||
/// Tracks what query ids are currently active
|
/// Tracks what query ids are currently active
|
||||||
|
|
||||||
struct SharedSlab<T = ()> {
|
pub(crate) struct SharedSlab<T = ()> {
|
||||||
slab: Rc<RefCell<Slab<T>>>,
|
pub slab: Rc<RefCell<Slab<T>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Clone for SharedSlab<T> {
|
impl<T> Clone for SharedSlab<T> {
|
||||||
@@ -63,9 +64,10 @@ impl<T> Default for SharedSlab<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct QueryEntry {
|
pub(crate) struct QueryEntry {
|
||||||
channel_sender: futures_channel::mpsc::UnboundedSender<Value>,
|
channel_sender: futures_channel::mpsc::UnboundedSender<Value>,
|
||||||
return_sender: Option<futures_channel::oneshot::Sender<Value>>,
|
return_sender: Option<futures_channel::oneshot::Sender<Value>>,
|
||||||
|
pub owner: Option<Owner>,
|
||||||
}
|
}
|
||||||
|
|
||||||
const QUEUE_NAME: &str = "__msg_queues";
|
const QUEUE_NAME: &str = "__msg_queues";
|
||||||
@@ -73,7 +75,7 @@ const QUEUE_NAME: &str = "__msg_queues";
|
|||||||
/// Handles sending and receiving arbitrary queries from the webview. Queries can be resolved non-sequentially, so we use ids to track them.
|
/// Handles sending and receiving arbitrary queries from the webview. Queries can be resolved non-sequentially, so we use ids to track them.
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub(crate) struct QueryEngine {
|
pub(crate) struct QueryEngine {
|
||||||
active_requests: SharedSlab<QueryEntry>,
|
pub active_requests: SharedSlab<QueryEntry>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl QueryEngine {
|
impl QueryEngine {
|
||||||
@@ -88,6 +90,7 @@ impl QueryEngine {
|
|||||||
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
|
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
|
||||||
channel_sender: tx,
|
channel_sender: tx,
|
||||||
return_sender: Some(return_tx),
|
return_sender: Some(return_tx),
|
||||||
|
owner: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
// start the query
|
// start the query
|
||||||
@@ -161,7 +164,7 @@ pub(crate) struct Query<V: DeserializeOwned> {
|
|||||||
slab: SharedSlab<QueryEntry>,
|
slab: SharedSlab<QueryEntry>,
|
||||||
receiver: futures_channel::mpsc::UnboundedReceiver<Value>,
|
receiver: futures_channel::mpsc::UnboundedReceiver<Value>,
|
||||||
return_receiver: Option<futures_channel::oneshot::Receiver<Value>>,
|
return_receiver: Option<futures_channel::oneshot::Receiver<Value>>,
|
||||||
id: usize,
|
pub id: usize,
|
||||||
phantom: std::marker::PhantomData<V>,
|
phantom: std::marker::PhantomData<V>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,9 +201,14 @@ impl<V: DeserializeOwned> Query<V> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receive a message from the query
|
/// Poll the query for a message
|
||||||
pub async fn recv(&mut self) -> Result<Value, QueryError> {
|
pub fn poll_recv(
|
||||||
self.receiver.next().await.ok_or(QueryError::Recv)
|
&mut self,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<Value, QueryError>> {
|
||||||
|
self.receiver
|
||||||
|
.poll_next_unpin(cx)
|
||||||
|
.map(|result| result.ok_or(QueryError::Recv))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receive the result of the query
|
/// Receive the result of the query
|
||||||
@@ -210,6 +218,17 @@ impl<V: DeserializeOwned> Query<V> {
|
|||||||
None => Err(QueryError::Finished),
|
None => Err(QueryError::Finished),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Poll the query for a result
|
||||||
|
pub fn poll_result(
|
||||||
|
&mut self,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<Value, QueryError>> {
|
||||||
|
match self.return_receiver.as_mut() {
|
||||||
|
Some(receiver) => receiver.poll_unpin(cx).map_err(|_| QueryError::Recv),
|
||||||
|
None => std::task::Poll::Ready(Err(QueryError::Finished)),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: DeserializeOwned> Drop for Query<V> {
|
impl<V: DeserializeOwned> Drop for Query<V> {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ keywords = ["dom", "ui", "gui", "react"]
|
|||||||
dioxus-core = { workspace = true }
|
dioxus-core = { workspace = true }
|
||||||
dioxus-rsx = { workspace = true, features = ["hot_reload"], optional = true }
|
dioxus-rsx = { workspace = true, features = ["hot_reload"], optional = true }
|
||||||
dioxus-html-internal-macro = { workspace = true }
|
dioxus-html-internal-macro = { workspace = true }
|
||||||
|
generational-box = { workspace = true }
|
||||||
serde = { version = "1", features = ["derive"], optional = true }
|
serde = { version = "1", features = ["derive"], optional = true }
|
||||||
serde_repr = { version = "0.1", optional = true }
|
serde_repr = { version = "0.1", optional = true }
|
||||||
wasm-bindgen = { workspace = true, optional = true }
|
wasm-bindgen = { workspace = true, optional = true }
|
||||||
|
|||||||
+26
-12
@@ -1,26 +1,32 @@
|
|||||||
#![allow(clippy::await_holding_refcell_ref)]
|
#![allow(clippy::await_holding_refcell_ref)]
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use dioxus_core::prelude::*;
|
use dioxus_core::prelude::*;
|
||||||
use std::future::{Future, IntoFuture};
|
use generational_box::GenerationalBox;
|
||||||
|
use std::future::{poll_fn, Future, IntoFuture};
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
use std::task::{Context, Poll};
|
||||||
|
|
||||||
/// A struct that implements EvalProvider is sent through [`ScopeState`]'s provide_context function
|
/// A struct that implements EvalProvider is sent through [`ScopeState`]'s provide_context function
|
||||||
/// so that [`use_eval`] can provide a platform agnostic interface for evaluating JavaScript code.
|
/// so that [`use_eval`] can provide a platform agnostic interface for evaluating JavaScript code.
|
||||||
pub trait EvalProvider {
|
pub trait EvalProvider {
|
||||||
fn new_evaluator(&self, js: String) -> Result<Box<dyn Evaluator>, EvalError>;
|
fn new_evaluator(&self, js: String) -> Result<GenerationalBox<Box<dyn Evaluator>>, EvalError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The platform's evaluator.
|
/// The platform's evaluator.
|
||||||
#[async_trait(?Send)]
|
|
||||||
pub trait Evaluator {
|
pub trait Evaluator {
|
||||||
/// Sends a message to the evaluated JavaScript.
|
/// Sends a message to the evaluated JavaScript.
|
||||||
fn send(&self, data: serde_json::Value) -> Result<(), EvalError>;
|
fn send(&self, data: serde_json::Value) -> Result<(), EvalError>;
|
||||||
/// Receive any queued messages from the evaluated JavaScript.
|
/// Receive any queued messages from the evaluated JavaScript.
|
||||||
async fn recv(&mut self) -> Result<serde_json::Value, EvalError>;
|
fn poll_recv(
|
||||||
|
&mut self,
|
||||||
|
context: &mut Context<'_>,
|
||||||
|
) -> Poll<Result<serde_json::Value, EvalError>>;
|
||||||
/// Gets the return value of the JavaScript
|
/// Gets the return value of the JavaScript
|
||||||
async fn join(&self) -> Result<serde_json::Value, EvalError>;
|
fn poll_join(
|
||||||
|
&mut self,
|
||||||
|
context: &mut Context<'_>,
|
||||||
|
) -> Poll<Result<serde_json::Value, EvalError>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
type EvalCreator = Rc<dyn Fn(&str) -> Result<UseEval, EvalError>>;
|
type EvalCreator = Rc<dyn Fn(&str) -> Result<UseEval, EvalError>>;
|
||||||
@@ -54,28 +60,36 @@ pub fn eval(script: &str) -> Result<UseEval, EvalError> {
|
|||||||
|
|
||||||
/// A wrapper around the target platform's evaluator.
|
/// A wrapper around the target platform's evaluator.
|
||||||
pub struct UseEval {
|
pub struct UseEval {
|
||||||
evaluator: Box<dyn Evaluator + 'static>,
|
evaluator: GenerationalBox<Box<dyn Evaluator>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UseEval {
|
impl UseEval {
|
||||||
/// Creates a new UseEval
|
/// Creates a new UseEval
|
||||||
pub fn new(evaluator: Box<dyn Evaluator + 'static>) -> Self {
|
pub fn new(evaluator: GenerationalBox<Box<dyn Evaluator + 'static>>) -> Self {
|
||||||
Self { evaluator }
|
Self { evaluator }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends a [`serde_json::Value`] to the evaluated JavaScript.
|
/// Sends a [`serde_json::Value`] to the evaluated JavaScript.
|
||||||
pub fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
pub fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
||||||
self.evaluator.send(data)
|
self.evaluator.read().send(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
||||||
pub async fn recv(&mut self) -> Result<serde_json::Value, EvalError> {
|
pub async fn recv(&mut self) -> Result<serde_json::Value, EvalError> {
|
||||||
self.evaluator.recv().await
|
poll_fn(|cx| match self.evaluator.try_write() {
|
||||||
|
Ok(mut evaluator) => evaluator.poll_recv(cx),
|
||||||
|
Err(_) => Poll::Ready(Err(EvalError::Finished)),
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the return value of the evaluated JavaScript.
|
/// Gets the return value of the evaluated JavaScript.
|
||||||
pub async fn join(self) -> Result<serde_json::Value, EvalError> {
|
pub async fn join(self) -> Result<serde_json::Value, EvalError> {
|
||||||
self.evaluator.join().await
|
poll_fn(|cx| match self.evaluator.try_write() {
|
||||||
|
Ok(mut evaluator) => evaluator.poll_join(cx),
|
||||||
|
Err(_) => Poll::Ready(Err(EvalError::Finished)),
|
||||||
|
})
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -92,7 +106,7 @@ impl IntoFuture for UseEval {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub enum EvalError {
|
pub enum EvalError {
|
||||||
/// The platform does not support evaluating JavaScript.
|
/// The platform does not support evaluating JavaScript.
|
||||||
Unspported,
|
Unsupported,
|
||||||
|
|
||||||
/// The provided JavaScript has already been ran.
|
/// The provided JavaScript has already been ran.
|
||||||
Finished,
|
Finished,
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ dioxus-core = { workspace = true, features = ["serialize"] }
|
|||||||
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
|
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
|
||||||
dioxus-hot-reload = { workspace = true, optional = true }
|
dioxus-hot-reload = { workspace = true, optional = true }
|
||||||
dioxus-cli-config = { workspace = true }
|
dioxus-cli-config = { workspace = true }
|
||||||
|
generational-box = { workspace = true }
|
||||||
|
|
||||||
# warp
|
# warp
|
||||||
warp = { version = "0.3.3", optional = true }
|
warp = { version = "0.3.3", optional = true }
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
#![allow(clippy::await_holding_refcell_ref)]
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
|
||||||
use dioxus_core::ScopeId;
|
use dioxus_core::ScopeId;
|
||||||
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
||||||
use std::{cell::RefCell, rc::Rc};
|
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
use crate::query::{Query, QueryEngine};
|
use crate::query::{Query, QueryEngine};
|
||||||
|
|
||||||
@@ -14,48 +12,51 @@ pub fn init_eval() {
|
|||||||
ScopeId::ROOT.provide_context(provider);
|
ScopeId::ROOT.provide_context(provider);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reprents the desktop-target's provider of evaluators.
|
/// Reprints the desktop-target's provider of evaluators.
|
||||||
pub struct DesktopEvalProvider {
|
pub struct DesktopEvalProvider {
|
||||||
query: QueryEngine,
|
query: QueryEngine,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EvalProvider for DesktopEvalProvider {
|
impl EvalProvider for DesktopEvalProvider {
|
||||||
fn new_evaluator(&self, js: String) -> Result<Box<dyn Evaluator>, EvalError> {
|
fn new_evaluator(&self, js: String) -> Result<GenerationalBox<Box<dyn Evaluator>>, EvalError> {
|
||||||
Ok(Box::new(DesktopEvaluator::new(self.query.clone(), js)))
|
Ok(DesktopEvaluator::create(self.query.clone(), js))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reprents a desktop-target's JavaScript evaluator.
|
/// Reprents a desktop-target's JavaScript evaluator.
|
||||||
pub(crate) struct DesktopEvaluator {
|
pub(crate) struct DesktopEvaluator {
|
||||||
query: Rc<RefCell<Query<serde_json::Value>>>,
|
query: Query<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DesktopEvaluator {
|
impl DesktopEvaluator {
|
||||||
/// Creates a new evaluator for desktop-based targets.
|
/// Creates a new evaluator for desktop-based targets.
|
||||||
pub fn new(query: QueryEngine, js: String) -> Self {
|
pub fn create(query_engine: QueryEngine, js: String) -> GenerationalBox<Box<dyn Evaluator>> {
|
||||||
let query = query.new_query(&js);
|
let query = query_engine.new_query(&js);
|
||||||
|
// We create a generational box that is owned by the query slot so that when we drop the query slot, the generational box is also dropped.
|
||||||
|
let owner = UnsyncStorage::owner();
|
||||||
|
let query_id = query.id;
|
||||||
|
let query = owner.insert(Box::new(DesktopEvaluator { query }) as Box<dyn Evaluator>);
|
||||||
|
query_engine.active_requests.slab.borrow_mut()[query_id].owner = Some(owner);
|
||||||
|
|
||||||
Self {
|
query
|
||||||
query: Rc::new(RefCell::new(query)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl Evaluator for DesktopEvaluator {
|
impl Evaluator for DesktopEvaluator {
|
||||||
/// # Panics
|
/// # Panics
|
||||||
/// This will panic if the query is currently being awaited.
|
/// This will panic if the query is currently being awaited.
|
||||||
async fn join(&self) -> Result<serde_json::Value, EvalError> {
|
fn poll_join(
|
||||||
|
&mut self,
|
||||||
|
context: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
self.query
|
self.query
|
||||||
.borrow_mut()
|
.poll_result(context)
|
||||||
.result()
|
|
||||||
.await
|
|
||||||
.map_err(|e| EvalError::Communication(e.to_string()))
|
.map_err(|e| EvalError::Communication(e.to_string()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends a message to the evaluated JavaScript.
|
/// Sends a message to the evaluated JavaScript.
|
||||||
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
fn send(&self, data: serde_json::Value) -> Result<(), EvalError> {
|
||||||
if let Err(e) = self.query.borrow_mut().send(data) {
|
if let Err(e) = self.query.send(data) {
|
||||||
return Err(EvalError::Communication(e.to_string()));
|
return Err(EvalError::Communication(e.to_string()));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -65,11 +66,12 @@ impl Evaluator for DesktopEvaluator {
|
|||||||
///
|
///
|
||||||
/// # Panics
|
/// # Panics
|
||||||
/// This will panic if the query is currently being awaited.
|
/// This will panic if the query is currently being awaited.
|
||||||
async fn recv(&mut self) -> Result<serde_json::Value, EvalError> {
|
fn poll_recv(
|
||||||
|
&mut self,
|
||||||
|
context: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
self.query
|
self.query
|
||||||
.borrow_mut()
|
.poll_recv(context)
|
||||||
.recv()
|
|
||||||
.await
|
|
||||||
.map_err(|e| EvalError::Communication(e.to_string()))
|
.map_err(|e| EvalError::Communication(e.to_string()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
use std::{cell::RefCell, rc::Rc};
|
use std::{cell::RefCell, rc::Rc};
|
||||||
|
|
||||||
|
use futures_util::FutureExt;
|
||||||
|
use generational_box::{Owner, UnsyncStorage};
|
||||||
use serde::{de::DeserializeOwned, Deserialize};
|
use serde::{de::DeserializeOwned, Deserialize};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use slab::Slab;
|
use slab::Slab;
|
||||||
@@ -42,8 +44,8 @@ let dioxus = {
|
|||||||
|
|
||||||
/// Tracks what query ids are currently active
|
/// Tracks what query ids are currently active
|
||||||
|
|
||||||
struct SharedSlab<T = ()> {
|
pub(crate) struct SharedSlab<T = ()> {
|
||||||
slab: Rc<RefCell<Slab<T>>>,
|
pub(crate) slab: Rc<RefCell<Slab<T>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Clone for SharedSlab<T> {
|
impl<T> Clone for SharedSlab<T> {
|
||||||
@@ -62,9 +64,10 @@ impl<T> Default for SharedSlab<T> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct QueryEntry {
|
pub(crate) struct QueryEntry {
|
||||||
channel_sender: tokio::sync::mpsc::UnboundedSender<Value>,
|
channel_sender: tokio::sync::mpsc::UnboundedSender<Value>,
|
||||||
return_sender: Option<tokio::sync::oneshot::Sender<Value>>,
|
return_sender: Option<tokio::sync::oneshot::Sender<Value>>,
|
||||||
|
pub(crate) owner: Option<Owner<UnsyncStorage>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
const QUEUE_NAME: &str = "__msg_queues";
|
const QUEUE_NAME: &str = "__msg_queues";
|
||||||
@@ -72,7 +75,7 @@ const QUEUE_NAME: &str = "__msg_queues";
|
|||||||
/// Handles sending and receiving arbitrary queries from the webview. Queries can be resolved non-sequentially, so we use ids to track them.
|
/// Handles sending and receiving arbitrary queries from the webview. Queries can be resolved non-sequentially, so we use ids to track them.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub(crate) struct QueryEngine {
|
pub(crate) struct QueryEngine {
|
||||||
active_requests: SharedSlab<QueryEntry>,
|
pub(crate) active_requests: SharedSlab<QueryEntry>,
|
||||||
query_tx: tokio::sync::mpsc::UnboundedSender<String>,
|
query_tx: tokio::sync::mpsc::UnboundedSender<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,6 +94,7 @@ impl QueryEngine {
|
|||||||
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
|
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
|
||||||
channel_sender: tx,
|
channel_sender: tx,
|
||||||
return_sender: Some(return_tx),
|
return_sender: Some(return_tx),
|
||||||
|
owner: None,
|
||||||
});
|
});
|
||||||
|
|
||||||
// start the query
|
// start the query
|
||||||
@@ -162,7 +166,7 @@ pub(crate) struct Query<V: DeserializeOwned> {
|
|||||||
query_engine: QueryEngine,
|
query_engine: QueryEngine,
|
||||||
pub receiver: tokio::sync::mpsc::UnboundedReceiver<Value>,
|
pub receiver: tokio::sync::mpsc::UnboundedReceiver<Value>,
|
||||||
pub return_receiver: Option<tokio::sync::oneshot::Receiver<Value>>,
|
pub return_receiver: Option<tokio::sync::oneshot::Receiver<Value>>,
|
||||||
id: usize,
|
pub id: usize,
|
||||||
phantom: std::marker::PhantomData<V>,
|
phantom: std::marker::PhantomData<V>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -198,12 +202,14 @@ impl<V: DeserializeOwned> Query<V> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receive a message from the query
|
/// Poll the query for a message
|
||||||
pub async fn recv(&mut self) -> Result<Value, QueryError> {
|
pub fn poll_recv(
|
||||||
|
&mut self,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<Value, QueryError>> {
|
||||||
self.receiver
|
self.receiver
|
||||||
.recv()
|
.poll_recv(cx)
|
||||||
.await
|
.map(|result| result.ok_or(QueryError::Recv(RecvError::Closed)))
|
||||||
.ok_or(QueryError::Recv(RecvError::Closed))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receive the result of the query
|
/// Receive the result of the query
|
||||||
@@ -215,6 +221,19 @@ impl<V: DeserializeOwned> Query<V> {
|
|||||||
None => Err(QueryError::Finished),
|
None => Err(QueryError::Finished),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Poll the query for a result
|
||||||
|
pub fn poll_result(
|
||||||
|
&mut self,
|
||||||
|
cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<Value, QueryError>> {
|
||||||
|
match self.return_receiver.as_mut() {
|
||||||
|
Some(receiver) => receiver
|
||||||
|
.poll_unpin(cx)
|
||||||
|
.map_err(|_| QueryError::Recv(RecvError::Closed)),
|
||||||
|
None => std::task::Poll::Ready(Err(QueryError::Finished)),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: DeserializeOwned> Drop for Query<V> {
|
impl<V: DeserializeOwned> Drop for Query<V> {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ keywords = ["dom", "ui", "gui", "react", "ssr"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
dioxus-core = { workspace = true, features = ["serialize"] }
|
dioxus-core = { workspace = true, features = ["serialize"] }
|
||||||
dioxus-html = { workspace = true, features = ["eval"]}
|
dioxus-html = { workspace = true, features = ["eval"]}
|
||||||
|
generational-box = { workspace = true }
|
||||||
askama_escape = "0.10.3"
|
askama_escape = "0.10.3"
|
||||||
thiserror = "1.0.23"
|
thiserror = "1.0.23"
|
||||||
rustc-hash = "1.1.0"
|
rustc-hash = "1.1.0"
|
||||||
|
|||||||
+16
-12
@@ -1,6 +1,7 @@
|
|||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use dioxus_core::ScopeId;
|
use dioxus_core::ScopeId;
|
||||||
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
||||||
|
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
/// Provides the SSREvalProvider through [`cx.provide_context`].
|
/// Provides the SSREvalProvider through [`cx.provide_context`].
|
||||||
@@ -12,8 +13,9 @@ pub fn init_eval() {
|
|||||||
/// Reprents the ssr-target's provider of evaluators.
|
/// Reprents the ssr-target's provider of evaluators.
|
||||||
pub struct SSREvalProvider;
|
pub struct SSREvalProvider;
|
||||||
impl EvalProvider for SSREvalProvider {
|
impl EvalProvider for SSREvalProvider {
|
||||||
fn new_evaluator(&self, _: String) -> Result<Box<dyn Evaluator>, EvalError> {
|
fn new_evaluator(&self, _: String) -> Result<GenerationalBox<Box<dyn Evaluator>>, EvalError> {
|
||||||
Ok(Box::new(SSREvaluator) as Box<dyn Evaluator + 'static>)
|
let owner = UnsyncStorage::owner();
|
||||||
|
Ok(owner.insert(Box::new(SSREvaluator) as Box<dyn Evaluator + 'static>))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,20 +25,22 @@ pub struct SSREvaluator;
|
|||||||
// In ssr rendering we never run or resolve evals.
|
// In ssr rendering we never run or resolve evals.
|
||||||
#[async_trait(?Send)]
|
#[async_trait(?Send)]
|
||||||
impl Evaluator for SSREvaluator {
|
impl Evaluator for SSREvaluator {
|
||||||
/// Runs the evaluated JavaScript.
|
|
||||||
async fn join(&self) -> Result<serde_json::Value, EvalError> {
|
|
||||||
std::future::pending::<()>().await;
|
|
||||||
unreachable!()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sends a message to the evaluated JavaScript.
|
/// Sends a message to the evaluated JavaScript.
|
||||||
fn send(&self, _el: serde_json::Value) -> Result<(), EvalError> {
|
fn send(&self, _el: serde_json::Value) -> Result<(), EvalError> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
fn poll_recv(
|
||||||
async fn recv(&mut self) -> Result<serde_json::Value, EvalError> {
|
&mut self,
|
||||||
std::future::pending::<()>().await;
|
_cx: &mut std::task::Context<'_>,
|
||||||
unreachable!()
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
|
std::task::Poll::Pending
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_join(
|
||||||
|
&mut self,
|
||||||
|
_cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
|
std::task::Poll::Pending
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,6 +16,7 @@ dioxus-interpreter-js = { workspace = true, features = [
|
|||||||
"minimal_bindings",
|
"minimal_bindings",
|
||||||
"webonly",
|
"webonly",
|
||||||
] }
|
] }
|
||||||
|
generational-box = { workspace = true }
|
||||||
|
|
||||||
js-sys = "0.3.56"
|
js-sys = "0.3.56"
|
||||||
wasm-bindgen = { workspace = true }
|
wasm-bindgen = { workspace = true }
|
||||||
|
|||||||
+34
-18
@@ -1,10 +1,10 @@
|
|||||||
use async_trait::async_trait;
|
|
||||||
use dioxus_core::ScopeId;
|
use dioxus_core::ScopeId;
|
||||||
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
use dioxus_html::prelude::{EvalError, EvalProvider, Evaluator};
|
||||||
use futures_util::StreamExt;
|
use futures_util::StreamExt;
|
||||||
|
use generational_box::{AnyStorage, GenerationalBox, UnsyncStorage};
|
||||||
use js_sys::Function;
|
use js_sys::Function;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
use std::{cell::RefCell, rc::Rc, str::FromStr};
|
use std::{rc::Rc, str::FromStr};
|
||||||
use wasm_bindgen::prelude::*;
|
use wasm_bindgen::prelude::*;
|
||||||
|
|
||||||
/// Provides the WebEvalProvider through [`cx.provide_context`].
|
/// Provides the WebEvalProvider through [`cx.provide_context`].
|
||||||
@@ -16,8 +16,8 @@ pub fn init_eval() {
|
|||||||
/// Represents the web-target's provider of evaluators.
|
/// Represents the web-target's provider of evaluators.
|
||||||
pub struct WebEvalProvider;
|
pub struct WebEvalProvider;
|
||||||
impl EvalProvider for WebEvalProvider {
|
impl EvalProvider for WebEvalProvider {
|
||||||
fn new_evaluator(&self, js: String) -> Result<Box<dyn Evaluator>, EvalError> {
|
fn new_evaluator(&self, js: String) -> Result<GenerationalBox<Box<dyn Evaluator>>, EvalError> {
|
||||||
WebEvaluator::new(js).map(|eval| Box::new(eval) as Box<dyn Evaluator + 'static>)
|
WebEvaluator::create(js)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,19 +30,23 @@ const PROMISE_WRAPPER: &str = r#"
|
|||||||
"#;
|
"#;
|
||||||
|
|
||||||
/// Represents a web-target's JavaScript evaluator.
|
/// Represents a web-target's JavaScript evaluator.
|
||||||
pub struct WebEvaluator {
|
struct WebEvaluator {
|
||||||
dioxus: Dioxus,
|
dioxus: Dioxus,
|
||||||
channel_receiver: futures_channel::mpsc::UnboundedReceiver<serde_json::Value>,
|
channel_receiver: futures_channel::mpsc::UnboundedReceiver<serde_json::Value>,
|
||||||
result: RefCell<Option<serde_json::Value>>,
|
result: Option<serde_json::Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WebEvaluator {
|
impl WebEvaluator {
|
||||||
/// Creates a new evaluator for web-based targets.
|
/// Creates a new evaluator for web-based targets.
|
||||||
pub fn new(js: String) -> Result<Self, EvalError> {
|
fn create(js: String) -> Result<GenerationalBox<Box<dyn Evaluator>>, EvalError> {
|
||||||
let (mut channel_sender, channel_receiver) = futures_channel::mpsc::unbounded();
|
let (mut channel_sender, channel_receiver) = futures_channel::mpsc::unbounded();
|
||||||
|
let owner = UnsyncStorage::owner();
|
||||||
|
let invalid = owner.invalid();
|
||||||
|
|
||||||
// This Rc cloning mess hurts but it seems to work..
|
// This Rc cloning mess hurts but it seems to work..
|
||||||
let recv_value = Closure::<dyn FnMut(JsValue)>::new(move |data| {
|
let recv_value = Closure::<dyn FnMut(JsValue)>::new(move |data| {
|
||||||
|
// Drop the owner when the sender is dropped.
|
||||||
|
let _ = &owner;
|
||||||
match serde_wasm_bindgen::from_value::<serde_json::Value>(data) {
|
match serde_wasm_bindgen::from_value::<serde_json::Value>(data) {
|
||||||
Ok(data) => _ = channel_sender.start_send(data),
|
Ok(data) => _ = channel_sender.start_send(data),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -84,19 +88,27 @@ impl WebEvaluator {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(Self {
|
invalid.set(Box::new(Self {
|
||||||
dioxus,
|
dioxus,
|
||||||
channel_receiver,
|
channel_receiver,
|
||||||
result: RefCell::new(Some(result)),
|
result: Some(result),
|
||||||
})
|
}) as Box<dyn Evaluator + 'static>);
|
||||||
|
|
||||||
|
Ok(invalid)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait(?Send)]
|
|
||||||
impl Evaluator for WebEvaluator {
|
impl Evaluator for WebEvaluator {
|
||||||
/// Runs the evaluated JavaScript.
|
/// Runs the evaluated JavaScript.
|
||||||
async fn join(&self) -> Result<serde_json::Value, EvalError> {
|
fn poll_join(
|
||||||
self.result.take().ok_or(EvalError::Finished)
|
&mut self,
|
||||||
|
_cx: &mut std::task::Context<'_>,
|
||||||
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
|
if let Some(result) = self.result.take() {
|
||||||
|
std::task::Poll::Ready(Ok(result))
|
||||||
|
} else {
|
||||||
|
std::task::Poll::Ready(Err(EvalError::Finished))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends a message to the evaluated JavaScript.
|
/// Sends a message to the evaluated JavaScript.
|
||||||
@@ -111,11 +123,15 @@ impl Evaluator for WebEvaluator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
/// Gets an UnboundedReceiver to receive messages from the evaluated JavaScript.
|
||||||
async fn recv(&mut self) -> Result<serde_json::Value, EvalError> {
|
fn poll_recv(
|
||||||
self.channel_receiver
|
&mut self,
|
||||||
.next()
|
context: &mut std::task::Context<'_>,
|
||||||
.await
|
) -> std::task::Poll<Result<serde_json::Value, EvalError>> {
|
||||||
.ok_or_else(|| EvalError::Communication("failed to receive data from js".to_string()))
|
self.channel_receiver.poll_next_unpin(context).map(|poll| {
|
||||||
|
poll.ok_or_else(|| {
|
||||||
|
EvalError::Communication("failed to receive data from js".to_string())
|
||||||
|
})
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user