refactor: Simplify tray icon event handling across platforms

This commit is contained in:
wonfen 2025-02-20 07:03:28 +08:00
parent 39a1d6202a
commit 23d1d210c7
3 changed files with 45 additions and 55 deletions

View File

@ -68,44 +68,23 @@ 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 = app_handle.tray_by_id(&tray_incon_id).unwrap();
// 创建初始菜单 #[cfg(target_os = "macos")]
let initial_menu = create_tray_menu( tray.set_show_menu_on_left_click(false)?;
&app_handle,
Some("rule"),
false,
false,
Vec::new(),
)?;
// 使用 TrayIconBuilder 构建托盘 tray.on_tray_icon_event(|_, event| {
let _tray = tauri::tray::TrayIconBuilder::<Wry>::with_id(TrayIconId::new("main")) let tray_event = { Config::verge().latest().tray_event.clone() };
.menu(&initial_menu) // 先设置菜单 let tray_event: String = tray_event.unwrap_or("main_window".into());
.show_menu_on_left_click(false) // 再禁用左键菜单
.on_tray_icon_event(move |_tray, event| { #[cfg(target_os = "macos")]
// 处理左键点击事件
if let TrayIconEvent::Click { if let TrayIconEvent::Click {
button, button: MouseButton::Left,
button_state: MouseButtonState::Down, button_state: MouseButtonState::Down,
.. ..
} = event } = 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() { match tray_event.as_str() {
"system_proxy" => feat::toggle_system_proxy(), "system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(), "tun_mode" => feat::toggle_tun_mode(),
@ -113,19 +92,23 @@ impl Tray {
_ => {} _ => {}
} }
} }
// 其他按钮点击不处理
#[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(),
_ => {} _ => {}
} }
} }
}) });
.on_menu_event(on_menu_event) tray.on_menu_event(on_menu_event);
.build(&app_handle)?;
// 初始化托盘状态
self.update_menu()?;
self.update_icon(None)?;
self.update_tooltip()?;
Ok(()) Ok(())
} }

View File

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

View File

@ -19,5 +19,13 @@
"template": "./packages/windows/installer.nsi" "template": "./packages/windows/installer.nsi"
} }
} }
},
"app": {
"trayIcon": {
"iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true,
"showMenuOnLeftClick": false
},
"windows": []
} }
} }