Skip to content

Commit 2558fab

Browse files
refactor!: remove uuid and rand dependencies where applicable (#7939)
* refactor: remove uuid and rand dependencies where applicable ref: #7756 * replace rand with getrandom * change files * InnerListeners private * revert listeners_object_name [skip ci] * default for next_event_id * remove raw listen function * fix event system * Apply suggestions from code review [skip ci] * update names [skip ci] --------- Co-authored-by: Lucas Nogueira <lucas@tauri.studio> Co-authored-by: Lucas Fernandes Nogueira <lucas@tauri.app>
1 parent 2fe8782 commit 2558fab

File tree

22 files changed

+288
-203
lines changed

22 files changed

+288
-203
lines changed

.changes/tauri-runtime-uuid.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'tauri-runtime': 'patch:breaking'
3+
---
4+
5+
Added `WindowEventId` type and Changed `Dispatch::on_window_event` return type from `Uuid` to `WindowEventId`

.changes/tauri-runtime-wry-uuid.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'tauri-runtime-wry': 'patch:breaking'
3+
---
4+
5+
Changed `WebviewId` to be an alias for `u32` instead of `u64`

.changes/tauri-uuid-rand.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'tauri': 'patch:breaking'
3+
---
4+
5+
This release contains a number of breaking changes to improve the consistency of tauri internals and the public facing APIs
6+
and simplifying the types where applicable:
7+
8+
- Removed `EventHandler` type.
9+
- Added `EventId` type
10+
- Changed `Manager::listen_global` and `Window::listen` to return the new `EventId` type instead of `EventHandler`.
11+
- Removed the return type of `Manager::once_global` and `Window::once`
12+
- Changed `Manager::unlisten` and `Window::unlisten` to take he new `EventId` type.
13+
- Added `tauri::scope::ScopeEventId`
14+
- Changed `FsScope::listen` to return the new `ScopeEventId` instead of `Uuid`.
15+
- Added `FsScope::unlisten`

core/tauri-runtime-wry/Cargo.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@ features = [ "dox" ]
1919
wry = { version = "0.33", default-features = false, features = [ "tao", "file-drop", "protocol" ] }
2020
tauri-runtime = { version = "1.0.0-alpha.2", path = "../tauri-runtime" }
2121
tauri-utils = { version = "2.0.0-alpha.8", path = "../tauri-utils" }
22-
uuid = { version = "1", features = [ "v4" ] }
23-
rand = "0.8"
2422
raw-window-handle = "0.5"
2523
http = "0.2"
2624

core/tauri-runtime-wry/src/lib.rs

Lines changed: 33 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use tauri_runtime::{
2121
},
2222
DeviceEventFilter, Dispatch, Error, EventLoopProxy, ExitRequestedEventAction, Icon, Result,
2323
RunEvent, RunIteration, Runtime, RuntimeHandle, RuntimeInitArgs, UserAttentionType, UserEvent,
24+
WindowEventId,
2425
};
2526

