Changed directory to webkitdirectory in bool_attrs definitions.

This commit is contained in:
Kaid committed 2023-07-10 17:19:11 +08:00
commit e39d8708fa
285 files changed
+20566 -1330

No files matched your search

+29
View File
@@ -11,6 +11,17 @@ use wry::{
// pub(crate) type DynEventHandlerFn = dyn Fn(&mut EventLoop<()>, &mut WebView);
/// The behaviour of the application when the last window is closed.
#[derive(Copy, Clone, Eq, PartialEq)]
pub enum WindowCloseBehaviour {
/// Default behaviour, closing the last window exits the app
LastWindowExitsApp,
/// Closing the last window will not actually close it, just hide it
LastWindowHides,
/// Closing the last window will close it but the app will keep running so that new windows can be opened
CloseWindow,
}
/// The configuration for the desktop application.
pub struct Config {
pub(crate) window: WindowBuilder,
@@ -23,6 +34,8 @@ pub struct Config {
pub(crate) custom_head: Option<String>,
pub(crate) custom_index: Option<String>,
pub(crate) root_name: String,
pub(crate) background_color: Option<(u8, u8, u8, u8)>,
pub(crate) last_window_close_behaviour: WindowCloseBehaviour,
}
type DropHandler = Box<dyn Fn(&Window, FileDropEvent) -> bool>;
@@ -50,6 +63,8 @@ impl Config {
custom_head: None,
custom_index: None,
root_name: "main".to_string(),
background_color: None,
last_window_close_behaviour: WindowCloseBehaviour::LastWindowExitsApp,
}
}
@@ -87,6 +102,12 @@ impl Config {
self
}
/// Sets the behaviour of the application when the last window is closed.
pub fn with_close_behaviour(mut self, behaviour: WindowCloseBehaviour) -> Self {
self.last_window_close_behaviour = behaviour;
self
}
/// Set a file drop handler
pub fn with_file_drop_handler(
mut self,
@@ -137,6 +158,14 @@ impl Config {
self.root_name = name.into();
self
}
/// Sets the background color of the WebView.
/// This will be set before the HTML is rendered and can be used to prevent flashing when the page loads.
/// Accepts a color in RGBA format
pub fn with_background_color(mut self, color: (u8, u8, u8, u8)) -> Self {
self.background_color = Some(color);
self
}
}
impl Default for Config {
+22 -21
View File
@@ -6,8 +6,6 @@ use crate::create_new_window;
use crate::eval::EvalResult;
use crate::events::IpcMessage;
use crate::query::QueryEngine;
use crate::shortcut::IntoKeyCode;
use crate::shortcut::IntoModifersState;
use crate::shortcut::ShortcutId;
use crate::shortcut::ShortcutRegistry;
use crate::shortcut::ShortcutRegistryError;
@@ -18,6 +16,7 @@ use dioxus_core::VirtualDom;
#[cfg(all(feature = "hot-reload", debug_assertions))]
use dioxus_hot_reload::HotReloadMsg;
use slab::Slab;
use wry::application::accelerator::Accelerator;
use wry::application::event::Event;
use wry::application::event_loop::EventLoopProxy;
use wry::application::event_loop::EventLoopWindowTarget;
@@ -51,8 +50,7 @@ pub(crate) type WebviewQueue = Rc<RefCell<Vec<WebviewHandler>>>;
/// ```rust, ignore
/// let desktop = cx.consume_context::<DesktopContext>().unwrap();
/// ```
#[derive(Clone)]
pub struct DesktopContext {
pub struct DesktopService {
/// The wry/tao proxy to the current window
pub webview: Rc<WebView>,
@@ -74,8 +72,11 @@ pub struct DesktopContext {
pub(crate) views: Rc<RefCell<Vec<*mut objc::runtime::Object>>>,
}
/// A handle to the [`DesktopService`] that can be passed around.
pub type DesktopContext = Rc<DesktopService>;
/// A smart pointer to the current window.
impl std::ops::Deref for DesktopContext {
impl std::ops::Deref for DesktopService {
type Target = Window;
fn deref(&self) -> &Self::Target {
@@ -83,9 +84,9 @@ impl std::ops::Deref for DesktopContext {
}
}
impl DesktopContext {
impl DesktopService {
pub(crate) fn new(
webview: Rc<WebView>,
webview: WebView,
proxy: ProxyType,
event_loop: EventLoopWindowTarget<UserWindowEvent>,
webviews: WebviewQueue,
@@ -93,7 +94,7 @@ impl DesktopContext {
shortcut_manager: ShortcutRegistry,
) -> Self {
Self {
webview,
webview: Rc::new(webview),
proxy,
event_loop,
query: Default::default(),
@@ -112,7 +113,7 @@ impl DesktopContext {
/// You can use this to control other windows from the current window.
///
/// Be careful to not create a cycle of windows, or you might leak memory.
pub fn new_window(&self, dom: VirtualDom, cfg: Config) -> Weak<WebView> {
pub fn new_window(&self, dom: VirtualDom, cfg: Config) -> Weak<DesktopService> {
let window = create_new_window(
cfg,
&self.event_loop,
@@ -123,7 +124,13 @@ impl DesktopContext {
self.shortcut_manager.clone(),
);
let id = window.webview.window().id();
let desktop_context = window
.dom
.base_scope()
.consume_context::<Rc<DesktopService>>()
.unwrap();
let id = window.desktop_context.webview.window().id();
self.proxy
.send_event(UserWindowEvent(EventData::NewWindow, id))
@@ -133,11 +140,9 @@ impl DesktopContext {
.send_event(UserWindowEvent(EventData::Poll, id))
.unwrap();
let webview = window.webview.clone();
self.pending_windows.borrow_mut().push(window);
Rc::downgrade(&webview)
Rc::downgrade(&desktop_context)
}
/// trigger the drag-window event
@@ -237,15 +242,11 @@ impl DesktopContext {
/// Linux: Only works on x11. See [this issue](https://github.com/tauri-apps/tao/issues/331) for more information.
pub fn create_shortcut(
&self,
key: impl IntoKeyCode,
modifiers: impl IntoModifersState,
accelerator: Accelerator,
callback: impl FnMut() + 'static,
) -> Result<ShortcutId, ShortcutRegistryError> {
self.shortcut_manager.add_shortcut(
modifiers.into_modifiers_state(),
key.into_key_code(),
Box::new(callback),
)
self.shortcut_manager
.add_shortcut(accelerator, Box::new(callback))
}
/// Remove a global shortcut
@@ -405,7 +406,7 @@ pub fn use_wry_event_handler(
let id = desktop.create_wry_event_handler(handler);
WryEventHandler {
handlers: desktop.event_handlers,
handlers: desktop.event_handlers.clone(),
id,
}
})
+6 -9
View File
@@ -1,20 +1,17 @@
use std::rc::Rc;
use dioxus_core::ElementId;
use dioxus_html::{geometry::euclid::Rect, MountedResult, RenderedElementBacking};
use wry::webview::WebView;
use crate::query::QueryEngine;
use crate::{desktop_context::DesktopContext, query::QueryEngine};
/// A mounted element passed to onmounted events
pub struct DesktopElement {
id: ElementId,
webview: Rc<WebView>,
webview: DesktopContext,
query: QueryEngine,
}
impl DesktopElement {
pub(crate) fn new(id: ElementId, webview: Rc<WebView>, query: QueryEngine) -> Self {
pub(crate) fn new(id: ElementId, webview: DesktopContext, query: QueryEngine) -> Self {
Self { id, webview, query }
}
}
@@ -37,7 +34,7 @@ impl RenderedElementBacking for DesktopElement {
let fut = self
.query
.new_query::<Option<Rect<f64, f64>>>(&script, &self.webview)
.new_query::<Option<Rect<f64, f64>>>(&script, &self.webview.webview)
.resolve();
Box::pin(async move {
match fut.await {
@@ -64,7 +61,7 @@ impl RenderedElementBacking for DesktopElement {
let fut = self
.query
.new_query::<bool>(&script, &self.webview)
.new_query::<bool>(&script, &self.webview.webview)
.resolve();
Box::pin(async move {
match fut.await {
@@ -90,7 +87,7 @@ impl RenderedElementBacking for DesktopElement {
let fut = self
.query
.new_query::<bool>(&script, &self.webview)
.new_query::<bool>(&script, &self.webview.webview)
.resolve();
Box::pin(async move {
+32 -7
View File
@@ -1,9 +1,10 @@
use std::{path::PathBuf, str::FromStr};
#![allow(unused)]
use serde::Deserialize;
use std::{path::PathBuf, str::FromStr};
#[derive(Debug, Deserialize)]
pub(crate) struct FileDiologRequest {
pub(crate) struct FileDialogRequest {
#[serde(default)]
accept: Option<String>,
multiple: bool,
@@ -13,7 +14,7 @@ pub(crate) struct FileDiologRequest {
pub bubbles: bool,
}
fn get_file_event_for_folder(request: &FileDiologRequest, dialog: rfd::FileDialog) -> Vec<PathBuf> {
fn get_file_event_for_folder(request: &FileDialogRequest, dialog: rfd::FileDialog) -> Vec<PathBuf> {
if request.multiple {
dialog.pick_folders().into_iter().flatten().collect()
} else {
@@ -22,7 +23,7 @@ fn get_file_event_for_folder(request: &FileDiologRequest, dialog: rfd::FileDialo
}
fn get_file_event_for_file(
request: &FileDiologRequest,
request: &FileDialogRequest,
mut dialog: rfd::FileDialog,
) -> Vec<PathBuf> {
let filters: Vec<_> = request
@@ -40,14 +41,38 @@ fn get_file_event_for_file(
dialog = dialog.add_filter("name", file_extensions.as_slice());
if request.multiple {
let files: Vec<_> = if request.multiple {
dialog.pick_files().into_iter().flatten().collect()
} else {
dialog.pick_file().into_iter().collect()
}
};
files
}
pub(crate) fn get_file_event(request: &FileDiologRequest) -> Vec<PathBuf> {
#[cfg(not(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)))]
pub(crate) fn get_file_event(_request: &FileDialogRequest) -> Vec<PathBuf> {
vec![]
}
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub(crate) fn get_file_event(request: &FileDialogRequest) -> Vec<PathBuf> {
let dialog = rfd::FileDialog::new();
if request.directory {
+115 -46
View File
@@ -16,10 +16,14 @@ mod shortcut;
mod waker;
mod webview;
#[cfg(any(target_os = "ios", target_os = "android"))]
mod mobile_shortcut;
use crate::query::QueryResult;
pub use cfg::Config;
pub use cfg::{Config, WindowCloseBehaviour};
pub use desktop_context::DesktopContext;
pub use desktop_context::{
use_window, use_wry_event_handler, DesktopContext, WryEventHandler, WryEventHandlerId,
use_window, use_wry_event_handler, DesktopService, WryEventHandler, WryEventHandlerId,
};
use desktop_context::{EventData, UserWindowEvent, WebviewQueue, WindowEventHandlers};
use dioxus_core::*;
@@ -30,6 +34,7 @@ pub use eval::{use_eval, EvalResult};
use futures_util::{pin_mut, FutureExt};
use shortcut::ShortcutRegistry;
pub use shortcut::{use_global_shortcut, ShortcutHandle, ShortcutId, ShortcutRegistryError};
use std::cell::Cell;
use std::rc::Rc;
use std::task::Waker;
use std::{collections::HashMap, sync::Arc};
@@ -117,17 +122,19 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
let proxy = event_loop.create_proxy();
let window_behaviour = cfg.last_window_close_behaviour;
// Intialize hot reloading if it is enabled
#[cfg(all(feature = "hot-reload", debug_assertions))]
{
dioxus_hot_reload::connect({
let proxy = proxy.clone();
dioxus_hot_reload::connect(move |template| {
move |template| {
let _ = proxy.send_event(UserWindowEvent(
EventData::HotReloadEvent(template),
unsafe { WindowId::dummy() },
));
});
}
}
});
// We start the tokio runtime *on this thread*
// Any future we poll later will use this runtime to spawn tasks and for IO
@@ -150,16 +157,10 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
let shortcut_manager = ShortcutRegistry::new(&event_loop);
// By default, we'll create a new window when the app starts
queue.borrow_mut().push(create_new_window(
cfg,
&event_loop,
&proxy,
VirtualDom::new_with_props(root, props),
&queue,
&event_handlers,
shortcut_manager.clone(),
));
// move the props into a cell so we can pop it out later to create the first window
// iOS panics if we create a window before the event loop is started
let props = Rc::new(Cell::new(Some(props)));
let cfg = Rc::new(Cell::new(Some(cfg)));
event_loop.run(move |window_event, event_loop, control_flow| {
*control_flow = ControlFlow::Wait;
@@ -170,27 +171,61 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
Event::WindowEvent {
event, window_id, ..
} => match event {
WindowEvent::CloseRequested => {
webviews.remove(&window_id);
WindowEvent::CloseRequested => match window_behaviour {
cfg::WindowCloseBehaviour::LastWindowExitsApp => {
webviews.remove(&window_id);
if webviews.is_empty() {
*control_flow = ControlFlow::Exit
if webviews.is_empty() {
*control_flow = ControlFlow::Exit
}
}
}
cfg::WindowCloseBehaviour::LastWindowHides => {
let Some(webview) = webviews.get(&window_id) else {
return;
};
hide_app_window(&webview.desktop_context.webview);
}
cfg::WindowCloseBehaviour::CloseWindow => {
webviews.remove(&window_id);
}
},
WindowEvent::Destroyed { .. } => {
webviews.remove(&window_id);
if webviews.is_empty() {
*control_flow = ControlFlow::Exit;
if matches!(
window_behaviour,
cfg::WindowCloseBehaviour::LastWindowExitsApp
) && webviews.is_empty()
{
*control_flow = ControlFlow::Exit
}
}
_ => {}
},
Event::NewEvents(StartCause::Init)
| Event::UserEvent(UserWindowEvent(EventData::NewWindow, _)) => {
Event::NewEvents(StartCause::Init) => {
//
let props = props.take().unwrap();
let cfg = cfg.take().unwrap();
let handler = create_new_window(
cfg,
event_loop,
&proxy,
VirtualDom::new_with_props(root, props),
&queue,
&event_handlers,
shortcut_manager.clone(),
);
let id = handler.desktop_context.webview.window().id();
webviews.insert(id, handler);
_ = proxy.send_event(UserWindowEvent(EventData::Poll, id));
}
Event::UserEvent(UserWindowEvent(EventData::NewWindow, _)) => {
for handler in queue.borrow_mut().drain(..) {
let id = handler.webview.window().id();
let id = handler.desktop_context.webview.window().id();
webviews.insert(id, handler);
_ = proxy.send_event(UserWindowEvent(EventData::Poll, id));
}
@@ -249,9 +284,11 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
.base_scope()
.consume_context::<DesktopContext>()
.unwrap()
.query;
.query
.clone();
let element = DesktopElement::new(element, view.webview.clone(), query);
let element =
DesktopElement::new(element, view.desktop_context.clone(), query);
Rc::new(MountedData::new(element))
} else {
@@ -260,7 +297,7 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
view.dom.handle_event(&name, as_any, element, bubbles);
send_edits(view.dom.render_immediate(), &view.webview);
send_edits(view.dom.render_immediate(), &view.desktop_context.webview);
}
// When the webview sends a query, we need to send it to the query manager which handles dispatching the data to the correct pending query
@@ -274,7 +311,8 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
.base_scope()
.consume_context::<DesktopContext>()
.unwrap()
.query;
.query
.clone();
query.send(result);
}
@@ -282,7 +320,7 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
EventData::Ipc(msg) if msg.method() == "initialize" => {
let view = webviews.get_mut(&event.1).unwrap();
send_edits(view.dom.rebuild(), &view.webview);
send_edits(view.dom.rebuild(), &view.desktop_context.webview);
}
EventData::Ipc(msg) if msg.method() == "browser_open" => {
@@ -298,7 +336,7 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
EventData::Ipc(msg) if msg.method() == "file_diolog" => {
if let Ok(file_diolog) =
serde_json::from_value::<file_upload::FileDiologRequest>(msg.params())
serde_json::from_value::<file_upload::FileDialogRequest>(msg.params())
{
let id = ElementId(file_diolog.target);
let event_name = &file_diolog.event;
@@ -320,7 +358,7 @@ pub fn launch_with_props<P: 'static>(root: Component<P>, props: P, cfg: Config)
view.dom.handle_event(event_name, data, id, event_bubbles);
}
send_edits(view.dom.render_immediate(), &view.webview);
send_edits(view.dom.render_immediate(), &view.desktop_context.webview);
}
}
@@ -342,9 +380,8 @@ fn create_new_window(
shortcut_manager: ShortcutRegistry,
) -> WebviewHandler {
let (webview, web_context) = webview::build(&mut cfg, event_loop, proxy.clone());
dom.base_scope().provide_context(DesktopContext::new(
webview.clone(),
let desktop_context = Rc::from(DesktopService::new(
webview,
proxy.clone(),
event_loop.clone(),
queue.clone(),
@@ -352,24 +389,25 @@ fn create_new_window(
shortcut_manager,
));
let id = webview.window().id();
dom.base_scope().provide_context(desktop_context.clone());
// We want to poll the virtualdom and the event loop at the same time, so the waker will be connected to both
WebviewHandler {
webview,
// We want to poll the virtualdom and the event loop at the same time, so the waker will be connected to both
waker: waker::tao_waker(proxy, desktop_context.webview.window().id()),
desktop_context,
dom,
waker: waker::tao_waker(proxy, id),
web_context,
_web_context: web_context,
}
}
struct WebviewHandler {
dom: VirtualDom,
webview: Rc<wry::webview::WebView>,
desktop_context: DesktopContext,
waker: Waker,
// This is nessisary because of a bug in wry. Wry assumes the webcontext is alive for the lifetime of the webview. We need to keep the webcontext alive, otherwise the webview will crash
#[allow(dead_code)]
web_context: WebContext,
// Wry assumes the webcontext is alive for the lifetime of the webview.
// We need to keep the webcontext alive, otherwise the webview will crash
_web_context: WebContext,
}
/// Poll the virtualdom until it's pending
@@ -391,7 +429,7 @@ fn poll_vdom(view: &mut WebviewHandler) {
}
}
send_edits(view.dom.render_immediate(), &view.webview);
send_edits(view.dom.render_immediate(), &view.desktop_context.webview);
}
}
@@ -402,3 +440,34 @@ fn send_edits(edits: Mutations, webview: &WebView) {
// todo: use SSE and binary data to send the edits with lower overhead
_ = webview.evaluate_script(&format!("window.interpreter.handleEdits({serialized})"));
}
/// Different hide implementations per platform
#[allow(unused)]
fn hide_app_window(webview: &WebView) {
#[cfg(target_os = "windows")]
{
use wry::application::platform::windows::WindowExtWindows;
webview.window().set_visible(false);
webview.window().set_skip_taskbar(true);
}
#[cfg(target_os = "linux")]
{
use wry::application::platform::unix::WindowExtUnix;
webview.window().set_visible(false);
}
#[cfg(target_os = "macos")]
{
// webview.window().set_visible(false); has the wrong behaviour on macOS
// It will hide the window but not show it again when the user switches
// back to the app. `NSApplication::hide:` has the correct behaviour
use objc::runtime::Object;
use objc::{msg_send, sel, sel_impl};
objc::rc::autoreleasepool(|| unsafe {
let app: *mut Object = msg_send![objc::class!(NSApplication), sharedApplication];
let nil = std::ptr::null_mut::<Object>();
let _: () = msg_send![app, hide: nil];
});
}
}
+55
View File
@@ -0,0 +1,55 @@
#![allow(unused)]
use super::*;
use wry::application::accelerator::Accelerator;
use wry::application::event_loop::EventLoopWindowTarget;
pub struct GlobalShortcut();
pub struct ShortcutManager();
impl ShortcutManager {
pub fn new<T>(target: &EventLoopWindowTarget<T>) -> Self {
Self()
}
pub fn register(
&mut self,
accelerator: Accelerator,
) -> Result<GlobalShortcut, ShortcutManagerError> {
Ok(GlobalShortcut())
}
pub fn unregister(&mut self, id: ShortcutId) -> Result<(), ShortcutManagerError> {
Ok(())
}
pub fn unregister_all(&mut self) -> Result<(), ShortcutManagerError> {
Ok(())
}
}
use std::{error, fmt};
/// An error whose cause the `ShortcutManager` to fail.
#[non_exhaustive]
#[derive(Debug)]
pub enum ShortcutManagerError {
AcceleratorAlreadyRegistered(Accelerator),
AcceleratorNotRegistered(Accelerator),
InvalidAccelerator(String),
}
impl error::Error for ShortcutManagerError {}
impl fmt::Display for ShortcutManagerError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
ShortcutManagerError::AcceleratorAlreadyRegistered(e) => {
f.pad(&format!("hotkey already registered: {:?}", e))
}
ShortcutManagerError::AcceleratorNotRegistered(e) => {
f.pad(&format!("hotkey not registered: {:?}", e))
}
ShortcutManagerError::InvalidAccelerator(e) => e.fmt(f),
}
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ pub(crate) struct QueryEngine {
impl Default for QueryEngine {
fn default() -> Self {
let (sender, _) = tokio::sync::broadcast::channel(8);
let (sender, _) = tokio::sync::broadcast::channel(1000);
Self {
sender: Rc::new(sender),
active_requests: SharedSlab::default(),
+59 -21
View File
@@ -1,4 +1,4 @@
use std::{cell::RefCell, collections::HashMap, rc::Rc};
use std::{cell::RefCell, collections::HashMap, rc::Rc, str::FromStr};
use dioxus_core::ScopeState;
use dioxus_html::input_data::keyboard_types::Modifiers;
@@ -6,11 +6,24 @@ use slab::Slab;
use wry::application::{
accelerator::{Accelerator, AcceleratorId},
event_loop::EventLoopWindowTarget,
global_shortcut::{GlobalShortcut, ShortcutManager, ShortcutManagerError},
keyboard::{KeyCode, ModifiersState},
};
use crate::{use_window, DesktopContext};
use crate::{desktop_context::DesktopContext, use_window};
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
use wry::application::global_shortcut::{GlobalShortcut, ShortcutManager, ShortcutManagerError};
#[cfg(any(target_os = "ios", target_os = "android"))]
pub use crate::mobile_shortcut::*;
#[derive(Clone)]
pub(crate) struct ShortcutRegistry {
@@ -21,6 +34,7 @@ pub(crate) struct ShortcutRegistry {
type ShortcutMap = Rc<RefCell<HashMap<AcceleratorId, Shortcut>>>;
struct Shortcut {
#[allow(unused)]
shortcut: GlobalShortcut,
callbacks: Slab<Box<dyn FnMut()>>,
}
@@ -57,11 +71,9 @@ impl ShortcutRegistry {
pub(crate) fn add_shortcut(
&self,
modifiers: impl Into<Option<ModifiersState>>,
key: KeyCode,
accelerator: Accelerator,
callback: Box<dyn FnMut()>,
) -> Result<ShortcutId, ShortcutRegistryError> {
let accelerator = Accelerator::new(modifiers, key);
let accelerator_id = accelerator.clone().id();
let mut shortcuts = self.shortcuts.borrow_mut();
Ok(
@@ -100,8 +112,17 @@ impl ShortcutRegistry {
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.borrow_mut().unregister(shortcut.shortcut);
if let Some(_shortcut) = shortcuts.remove(&id.id) {
#[cfg(any(
target_os = "windows",
target_os = "macos",
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
let _ = self.manager.borrow_mut().unregister(_shortcut.shortcut);
}
}
}
@@ -111,12 +132,6 @@ impl ShortcutRegistry {
let mut shortcuts = self.shortcuts.borrow_mut();
shortcuts.clear();
let _ = self.manager.borrow_mut().unregister_all();
// prevent CTRL+R from reloading the page which breaks apps
let _ = self.add_shortcut(
Some(ModifiersState::CONTROL),
KeyCode::KeyR,
Box::new(|| {}),
);
}
}
@@ -144,22 +159,45 @@ pub struct ShortcutHandle {
pub shortcut_id: ShortcutId,
}
pub trait IntoAccelerator {
fn accelerator(&self) -> Accelerator;
}
impl IntoAccelerator for (dioxus_html::KeyCode, ModifiersState) {
fn accelerator(&self) -> Accelerator {
Accelerator::new(Some(self.1), self.0.into_key_code())
}
}
impl IntoAccelerator for (ModifiersState, dioxus_html::KeyCode) {
fn accelerator(&self) -> Accelerator {
Accelerator::new(Some(self.0), self.1.into_key_code())
}
}
impl IntoAccelerator for dioxus_html::KeyCode {
fn accelerator(&self) -> Accelerator {
Accelerator::new(None, self.into_key_code())
}
}
impl IntoAccelerator for &str {
fn accelerator(&self) -> Accelerator {
Accelerator::from_str(self).unwrap()
}
}
/// Get a closure that executes any JavaScript in the WebView context.
pub fn use_global_shortcut(
cx: &ScopeState,
key: impl IntoKeyCode,
modifiers: impl IntoModifersState,
accelerator: impl IntoAccelerator,
handler: impl FnMut() + 'static,
) -> &Result<ShortcutHandle, ShortcutRegistryError> {
let desktop = use_window(cx);
cx.use_hook(move || {
let desktop = desktop.clone();
let id = desktop.create_shortcut(
key.into_key_code(),
modifiers.into_modifiers_state(),
handler,
);
let id = desktop.create_shortcut(accelerator.accelerator(), handler);
Ok(ShortcutHandle {
desktop,
+6 -4
View File
@@ -1,5 +1,3 @@
use std::rc::Rc;
use crate::desktop_context::EventData;
use crate::protocol;
use crate::{desktop_context::UserWindowEvent, Config};
@@ -13,7 +11,7 @@ pub fn build(
cfg: &mut Config,
event_loop: &EventLoopWindowTarget<UserWindowEvent>,
proxy: EventLoopProxy<UserWindowEvent>,
) -> (Rc<WebView>, WebContext) {
) -> (WebView, WebContext) {
let builder = cfg.window.clone();
let window = builder.build(event_loop).unwrap();
let file_handler = cfg.file_drop_handler.take();
@@ -64,6 +62,10 @@ pub fn build(
webview = webview.with_browser_accelerator_keys(false);
}
if let Some(color) = cfg.background_color {
webview = webview.with_background_color(color);
}
// These are commented out because wry is currently broken in wry
// let mut web_context = WebContext::new(cfg.data_dir.clone());
// .with_web_context(&mut web_context);
@@ -92,5 +94,5 @@ pub fn build(
webview = webview.with_devtools(true);
}
(Rc::new(webview.build().unwrap()), web_context)
(webview.build().unwrap(), web_context)
}