refactor: mod tray

This commit is contained in:
椰子 2024-11-01 19:36:41 +08:00
parent 575311b40d
commit 82496dee31
2 changed files with 49 additions and 37 deletions

View File

@ -1,3 +1,5 @@
mod tray;
use tauri::{ use tauri::{
menu::{Menu, MenuItem}, menu::{Menu, MenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent}, tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
@ -14,43 +16,7 @@ fn greet(name: &str) -> String {
pub fn run() { pub fn run() {
tauri::Builder::default() tauri::Builder::default()
.setup(|app| { .setup(|app| {
let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?; tray::tray(app);
let menu = Menu::with_items(app, &[&quit_i])?;
let _tray: tauri::tray::TrayIcon = TrayIconBuilder::new()
.tooltip("Realtime Voice Changer")
.icon(app.default_window_icon().unwrap().clone())
.on_tray_icon_event(|icon: &tauri::tray::TrayIcon, event| match event {
TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} => {
let window = icon.app_handle().get_window("main").unwrap();
if !window.is_visible().unwrap() {
window.show().unwrap();
}
if window.is_minimized().unwrap() {
window.unminimize().unwrap();
}
if !window.is_focused().unwrap() {
window.set_focus().unwrap();
}
println!("Tray icon clicked");
}
_ => {}
})
.menu(&menu)
.menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"quit" => {
println!("quit menu item was clicked");
app.exit(0);
}
_ => {
println!("menu item {:?} not handled", event.id);
}
})
.build(app)?;
Ok(()) Ok(())
}) })
.on_window_event(|window, event| match event { .on_window_event(|window, event| match event {

46
src-tauri/src/tray.rs Normal file
View File

@ -0,0 +1,46 @@
use tauri::{
menu::{Menu, MenuItem},
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
App, Manager,
};
pub fn tray(app: &mut App) {
let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None::<&str>).unwrap();
let menu = Menu::with_items(app, &[&quit_i]).unwrap();
let _tray: tauri::tray::TrayIcon = TrayIconBuilder::new()
.tooltip("Realtime Voice Changer")
.icon(app.default_window_icon().unwrap().clone())
.on_tray_icon_event(|icon: &tauri::tray::TrayIcon, event| match event {
TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
} => {
let window = icon.app_handle().get_window("main").unwrap();
if !window.is_visible().unwrap() {
window.show().unwrap();
}
if window.is_minimized().unwrap() {
window.unminimize().unwrap();
}
if !window.is_focused().unwrap() {
window.set_focus().unwrap();
}
println!("Tray icon clicked");
}
_ => {}
})
.menu(&menu)
.menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"quit" => {
println!("quit menu item was clicked");
app.exit(0);
}
_ => {
println!("menu item {:?} not handled", event.id);
}
})
.build(app)
.unwrap();
}