2627
#[cfg(windows)]
@@ -41,7 +42,6 @@ use wry::webview::WebViewBuilderExtWindows;
4142
#[cfg(target_os = "macos")]
4243
use tauri_utils::TitleBarStyle;
4344
use tauri_utils::{config::WindowConfig, debug_eprintln, Theme};
44-
use uuid::Uuid;
4545
use wry::{
4646
application::{
4747
dpi::{
@@ -93,13 +93,14 @@ use std::{
9393
path::PathBuf,
9494
rc::Rc,
9595
sync::{
96+
atomic::{AtomicU32, Ordering},
9697
mpsc::{channel, Sender},
9798
Arc, Mutex, Weak,
9899
},
99100
thread::{current as current_thread, ThreadId},
100101
};
101102

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

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

114115
#[derive(Debug, Clone, Default)]
115116
pub struct WebviewIdStore(Arc<Mutex<HashMap<WindowId, WebviewId>>>);
@@ -171,6 +172,9 @@ pub struct Context<T: UserEvent> {
171172
pub proxy: WryEventLoopProxy<Message<T>>,
172173
main_thread: DispatcherMainThreadContext<T>,
173174
plugins: Arc<Mutex<Vec<Box<dyn Plugin<T> + Send>>>>,
175+
next_window_id: Arc<AtomicU32>,
176+
next_window_event_id: Arc<AtomicU32>,
177+
next_webcontext_id: Arc<AtomicU32>,
174178
}
175179

176180
impl<T: UserEvent> Context<T> {
@@ -184,6 +188,18 @@ impl<T: UserEvent> Context<T> {
184188
None
185189
})
186190
}
191+
192+
fn next_window_id(&self) -> WebviewId {
193+
self.next_window_id.fetch_add(1, Ordering::Relaxed)
194+
}
195+
196+
fn next_window_event_id(&self) -> WebviewId {
197+
self.next_window_event_id.fetch_add(1, Ordering::Relaxed)
198+
}
199+
200+
fn next_webcontext_id(&self) -> WebviewId {
201+
self.next_webcontext_id.fetch_add(1, Ordering::Relaxed)
202+
}
187203
}
188204

189205
impl<T: UserEvent> Context<T> {
@@ -194,7 +210,7 @@ impl<T: UserEvent> Context<T> {
194210
) -> Result<DetachedWindow<T, Wry<T>>> {
195211
let label = pending.label.clone();
196212
let context = self.clone();
197-
let window_id = rand::random();
213+
let window_id = self.next_window_id();
198214

199215
send_user_message(
200216
self,
@@ -909,7 +925,7 @@ pub enum ApplicationMessage {
909925

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

1059-
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> Uuid {
1060-
let id = Uuid::new_v4();
1075+
fn on_window_event<F: Fn(&WindowEvent) + Send + 'static>(&self, f: F) -> WindowEventId {
1076+
let id = self.context.next_window_event_id();
10611077
let _ = self.context.proxy.send_event(Message::Window(
10621078
self.window_id,
10631079
WindowMessage::AddEventListener(id, Box::new(f)),
@@ -1640,11 +1656,9 @@ impl<T: UserEvent> WryHandle<T> {
16401656
&self,
16411657
f: F,
16421658
) -> Result<Weak<Window>> {
1659+
let id = self.context.next_window_id();
16431660
let (tx, rx) = channel();
1644-
send_user_message(
1645-
&self.context,
1646-
Message::CreateWindow(rand::random(), Box::new(f), tx),
1647-
)?;
1661+
send_user_message(&self.context, Message::CreateWindow(id, Box::new(f), tx))?;
16481662
rx.recv().unwrap()
16491663
}
16501664

@@ -1794,6 +1808,9 @@ impl<T: UserEvent> Wry<T> {
17941808
windows,
17951809
},
17961810
plugins: Default::default(),
1811+
next_window_id: Default::default(),
1812+
next_window_event_id: Default::default(),
1813+
next_webcontext_id: Default::default(),
17971814
};
17981815

17991816
Ok(Self {
@@ -1850,7 +1867,7 @@ impl<T: UserEvent> Runtime<T> for Wry<T> {
18501867
before_webview_creation: Option<F>,
18511868
) -> Result<DetachedWindow<T, Self>> {
18521869
let label = pending.label.clone();
1853-
let window_id = rand::random();
1870+
let window_id = self.context.next_window_id();
18541871

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

26622679
if let Some(handler) = ipc_handler {
26632680
webview_builder =
2664-
webview_builder.with_ipc_handler(create_ipc_handler(context, label.clone(), handler));
2681+
webview_builder.with_ipc_handler(create_ipc_handler(context.clone(), label.clone(), handler));
26652682
}
26662683

26672684
for (scheme, protocol) in uri_scheme_protocols {
@@ -2686,8 +2703,9 @@ fn create_webview<T: UserEvent, F: Fn(RawWindow) + Send + 'static>(
26862703
if automation_enabled {
26872704
webview_attributes.data_directory.clone()
26882705
} else {
2689-
// random unique key
2690-
Some(Uuid::new_v4().as_hyphenated().to_string().into())
2706+
// unique key
2707+
let key = context.next_webcontext_id().to_string().into();
2708+
Some(key)
26912709
};
26922710
let entry = web_context.entry(web_context_key.clone());
26932711
let web_context = match entry {

core/tauri-runtime/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ serde = { version = "1.0", features = [ "derive" ] }
2929
serde_json = "1.0"
3030
thiserror = "1.0"
3131
tauri-utils = { version = "2.0.0-alpha.8", path = "../tauri-utils" }
32-
uuid = { version = "1", features = [ "v4" ] }
3332
http = "0.2.4"
3433
raw-window-handle = "0.5"
3534
url = { version = "2" }

core/tauri-runtime/src/lib.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ use serde::Deserialize;
1717
use std::{fmt::Debug, sync::mpsc::Sender};
1818
use tauri_utils::Theme;
1919
use url::Url;
20-
use uuid::Uuid;
2120

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

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

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

332333
/// Runs a closure with the platform webview object as argument.
333334
fn with_webview<F: FnOnce(Box<dyn std::any::Any>) + Send + 'static>(&self, f: F) -> Result<()>;

core/tauri/Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ serde_json = { version = "1.0", features = [ "raw_value" ] }
4545
serde = { version = "1.0", features = [ "derive" ] }
4646
tokio = { version = "1", features = [ "rt", "rt-multi-thread", "sync", "fs", "io-util" ] }
4747
futures-util = "0.3"
48-
uuid = { version = "1", features = [ "v4" ] }
48+
uuid = { version = "1", features = [ "v4" ], optional = true }
4949
url = { version = "2.4" }
5050
anyhow = "1.0"
5151
thiserror = "1.0"
@@ -54,7 +54,7 @@ tauri-runtime = { version = "1.0.0-alpha.2", path = "../tauri-runtime" }
5454
tauri-macros = { version = "2.0.0-alpha.8", path = "../tauri-macros" }
5555
tauri-utils = { version = "2.0.0-alpha.8", features = [ "resources" ], path = "../tauri-utils" }
5656
tauri-runtime-wry = { version = "1.0.0-alpha.3", path = "../tauri-runtime-wry", optional = true }
57-
rand = "0.8"
57+
getrandom = "0.2"
5858
serde_repr = "0.1"
5959
state = "0.6"
6060
http = "0.2"
@@ -137,7 +137,7 @@ wry = [ "tauri-runtime-wry" ]
137137
objc-exception = [ "tauri-runtime-wry/objc-exception" ]
138138
linux-ipc-protocol = [ "tauri-runtime-wry/linux-protocol-body", "webkit2gtk/v2_40" ]
139139
linux-libxdo = [ "tray-icon/libxdo", "muda/libxdo" ]
140-
isolation = [ "tauri-utils/isolation", "tauri-macros/isolation" ]
140+
isolation = [ "tauri-utils/isolation", "tauri-macros/isolation", "uuid" ]
141141
custom-protocol = [ "tauri-macros/custom-protocol" ]
142142
native-tls = [ "reqwest/native-tls" ]
143143
native-tls-vendored = [ "reqwest/native-tls-vendored" ]

core/tauri/scripts/init.js

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,6 @@
1212
__RAW_bundle_script__
1313
})()
1414

15-
__RAW_listen_function__
16-
1715
__RAW_core_script__
1816

1917
__RAW_event_initialization_script__

core/tauri/src/event/commands.rs

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,29 @@
22
// SPDX-License-Identifier: Apache-2.0
33
// SPDX-License-Identifier: MIT
44

5-
use crate::{command, ipc::CallbackFn, Manager, Result, Runtime, Window};
5+
use crate::{command, ipc::CallbackFn, EventId, Manager, Result, Runtime, Window};
66
use serde::{Deserialize, Deserializer};
77
use serde_json::Value as JsonValue;
88
use tauri_runtime::window::is_label_valid;
99

1010
use super::is_event_name_valid;
1111

12-
pub struct EventId(String);
12+
pub struct EventName(String);
1313

14-
impl<'de> Deserialize<'de> for EventId {
14+
impl AsRef<str> for EventName {
15+
fn as_ref(&self) -> &str {
16+
&self.0
17+
}
18+
}
19+
20+
impl<'de> Deserialize<'de> for EventName {
1521
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1622
where
1723
D: Deserializer<'de>,
1824
{
1925
let event_id = String::deserialize(deserializer)?;
2026
if is_event_name_valid(&event_id) {
21-
Ok(EventId(event_id))
27+
Ok(EventName(event_id))
2228
} else {
2329
Err(serde::de::Error::custom(
2430
"Event name must include only alphanumeric characters, `-`, `/`, `:` and `_`.",
@@ -48,22 +54,22 @@ impl<'de> Deserialize<'de> for WindowLabel {
4854
#[command(root = "crate")]
4955
pub fn listen<R: Runtime>(
5056
window: Window<R>,
51-
event: EventId,
57+
event: EventName,
5258
window_label: Option<WindowLabel>,
5359
handler: CallbackFn,
54-
) -> Result<usize> {
60+
) -> Result<EventId> {
5561
window.listen_js(window_label.map(|l| l.0), event.0, handler)
5662
}
5763

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

6369
#[command(root = "crate")]
6470
pub fn emit<R: Runtime>(
6571
window: Window<R>,
66-
event: EventId,
72+
event: EventName,
6773
window_label: Option<WindowLabel>,
6874
payload: Option<JsonValue>,
6975
) -> Result<()> {

0 commit comments

Comments
 (0)