From 3b00be10298e158f757b6cf24e09ba08f4217434 Mon Sep 17 00:00:00 2001 From: Puyodead1 Date: Wed, 20 Dec 2023 09:49:25 -0500 Subject: [PATCH] tauri: tray icon --- src-tauri/Cargo.toml | 1 + src-tauri/src/lib.rs | 17 +++++++++++++++++ src-tauri/src/tray.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src-tauri/src/tray.rs diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index bd30e45..3b9c970 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -20,6 +20,7 @@ tauri-build = { version = "2.0.0-alpha", features = [] } # tauri = { version = "2.0.0-alpha", features = [] } tauri = { git = "https://github.com/tauri-apps/tauri.git", branch = "dev", features = [ "devtools", + "tray-icon", ] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 3aca19e..873bdac 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,5 +1,6 @@ #[cfg(desktop)] use tauri::Manager; +mod tray; #[tauri::command] async fn close_splashscreen(window: tauri::Window) { @@ -21,6 +22,22 @@ pub fn run() { std::env::set_var("RUST_LOG", "debug"); tauri::Builder::default() + .setup(move |app| { + #[cfg(desktop)] + { + let handle = app.handle(); + tray::create_tray(handle)?; + } + + Ok(()) + }) + .on_window_event(|event| match event.event() { + tauri::WindowEvent::CloseRequested { api, .. } => { + event.window().hide().unwrap(); + api.prevent_close(); + } + _ => {} + }) .invoke_handler(tauri::generate_handler![close_splashscreen,]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs new file mode 100644 index 0000000..29e204f --- /dev/null +++ b/src-tauri/src/tray.rs @@ -0,0 +1,36 @@ +use tauri::{ + menu::{Menu, MenuItem}, + tray::{ClickType, TrayIconBuilder}, + Manager, Runtime, +}; + +pub fn create_tray(app: &tauri::AppHandle) -> tauri::Result<()> { + let branding = MenuItem::with_id(app, "name", "Spacebar", false, None); + let quit_i = MenuItem::with_id(app, "quit", "Quit", true, None); + let menu1 = Menu::with_items(app, &[&branding, &quit_i])?; + + let _ = TrayIconBuilder::with_id("main") + .tooltip("Spacebar") + .icon(app.default_window_icon().unwrap().clone()) + .menu(&menu1) + .menu_on_left_click(false) + .on_menu_event(move |app, event| match event.id.as_ref() { + "quit" => { + app.exit(0); + } + + _ => {} + }) + .on_tray_icon_event(|tray, event| { + if event.click_type == ClickType::Left { + let app = tray.app_handle(); + if let Some(window) = app.get_window("main") { + let _ = window.show(); + let _ = window.set_focus(); + } + } + }) + .build(app); + + Ok(()) +}