Skip to content

Commit d52ce50

Browse files
committed
重构事件监听
1 parent 519cd12 commit d52ce50

File tree

14 files changed

+443
-246
lines changed

14 files changed

+443
-246
lines changed

src-tauri/src/api/launcher_api.rs

Lines changed: 50 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
11
use anyhow::Result;
22
use rand::{Rng, distributions::Alphanumeric};
3-
use tauri::{AppHandle, Emitter, Manager, State};
4-
use tracing::{debug, info};
3+
use tauri::{AppHandle, State};
4+
use tracing::info;
55

66
use crate::{
7-
DatabaseManager, check_launch_then_exit,
7+
DatabaseManager,
88
db::{
99
launcher,
1010
launcher_resource::{self, LauncherResource},
1111
},
1212
error::OneClickLaunchError,
1313
events::{
14-
payloads::{LauncherLaunched, LauncherLaunchedPayload},
15-
types::{EventDispatcher, EventSystem},
14+
EventDispatcher,
15+
types::{
16+
LauncherBasicInfoUpdated, LauncherBasicInfoUpdatedPayload, LauncherLaunched,
17+
LauncherLaunchedPayload,
18+
},
1619
},
1720
open_using_default_program,
1821
};
1922

20-
pub const LAUNCHER_LAUNCHED_EVENT: &str = "launcher_launched";
21-
pub const LAUNCHER_BASIC_INFO_UPDATED_EVENT: &str = "launcher_basic_info_updated";
22-
2323
/// 创建新的启动器
2424
#[tauri::command]
2525
pub async fn craete_launcher(
@@ -29,7 +29,14 @@ pub async fn craete_launcher(
2929
) -> Result<i64, OneClickLaunchError> {
3030
let name = name.unwrap_or_else(generate_default_launcher_name);
3131
let launcher_id = launcher::create(&db.pool, &name, None).await?;
32-
let _ = app.emit(LAUNCHER_BASIC_INFO_UPDATED_EVENT, "");
32+
33+
let _ = EventDispatcher::<LauncherBasicInfoUpdated>::send_event(
34+
&app,
35+
LauncherBasicInfoUpdatedPayload {
36+
launcher_ids: vec![launcher_id],
37+
},
38+
);
39+
3340
Ok(launcher_id)
3441
}
3542

@@ -57,7 +64,14 @@ pub async fn modify_launcher_name(
5764
name: String,
5865
) -> Result<(), OneClickLaunchError> {
5966
launcher::modify_launcher_name(&db.pool, launcher_id, &name).await?;
60-
let _ = app.emit(LAUNCHER_BASIC_INFO_UPDATED_EVENT, "");
67+
68+
let _ = EventDispatcher::<LauncherBasicInfoUpdated>::send_event(
69+
&app,
70+
LauncherBasicInfoUpdatedPayload {
71+
launcher_ids: vec![launcher_id],
72+
},
73+
);
74+
6175
Ok(())
6276
}
6377

@@ -86,7 +100,12 @@ pub async fn copy_launcher(
86100

87101
tx.commit().await?;
88102

89-
let _ = app.emit(LAUNCHER_BASIC_INFO_UPDATED_EVENT, "");
103+
let _ = EventDispatcher::<LauncherBasicInfoUpdated>::send_event(
104+
&app,
105+
LauncherBasicInfoUpdatedPayload {
106+
launcher_ids: vec![launcher_id],
107+
},
108+
);
90109

91110
Ok(new_launcher_id)
92111
}
@@ -154,7 +173,12 @@ pub async fn delete_launcher(
154173

155174
tx.commit().await?;
156175

157-
let _ = app.emit(LAUNCHER_BASIC_INFO_UPDATED_EVENT, "");
176+
let _ = EventDispatcher::<LauncherBasicInfoUpdated>::send_event(
177+
&app,
178+
LauncherBasicInfoUpdatedPayload {
179+
launcher_ids: vec![launcher_id],
180+
},
181+
);
158182

159183
Ok(())
160184
}
@@ -180,7 +204,12 @@ pub async fn modify_launcher_sort(
180204

181205
tx.commit().await?;
182206

183-
let _ = app.emit(LAUNCHER_BASIC_INFO_UPDATED_EVENT, "");
207+
let _ = EventDispatcher::<LauncherBasicInfoUpdated>::send_event(
208+
&app,
209+
LauncherBasicInfoUpdatedPayload {
210+
launcher_ids: launchers.iter().map(|e| e.id).collect(),
211+
},
212+
);
184213

185214
Ok(())
186215
}
@@ -241,19 +270,19 @@ pub async fn launch(
241270
) -> Result<(), OneClickLaunchError> {
242271
let resources = launcher_resource::query_by_launcher_id(&db.pool, launcher_id).await?;
243272

244-
launch_launcher_resources(&app, &resources);
273+
launch_resources(&app, &resources);
245274

246-
// app.emit(
247-
// LAUNCHER_LAUNCHED_EVENT,
248-
// LauncherLaunchedPayload { launcher_id },
249-
// )?;
250-
251-
EventDispatcher::<LauncherLaunched>::send_event(&app, LauncherLaunchedPayload { launcher_id })?;
275+
EventDispatcher::<LauncherLaunched>::send_event(
276+
&app,
277+
LauncherLaunchedPayload {
278+
launcher_ids: vec![launcher_id],
279+
},
280+
)?;
252281

253282
Ok(())
254283
}
255284

256-
pub fn launch_launcher_resources(app: &AppHandle, resources: &[LauncherResource]) {
285+
pub fn launch_resources(app: &AppHandle, resources: &[LauncherResource]) {
257286
for resource in resources.iter() {
258287
if let Err(e) = open_using_default_program(app, resource.path.as_str()) {
259288
info!(
@@ -263,30 +292,3 @@ pub fn launch_launcher_resources(app: &AppHandle, resources: &[LauncherResource]
263292
}
264293
}
265294
}
266-
267-
pub fn de(app: AppHandle) {
268-
// 监听 `event-name`(无论其在什么窗口中触发)
269-
let app_handle = app; // 获取 AppHandle
270-
271-
EventSystem::register_listener(&app_handle.clone(), LauncherLaunched, move |_payload| {
272-
let inner_app_handle = app_handle.clone();
273-
tauri::async_runtime::spawn(async move {
274-
let db = inner_app_handle.state::<DatabaseManager>();
275-
if let Ok(_exit @ true) = check_launch_then_exit(&db.pool).await {
276-
debug!("监听到启动器启动完成事件, 已设置启动后退出, 正在退出程序.");
277-
inner_app_handle.exit(0);
278-
}
279-
});
280-
});
281-
282-
// let _id = app.listen(launcher_api::LAUNCHER_LAUNCHED_EVENT, move |_event| {
283-
// let inner_app_handle = app_handle.clone();
284-
// tauri::async_runtime::spawn(async move {
285-
// let db = inner_app_handle.state::<DatabaseManager>();
286-
// if let Ok(_exit @ true) = check_launch_then_exit(&db.pool).await {
287-
// debug!("监听到启动器启动完成事件, 已设置启动后退出, 正在退出程序.");
288-
// inner_app_handle.exit(0);
289-
// }
290-
// });
291-
// });
292-
}

src-tauri/src/api/setting_api.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,34 @@
1-
use tauri::State;
1+
use tauri::{AppHandle, State};
22

33
use crate::{
44
DatabaseManager,
55
db::settings::{self, Settings},
66
error::OneClickLaunchError,
7+
events::{
8+
EventDispatcher,
9+
types::{SettingUpdated, SettingUpdatedPayload},
10+
},
711
};
812

913
/// 保存设置
1014
#[tauri::command]
1115
pub async fn save_setting(
16+
app: AppHandle,
1217
db: State<'_, DatabaseManager>,
1318
key: String,
1419
value: String,
1520
) -> Result<(), OneClickLaunchError> {
1621
let setting = Settings { key, value };
1722
settings::save(&db.pool, &setting).await?;
23+
24+
let _ = EventDispatcher::<SettingUpdated>::send_event(
25+
&app,
26+
SettingUpdatedPayload {
27+
key: setting.key.clone(),
28+
value: setting.value.clone(),
29+
},
30+
);
31+
1832
Ok(())
1933
}
2034

src-tauri/src/api/window_api.rs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,13 @@ use tauri::{
55

66
use crate::{DatabaseManager, WindowContext, db::launcher, error::OneClickLaunchError};
77

8-
/// 关闭窗口
9-
#[tauri::command]
10-
pub async fn hide_window(app: AppHandle) -> Result<(), OneClickLaunchError> {
11-
hide_window_sync(app)
12-
}
13-
14-
pub fn hide_window_sync(app: AppHandle) -> Result<(), OneClickLaunchError> {
8+
pub fn hide_window(app: &AppHandle) -> Result<(), OneClickLaunchError> {
159
let window = app.get_webview_window("main").unwrap();
1610
window.hide()?;
1711
Ok(())
1812
}
1913

2014
/// 刷新系统图标菜单
21-
#[tauri::command]
2215
pub async fn refresh_tray(app: AppHandle) -> Result<(), OneClickLaunchError> {
2316
// 获取全局状态
2417
let window_context: State<'_, WindowContext> = app.state();
@@ -47,9 +40,7 @@ pub async fn refresh_tray(app: AppHandle) -> Result<(), OneClickLaunchError> {
4740
Ok(())
4841
}
4942

50-
/// 修改窗口主题
51-
#[tauri::command]
52-
pub async fn change_windows_theme(app: AppHandle, theme: &str) -> Result<(), OneClickLaunchError> {
43+
pub fn change_windows_theme(app: &AppHandle, theme: &str) -> Result<(), OneClickLaunchError> {
5344
if let Some(window) = app.get_webview_window("main") {
5445
window.set_theme(match theme {
5546
"dark" => Some(Theme::Dark),

src-tauri/src/constants.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use lazy_static::lazy_static;
2+
3+
lazy_static! {
4+
pub static ref AUTO_START_FLAG: String = "--auto".to_string();
5+
}
6+
7+
pub static APPLICATION_NAME: &str = "一键启动";
8+
pub static THEME: &str = "theme";

src-tauri/src/db/launcher_resource.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ where
100100
// 按launcher_id查询
101101
pub async fn query_by_launcher_ids<'a, E>(
102102
executor: E,
103-
launcher_ids: Vec<i64>,
103+
launcher_ids: &[i64],
104104
) -> Result<Vec<LauncherResource>>
105105
where
106106
E: Executor<'a, Database = Sqlite>,

src-tauri/src/events.rs

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,47 @@
1-
pub mod payloads;
1+
pub mod system_listeners;
22
pub mod types;
3+
4+
use std::marker::PhantomData;
5+
6+
use serde::{Deserialize, Serialize};
7+
use tauri::{AppHandle, Emitter, Listener};
8+
use tracing::error;
9+
10+
use crate::error::OneClickLaunchError;
11+
12+
pub trait Event {
13+
type Payload: Serialize + for<'a> Deserialize<'a> + Clone;
14+
15+
fn name() -> &'static str;
16+
}
17+
18+
// 事件发送器
19+
pub struct EventDispatcher<E: Event> {
20+
_marker: PhantomData<E>,
21+
}
22+
23+
impl<E: Event> EventDispatcher<E> {
24+
pub fn send_event(app: &AppHandle, payload: E::Payload) -> Result<(), OneClickLaunchError> {
25+
app.emit(E::name(), payload)?;
26+
Ok(())
27+
}
28+
}
29+
30+
// 事件监听器注册系统
31+
pub struct EventSystem;
32+
33+
impl EventSystem {
34+
pub fn register_listener<E, F>(app: &AppHandle, _event: E, callback: F)
35+
where
36+
E: Event + 'static,
37+
F: Fn(E::Payload) + Send + 'static,
38+
{
39+
app.listen(E::name(), move |e| {
40+
if let Ok(payload) = serde_json::from_str(e.payload()) {
41+
callback(payload);
42+
} else {
43+
error!("{}事件payload反序列化失败.原始数据: {}", "", e.payload());
44+
}
45+
});
46+
}
47+
}

src-tauri/src/events/payloads.rs

Lines changed: 0 additions & 17 deletions
This file was deleted.

0 commit comments

Comments
 (0)