Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: remove uuid and rand dependencies where applicable #7939

Merged
merged 12 commits into from
Oct 17, 2023
5 changes: 5 additions & 0 deletions .changes/tauri-runtime-uuid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'tauri-runtime': 'patch:breaking'
---

Added `WindowEventId` type and Changed `Dispatch::on_window_event` return type from `Uuid` to `WindowEventId`
5 changes: 5 additions & 0 deletions .changes/tauri-runtime-wry-uuid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'tauri-runtime-wry': 'patch:breaking'
---

Changed `WebviewId` to be an alias for `u32` instead of `u64`
15 changes: 15 additions & 0 deletions .changes/tauri-uuid-rand.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'tauri': 'patch:breaking'
---

This release contains a number of breaking changes to improve the consistency of tauri internals and the public facing APIs
and simplifying the types where applicable:

- Removed `EventHandler` type.
- Added `EventId` type
- Changed `Manager::listen_global` and `Window::listen` to return the new `EventId` type instead of `EventHandler`.
- Removed the return type of `Manager::once_global` and `Window::once`
- Changed `Manager::unlisten` and `Window::unlisten` to take he new `EventId` type.
- Added `tauri::scope::ScopeEventId`
- Changed `FsScope::listen` to return the new `ScopeEventId` instead of `Uuid`.
- Added `FsScope::unlisten`
2 changes: 0 additions & 2 deletions core/tauri-runtime-wry/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ features = [ "dox" ]
wry = { version = "0.33", default-features = false, features = [ "tao", "file-drop", "protocol" ] }
tauri-runtime = { version = "1.0.0-alpha.2", path = "../tauri-runtime" }
tauri-utils = { version = "2.0.0-alpha.8", path = "../tauri-utils" }
uuid = { version = "1", features = [ "v4" ] }
rand = "0.8"
raw-window-handle = "0.5"
http = "0.2"

Expand Down
48 changes: 33 additions & 15 deletions core/tauri-runtime-wry/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use tauri_runtime::{
},
DeviceEventFilter, Dispatch, Error, EventLoopProxy, ExitRequestedEventAction, Icon, Result,
RunEvent, RunIteration, Runtime, RuntimeHandle, RuntimeInitArgs, UserAttentionType, UserEvent,
WindowEventId,
};

