Merge branch 'master' into binary-protocal
This commit is contained in:
76 files changed
+1918
-625
No files matched your search
@@ -35,6 +35,7 @@ pub struct Config {
|
||||
pub(crate) root_name: String,
|
||||
pub(crate) background_color: Option<(u8, u8, u8, u8)>,
|
||||
pub(crate) last_window_close_behaviour: WindowCloseBehaviour,
|
||||
pub(crate) enable_default_menu_bar: bool,
|
||||
}
|
||||
|
||||
type DropHandler = Box<dyn Fn(&Window, FileDropEvent) -> bool>;
|
||||
@@ -64,9 +65,18 @@ impl Config {
|
||||
root_name: "main".to_string(),
|
||||
background_color: None,
|
||||
last_window_close_behaviour: WindowCloseBehaviour::LastWindowExitsApp,
|
||||
enable_default_menu_bar: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set whether the default menu bar should be enabled.
|
||||
///
|
||||
/// > Note: `enable` is `true` by default. To disable the default menu bar pass `false`.
|
||||
pub fn with_default_menu_bar(mut self, enable: bool) -> Self {
|
||||
self.enable_default_menu_bar = enable;
|
||||
self
|
||||
}
|
||||
|
||||
/// set the directory from which assets will be searched in release mode
|
||||
pub fn with_resource_directory(mut self, path: impl Into<PathBuf>) -> Self {
|
||||
self.resource_dir = Some(path.into());
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::create_new_window;
|
||||
use crate::events::IpcMessage;
|
||||
use crate::protocol::AssetFuture;
|
||||
use crate::protocol::AssetHandlerRegistry;
|
||||
use crate::query::QueryEngine;
|
||||
use crate::shortcut::{HotKey, ShortcutId, ShortcutRegistry, ShortcutRegistryError};
|
||||
use crate::AssetHandler;
|
||||
use crate::Config;
|
||||
use crate::WebviewHandler;
|
||||
use dioxus_core::ScopeState;
|
||||
@@ -114,6 +117,7 @@ pub struct DesktopService {
|
||||
pub(crate) max_template_count: AtomicU16,
|
||||
|
||||
pub(crate) channel: RefCell<Channel>,
|
||||
pub(crate) asset_handlers: AssetHandlerRegistry,
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
pub(crate) views: Rc<RefCell<Vec<*mut objc::runtime::Object>>>,
|
||||
@@ -140,6 +144,7 @@ impl DesktopService {
|
||||
event_handlers: WindowEventHandlers,
|
||||
shortcut_manager: ShortcutRegistry,
|
||||
edit_queue: EditQueue,
|
||||
asset_handlers: AssetHandlerRegistry,
|
||||
) -> Self {
|
||||
Self {
|
||||
webview: Rc::new(webview),
|
||||
@@ -153,6 +158,7 @@ impl DesktopService {
|
||||
templates: Default::default(),
|
||||
max_template_count: Default::default(),
|
||||
channel: Default::default(),
|
||||
asset_handlers,
|
||||
#[cfg(target_os = "ios")]
|
||||
views: Default::default(),
|
||||
}
|
||||
@@ -303,6 +309,20 @@ impl DesktopService {
|
||||
self.shortcut_manager.remove_all()
|
||||
}
|
||||
|
||||
/// Provide a callback to handle asset loading yourself.
|
||||
///
|
||||
/// See [`use_asset_handle`](crate::use_asset_handle) for a convenient hook.
|
||||
pub async fn register_asset_handler<F: AssetFuture>(&self, f: impl AssetHandler<F>) -> usize {
|
||||
self.asset_handlers.register_handler(f).await
|
||||
}
|
||||
|
||||
/// Removes an asset handler by its identifier.
|
||||
///
|
||||
/// Returns `None` if the handler did not exist.
|
||||
pub async fn remove_asset_handler(&self, id: usize) -> Option<()> {
|
||||
self.asset_handlers.remove_handler(id).await
|
||||
}
|
||||
|
||||
/// Push an objc view to the window
|
||||
#[cfg(target_os = "ios")]
|
||||
pub fn push_view(&self, view: objc_id::ShareId<objc::runtime::Object>) {
|
||||
|
||||
@@ -34,6 +34,7 @@ use element::DesktopElement;
|
||||
use eval::init_eval;
|
||||
use futures_util::{pin_mut, FutureExt};
|
||||
use rustc_hash::FxHashMap;
|
||||
pub use protocol::{use_asset_handler, AssetFuture, AssetHandler, AssetRequest, AssetResponse};
|
||||
use shortcut::ShortcutRegistry;
|
||||
pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError};
|
||||
use std::cell::Cell;
|
||||
@@ -48,6 +49,7 @@ use tao::{
|
||||
event::{Event, StartCause, WindowEvent},
|
||||
event_loop::ControlFlow,
|
||||
};
|
||||
pub use webview::build_default_menu_bar;
|
||||
pub use wry;
|
||||
pub use wry::application as tao;
|
||||
use wry::application::event_loop::EventLoopBuilder;
|
||||
@@ -401,7 +403,8 @@ fn create_new_window(
|
||||
event_handlers: &WindowEventHandlers,
|
||||
shortcut_manager: ShortcutRegistry,
|
||||
) -> WebviewHandler {
|
||||
let (webview, web_context, edit_queue) = webview::build(&mut cfg, event_loop, proxy.clone());
|
||||
let (webview, web_context, asset_handlers, edit_queue) =
|
||||
webview::build(&mut cfg, event_loop, proxy.clone());
|
||||
let desktop_context = Rc::from(DesktopService::new(
|
||||
webview,
|
||||
proxy.clone(),
|
||||
@@ -409,6 +412,7 @@ fn create_new_window(
|
||||
queue.clone(),
|
||||
event_handlers.clone(),
|
||||
shortcut_manager,
|
||||
asset_handlers,
|
||||
edit_queue,
|
||||
));
|
||||
|
||||
|
||||
@@ -1,18 +1,58 @@
|
||||
use dioxus_core::ScopeState;
|
||||
use dioxus_interpreter_js::{COMMON_JS, INTERPRETER_JS};
|
||||
use slab::Slab;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
future::Future,
|
||||
ops::Deref,
|
||||
path::{Path, PathBuf},
|
||||
pin::Pin,
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
};
|
||||
use tokio::{
|
||||
runtime::Handle,
|
||||
sync::{OnceCell, RwLock},
|
||||
};
|
||||
use wry::{
|
||||
http::{status::StatusCode, Request, Response},
|
||||
webview::RequestAsyncResponder,
|
||||
Result,
|
||||
};
|
||||
use crate::{use_window, DesktopContext};
|
||||
|
||||
use crate::desktop_context::EditQueue;
|
||||
|
||||
static MINIFIED: &str = include_str!("./minified.js");
|
||||
|
||||
fn module_loader(root_name: &str, headless: bool) -> String {
|
||||
let js = INTERPRETER_JS.replace(
|
||||
"/*POST_HANDLE_EDITS*/",
|
||||
r#"// Prevent file inputs from opening the file dialog on click
|
||||
let inputs = document.querySelectorAll("input");
|
||||
for (let input of inputs) {
|
||||
if (!input.getAttribute("data-dioxus-file-listener")) {
|
||||
// prevent file inputs from opening the file dialog on click
|
||||
const type = input.getAttribute("type");
|
||||
if (type === "file") {
|
||||
input.setAttribute("data-dioxus-file-listener", true);
|
||||
input.addEventListener("click", (event) => {
|
||||
let target = event.target;
|
||||
let target_id = find_real_id(target);
|
||||
if (target_id !== null) {
|
||||
const send = (event_name) => {
|
||||
const message = serializeIpcMessage("file_diolog", { accept: target.getAttribute("accept"), directory: target.getAttribute("webkitdirectory") === "true", multiple: target.hasAttribute("multiple"), target: parseInt(target_id), bubbles: event_bubbles(event_name), event: event_name });
|
||||
window.ipc.postMessage(message);
|
||||
};
|
||||
send("change&input");
|
||||
}
|
||||
event.preventDefault();
|
||||
});
|
||||
}
|
||||
}
|
||||
}"#,
|
||||
);
|
||||
|
||||
format!(
|
||||
r#"
|
||||
<script type="module">
|
||||
@@ -32,15 +72,158 @@ fn module_loader(root_name: &str, headless: bool) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn desktop_handler(
|
||||
request: &Request<Vec<u8>>,
|
||||
responder: RequestAsyncResponder,
|
||||
/// An arbitrary asset is an HTTP response containing a binary body.
|
||||
pub type AssetResponse = Response<Cow<'static, [u8]>>;
|
||||
|
||||
/// A future that returns an [`AssetResponse`]. This future may be spawned in a new thread,
|
||||
/// so it must be [`Send`], [`Sync`], and `'static`.
|
||||
pub trait AssetFuture: Future<Output = Option<AssetResponse>> + Send + Sync + 'static {}
|
||||
impl<T: Future<Output = Option<AssetResponse>> + Send + Sync + 'static> AssetFuture for T {}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
/// A request for an asset. This is a wrapper around [`Request<Vec<u8>>`] that provides methods specific to asset requests.
|
||||
pub struct AssetRequest {
|
||||
path: PathBuf,
|
||||
request: Arc<Request<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl AssetRequest {
|
||||
/// Get the path the asset request is for
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.path
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Request<Vec<u8>>> for AssetRequest {
|
||||
fn from(request: Request<Vec<u8>>) -> Self {
|
||||
let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/'))
|
||||
.expect("expected URL to be UTF-8 encoded");
|
||||
let path = PathBuf::from(&*decoded);
|
||||
Self {
|
||||
request: Arc::new(request),
|
||||
path,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for AssetRequest {
|
||||
type Target = Request<Vec<u8>>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.request
|
||||
}
|
||||
}
|
||||
|
||||
/// A handler that takes an [`AssetRequest`] and returns a future that either loads the asset, or returns `None`.
|
||||
/// This handler is stashed indefinitely in a context object, so it must be `'static`.
|
||||
pub trait AssetHandler<F: AssetFuture>: Send + Sync + 'static {
|
||||
/// Handle an asset request, returning a future that either loads the asset, or returns `None`
|
||||
fn handle_request(&self, request: &AssetRequest) -> F;
|
||||
}
|
||||
|
||||
impl<F: AssetFuture, T: Fn(&AssetRequest) -> F + Send + Sync + 'static> AssetHandler<F> for T {
|
||||
fn handle_request(&self, request: &AssetRequest) -> F {
|
||||
self(request)
|
||||
}
|
||||
}
|
||||
|
||||
type AssetHandlerRegistryInner =
|
||||
Slab<Box<dyn Fn(&AssetRequest) -> Pin<Box<dyn AssetFuture>> + Send + Sync + 'static>>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AssetHandlerRegistry(Arc<RwLock<AssetHandlerRegistryInner>>);
|
||||
|
||||
impl AssetHandlerRegistry {
|
||||
pub fn new() -> Self {
|
||||
AssetHandlerRegistry(Arc::new(RwLock::new(Slab::new())))
|
||||
}
|
||||
|
||||
pub async fn register_handler<F: AssetFuture>(&self, f: impl AssetHandler<F>) -> usize {
|
||||
let mut registry = self.0.write().await;
|
||||
registry.insert(Box::new(move |req| Box::pin(f.handle_request(req))))
|
||||
}
|
||||
|
||||
pub async fn remove_handler(&self, id: usize) -> Option<()> {
|
||||
let mut registry = self.0.write().await;
|
||||
registry.try_remove(id).map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn try_handlers(&self, req: &AssetRequest) -> Option<AssetResponse> {
|
||||
let registry = self.0.read().await;
|
||||
for (_, handler) in registry.iter() {
|
||||
if let Some(response) = handler(req).await {
|
||||
return Some(response);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle to a registered asset handler.
|
||||
pub struct AssetHandlerHandle {
|
||||
desktop: DesktopContext,
|
||||
handler_id: Rc<OnceCell<usize>>,
|
||||
}
|
||||
|
||||
impl AssetHandlerHandle {
|
||||
/// Returns the ID for this handle.
|
||||
///
|
||||
/// Because registering an ID is asynchronous, this may return `None` if the
|
||||
/// registration has not completed yet.
|
||||
pub fn handler_id(&self) -> Option<usize> {
|
||||
self.handler_id.get().copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AssetHandlerHandle {
|
||||
fn drop(&mut self) {
|
||||
let cell = Rc::clone(&self.handler_id);
|
||||
let desktop = Rc::clone(&self.desktop);
|
||||
tokio::task::block_in_place(move || {
|
||||
Handle::current().block_on(async move {
|
||||
if let Some(id) = cell.get() {
|
||||
desktop.asset_handlers.remove_handler(*id).await;
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide a callback to handle asset loading yourself.
|
||||
///
|
||||
/// The callback takes a path as requested by the web view, and it should return `Some(response)`
|
||||
/// if you want to load the asset, and `None` if you want to fallback on the default behavior.
|
||||
pub fn use_asset_handler<F: AssetFuture>(
|
||||
cx: &ScopeState,
|
||||
handler: impl AssetHandler<F>,
|
||||
) -> &AssetHandlerHandle {
|
||||
let desktop = Rc::clone(use_window(cx));
|
||||
cx.use_hook(|| {
|
||||
let handler_id = Rc::new(OnceCell::new());
|
||||
let handler_id_ref = Rc::clone(&handler_id);
|
||||
let desktop_ref = Rc::clone(&desktop);
|
||||
cx.push_future(async move {
|
||||
let id = desktop.asset_handlers.register_handler(handler).await;
|
||||
handler_id.set(id).unwrap();
|
||||
});
|
||||
AssetHandlerHandle {
|
||||
desktop: desktop_ref,
|
||||
handler_id: handler_id_ref,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn desktop_handler(
|
||||
request: Request<Vec<u8>>,
|
||||
custom_head: Option<String>,
|
||||
custom_index: Option<String>,
|
||||
root_name: &str,
|
||||
asset_handlers: &AssetHandlerRegistry,
|
||||
edit_queue: &EditQueue,
|
||||
headless: bool,
|
||||
) {
|
||||
) -> Result<AssetResponse> {
|
||||
let request = AssetRequest::from(request);
|
||||
|
||||
// If the request is for the root, we'll serve the index.html file.
|
||||
if request.uri().path() == "/" {
|
||||
// If a custom index is provided, just defer to that, expecting the user to know what they're doing.
|
||||
@@ -86,18 +269,21 @@ pub(super) fn desktop_handler(
|
||||
return;
|
||||
}
|
||||
|
||||
// If the user provided a custom asset handler, then call it and return the response
|
||||
// if the request was handled.
|
||||
if let Some(response) = asset_handlers.try_handlers(&request).await {
|
||||
return Ok(response);
|
||||
}
|
||||
|
||||
// Else, try to serve a file from the filesystem.
|
||||
let decoded = urlencoding::decode(request.uri().path().trim_start_matches('/'))
|
||||
.expect("expected URL to be UTF-8 encoded");
|
||||
let path = PathBuf::from(&*decoded);
|
||||
|
||||
// If the path is relative, we'll try to serve it from the assets directory.
|
||||
let mut asset = get_asset_root()
|
||||
.unwrap_or_else(|| Path::new(".").to_path_buf())
|
||||
.join(&path);
|
||||
.join(&request.path);
|
||||
|
||||
if !asset.exists() {
|
||||
asset = PathBuf::from("/").join(path);
|
||||
asset = PathBuf::from("/").join(request.path);
|
||||
}
|
||||
|
||||
if asset.exists() {
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
use crate::desktop_context::{EditQueue, EventData};
|
||||
use crate::protocol;
|
||||
use crate::protocol::{self, AssetHandlerRegistry};
|
||||
use crate::{desktop_context::UserWindowEvent, Config};
|
||||
use tao::event_loop::{EventLoopProxy, EventLoopWindowTarget};
|
||||
pub use wry;
|
||||
pub use wry::application as tao;
|
||||
use wry::application::menu::{MenuBar, MenuItem};
|
||||
use wry::application::window::Window;
|
||||
use wry::http::Response;
|
||||
use wry::webview::{WebContext, WebView, WebViewBuilder};
|
||||
|
||||
pub(crate) fn build(
|
||||
cfg: &mut Config,
|
||||
event_loop: &EventLoopWindowTarget<UserWindowEvent>,
|
||||
proxy: EventLoopProxy<UserWindowEvent>,
|
||||
) -> (WebView, WebContext, EditQueue) {
|
||||
) -> (WebView, WebContext, AssetHandlerRegistry, EditQueue) {
|
||||
let builder = cfg.window.clone();
|
||||
let window = builder.with_visible(false).build(event_loop).unwrap();
|
||||
let file_handler = cfg.file_drop_handler.take();
|
||||
@@ -19,6 +21,12 @@ pub(crate) fn build(
|
||||
let index_file = cfg.custom_index.clone();
|
||||
let root_name = cfg.root_name.clone();
|
||||
|
||||
if cfg.enable_default_menu_bar {
|
||||
builder = builder.with_menu(build_default_menu_bar());
|
||||
}
|
||||
|
||||
let window = builder.with_visible(false).build(event_loop).unwrap();
|
||||
|
||||
// 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() {
|
||||
window.set_window_icon(Some(
|
||||
@@ -34,6 +42,8 @@ pub(crate) fn build(
|
||||
let mut web_context = WebContext::new(cfg.data_dir.clone());
|
||||
let edit_queue = EditQueue::default();
|
||||
let headless = !cfg.window.window.visible;
|
||||
let asset_handlers = AssetHandlerRegistry::new();
|
||||
let asset_handlers_ref = asset_handlers.clone();
|
||||
|
||||
let mut webview = WebViewBuilder::new(window)
|
||||
.unwrap()
|
||||
@@ -46,19 +56,22 @@ pub(crate) fn build(
|
||||
_ = proxy.send_event(UserWindowEvent(EventData::Ipc(message), window.id()));
|
||||
}
|
||||
})
|
||||
.with_asynchronous_custom_protocol("dioxus".into(), {
|
||||
let edit_queue = edit_queue.clone();
|
||||
move |r, responder| {
|
||||
protocol::desktop_handler(
|
||||
&r,
|
||||
responder,
|
||||
.with_asynchronous_custom_protocol(String::from("dioxus"), move |request, responder| {
|
||||
let custom_head = custom_head.clone();
|
||||
let index_file = index_file.clone();
|
||||
let root_name = root_name.clone();
|
||||
let asset_handlers_ref = asset_handlers_ref.clone();
|
||||
tokio::spawn(async move {
|
||||
let response_res = protocol::desktop_handler(
|
||||
request,
|
||||
custom_head.clone(),
|
||||
index_file.clone(),
|
||||
&root_name,
|
||||
&edit_queue,
|
||||
headless,
|
||||
&asset_handlers_ref,
|
||||
)
|
||||
}
|
||||
.await;
|
||||
responder.respond(response);
|
||||
});
|
||||
})
|
||||
.with_file_drop_handler(move |window, evet| {
|
||||
file_handler
|
||||
@@ -84,7 +97,16 @@ pub(crate) fn build(
|
||||
// .with_web_context(&mut web_context);
|
||||
|
||||
for (name, handler) in cfg.protocols.drain(..) {
|
||||
webview = webview.with_custom_protocol(name, handler)
|
||||
webview = webview.with_custom_protocol(name, move |r| match handler(&r) {
|
||||
Ok(response) => response,
|
||||
Err(err) => {
|
||||
tracing::error!("Error: {}", err);
|
||||
Response::builder()
|
||||
.status(500)
|
||||
.body(err.to_string().into_bytes().into())
|
||||
.unwrap()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if cfg.disable_context_menu {
|
||||
@@ -107,5 +129,63 @@ pub(crate) fn build(
|
||||
webview = webview.with_devtools(true);
|
||||
}
|
||||
|
||||
(webview.build().unwrap(), web_context, edit_queue)
|
||||
(webview.build().unwrap(), web_context, asset_handlers, edit_queue)
|
||||
}
|
||||
|
||||
/// Builds a standard menu bar depending on the users platform. It may be used as a starting point
|
||||
/// to further customize the menu bar and pass it to a [`WindowBuilder`](tao::window::WindowBuilder).
|
||||
/// > Note: The default menu bar enables macOS shortcuts like cut/copy/paste.
|
||||
/// > The menu bar differs per platform because of constraints introduced
|
||||
/// > by [`MenuItem`](tao::menu::MenuItem).
|
||||
pub fn build_default_menu_bar() -> MenuBar {
|
||||
let mut menu_bar = MenuBar::new();
|
||||
|
||||
// since it is uncommon on windows to have an "application menu"
|
||||
// we add a "window" menu to be more consistent across platforms with the standard menu
|
||||
let mut window_menu = MenuBar::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
window_menu.add_native_item(MenuItem::EnterFullScreen);
|
||||
window_menu.add_native_item(MenuItem::Zoom);
|
||||
window_menu.add_native_item(MenuItem::Separator);
|
||||
}
|
||||
|
||||
window_menu.add_native_item(MenuItem::Hide);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
window_menu.add_native_item(MenuItem::HideOthers);
|
||||
window_menu.add_native_item(MenuItem::ShowAll);
|
||||
}
|
||||
|
||||
window_menu.add_native_item(MenuItem::Minimize);
|
||||
window_menu.add_native_item(MenuItem::CloseWindow);
|
||||
window_menu.add_native_item(MenuItem::Separator);
|
||||
window_menu.add_native_item(MenuItem::Quit);
|
||||
menu_bar.add_submenu("Window", true, window_menu);
|
||||
|
||||
// since tao supports none of the below items on linux we should only add them on macos/windows
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let mut edit_menu = MenuBar::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
edit_menu.add_native_item(MenuItem::Undo);
|
||||
edit_menu.add_native_item(MenuItem::Redo);
|
||||
edit_menu.add_native_item(MenuItem::Separator);
|
||||
}
|
||||
|
||||
edit_menu.add_native_item(MenuItem::Cut);
|
||||
edit_menu.add_native_item(MenuItem::Copy);
|
||||
edit_menu.add_native_item(MenuItem::Paste);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
edit_menu.add_native_item(MenuItem::Separator);
|
||||
edit_menu.add_native_item(MenuItem::SelectAll);
|
||||
}
|
||||
menu_bar.add_submenu("Edit", true, edit_menu);
|
||||
}
|
||||
|
||||
menu_bar
|
||||
}
|
||||
Reference in new issue
Block a user