Merge branch 'breaking' of https://github.com/Demonthos/dioxus into breaking

This commit is contained in:
Evan Almloff committed 2024-01-18 10:20:35 -06:00
commit b165d707c4
29 files changed
+356 -1145

No files matched your search

+2 -2
View File
@@ -30,7 +30,7 @@ wry = { version = "0.35.0", default-features = false, features = [
"protocol",
"file-drop",
] }
futures-channel = { workspace = true }
futures-channel.workspace = true
tokio = { workspace = true, features = [
"sync",
"rt-multi-thread",
@@ -81,8 +81,8 @@ features = ["tokio_runtime", "hot-reload"]
[dev-dependencies]
dioxus-core-macro = { workspace = true }
dioxus-hooks = { workspace = true }
dioxus-signals = { workspace = true }
exitcode = "1.1.2"
scraper = "0.16.0"
[build-dependencies]
dioxus-interpreter-js = { workspace = true, features = ["binary-protocol"] }
+23 -23
View File
@@ -1,6 +1,11 @@
use dioxus::prelude::*;
use dioxus_core::Element;
use dioxus_desktop::DesktopContext;
fn main() {
check_app_exits(check_html_renders);
}
pub(crate) fn check_app_exits(app: Component) {
use dioxus_desktop::Config;
use tao::window::WindowBuilder;
@@ -22,28 +27,20 @@ pub(crate) fn check_app_exits(app: Component) {
should_panic.store(false, std::sync::atomic::Ordering::SeqCst);
}
fn main() {
check_app_exits(check_html_renders);
}
fn use_inner_html(d: &'static str) -> Option<String> {
let eval_provider = use_eval(cx);
let value: Signal<Option<String>> = use_signal(|| None);
use_effect((), |_| {
to_owned![value, eval_provider];
async move {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
let html = eval_provider(&format!(
r#"let element = document.getElementById('{}');
use_effect(|| async move {
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
window().eval();
let html = eval_provider(&format!(
r#"let element = document.getElementById('{}');
return element.innerHTML"#,
id
))
.unwrap();
if let Ok(serde_json::Value::String(html)) = html.await {
println!("html: {}", html);
value.set(Some(html));
}
id
))
.unwrap();
if let Ok(serde_json::Value::String(html)) = html.await {
println!("html: {}", html);
value.set(Some(html));
}
});
value.read().clone()
@@ -58,10 +55,13 @@ fn check_html_renders() -> Element {
if let Some(raw_html) = inner_html {
println!("{}", raw_html);
let fragment = scraper::Html::parse_fragment(&raw_html);
println!("fragment: {}", fragment.html());
let expected = scraper::Html::parse_fragment(EXPECTED_HTML);
println!("expected: {}", expected.html());
let fragment = &raw_html;
let expected = EXPECTED_HTML;
// let fragment = scraper::Html::parse_fragment(&raw_html);
// println!("fragment: {}", fragment.html());
// let expected = scraper::Html::parse_fragment(EXPECTED_HTML);
// println!("expected: {}", expected.html());
assert_eq!(raw_html, EXPECTED_HTML);
if fragment == expected {
println!("html matches");
desktop_context.close();
+1 -1
View File
@@ -1,7 +1,7 @@
use crate::{
config::{Config, WindowCloseBehaviour},
desktop_context::WindowEventHandlers,
element::DesktopElement,
event_handlers::WindowEventHandlers,
file_upload::FileDialogRequest,
ipc::IpcMessage,
ipc::{EventData, UserWindowEvent},
+10 -114
View File
@@ -4,17 +4,16 @@ use crate::{
edits::EditQueue,
ipc::{EventData, UserWindowEvent},
query::QueryEngine,
shortcut::{HotKey, ShortcutId, ShortcutRegistryError},
shortcut::{HotKey, ShortcutHandle, ShortcutRegistryError},
webview::WebviewInstance,
AssetRequest, Config,
AssetRequest, Config, WryEventHandler,
};
use dioxus_core::{
prelude::{current_scope_id, ScopeId},
use_hook, VirtualDom,
VirtualDom,
};
use dioxus_interpreter_js::MutationState;
use slab::Slab;
use std::{cell::RefCell, fmt::Debug, rc::Rc, rc::Weak};
use std::{cell::RefCell, rc::Rc, rc::Weak};
use tao::{
event::Event,
event_loop::EventLoopWindowTarget,
@@ -208,12 +207,12 @@ impl DesktopService {
pub fn create_wry_event_handler(
&self,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandlerId {
) -> WryEventHandler {
self.shared.event_handlers.add(self.window.id(), handler)
}
/// Remove a wry event handler created with [`DesktopContext::create_wry_event_handler`]
pub fn remove_wry_event_handler(&self, id: WryEventHandlerId) {
pub fn remove_wry_event_handler(&self, id: WryEventHandler) {
self.shared.event_handlers.remove(id)
}
@@ -224,14 +223,14 @@ impl DesktopService {
&self,
hotkey: HotKey,
callback: impl FnMut() + 'static,
) -> Result<ShortcutId, ShortcutRegistryError> {
) -> Result<ShortcutHandle, ShortcutRegistryError> {
self.shared
.shortcut_manager
.add_shortcut(hotkey, Box::new(callback))
}
/// Remove a global shortcut
pub fn remove_shortcut(&self, id: ShortcutId) {
pub fn remove_shortcut(&self, id: ShortcutHandle) {
self.shared.shortcut_manager.remove_shortcut(id)
}
@@ -250,12 +249,12 @@ impl DesktopService {
pub fn register_asset_handler(
&self,
name: String,
f: Box<dyn Fn(AssetRequest, RequestAsyncResponder) + 'static>,
handler: Box<dyn Fn(AssetRequest, RequestAsyncResponder) + 'static>,
scope: Option<ScopeId>,
) {
self.asset_handlers.register_handler(
name,
f,
handler,
scope.unwrap_or(current_scope_id().unwrap_or(ScopeId(0))),
)
}
@@ -313,106 +312,3 @@ fn is_main_thread() -> bool {
let result: BOOL = unsafe { msg_send![cls, isMainThread] };
result != NO
}
/// The unique identifier of a window event handler. This can be used to later remove the handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WryEventHandlerId(usize);
#[derive(Clone, Default)]
pub(crate) struct WindowEventHandlers {
handlers: Rc<RefCell<Slab<WryWindowEventHandlerInner>>>,
}
impl WindowEventHandlers {
pub(crate) fn add(
&self,
window_id: WindowId,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandlerId {
WryEventHandlerId(
self.handlers
.borrow_mut()
.insert(WryWindowEventHandlerInner {
window_id,
handler: Box::new(handler),
}),
)
}
pub(crate) fn remove(&self, id: WryEventHandlerId) {
self.handlers.borrow_mut().try_remove(id.0);
}
pub(crate) fn apply_event(
&self,
event: &Event<UserWindowEvent>,
target: &EventLoopWindowTarget<UserWindowEvent>,
) {
for (_, handler) in self.handlers.borrow_mut().iter_mut() {
handler.apply_event(event, target);
}
}
}
struct WryWindowEventHandlerInner {
window_id: WindowId,
handler: WryEventHandlerCallback,
}
type WryEventHandlerCallback =
Box<dyn FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static>;
impl WryWindowEventHandlerInner {
fn apply_event(
&mut self,
event: &Event<UserWindowEvent>,
target: &EventLoopWindowTarget<UserWindowEvent>,
) {
// if this event does not apply to the window this listener cares about, return
if let Event::WindowEvent { window_id, .. } = event {
if *window_id != self.window_id {
return;
}
}
(self.handler)(event, target)
}
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_wry_event_handler(
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
use_hook(move || {
let desktop = window();
let id = desktop.create_wry_event_handler(handler);
WryEventHandler {
handlers: desktop.shared.event_handlers.clone(),
id,
}
})
}
/// A wry event handler that is scoped to the current component and window. The event handler will only receive events for the window it was created for and global events.
///
/// This will automatically be removed when the component is unmounted.
#[derive(Clone)]
pub struct WryEventHandler {
pub(crate) handlers: WindowEventHandlers,
/// The unique identifier of the event handler.
pub id: WryEventHandlerId,
}
impl WryEventHandler {
/// Remove the event handler.
pub fn remove(&self) {
self.handlers.remove(self.id);
}
}
impl Drop for WryEventHandler {
fn drop(&mut self) {
self.handlers.remove(self.id);
}
}
+8 -137
View File
@@ -1,4 +1,4 @@
use std::{sync::Arc, sync::Mutex};
use std::{cell::RefCell, rc::Rc, sync::Arc, sync::Mutex};
use std::fmt::{Debug, Formatter};
@@ -6,8 +6,8 @@ use std::fmt::{Debug, Formatter};
/// It will hold onto the requests until the interpreter is ready to handle them and hold onto any pending edits until a new request is made.
#[derive(Default, Clone)]
pub(crate) struct EditQueue {
queue: Arc<Mutex<Vec<Vec<u8>>>>,
responder: Arc<Mutex<Option<wry::RequestAsyncResponder>>>,
queue: Rc<RefCell<Vec<Vec<u8>>>>,
responder: Rc<RefCell<Option<wry::RequestAsyncResponder>>>,
}
impl Debug for EditQueue {
@@ -15,7 +15,7 @@ impl Debug for EditQueue {
f.debug_struct("EditQueue")
.field("queue", &self.queue)
.field("responder", {
&self.responder.lock().unwrap().as_ref().map(|_| ())
&self.responder.borrow().as_ref().map(|_| ())
})
.finish()
}
@@ -23,149 +23,20 @@ impl Debug for EditQueue {
impl EditQueue {
pub fn handle_request(&self, responder: wry::RequestAsyncResponder) {
let mut queue = self.queue.lock().unwrap();
let mut queue = self.queue.borrow_mut();
if let Some(bytes) = queue.pop() {
responder.respond(wry::http::Response::new(bytes));
} else {
*self.responder.lock().unwrap() = Some(responder);
*self.responder.borrow_mut() = Some(responder);
}
}
pub fn add_edits(&self, edits: Vec<u8>) {
let mut responder = self.responder.lock().unwrap();
let mut responder = self.responder.borrow_mut();
if let Some(responder) = responder.take() {
responder.respond(wry::http::Response::new(edits));
} else {
self.queue.lock().unwrap().push(edits);
self.queue.borrow_mut().push(edits);
}
}
}
// pub(crate) fn apply_edits(
// mutations: Mutations,
// channel: &mut Channel,
// templates: &mut FxHashMap<String, u16>,
// max_template_count: &AtomicU16,
// ) -> Option<Vec<u8>> {
// if mutations.templates.is_empty() && mutations.edits.is_empty() {
// return None;
// }
// for template in mutations.templates {
// add_template(&template, channel, templates, max_template_count);
// }
// use dioxus_core::Mutation::*;
// for edit in mutations.edits {
// match edit {
// AppendChildren { id, m } => channel.append_children(id.0 as u32, m as u16),
// AssignId { path, id } => channel.assign_id(path, id.0 as u32),
// CreatePlaceholder { id } => channel.create_placeholder(id.0 as u32),
// CreateTextNode { value, id } => channel.create_text_node(value, id.0 as u32),
// HydrateText { path, value, id } => channel.hydrate_text(path, value, id.0 as u32),
// LoadTemplate { name, index, id } => {
// if let Some(tmpl_id) = templates.get(name) {
// channel.load_template(*tmpl_id, index as u16, id.0 as u32)
// }
// }
// ReplaceWith { id, m } => channel.replace_with(id.0 as u32, m as u16),
// ReplacePlaceholder { path, m } => channel.replace_placeholder(path, m as u16),
// InsertAfter { id, m } => channel.insert_after(id.0 as u32, m as u16),
// InsertBefore { id, m } => channel.insert_before(id.0 as u32, m as u16),
// SetAttribute {
// name,
// value,
// id,
// ns,
// } => match value {
// AttributeValue::Text(txt) => {
// channel.set_attribute(id.0 as u32, name, txt, ns.unwrap_or_default())
// }
// AttributeValue::Float(f) => {
// channel.set_attribute(id.0 as u32, name, &f.to_string(), ns.unwrap_or_default())
// }
// AttributeValue::Int(n) => {
// channel.set_attribute(id.0 as u32, name, &n.to_string(), ns.unwrap_or_default())
// }
// AttributeValue::Bool(b) => channel.set_attribute(
// id.0 as u32,
// name,
// if b { "true" } else { "false" },
// ns.unwrap_or_default(),
// ),
// AttributeValue::None => {
// channel.remove_attribute(id.0 as u32, name, ns.unwrap_or_default())
// }
// _ => unreachable!(),
// },
// SetText { value, id } => channel.set_text(id.0 as u32, value),
// NewEventListener { name, id, .. } => {
// channel.new_event_listener(name, id.0 as u32, event_bubbles(name) as u8)
// }
// RemoveEventListener { name, id } => {
// channel.remove_event_listener(name, id.0 as u32, event_bubbles(name) as u8)
// }
// Remove { id } => channel.remove(id.0 as u32),
// PushRoot { id } => channel.push_root(id.0 as u32),
// }
// }
// let bytes: Vec<_> = channel.export_memory().collect();
// channel.reset();
// Some(bytes)
// }
// pub fn add_template(
// template: &Template,
// channel: &mut Channel,
// templates: &mut FxHashMap<String, u16>,
// max_template_count: &AtomicU16,
// ) {
// let current_max_template_count = max_template_count.load(Ordering::Relaxed);
// for root in template.roots.iter() {
// create_template_node(channel, root);
// templates.insert(template.name.to_owned(), current_max_template_count);
// }
// channel.add_templates(current_max_template_count, template.roots.len() as u16);
// max_template_count.fetch_add(1, Ordering::Relaxed);
// }
// pub fn create_template_node(channel: &mut Channel, node: &'static TemplateNode) {
// use TemplateNode::*;
// match node {
// Element {
// tag,
// namespace,
// attrs,
// children,
// ..
// } => {
// // Push the current node onto the stack
// match namespace {
// Some(ns) => channel.create_element_ns(tag, ns),
// None => channel.create_element(tag),
// }
// // Set attributes on the current node
// for attr in *attrs {
// if let TemplateAttribute::Static {
// name,
// value,
// namespace,
// } = attr
// {
// channel.set_top_attribute(name, value, namespace.unwrap_or_default())
// }
// }
// // Add each child to the stack
// for child in *children {
// create_template_node(channel, child);
// }
// // Add all children to the parent
// channel.append_children_to_top(children.len() as u16);
// }
// Text { text } => channel.create_raw_text(text),
// DynamicText { .. } => channel.create_raw_text("p"),
// Dynamic { .. } => channel.add_placeholder(),
// }
// }
-82
View File
@@ -1,82 +0,0 @@
use std::fmt::{self, Write};
/// Escape a string to pass it into JavaScript.
///
/// # Example
///
/// ```rust,ignore
/// # use web_view::WebView;
/// # use std::mem;
/// #
/// # let mut view: WebView<()> = unsafe { mem::uninitialized() };
/// #
/// let string = "Hello, world!";
///
/// // Calls the function callback with "Hello, world!" as its parameter.
///
/// view.eval(&format!("callback({});", web_view::escape(string)));
/// ```
#[allow(unused)]
pub fn escape_js_string(string: &str) -> Escaper {
Escaper(string)
}
// "All code points may appear literally in a string literal except for the
// closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE
// RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A
// (LINE FEED)." - ES6 Specification
pub struct Escaper<'a>(&'a str);
const SPECIAL: &[char] = &[
'\n', // U+000A (LINE FEED)
'\r', // U+000D (CARRIAGE RETURN)
'\'', // U+0027 (APOSTROPHE)
'\\', // U+005C (REVERSE SOLIDUS)
'\u{2028}', // U+2028 (LINE SEPARATOR)
'\u{2029}', // U+2029 (PARAGRAPH SEPARATOR)
];
impl<'a> fmt::Display for Escaper<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let &Escaper(mut string) = self;
f.write_char('\'')?;
while !string.is_empty() {
if let Some(i) = string.find(SPECIAL) {
if i > 0 {
f.write_str(&string[..i])?;
}
let mut chars = string[i..].chars();
f.write_str(match chars.next().unwrap() {
'\n' => "\\n",
'\r' => "\\r",
'\'' => "\\'",
'\\' => "\\\\",
'\u{2028}' => "\\u2028",
'\u{2029}' => "\\u2029",
_ => unreachable!(),
})?;
string = chars.as_str();
} else {
f.write_str(string)?;
break;
}
}
f.write_char('\'')?;
Ok(())
}
}
#[test]
fn test() {
let plain = "ABC \n\r' abc \\ \u{2028} \u{2029}123";
let escaped = escape_js_string(plain).to_string();
assert!(escaped == "'ABC \\n\\r\\' abc \\\\ \\u2028 \\u2029123'");
}
+65
View File
@@ -0,0 +1,65 @@
use crate::{ipc::UserWindowEvent, window};
use slab::Slab;
use std::cell::RefCell;
use tao::{event::Event, event_loop::EventLoopWindowTarget, window::WindowId};
/// The unique identifier of a window event handler. This can be used to later remove the handler.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WryEventHandler(pub(crate) usize);
impl WryEventHandler {
/// Unregister this event handler from the window
pub fn remove(&self) {
window().shared.event_handlers.remove(*self)
}
}
#[derive(Default)]
pub struct WindowEventHandlers {
handlers: RefCell<Slab<WryWindowEventHandlerInner>>,
}
struct WryWindowEventHandlerInner {
window_id: WindowId,
#[allow(clippy::type_complexity)]
handler:
Box<dyn FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static>,
}
impl WindowEventHandlers {
pub(crate) fn add(
&self,
window_id: WindowId,
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
WryEventHandler(
self.handlers
.borrow_mut()
.insert(WryWindowEventHandlerInner {
window_id,
handler: Box::new(handler),
}),
)
}
pub(crate) fn remove(&self, id: WryEventHandler) {
self.handlers.borrow_mut().try_remove(id.0);
}
pub fn apply_event(
&self,
event: &Event<UserWindowEvent>,
target: &EventLoopWindowTarget<UserWindowEvent>,
) {
for (_, handler) in self.handlers.borrow_mut().iter_mut() {
// if this event does not apply to the window this listener cares about, return
if let Event::WindowEvent { window_id, .. } = event {
if *window_id != handler.window_id {
return;
}
}
(handler.handler)(event, target)
}
}
}
+27 -34
View File
@@ -8,29 +8,23 @@ use dioxus_core::{
prelude::{consume_context, current_scope_id},
use_hook,
};
use dioxus_hooks::use_on_drop;
use dioxus_hooks::use_hook_with_cleanup;
use tao::{event::Event, event_loop::EventLoopWindowTarget};
use wry::RequestAsyncResponder;
/// Get an imperative handle to the current window
pub fn use_window() -> DesktopContext {
use_hook(|| consume_context::<DesktopContext>())
use_hook(consume_context::<DesktopContext>)
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_wry_event_handler(
handler: impl FnMut(&Event<UserWindowEvent>, &EventLoopWindowTarget<UserWindowEvent>) + 'static,
) -> WryEventHandler {
use_hook(move || {
let desktop = window();
let id = desktop.create_wry_event_handler(handler);
WryEventHandler {
handlers: desktop.shared.event_handlers.clone(),
id,
}
})
use_hook_with_cleanup(
move || window().create_wry_event_handler(handler),
move |handler| handler.remove(),
)
}
/// Provide a callback to handle asset loading yourself.
@@ -41,19 +35,20 @@ pub fn use_asset_handler(
name: &str,
handler: impl Fn(AssetRequest, RequestAsyncResponder) + 'static,
) {
let name = use_hook(|| {
crate::window().asset_handlers.register_handler(
name.to_string(),
Box::new(handler),
current_scope_id().unwrap(),
);
use_hook_with_cleanup(
|| {
crate::window().asset_handlers.register_handler(
name.to_string(),
Box::new(handler),
current_scope_id().unwrap(),
);
Rc::new(name.to_string())
});
use_on_drop(move || {
_ = crate::window().asset_handlers.remove_handler(name.as_ref());
});
Rc::new(name.to_string())
},
move |name| {
_ = crate::window().asset_handlers.remove_handler(name.as_ref());
},
);
}
/// Get a closure that executes any JavaScript in the WebView context.
@@ -61,14 +56,12 @@ pub fn use_global_shortcut(
accelerator: impl IntoAccelerator,
handler: impl FnMut() + 'static,
) -> Result<ShortcutHandle, ShortcutRegistryError> {
use_hook(move || {
let desktop = window();
let id = desktop.create_shortcut(accelerator.accelerator(), handler);
Ok(ShortcutHandle {
desktop,
shortcut_id: id?,
})
})
use_hook_with_cleanup(
move || window().create_shortcut(accelerator.accelerator(), handler),
|handle| {
if let Ok(handle) = handle {
handle.remove();
}
},
)
}
+1 -1
View File
@@ -85,5 +85,5 @@ pub fn launch(
}));
#[cfg(not(feature = "tokio"))]
launch_with_props_blocking(config, platform_config)
launch_with_props_blocking(virtual_dom, platform_config)
}
+4 -7
View File
@@ -9,8 +9,8 @@ mod config;
mod desktop_context;
mod edits;
mod element;
mod escape;
mod eval;
mod event_handlers;
mod events;
mod file_upload;
mod hooks;
@@ -39,11 +39,8 @@ pub use wry;
// Public exports
pub use assets::AssetRequest;
pub use config::{Config, WindowCloseBehaviour};
pub use desktop_context::{
window, DesktopContext, DesktopService, WryEventHandler, WryEventHandlerId,
};
pub use desktop_context::{window, DesktopContext, DesktopService};
pub use event_handlers::WryEventHandler;
pub use hooks::{use_asset_handler, use_global_shortcut, use_window, use_wry_event_handler};
pub use shortcut::{ShortcutHandle, ShortcutId, ShortcutRegistryError};
pub use shortcut::{ShortcutHandle, ShortcutRegistryError};
pub use wry::RequestAsyncResponder;
pub use hooks::*;
+15 -20
View File
@@ -1,11 +1,11 @@
use std::{cell::RefCell, rc::Rc};
use crate::DesktopContext;
use futures_util::StreamExt;
use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;
use slab::Slab;
use thiserror::Error;
use tokio::sync::broadcast::error::RecvError;
const DIOXUS_CODE: &str = r#"
let dioxus = {
@@ -64,8 +64,8 @@ impl<T> Default for SharedSlab<T> {
}
struct QueryEntry {
channel_sender: tokio::sync::mpsc::UnboundedSender<Value>,
return_sender: Option<tokio::sync::oneshot::Sender<Value>>,
channel_sender: futures_channel::mpsc::UnboundedSender<Value>,
return_sender: Option<futures_channel::oneshot::Sender<Value>>,
}
const QUEUE_NAME: &str = "__msg_queues";
@@ -83,8 +83,8 @@ impl QueryEngine {
script: &str,
context: DesktopContext,
) -> Query<V> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let (return_tx, return_rx) = tokio::sync::oneshot::channel();
let (tx, rx) = futures_channel::mpsc::unbounded();
let (return_tx, return_rx) = futures_channel::oneshot::channel();
let request_id = self.active_requests.slab.borrow_mut().insert(QueryEntry {
channel_sender: tx,
return_sender: Some(return_tx),
@@ -99,14 +99,14 @@ impl QueryEngine {
if (!window.{QUEUE_NAME}) {{
window.{QUEUE_NAME} = [];
}}
let _request_id = {request_id};
if (!window.{QUEUE_NAME}[{request_id}]) {{
window.{QUEUE_NAME}[{request_id}] = [];
}}
let _message_queue = window.{QUEUE_NAME}[{request_id}];
{script}
}})().then((result)=>{{
let returned_value = {{
@@ -150,7 +150,7 @@ impl QueryEngine {
let _ = sender.send(data);
}
} else {
let _ = entry.channel_sender.send(data);
let _ = entry.channel_sender.unbounded_send(data);
}
}
}
@@ -159,8 +159,8 @@ impl QueryEngine {
pub(crate) struct Query<V: DeserializeOwned> {
desktop: DesktopContext,
slab: SharedSlab<QueryEntry>,
receiver: tokio::sync::mpsc::UnboundedReceiver<Value>,
return_receiver: Option<tokio::sync::oneshot::Receiver<Value>>,
receiver: futures_channel::mpsc::UnboundedReceiver<Value>,
return_receiver: Option<futures_channel::oneshot::Receiver<Value>>,
id: usize,
phantom: std::marker::PhantomData<V>,
}
@@ -200,18 +200,13 @@ impl<V: DeserializeOwned> Query<V> {
/// Receive a message from the query
pub async fn recv(&mut self) -> Result<Value, QueryError> {
self.receiver
.recv()
.await
.ok_or(QueryError::Recv(RecvError::Closed))
self.receiver.next().await.ok_or(QueryError::Recv)
}
/// Receive the result of the query
pub async fn result(&mut self) -> Result<Value, QueryError> {
match self.return_receiver.take() {
Some(receiver) => receiver
.await
.map_err(|_| QueryError::Recv(RecvError::Closed)),
Some(receiver) => receiver.await.map_err(|_| QueryError::Recv),
None => Err(QueryError::Finished),
}
}
@@ -238,8 +233,8 @@ impl<V: DeserializeOwned> Drop for Query<V> {
#[derive(Error, Debug)]
pub enum QueryError {
#[error("Error receiving query result: {0}")]
Recv(RecvError),
#[error("Error receiving query result.")]
Recv,
#[error("Error sending message to query: {0}")]
Send(String),
#[error("Error deserializing query result: {0}")]
+95 -125
View File
@@ -1,11 +1,3 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc, str::FromStr};
use dioxus_html::input_data::keyboard_types::Modifiers;
use slab::Slab;
use tao::keyboard::ModifiersState;
use crate::desktop_context::DesktopContext;
#[cfg(any(
target_os = "windows",
target_os = "macos",
@@ -23,101 +15,23 @@ pub use global_hotkey::{
#[cfg(any(target_os = "ios", target_os = "android"))]
pub use crate::mobile_shortcut::*;
pub(crate) struct ShortcutRegistry {
manager: GlobalHotKeyManager,
shortcuts: RefCell<HashMap<u32, Shortcut>>,
use crate::window;
use dioxus_html::input_data::keyboard_types::Modifiers;
use slab::Slab;
use std::{cell::RefCell, collections::HashMap, rc::Rc, str::FromStr};
use tao::keyboard::ModifiersState;
/// An global id for a shortcut.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShortcutHandle {
id: u32,
number: usize,
}
struct Shortcut {
#[allow(unused)]
shortcut: HotKey,
callbacks: Slab<Box<dyn FnMut()>>,
}
impl Shortcut {
fn insert(&mut self, callback: Box<dyn FnMut()>) -> usize {
self.callbacks.insert(callback)
}
fn remove(&mut self, id: usize) {
let _ = self.callbacks.remove(id);
}
fn is_empty(&self) -> bool {
self.callbacks.is_empty()
}
}
impl ShortcutRegistry {
pub fn new() -> Self {
Self {
manager: GlobalHotKeyManager::new().unwrap(),
shortcuts: RefCell::new(HashMap::new()),
}
}
pub(crate) fn call_handlers(&self, id: GlobalHotKeyEvent) {
if let Some(Shortcut { callbacks, .. }) = self.shortcuts.borrow_mut().get_mut(&id.id) {
for (_, callback) in callbacks.iter_mut() {
(callback)();
}
}
}
pub(crate) fn add_shortcut(
&self,
hotkey: HotKey,
callback: Box<dyn FnMut()>,
) -> Result<ShortcutId, ShortcutRegistryError> {
let accelerator_id = hotkey.clone().id();
let mut shortcuts = self.shortcuts.borrow_mut();
if let Some(callbacks) = shortcuts.get_mut(&accelerator_id) {
return Ok(ShortcutId {
id: accelerator_id,
number: callbacks.insert(callback),
});
};
self.manager.register(hotkey).map_err(|e| match e {
HotkeyError::HotKeyParseError(shortcut) => {
ShortcutRegistryError::InvalidShortcut(shortcut)
}
err => ShortcutRegistryError::Other(Rc::new(err)),
})?;
let mut shortcut = Shortcut {
shortcut: hotkey,
callbacks: Slab::new(),
};
let id = shortcut.callbacks.insert(callback);
shortcuts.insert(accelerator_id, shortcut);
Ok(ShortcutId {
id: accelerator_id,
number: id,
})
}
pub(crate) fn remove_shortcut(&self, id: ShortcutId) {
let mut shortcuts = self.shortcuts.borrow_mut();
if let Some(callbacks) = shortcuts.get_mut(&id.id) {
callbacks.remove(id.number);
if callbacks.is_empty() {
if let Some(_shortcut) = shortcuts.remove(&id.id) {
let _ = self.manager.unregister(_shortcut.shortcut);
}
}
}
}
pub(crate) fn remove_all(&self) {
let mut shortcuts = self.shortcuts.borrow_mut();
let hotkeys: Vec<_> = shortcuts.drain().map(|(_, v)| v.shortcut).collect();
let _ = self.manager.unregister_all(&hotkeys);
impl ShortcutHandle {
/// Remove the shortcut.
pub fn remove(&self) {
window().remove_shortcut(*self);
}
}
@@ -131,19 +45,88 @@ pub enum ShortcutRegistryError {
Other(Rc<dyn std::error::Error>),
}
/// An global id for a shortcut.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ShortcutId {
id: u32,
number: usize,
pub(crate) struct ShortcutRegistry {
manager: GlobalHotKeyManager,
shortcuts: RefCell<HashMap<u32, ShortcutInner>>,
}
/// A global shortcut. This will be automatically removed when it is dropped.
#[derive(Clone)]
pub struct ShortcutHandle {
pub(crate) desktop: DesktopContext,
/// The id of the shortcut
pub shortcut_id: ShortcutId,
struct ShortcutInner {
#[allow(unused)]
shortcut: HotKey,
callbacks: Slab<Box<dyn FnMut()>>,
}
impl ShortcutRegistry {
pub fn new() -> Self {
Self {
manager: GlobalHotKeyManager::new().unwrap(),
shortcuts: RefCell::new(HashMap::new()),
}
}
pub(crate) fn call_handlers(&self, id: GlobalHotKeyEvent) {
if let Some(ShortcutInner { callbacks, .. }) = self.shortcuts.borrow_mut().get_mut(&id.id) {
for (_, callback) in callbacks.iter_mut() {
(callback)();
}
}
}
pub(crate) fn add_shortcut(
&self,
hotkey: HotKey,
callback: Box<dyn FnMut()>,
) -> Result<ShortcutHandle, ShortcutRegistryError> {
let accelerator_id = hotkey.clone().id();
let mut shortcuts = self.shortcuts.borrow_mut();
if let Some(callbacks) = shortcuts.get_mut(&accelerator_id) {
return Ok(ShortcutHandle {
id: accelerator_id,
number: callbacks.callbacks.insert(callback),
});
};
self.manager.register(hotkey).map_err(|e| match e {
HotkeyError::HotKeyParseError(shortcut) => {
ShortcutRegistryError::InvalidShortcut(shortcut)
}
err => ShortcutRegistryError::Other(Rc::new(err)),
})?;
let mut shortcut = ShortcutInner {
shortcut: hotkey,
callbacks: Slab::new(),
};
let id = shortcut.callbacks.insert(callback);
shortcuts.insert(accelerator_id, shortcut);
Ok(ShortcutHandle {
id: accelerator_id,
number: id,
})
}
pub(crate) fn remove_shortcut(&self, id: ShortcutHandle) {
let mut shortcuts = self.shortcuts.borrow_mut();
if let Some(callbacks) = shortcuts.get_mut(&id.id) {
let _ = callbacks.callbacks.remove(id.number);
if callbacks.callbacks.is_empty() {
if let Some(_shortcut) = shortcuts.remove(&id.id) {
let _ = self.manager.unregister(_shortcut.shortcut);
}
}
}
}
pub(crate) fn remove_all(&self) {
let mut shortcuts = self.shortcuts.borrow_mut();
let hotkeys: Vec<_> = shortcuts.drain().map(|(_, v)| v.shortcut).collect();
let _ = self.manager.unregister_all(&hotkeys);
}
}
pub trait IntoAccelerator {
@@ -174,19 +157,6 @@ impl IntoAccelerator for &str {
}
}
impl ShortcutHandle {
/// Remove the shortcut.
pub fn remove(&self) {
self.desktop.remove_shortcut(self.shortcut_id);
}
}
impl Drop for ShortcutHandle {
fn drop(&mut self) {
self.remove()
}
}
pub trait IntoModifersState {
fn into_modifiers_state(self) -> Modifiers;
}
+5 -21
View File
@@ -8,7 +8,7 @@ use crate::{
waker::tao_waker,
Config, DesktopContext, DesktopService,
};
use dioxus_core::VirtualDom;
use dioxus_core::{ScopeId, VirtualDom};
use dioxus_html::prelude::EvalProvider;
use futures_util::{pin_mut, FutureExt};
use std::{any::Any, rc::Rc, task::Waker};
@@ -148,27 +148,13 @@ impl WebviewInstance {
asset_handlers,
));
// Provide the desktop context to the virtualdom
// dom.base_scope().provide_context(desktop_context.clone());
// let query = dom.in_runtime(|| {
// let query = ScopeId::ROOT.provide_context(desktop_context.clone());
// // Init eval
// init_eval();
// query
// });
// let desktop_ctx = ScopeId::ROOT.consume_context::<DesktopContext>().unwrap();
// let provider: Rc<dyn EvalProvider> = Rc::new(DesktopEvalProvider { desktop_ctx });
// ScopeId::ROOT.provide_context(provider);
// Also set up its eval provider
// It's important that we provide as dyn EvalProvider - using the concrete type has
// a different TypeId and can not be downcasted as dyn EvalProvider
let provider: Rc<dyn EvalProvider> =
Rc::new(DesktopEvalProvider::new(desktop_context.clone()));
// dom.base_scope().provide_context(provider);
dom.in_runtime(|| {
ScopeId::ROOT.provide_context(desktop_context.clone());
ScopeId::ROOT.provide_context(provider);
});
WebviewInstance {
waker: tao_waker(shared.proxy.clone(), desktop_context.window.id()),
@@ -196,8 +182,6 @@ impl WebviewInstance {
}
}
// self.desktop_context.send_edits(self.dom.render_immediate());
self.dom
.render_immediate(&mut *self.desktop_context.mutation_state.borrow_mut());
self.desktop_context.send_edits();
+13 -19
View File
@@ -67,19 +67,7 @@ impl LaunchBuilder {
self
}
#[allow(clippy::unit_arg)]
/// Launch the app.
pub fn launch(self) {
current_platform::launch(
self.cross_platform_config,
Default::default(),
self.platform_config.unwrap_or_default(),
);
}
}
#[cfg(feature = "web")]
impl LaunchBuilder {
#[cfg(feature = "web")]
/// Launch your web application.
pub fn launch_web(self) {
dioxus_web::launch::launch(
@@ -88,11 +76,9 @@ impl LaunchBuilder {
Default::default(),
);
}
}
#[cfg(feature = "desktop")]
impl LaunchBuilder {
/// Launch your desktop application.
#[cfg(feature = "desktop")]
pub fn launch_desktop(self) {
dioxus_desktop::launch::launch(
self.cross_platform_config,
@@ -100,11 +86,9 @@ impl LaunchBuilder {
Default::default(),
);
}
}
#[cfg(feature = "fullstack")]
impl LaunchBuilder {
/// Launch your fullstack application.
#[cfg(feature = "fullstack")]
pub fn launch_fullstack(self) {
dioxus_fullstack::launch::launch(
self.cross_platform_config,
@@ -112,6 +96,16 @@ impl LaunchBuilder {
Default::default(),
);
}
#[allow(clippy::unit_arg)]
/// Launch the app.
pub fn launch(self) {
current_platform::launch(
self.cross_platform_config,
Default::default(),
self.platform_config.unwrap_or_default(),
);
}
}
mod current_platform {
-6
View File
@@ -67,12 +67,6 @@ pub use use_coroutine::*;
mod use_future;
pub use use_future::*;
// mod use_effect;
// pub use use_effect::*;
// mod use_memo;
// pub use use_memo::*;
// mod use_on_create;
// pub use use_on_create::*;
+10
View File
@@ -100,3 +100,13 @@ pub fn use_on_destroy<D: FnOnce() + 'static>(destroy: D) {
pub fn use_on_drop<D: FnOnce() + 'static>(ondrop: D) {
use_on_destroy(ondrop);
}
pub fn use_hook_with_cleanup<T: Clone + 'static>(
hook: impl FnOnce() -> T,
cleanup: impl FnOnce(T) + 'static,
) -> T {
let value = use_hook(|| hook());
let _value = value.clone();
use_on_destroy(move || cleanup(_value));
value
}
+14 -5
View File
@@ -13,18 +13,27 @@ keywords = ["dom", "ui", "gui", "react", "wasm"]
[dependencies]
wasm-bindgen = { workspace = true, optional = true }
js-sys = { version = "0.3.56", optional = true }
web-sys = { version = "0.3.56", optional = true, features = ["Element", "Node"] }
web-sys = { version = "0.3.56", optional = true, features = [
"Element",
"Node",
] }
sledgehammer_bindgen = { version = "0.3.1", default-features = false, optional = true }
sledgehammer_utils = { version = "0.2", optional = true }
serde = { version = "1.0", features = ["derive"], optional = true }
dioxus-core = { workspace = true , optional = true }
dioxus-html = { workspace = true , optional = true }
dioxus-core = { workspace = true, optional = true }
dioxus-html = { workspace = true, optional = true }
[features]
default = []
serialize = ["serde"]
sledgehammer = ["sledgehammer_bindgen", "sledgehammer_utils"]
web = ["sledgehammer", "wasm-bindgen", "js-sys", "web-sys", "sledgehammer_bindgen/web"]
binary-protocol = ["sledgehammer", "wasm-bindgen", "dioxus-core", "dioxus-html"]
web = [
"sledgehammer",
"wasm-bindgen",
"js-sys",
"web-sys",
"sledgehammer_bindgen/web",
]
binary-protocol = ["sledgehammer", "dioxus-core", "dioxus-html"]
minimal_bindings = []
+4 -4
View File
@@ -16,19 +16,19 @@ rust-version = "1.60.0"
dioxus-core = { workspace = true }
generational-box = { workspace = true }
tracing = { workspace = true }
simple_logger = "4.2.0"
serde = { version = "1", features = ["derive"], optional = true }
parking_lot = "0.12.1"
once_cell = "1.18.0"
rustc-hash.workspace = true
futures-channel.workspace = true
futures-util.workspace = true
rustc-hash = { workspace = true }
futures-channel = { workspace = true }
futures-util = { workspace = true }
[dev-dependencies]
dioxus = { workspace = true }
dioxus-desktop = { workspace = true }
tokio = { version = "1", features = ["full"] }
tracing-subscriber = "0.3.17"
simple_logger = "4.2.0"
[features]
default = []