refactor: Improve tray icon and event handling across platforms & unify click behavior

This commit is contained in:
wonfen 2025-02-11 14:48:31 +08:00
parent 20763a741a
commit e230981ac4
3 changed files with 59 additions and 38 deletions

View File

@ -69,43 +69,64 @@ impl Tray {
pub fn create_systray(&self) -> Result<()> { pub fn create_systray(&self) -> Result<()> {
let app_handle = handle::Handle::global().app_handle().unwrap(); let app_handle = handle::Handle::global().app_handle().unwrap();
let tray_incon_id = TrayIconId::new("main"); let tray_incon_id = TrayIconId::new("main");
let tray = app_handle.tray_by_id(&tray_incon_id).unwrap();
tray.on_tray_icon_event(|_, event| { // 创建初始菜单
let tray_event = { Config::verge().latest().tray_event.clone() }; let initial_menu = create_tray_menu(
let tray_event: String = tray_event.unwrap_or("main_window".into()); &app_handle,
Some("rule"),
false,
false,
Vec::new(),
)?;
#[cfg(target_os = "macos")] // 使用 TrayIconBuilder 构建托盘
if let TrayIconEvent::Click { let _tray = tauri::tray::TrayIconBuilder::<Wry>::with_id(tray_incon_id)
button: MouseButton::Right, .menu(&initial_menu) // 先设置菜单
button_state: MouseButtonState::Down, .show_menu_on_left_click(false) // 再禁用左键菜单
.. .on_tray_icon_event(move |tray, event| {
} = event // 处理左键点击事件
{ if let TrayIconEvent::Click {
match tray_event.as_str() { button,
"system_proxy" => feat::toggle_system_proxy(), button_state: MouseButtonState::Down,
"tun_mode" => feat::toggle_tun_mode(), ..
"main_window" => resolve::create_window(), } = event
_ => {} {
match button {
// 左键点击
MouseButton::Left => {
#[cfg(target_os = "macos")]
{
// 确保菜单不会显示
let _ = tray.set_show_menu_on_left_click(false);
}
// 获取并执行自定义事件
let tray_event = Config::verge()
.latest()
.tray_event
.clone()
.unwrap_or("main_window".into());
match tray_event.as_str() {
"system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(),
"main_window" => resolve::create_window(),
_ => {}
}
}
// 其他按钮点击不处理
_ => {}
}
} }
} })
.on_menu_event(on_menu_event)
.build(&app_handle)?;
// 初始化托盘状态
self.update_menu()?;
self.update_icon(None)?;
self.update_tooltip()?;
#[cfg(not(target_os = "macos"))]
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Down,
..
} = event
{
match tray_event.as_str() {
"system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(),
"main_window" => resolve::create_window(),
_ => {}
}
}
});
tray.on_menu_event(on_menu_event);
Ok(()) Ok(())
} }

View File

@ -33,7 +33,8 @@
}, },
"app": { "app": {
"trayIcon": { "trayIcon": {
"iconPath": "icons/tray-icon.ico" "iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true
} }
} }
} }

View File

@ -21,11 +21,10 @@
} }
}, },
"app": { "app": {
"windows": [],
"trayIcon": { "trayIcon": {
"iconPath": "icons/tray-icon.ico", "iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true, "iconAsTemplate": true
"showMenuOnLeftClick": false }
},
"windows": []
} }
} }