#[cfg(windows)]
Expand All @@ -41,7 +42,6 @@ use wry::webview::WebViewBuilderExtWindows;
#[cfg(target_os = "macos")]
use tauri_utils::TitleBarStyle;
use tauri_utils::{config::WindowConfig, debug_eprintln, Theme};
use uuid::Uuid;
use wry::{
application::{
dpi::{
Expand Down Expand Up @@ -93,13 +93,14 @@ use std::{
path::PathBuf,
rc::Rc,
sync::{
atomic::{AtomicU32, Ordering},
mpsc::{channel, Sender},
Arc, Mutex, Weak,
},
thread::{current as current_thread, ThreadId},
};

pub type WebviewId = u64;
pub type WebviewId = u32;
type IpcHandler = dyn Fn(&Window, String) + 'static;
type FileDropHandler = dyn Fn(&Window, WryFileDropEvent) -> bool + 'static;

Expand All @@ -109,7 +110,7 @@ pub use webview::Webview;
pub type WebContextStore = Arc<Mutex<HashMap<Option<PathBuf>, WebContext>>>;
// window
pub type WindowEventHandler = Box<dyn Fn(&WindowEvent) + Send>;
pub type WindowEventListeners = Arc<Mutex<HashMap<Uuid, WindowEventHandler>>>;
pub type WindowEventListeners = Arc<Mutex<HashMap<WindowEventId, WindowEventHandler>>>;

#[derive(Debug, Clone, Default)]
pub struct WebviewIdStore(Arc<Mutex<HashMap<WindowId, WebviewId>>>);
Expand Down Expand Up @@ -171,6 +172,9 @@ pub struct Context<T: UserEvent> {
pub proxy: WryEventLoopProxy<Message<T>>,
main_thread: DispatcherMainThreadContext<T>,
plugins: Arc<Mutex<Vec<Box<dyn Plugin<T> + Send>>>>,
next_window_id: Arc<AtomicU32>,
next_window_event_id: Arc<AtomicU32>,
next_webcontext_id: Arc<AtomicU32>,
}

impl<T: UserEvent> Context<T> {
Expand All @@ -184,6 +188,18 @@ impl<T: UserEvent> Context<T> {
None
})
}

fn next_window_id(&self) -> WebviewId {
self.next_window_id.fetch_add(1, Ordering::Relaxed)
}

fn next_window_event_id(&self) -> WebviewId {
self.next_window_event_id.fetch_add(1, Ordering::Relaxed)
}

fn next_webcontext_id(&self) -> WebviewId {
self.next_webcontext_id.fetch_add(1, Ordering::Relaxed)
}
}

impl<T: UserEvent> Context<T> {
Expand All @@ -194,7 +210,7 @@ impl<T: UserEvent> Context<T> {
) -> Result<DetachedWindow<T, Wry<T>>> {
let label = pending.label.clone();
let context = self.clone();
let window_id = rand::random();
let window_id = self.next_window_id();

send_user_message(
self,
Expand Down Expand Up @@ -909,7 +925,7 @@ pub enum ApplicationMessage {

pub enum WindowMessage {
WithWebview(Box<dyn FnOnce(Webview) + Send>),
AddEventListener(Uuid, Box<dyn Fn(&WindowEvent) + Send>),
AddEventListener(WindowEventId, Box<dyn Fn(&WindowEvent) + Send>),
// Devtools
#[cfg(any(debug_assertions, feature = "devtools"))]
OpenDevTools,
Expand Down Expand Up @@ -1056,8 +1072,8 @@ impl<T: UserEvent> Dispatch<T> for WryDispatcher<T> {
send_user_message(&self.context, Message::Task(Box::new(f)))
}

fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> Uuid {
let id = Uuid::new_v4();
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId {
let id = self.context.next_window_event_id();
let _ = self.context.proxy.send_event(Message::Window(
self.window_id,
WindowMessage::AddEventListener(id, Box::new(f)),
Expand Down Expand Up @@ -1640,11 +1656,9 @@ impl<T: UserEvent> WryHandle<T> {
&self,
f: F,
) -> Result<Weak<Window>> {
let id = self.context.next_window_id();
let (tx, rx) = channel();
send_user_message(
&self.context,
Message::CreateWindow(rand::random(), Box::new(f), tx),
)?;
send_user_message(&self.context, Message::CreateWindow(id, Box::new(f), tx))?;
rx.recv().unwrap()
}

Expand Down Expand Up @@ -1794,6 +1808,9 @@ impl<T: UserEvent> Wry<T> {
windows,
},
plugins: Default::default(),
next_window_id: Default::default(),
next_window_event_id: Default::default(),
next_webcontext_id: Default::default(),
};

Ok(Self {
Expand Down Expand Up @@ -1850,7 +1867,7 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
before_webview_creation: Option<F>,
) -> Result<DetachedWindow<T, Self>> {
let label = pending.label.clone();
let window_id = rand::random();
let window_id = self.context.next_window_id();

let webview = create_webview(
window_id,
Expand Down Expand Up @@ -2661,7 +2678,7 @@ fn create_webview<T: UserEvent, F: Fn(RawWindow) + Send + 'static>(

if let Some(handler) = ipc_handler {
webview_builder =
webview_builder.with_ipc_handler(create_ipc_handler(context, label.clone(), handler));
webview_builder.with_ipc_handler(create_ipc_handler(context.clone(), label.clone(), handler));
}

for (scheme, protocol) in uri_scheme_protocols {
Expand All @@ -2686,8 +2703,9 @@ fn create_webview<T: UserEvent, F: Fn(RawWindow) + Send + 'static>(
if automation_enabled {
webview_attributes.data_directory.clone()
} else {
// random unique key
Some(Uuid::new_v4().as_hyphenated().to_string().into())
// unique key
let key = context.next_webcontext_id().to_string().into();
Some(key)
};
let entry = web_context.entry(web_context_key.clone());
let web_context = match entry {
Expand Down
1 change: 0 additions & 1 deletion core/tauri-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ serde = { version = "1.0", features = [ "derive" ] }
serde_json = "1.0"
thiserror = "1.0"
tauri-utils = { version = "2.0.0-alpha.8", path = "../tauri-utils" }
uuid = { version = "1", features = [ "v4" ] }
http = "0.2.4"
raw-window-handle = "0.5"
url = { version = "2" }
Expand Down
5 changes: 3 additions & 2 deletions core/tauri-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use serde::Deserialize;
use std::{fmt::Debug, sync::mpsc::Sender};
use tauri_utils::Theme;
use url::Url;
use uuid::Uuid;

/// Types useful for interacting with a user's monitors.
pub mod monitor;
Expand All @@ -37,6 +36,8 @@ use http::{
status::InvalidStatusCode,
};

pub type WindowEventId = u32;

/// Type of user attention requested on a window.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(tag = "type")]
Expand Down Expand Up @@ -327,7 +328,7 @@ pub trait Dispatch<T: UserEvent>: Debug + Clone + Send + Sync + Sized + 'static
fn run_on_main_thread<F: FnOnce() + Send + 'static>(&self, f: F) -> Result<()>;

/// Registers a window event handler.
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> Uuid;
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId;

/// Runs a closure with the platform webview object as argument.
fn with_webview<F: FnOnce(Box<dyn std::any::Any>) + Send + 'static>(&self, f: F) -> Result<()>;
Expand Down
6 changes: 3 additions & 3 deletions core/tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ serde_json = { version = "1.0", features = [ "raw_value" ] }
serde = { version = "1.0", features = [ "derive" ] }
tokio = { version = "1", features = [ "rt", "rt-multi-thread", "sync", "fs", "io-util" ] }
futures-util = "0.3"
uuid = { version = "1", features = [ "v4" ] }
uuid = { version = "1", features = [ "v4" ], optional = true }
url = { version = "2.4" }
anyhow = "1.0"
thiserror = "1.0"
Expand All @@ -52,7 +52,7 @@ tauri-runtime = { version = "1.0.0-alpha.2", path = "../tauri-runtime" }
tauri-macros = { version = "2.0.0-alpha.8", path = "../tauri-macros" }
tauri-utils = { version = "2.0.0-alpha.8", features = [ "resources" ], path = "../tauri-utils" }
tauri-runtime-wry = { version = "1.0.0-alpha.3", path = "../tauri-runtime-wry", optional = true }
rand = "0.8"
getrandom = "0.2"
serde_repr = "0.1"
state = "0.6"
http = "0.2"
Expand Down Expand Up @@ -135,7 +135,7 @@ wry = [ "tauri-runtime-wry" ]
objc-exception = [ "tauri-runtime-wry/objc-exception" ]
linux-ipc-protocol = [ "tauri-runtime-wry/linux-protocol-body", "webkit2gtk/v2_40" ]
linux-libxdo = [ "tray-icon/libxdo", "muda/libxdo" ]
isolation = [ "tauri-utils/isolation", "tauri-macros/isolation" ]
isolation = [ "tauri-utils/isolation", "tauri-macros/isolation", "uuid" ]
custom-protocol = [ "tauri-macros/custom-protocol" ]
native-tls = [ "reqwest/native-tls" ]
native-tls-vendored = [ "reqwest/native-tls-vendored" ]
Expand Down
2 changes: 0 additions & 2 deletions core/tauri/scripts/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
__RAW_bundle_script__
})()

__RAW_listen_function__

__RAW_core_script__

__RAW_event_initialization_script__
Expand Down
24 changes: 15 additions & 9 deletions core/tauri/src/event/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,29 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT

use crate::{command, ipc::CallbackFn, Manager, Result, Runtime, Window};
use crate::{command, ipc::CallbackFn, EventId, Manager, Result, Runtime, Window};
use serde::{Deserialize, Deserializer};
use serde_json::Value as JsonValue;
use tauri_runtime::window::is_label_valid;

use super::is_event_name_valid;

pub struct EventId(String);
pub struct EventName(String);

impl<'de> Deserialize<'de> for EventId {
impl AsRef<str> for EventName {
fn as_ref(&self) -> &str {
&self.0
}
}

impl<'de> Deserialize<'de> for EventName {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let event_id = String::deserialize(deserializer)?;
if is_event_name_valid(&event_id) {
Ok(EventId(event_id))
Ok(EventName(event_id))
} else {
Err(serde::de::Error::custom(
"Event name must include only alphanumeric characters, `-`, `/`, `:` and `_`.",
Expand Down Expand Up @@ -48,22 +54,22 @@ impl<'de> Deserialize<'de> for WindowLabel {
#[command(root = "crate")]
pub fn listen<R: Runtime>(
window: Window<R>,
event: EventId,
event: EventName,
window_label: Option<WindowLabel>,
handler: CallbackFn,
) -> Result<usize> {
) -> Result<EventId> {
window.listen_js(window_label.map(|l| l.0), event.0, handler)
}

#[command(root = "crate")]
pub fn unlisten<R: Runtime>(window: Window<R>, event: EventId, event_id: usize) -> Result<()> {
window.unlisten_js(event.0, event_id)
pub fn unlisten<R: Runtime>(window: Window<R>, event: EventName, event_id: EventId) -> Result<()> {
window.unlisten_js(event.as_ref(), event_id)
}

#[command(root = "crate")]
pub fn emit<R: Runtime>(
window: Window<R>,
event: EventId,
event: EventName,
window_label: Option<WindowLabel>,
payload: Option<JsonValue>,
) -> Result<()> {
Expand Down
Loading