merge master

This commit is contained in:
Evan Almloff committed 2022-12-20 20:48:28 -06:00
1 parent 67921cacc3
commit e5a5850354
105 files changed
+1415 -2106

No files matched your search

+10
View File
@@ -21,6 +21,7 @@ pub struct Config {
pub(crate) resource_dir: Option<PathBuf>,
pub(crate) custom_head: Option<String>,
pub(crate) custom_index: Option<String>,
pub(crate) root_name: String,
}
type DropHandler = Box<dyn Fn(&Window, FileDropEvent) -> bool>;
@@ -46,6 +47,7 @@ impl Config {
resource_dir: None,
custom_head: None,
custom_index: None,
root_name: "main".to_string(),
}
}
@@ -126,6 +128,14 @@ impl Config {
self.custom_index = Some(index);
self
}
/// Set the name of the element that Dioxus will use as the root.
///
/// This is akint to calling React.render() on the element with the specified name.
pub fn with_root_name(mut self, name: impl Into<String>) -> Self {
self.root_name = name.into();
self
}
}
impl Default for Config {
+14 -8
View File
@@ -1,6 +1,6 @@
use crate::desktop_context::{DesktopContext, UserWindowEvent};
use crate::events::{decode_event, EventMessage};
use dioxus_core::*;
use dioxus_html::HtmlEvent;
use futures_channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender};
use futures_util::StreamExt;
#[cfg(target_os = "ios")]
@@ -54,6 +54,7 @@ impl DesktopController {
std::thread::spawn(move || {
// We create the runtime as multithreaded, so you can still "tokio::spawn" onto multiple threads
// I'd personally not require tokio to be built-in to Dioxus-Desktop, but the DX is worse without it
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
@@ -85,12 +86,14 @@ impl DesktopController {
}
_ = dom.wait_for_work() => {}
Some(json_value) = event_rx.next() => {
if let Ok(value) = serde_json::from_value::<EventMessage>(json_value) {
let name = value.event.clone();
let el_id = ElementId(value.mounted_dom_id);
if let Some(evt) = decode_event(value) {
dom.handle_event(&name, evt, el_id, dioxus_html::events::event_bubbles(&name));
}
if let Ok(value) = serde_json::from_value::<HtmlEvent>(json_value) {
let HtmlEvent {
name,
element,
bubbles,
data
} = value;
dom.handle_event(&name, data.into_any(), element, bubbles);
}
}
}
@@ -99,7 +102,10 @@ impl DesktopController {
.render_with_deadline(tokio::time::sleep(Duration::from_millis(16)))
.await;
edit_queue.lock().unwrap().push(serde_json::to_string(&muts).unwrap());
edit_queue
.lock()
.unwrap()
.push(serde_json::to_string(&muts).unwrap());
let _ = proxy.send_event(UserWindowEvent::EditsReady);
}
})
-61
View File
@@ -2,9 +2,6 @@
use dioxus_html::*;
use serde::{Deserialize, Serialize};
use serde_json::from_value;
use std::any::Any;
use std::rc::Rc;
#[derive(Deserialize, Serialize)]
pub(crate) struct IpcMessage {
@@ -31,61 +28,3 @@ pub(crate) fn parse_ipc_message(payload: &str) -> Option<IpcMessage> {
}
}
}
macro_rules! match_data {
(
$m:ident;
$name:ident;
$(
$tip:ty => $($mname:literal)|* ;
)*
) => {
match $name {
$( $($mname)|* => {
let val: $tip = from_value::<$tip>($m).ok()?;
Rc::new(val) as Rc<dyn Any>
})*
_ => return None,
}
};
}
#[derive(Deserialize)]
pub struct EventMessage {
pub contents: serde_json::Value,
pub event: String,
pub mounted_dom_id: usize,
}
pub fn decode_event(value: EventMessage) -> Option<Rc<dyn Any>> {
let val = value.contents;
let name = value.event.as_str();
type DragData = MouseData;
let evt = match_data! { val; name;
MouseData => "click" | "contextmenu" | "dblclick" | "doubleclick" | "mousedown" | "mouseenter" | "mouseleave" | "mousemove" | "mouseout" | "mouseover" | "mouseup";
ClipboardData => "copy" | "cut" | "paste";
CompositionData => "compositionend" | "compositionstart" | "compositionupdate";
KeyboardData => "keydown" | "keypress" | "keyup";
FocusData => "blur" | "focus" | "focusin" | "focusout";
FormData => "change" | "input" | "invalid" | "reset" | "submit";
DragData => "drag" | "dragend" | "dragenter" | "dragexit" | "dragleave" | "dragover" | "dragstart" | "drop";
PointerData => "pointerlockchange" | "pointerlockerror" | "pointerdown" | "pointermove" | "pointerup" | "pointerover" | "pointerout" | "pointerenter" | "pointerleave" | "gotpointercapture" | "lostpointercapture";
SelectionData => "selectstart" | "selectionchange" | "select";
TouchData => "touchcancel" | "touchend" | "touchmove" | "touchstart";
ScrollData => "scroll";
WheelData => "wheel";
MediaData => "abort" | "canplay" | "canplaythrough" | "durationchange" | "emptied"
| "encrypted" | "ended" | "interruptbegin" | "interruptend" | "loadeddata"
| "loadedmetadata" | "loadstart" | "pause" | "play" | "playing" | "progress"
| "ratechange" | "seeked" | "seeking" | "stalled" | "suspend" | "timeupdate"
| "volumechange" | "waiting" | "error" | "load" | "loadend" | "timeout";
AnimationData => "animationstart" | "animationend" | "animationiteration";
TransitionData => "transitionend";
ToggleData => "toggle";
// ImageData => "load" | "error";
// OtherData => "abort" | "afterprint" | "beforeprint" | "beforeunload" | "hashchange" | "languagechange" | "message" | "offline" | "online" | "pagehide" | "pageshow" | "popstate" | "rejectionhandled" | "storage" | "unhandledrejection" | "unload" | "userproximity" | "vrdisplayactivate" | "vrdisplayblur" | "vrdisplayconnect" | "vrdisplaydeactivate" | "vrdisplaydisconnect" | "vrdisplayfocus" | "vrdisplaypointerrestricted" | "vrdisplaypointerunrestricted" | "vrdisplaypresentchange";
};
Some(evt)
}
+33 -27
View File
@@ -167,6 +167,7 @@ fn build_webview(
let custom_head = cfg.custom_head.clone();
let resource_dir = cfg.resource_dir.clone();
let index_file = cfg.custom_index.clone();
let root_name = cfg.root_name.clone();
// We assume that if the icon is None in cfg, then the user just didnt set it
if cfg.window.window.window_icon.is_none() {
@@ -186,36 +187,40 @@ fn build_webview(
.with_url("dioxus://index.html/")
.unwrap()
.with_ipc_handler(move |_window: &Window, payload: String| {
parse_ipc_message(&payload)
.map(|message| match message.method() {
"eval_result" => {
let result = message.params();
eval_sender.send(result).unwrap();
}
"user_event" => {
_ = event_tx.unbounded_send(message.params());
}
"initialize" => {
is_ready.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = proxy.send_event(UserWindowEvent::EditsReady);
}
"browser_open" => {
let data = message.params();
log::trace!("Open browser: {:?}", data);
if let Some(temp) = data.as_object() {
if temp.contains_key("href") {
let url = temp.get("href").unwrap().as_str().unwrap();
if let Err(e) = webbrowser::open(url) {
log::error!("Open Browser error: {:?}", e);
}
let message = match parse_ipc_message(&payload) {
Some(message) => message,
None => {
log::error!("Failed to parse IPC message: {}", payload);
return;
}
};
match message.method() {
"eval_result" => {
let result = message.params();
eval_sender.send(result).unwrap();
}
"user_event" => {
_ = event_tx.unbounded_send(message.params());
}
"initialize" => {
is_ready.store(true, std::sync::atomic::Ordering::Relaxed);
let _ = proxy.send_event(UserWindowEvent::EditsReady);
}
"browser_open" => {
let data = message.params();
log::trace!("Open browser: {:?}", data);
if let Some(temp) = data.as_object() {
if temp.contains_key("href") {
let url = temp.get("href").unwrap().as_str().unwrap();
if let Err(e) = webbrowser::open(url) {
log::error!("Open Browser error: {:?}", e);
}
}
}
_ => (),
})
.unwrap_or_else(|| {
log::warn!("invalid IPC message received");
});
}
_ => (),
}
})
.with_custom_protocol(String::from("dioxus"), move |r| {
protocol::desktop_handler(
@@ -223,6 +228,7 @@ fn build_webview(
resource_dir.clone(),
custom_head.clone(),
index_file.clone(),
&root_name,
)
})
.with_file_drop_handler(move |window, evet| {
+19 -7
View File
@@ -1,22 +1,34 @@
use dioxus_interpreter_js::INTERPRETER_JS;
use std::path::{Path, PathBuf};
use wry::{
http::{status::StatusCode, Request, Response},
Result,
};
const MODULE_LOADER: &str = r#"
fn module_loader(root_name: &str) -> String {
format!(
r#"
<script>
import("./index.js").then(function (module) {
module.main();
});
{INTERPRETER_JS}
let rootname = "{}";
let root = window.document.getElementById(rootname);
if (root != null) {{
window.interpreter = new Interpreter(root);
window.ipc.postMessage(serializeIpcMessage("initialize"));
}}
</script>
"#;
"#,
root_name
)
}
pub(super) fn desktop_handler(
request: &Request<Vec<u8>>,
asset_root: Option<PathBuf>,
custom_head: Option<String>,
custom_index: Option<String>,
root_name: &str,
) -> Result<Response<Vec<u8>>> {
// Any content that uses the `dioxus://` scheme will be shuttled through this handler as a "special case".
// For now, we only serve two pieces of content which get included as bytes into the final binary.
@@ -30,7 +42,7 @@ pub(super) fn desktop_handler(
// we'll look for the closing </body> tag and insert our little module loader there.
if let Some(custom_index) = custom_index {
let rendered = custom_index
.replace("</body>", &format!("{}</body>", MODULE_LOADER))
.replace("</body>", &format!("{}</body>", module_loader(root_name)))
.into_bytes();
Response::builder()
.header("Content-Type", "text/html")
@@ -42,7 +54,7 @@ pub(super) fn desktop_handler(
if let Some(custom_head) = custom_head {
template = template.replace("<!-- CUSTOM HEAD -->", &custom_head);
}
template = template.replace("<!-- MODULE LOADER -->", MODULE_LOADER);
template = template.replace("<!-- MODULE LOADER -->", &module_loader(root_name));
Response::builder()
.header("Content-Type", "text/html")