### Minimal Tray Icon Example Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/OVERVIEW.md A basic example demonstrating how to create and display a tray icon with a tooltip. This example keeps the icon alive for a set duration. ```rust use tray_icon::{TrayIconBuilder, Icon}; fn main() -> Result<(), Box> { let icon = Icon::from_rgba(vec![0; 32*32*4], 32, 32)?; let _tray = TrayIconBuilder::new() .with_icon(icon) .with_tooltip("My App") .build()?; // Keep the icon alive std::thread::sleep(std::time::Duration::from_secs(10)); Ok(()) } ``` -------------------------------- ### Complete Menu Example Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md A comprehensive example demonstrating how to create a complex menu structure with submenus, menu items, predefined items, and checkable items, and how to attach it to a tray icon. ```APIDOC ## Complete Menu Example ```rust use tray_icon::{TrayIconBuilder, menu::*}; fn create_menu() -> Result> { let menu = Menu::new(); // File submenu let file_menu = Submenu::new("File", true); file_menu.append(&MenuItem::new("New", true, Some("Ctrl+N")))?; file_menu.append(&MenuItem::new("Open", true, Some("Ctrl+O")))?; file_menu.append(&PredefinedMenuItem::separator())?; file_menu.append(&MenuItem::new("Exit", true, Some("Ctrl+Q")))?; menu.append(&file_menu)?; // Edit submenu let edit_menu = Submenu::new("Edit", true); edit_menu.append(&PredefinedMenuItem::cut())?; edit_menu.append(&PredefinedMenuItem::copy())?; edit_menu.append(&PredefinedMenuItem::paste())?; menu.append(&edit_menu)?; // View submenu let view_menu = Submenu::new("View", true); view_menu.append(&CheckMenuItem::new("Always on Top", true, false, None))?; view_menu.append(&CheckMenuItem::new("Dark Mode", true, false, None))?; menu.append(&view_menu)?; // Help menu let help_menu = Submenu::new("Help", true); help_menu.append(&MenuItem::new("About", true, None))?; help_menu.append(&MenuItem::new("Documentation", true, None))?; menu.append(&help_menu)?; Ok(Box::new(menu)) } // Use with tray icon let menu = create_menu()?; let tray = TrayIconBuilder::new() .with_menu(menu) .build()?; // Listen for menu events if let Ok(event) = MenuEvent::receiver().try_recv() { println!("Menu item clicked: {:?}", event); } ``` ``` -------------------------------- ### Create Tray Icon With Menu Source: https://github.com/tauri-apps/tray-icon/blob/dev/README.md Example of creating a tray icon with an associated menu. Requires a Menu object and an icon. ```rs use tray_icon::{TrayIconBuilder, menu::Menu}; let tray_menu = Menu::new(); let tray_icon = TrayIconBuilder::new() .with_menu(Box::new(tray_menu)) .with_tooltip("system-tray - tray icon library!") .with_icon(icon) .build() .unwrap(); ``` -------------------------------- ### Install FreeBSD Dependencies Source: https://github.com/tauri-apps/tray-icon/blob/dev/README.md Install required dependencies for compiling tray-icon on FreeBSD using pkg. This includes rust, glib, pkgconf, and gtk3. ```sh pkg install -y rust glib pkgconf gtk3 ``` -------------------------------- ### Install Linux Dependencies (Debian / Ubuntu) Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/configuration.md Install development packages for GTK3, xdotool, and AppIndicator for tray icon support on Debian-based systems. ```bash sudo apt install libgtk-3-dev libxdo-dev libappindicator3-dev # OR sudo apt install libgtk-3-dev libxdo-dev libayatana-appindicator3-dev ``` -------------------------------- ### Complete Menu Example Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md Demonstrates how to create a comprehensive menu with submenus for File, Edit, View, and Help, including predefined items and checkable items. This menu can be attached to a tray icon. ```rust use tray_icon::{TrayIconBuilder, menu::*}; fn create_menu() -> Result> { let menu = Menu::new(); // File submenu let file_menu = Submenu::new("File", true); file_menu.append(&MenuItem::new("New", true, Some("Ctrl+N")))?; file_menu.append(&MenuItem::new("Open", true, Some("Ctrl+O")))?; file_menu.append(&PredefinedMenuItem::separator())?; file_menu.append(&MenuItem::new("Exit", true, Some("Ctrl+Q")))?; menu.append(&file_menu)?; // Edit submenu let edit_menu = Submenu::new("Edit", true); edit_menu.append(&PredefinedMenuItem::cut())?; edit_menu.append(&PredefinedMenuItem::copy())?; edit_menu.append(&PredefinedMenuItem::paste())?; menu.append(&edit_menu)?; // View submenu let view_menu = Submenu::new("View", true); view_menu.append(&CheckMenuItem::new("Always on Top", true, false, None))?; view_menu.append(&CheckMenuItem::new("Dark Mode", true, false, None))?; menu.append(&view_menu)?; // Help menu let help_menu = Submenu::new("Help", true); help_menu.append(&MenuItem::new("About", true, None))?; help_menu.append(&MenuItem::new("Documentation", true, None))?; menu.append(&help_menu)?; Ok(Box::new(menu)) } // Use with tray icon let menu = create_menu()?; let tray = TrayIconBuilder::new() .with_menu(menu) .build()?; // Listen for menu events if let Ok(event) = MenuEvent::receiver().try_recv() { println!("Menu item clicked: {:?}", event); } ``` -------------------------------- ### Complete TrayIconBuilder Example Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/configuration.md Construct a tray icon with various attributes using the TrayIconBuilder fluent API. Ensure necessary imports and error handling are in place. ```rust use tray_icon::{TrayIconBuilder, Icon, menu::Menu}; use std::path::Path; let icon = Icon::from_rgba(vec![/* RGBA data */], 32, 32)?; let menu = Menu::new(); let tray = TrayIconBuilder::new() .with_id("my-app-tray") .with_icon(icon) .with_menu(Box::new(menu)) .with_tooltip("My Application") .with_title("App") .with_menu_on_left_click(true) .with_menu_on_right_click(true) .with_icon_as_template(false) .build()?; ``` -------------------------------- ### Create Tray Icon Without Menu Source: https://github.com/tauri-apps/tray-icon/blob/dev/README.md Example of creating a basic tray icon using TrayIconBuilder. Requires an icon to be provided. ```rs use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new() .with_tooltip("system-tray - tray icon library!") .with_icon(icon) .build() .unwrap(); ``` -------------------------------- ### Install Debian/Ubuntu Dependencies Source: https://github.com/tauri-apps/tray-icon/blob/dev/README.md Install necessary development dependencies for tray-icon on Debian/Ubuntu systems. This includes gtk3, libxdo, and libappindicator3-dev. ```sh sudo apt install libgtk-3-dev libxdo-dev libappindicator3-dev #or libayatana-appindicator3-dev ``` -------------------------------- ### Importing from the Menu Module Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md This snippet shows the necessary imports from the tray_icon::menu module to start working with menus. ```APIDOC ## Importing from the Menu Module ```rust use tray_icon::menu::{ Menu, MenuItem, Submenu, CheckMenuItem, PredefinedMenuItem, AboutMetadata, MenuEvent, }; ``` ``` -------------------------------- ### Retrieving an icon's ID Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-id.md This example shows how to get the ID of an existing tray icon after it has been built. ```APIDOC ## Retrieving an icon's ID ### Description This example shows how to get the ID of an existing tray icon after it has been built. ### Code ```rust use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; let id = tray_icon.id(); println!("Icon ID: {}", id.as_ref()); ``` ``` -------------------------------- ### Get Tray Icon Screen Position and Size Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/types.md Example of how to retrieve and print the screen position and dimensions of a tray icon using its `rect()` method. ```rust use tray_icon::TrayIconBuilder; let tray = TrayIconBuilder::new().build()?; if let Some(rect) = tray.rect() { println!("Position: ({}, {})", rect.position.x, rect.position.y); println!("Size: {}x{}", rect.size.width, rect.size.height); } ``` -------------------------------- ### Install Arch Linux Dependencies Source: https://github.com/tauri-apps/tray-icon/blob/dev/README.md Install necessary dependencies for tray-icon on Arch Linux/Manjaro. This includes gtk3, xdotool, and libappindicator-gtk3. ```sh pacman -S gtk3 xdotool libappindicator-gtk3 #or libayatana-appindicator ``` -------------------------------- ### Using IDs to handle multiple tray icons Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-id.md This example illustrates how to manage multiple tray icons using their unique IDs, storing them in a HashMap and handling events based on the icon ID. ```APIDOC ## Using IDs to handle multiple tray icons ### Description This example illustrates how to manage multiple tray icons using their unique IDs, storing them in a HashMap and handling events based on the icon ID. ### Code ```rust use tray_icon::{TrayIconBuilder, TrayIconId, TrayIconEvent}; use std::collections::HashMap; let icon1 = TrayIconBuilder::new() .with_id("icon-1") .build()?; let icon2 = TrayIconBuilder::new() .with_id("icon-2") .build()?; let mut icons: HashMap = HashMap::new(); icons.insert(icon1.id().clone(), icon1); icons.insert(icon2.id().clone(), icon2); if let Ok(event) = TrayIconEvent::receiver().try_recv() { if let Some(icon) = icons.get(event.id()) { println!("Event from icon: {}", event.id().as_ref()); } } ``` ``` -------------------------------- ### Serialize TrayIconEvent to JSON with Serde Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/types.md This example requires the `serde` feature to be enabled. It demonstrates how to serialize a `TrayIconEvent` into a JSON string using `serde_json`. ```rust #[cfg(feature = "serde")] { use tray_icon::TrayIconEvent; use serde_json; let event = TrayIconEvent::Click { id: "my-icon".into(), position: (100.0, 200.0).into(), rect: Default::default(), button: Default::default(), button_state: Default::default(), }; let json = serde_json::to_string(&event)?; println!("Event JSON: {}", json); } ``` -------------------------------- ### Creating a tray icon with a specific ID Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-id.md This example demonstrates how to create a new tray icon and assign it a custom ID using `TrayIconId::new()` and `TrayIconBuilder::with_id()`. ```APIDOC ## Creating a tray icon with a specific ID ### Description This example demonstrates how to create a new tray icon and assign it a custom ID using `TrayIconId::new()` and `TrayIconBuilder::with_id()`. ### Code ```rust use tray_icon::{TrayIconBuilder, TrayIconId, Icon}; let id = TrayIconId::new("app-main-tray"); let icon = Icon::from_rgba(vec![/* RGBA */], 32, 32)?; let tray_icon = TrayIconBuilder::new() .with_id(id) .with_icon(icon) .build()?; ``` ``` -------------------------------- ### Create Tray Icon on macOS Initialization Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/configuration.md On macOS, the event loop must run on the main thread. This example shows creating a tray icon when the application initializes. ```rust use winit::event::StartCause; fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) { if cause == StartCause::Init { self.tray_icon = Some(TrayIconBuilder::new().build()?); } } ``` -------------------------------- ### Handle Optional Tray Icon Rect Availability Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/rect.md This example shows how to safely handle the `Option` returned by `tray.rect()`. Always check for `Some(rect)` before accessing its properties, as the rect may not be available on all platforms or at all times. ```rust use tray_icon::TrayIconBuilder; let tray = TrayIconBuilder::new().build()?; match tray.rect() { Some(rect) => println!("Icon at ({}, {}) size {}x{}", rect.position.x, rect.position.y, rect.size.width, rect.size.height), None => println!("Icon rect not available"), } ``` -------------------------------- ### Create a new TrayIconBuilder Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-builder.md Use `TrayIconBuilder::new()` to create a new builder instance with default attributes. This is the starting point for configuring a tray icon. ```rust use tray_icon::TrayIconBuilder; let builder = TrayIconBuilder::new(); ``` -------------------------------- ### Tray Icon with Winit Event Loop Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/OVERVIEW.md An example showing how to integrate a tray icon with the winit event loop. This allows for event handling and keeps the tray icon alive within the application's lifecycle. ```rust use tray_icon::{TrayIconBuilder, TrayIconEvent}; use winit::event_loop::EventLoop; fn main() -> Result<()> { let event_loop = EventLoop::new()?; event_loop.run(|event, _| { if let winit::event::Event::NewEvents(winit::event::StartCause::Init) = event { let icon = Icon::from_rgba(vec![0; 32*32*4], 32, 32).ok(); if let Ok(tray) = TrayIconBuilder::new().with_icon(icon.unwrap()).build() { // Keep tray alive std::mem::forget(tray); } } })?; Ok(()) } ``` -------------------------------- ### Integrate Menu Events with winit Event Loop Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md This example demonstrates how to integrate tray icon menu events with a winit event loop. A `MenuEvent` handler is set up to send custom `UserEvent`s through an `EventLoopProxy`. ```rust use tray_icon::menu::MenuEvent; use winit::event_loop::EventLoopProxy; enum UserEvent { MenuItemClicked(tray_icon::menu::MenuEvent), } let proxy = event_loop.create_proxy(); MenuEvent::set_event_handler(Some(move |event| { proxy.send_event(UserEvent::MenuItemClicked(event)).ok(); })); ``` -------------------------------- ### Handling Errors in Async Code Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/errors.md This example shows how to handle potential errors when building a tray icon within an asynchronous context using `tokio::task::spawn_blocking` and `Result` flattening. ```rust use tray_icon::{TrayIconBuilder, Result}; use tokio::task; async fn create_tray_icon() -> Result<() as tray_icon::Result> { let icon = task::spawn_blocking(|| { TrayIconBuilder::new().build() }) .await .map_err(|_| tray_icon::Error::OsError( std::io::Error::new( std::io::ErrorKind::Other, "Task panicked" ) ))? .map_err(|e| e)?; Ok(()) } ``` -------------------------------- ### Handle Tray Icon Click Events Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/types.md Example of how to check for and handle tray icon click events using `try_recv()` for non-blocking checks. Requires importing `TrayIconEvent`. ```rust use tray_icon::TrayIconEvent; // Non-blocking check for events if let Ok(event) = TrayIconEvent::receiver().try_recv() { match event { TrayIconEvent::Click { button, ..} => { println!("Clicked with {:?}", button); } _ => {} } } ``` -------------------------------- ### Ensure Tray Icon Operations on Main Thread (macOS) Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/errors.md This example demonstrates how to ensure tray icon operations are performed on the main thread on macOS, which is required due to AppKit's thread-safety limitations. It includes an assertion to check the current thread. ```rust #[cfg(target_os = "macos")] fn create_tray_icon() -> Result { assert!( std::thread::current() == std::thread::ThreadId::of(/* main thread */), "Must be called from main thread" ); TrayIconBuilder::new().build() } ``` -------------------------------- ### Catching OsError in Tray Icon Operations Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/errors.md Demonstrates how to catch and handle `OsError` specifically when building a tray icon. This example shows how to differentiate OS errors from other potential errors and inspect the error kind for more specific handling. ```rust use tray_icon::TrayIconBuilder; match TrayIconBuilder::new().build() { Ok(icon) => println!("Success"), Err(tray_icon::Error::OsError(e)) => { eprintln!("OS Error: {}", e); eprintln!("Kind: {:?}", e.kind()); // Check e.kind() for: // - io::ErrorKind::NotFound // - io::ErrorKind::PermissionDenied // - io::ErrorKind::Other (generic OS error) } Err(e) => eprintln!("Other error: {}", e), } ``` -------------------------------- ### Integrate Menu Events with tao Event Loop Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md This example shows how to integrate tray icon menu events with a tao event loop. Similar to winit, a `MenuEvent` handler is configured to send custom `UserEvent`s via an `EventLoopProxy`. ```rust use tray_icon::menu::MenuEvent; enum UserEvent { MenuItemClicked(tray_icon::menu::MenuEvent), } let proxy = event_loop.create_proxy(); MenuEvent::set_event_handler(Some(move |event| { proxy.send_event(UserEvent::MenuItemClicked(event)).ok(); })); ``` -------------------------------- ### Calculate Tray Icon Center and Check Point Inclusion Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/rect.md Demonstrates calculating the center coordinates of a tray icon and checking if a given point falls within its bounds. This example utilizes the Rect struct's position and size properties for geometric calculations. ```rust use tray_icon::TrayIconBuilder; let tray = TrayIconBuilder::new().build()?; if let Some(rect) = tray.rect() { // Center of the icon let center_x = rect.position.x + (rect.size.width as f64 / 2.0); let center_y = rect.position.y + (rect.size.height as f64 / 2.0); println!("Icon center: ({}, {})", center_x, center_y); // Check if point is within icon bounds fn is_in_icon(x: f64, y: f64, rect: &tray_icon::Rect) -> bool { x >= rect.position.x && x <= rect.position.x + rect.size.width as f64 && y >= rect.position.y && y <= rect.position.y + rect.size.height as f64 } let click_x = 150.0; let click_y = 210.0; if is_in_icon(click_x, click_y, &rect) { println!("Click was within icon bounds"); } } ``` -------------------------------- ### Basic Menu Creation in Rust Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/configuration.md Demonstrates how to create a basic menu with custom items and predefined options like 'Quit'. Ensure the `tray_icon::menu` module is imported. ```rust use tray_icon::menu::{Menu, MenuItem, PredefinedMenuItem}; let menu = Menu::new(); let item = MenuItem::new("Open", true, None); menu.append(&item)?; let quit = PredefinedMenuItem::quit(Default::default()); menu.append(&quit)?; ``` -------------------------------- ### Create a Simple Tray Icon Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/OVERVIEW.md The recommended way to create a tray icon with basic attributes like an icon and tooltip. Requires importing `TrayIconBuilder` and `Icon`. ```rust use tray_icon::{TrayIconBuilder, Icon}; let icon = Icon::from_rgba(rgba_data, 32, 32)?; let tray = TrayIconBuilder::new() .with_icon(icon) .with_tooltip("My App") .build()?; ``` -------------------------------- ### Manage Multiple Tray Icons (Rust) Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/OVERVIEW.md Demonstrates how to manage multiple tray icons by storing them in a HashMap. The icons are kept alive as long as they are present in the HashMap. ```rust use std::collections::HashMap; let mut icons: HashMap = HashMap::new(); icons.insert("main".to_string(), TrayIconBuilder::new().build()?); icons.insert("helper".to_string(), TrayIconBuilder::new().build()?); // Icons kept alive by HashMap ``` -------------------------------- ### ns_status_item() Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon.md Gets the underlying NSStatusItem for this tray icon on macOS. ```APIDOC ## ns_status_item() ### Description Gets the underlying NSStatusItem for this tray icon. ### Method `ns_status_item(&self) -> Option>` ### Returns `Option>` — The NSStatusItem, or `None` if unavailable. ### Platform-specific macOS only. ### Example ```rust #[cfg(target_os = "macos")] { use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; if let Some(status_item) = tray_icon.ns_status_item() { println!("Got NSStatusItem"); } } ``` ``` -------------------------------- ### Configure TrayIcon with Complete Attributes Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-attributes.md Shows how to configure a TrayIcon with all possible attributes set. Requires importing Icon, Menu, and PathBuf. ```rust use tray_icon::{TrayIcon, TrayIconAttributes, Icon, menu::Menu}; use std::path::PathBuf; let icon = Icon::from_rgba(vec![/* RGBA */], 32, 32)?; let menu = Menu::new(); let attrs = TrayIconAttributes { tooltip: Some("My Application".to_string()), menu: Some(Box::new(menu)), icon: Some(icon), temp_dir_path: Some(PathBuf::from("/tmp/tray")), icon_is_template: false, menu_on_left_click: true, menu_on_right_click: true, title: Some("0".to_string()), }; let tray = TrayIcon::new(attrs)?; ``` -------------------------------- ### app_indicator() Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon.md Gets the underlying AppIndicator pointer for Linux and BSD systems. ```APIDOC ## app_indicator() ### Description Gets the underlying AppIndicator pointer. ### Method `unsafe fn app_indicator(&self) -> *const libappindicator::AppIndicator` ### Returns `*const AppIndicator` — Raw pointer to the AppIndicator. ### Platform-specific Linux and BSD only (not macOS). ### Safety The returned pointer is valid as long as the `TrayIcon` exists. This is unsafe because it returns a raw pointer. ### Example ```rust #[cfg(all(unix, not(target_os = "macos")))] { use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; let indicator = unsafe { tray_icon.app_indicator() }; println!("Got AppIndicator: {:?}", indicator); } ``` ``` -------------------------------- ### Create a New Menu Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md Use this to create a new root context menu that can be attached to a tray icon. ```rust use tray_icon::menu::Menu; let menu = Menu::new(); ``` -------------------------------- ### receiver() Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-event.md Gets a reference to the event channel receiver for listening to tray events. This receiver will not receive events if `set_event_handler` has been called. ```APIDOC ## receiver() ### Description Gets a reference to the event channel receiver for listening to tray events. ### Returns `&TrayIconEventReceiver` — A channel receiver for tray events ### Note This receiver will not receive events if `TrayIconEvent::set_event_handler` has been called with a `Some` value. Only use one method (receiver or handler). ### Example ```rust use tray_icon::TrayIconEvent; loop { if let Ok(event) = TrayIconEvent::receiver().try_recv() { match event { TrayIconEvent::Click { id, button, .. } => { println!("Clicked icon {} with {:?}", id.as_ref(), button); } _ => {} } } } ``` ``` -------------------------------- ### build() Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-builder.md Constructs and registers the tray icon with the system tray. This method returns a `Result` which may contain the created `TrayIcon` or an error if the process fails. ```APIDOC ## build() ### Description Builds and adds the tray icon to the system tray. ### Method ```rust pub fn build(self) -> Result ``` ### Returns - **Result** — The created tray icon, or an error if creation fails ### Throws/Errors - `Error::OsError` — If the underlying OS functionality fails - `Error::NotMainThread` — On macOS, if not called from the main thread - `Error::PngEncodingError` — On Linux/macOS, if icon encoding fails ### Platform-specific - **Linux:** The icon may not be visible unless a menu is set. - **macOS:** Must be called from the main thread while the event loop is running. - **Windows:** Must be called on a thread with an active win32 event loop. ### Example ```rust use tray_icon::{TrayIconBuilder, Icon}; let icon = Icon::from_rgba(vec![/* RGBA data */], 32, 32).unwrap(); let tray_icon = TrayIconBuilder::new() .with_icon(icon) .with_tooltip("My App") .build()?; ``` ``` -------------------------------- ### Get Tray Icon ID Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-builder.md Retrieves the unique identifier assigned to the tray icon. This can be useful for referencing the icon later. ```rust use tray_icon::TrayIconBuilder; let builder = TrayIconBuilder::new(); let icon_id = builder.id(); println!("Icon ID: {}", icon_id.as_ref()); ``` -------------------------------- ### Platform Abstraction Directory Structure Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/OVERVIEW.md Illustrates the directory structure for platform-specific implementations within the `platform_impl` module. This shows how different operating systems are supported. ```text src/platform_impl/ ├── mod.rs (dispatcher) ├── windows/mod.rs (Win32 implementation) ├── macos/mod.rs (AppKit/Cocoa implementation) └── gtk/mod.rs (GTK implementation for Linux/BSD) ``` -------------------------------- ### Icon Creation and Loading Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/MANIFEST.txt Details on how to create and load icon resources for tray icons. ```APIDOC ## Icon API ### Description Provides functionality for creating and loading icon resources, supporting various formats and platform-specific requirements. ### Methods - `from_file(path)`: Loads an icon from a file path. - `from_bytes(bytes)`: Creates an icon from raw byte data. - `from_window_icon(window_icon)`: Creates an icon from a `winit::window::Icon`. - `from_platform_icon(platform_icon)`: Creates an icon from a platform-specific icon handle. ### Supported Formats - PNG, ICO (Windows), ICNS (macOS), etc. (Platform dependent) ### Platform Specific Notes - Icon loading and rendering are highly platform-dependent. Ensure correct formats and sizes are used for each target OS. ``` -------------------------------- ### Get NSStatusItem on macOS Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon.md Retrieves the underlying NSStatusItem for a tray icon on macOS. Use this to access macOS-specific status item features. ```rust #[cfg(target_os = "macos")] pub fn ns_status_item(&self) -> Option> ``` ```rust #[cfg(target_os = "macos")] { use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; if let Some(status_item) = tray_icon.ns_status_item() { println!("Got NSStatusItem"); } } ``` -------------------------------- ### Get Tray Icon ID from Event Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-event.md Retrieve the ID of the tray icon that triggered an event. This is useful for identifying which icon an event originated from. ```rust use tray_icon::TrayIconEvent; if let Ok(event) = TrayIconEvent::receiver().try_recv() { let icon_id = event.id(); println!("Event from icon: {}", icon_id.as_ref()); } ``` -------------------------------- ### Create Tray Icon with Menu Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/INDEX.md Attach a menu to a tray icon using `TrayIconBuilder` and `Menu::new()`. ```rust use tray_icon::{TrayIconBuilder, menu::Menu}; let menu = Menu::new(); let tray = TrayIconBuilder::new() .with_menu(Box::new(menu)) .build()?; ``` -------------------------------- ### Create Tray Icon with Menu (Rust) Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/OVERVIEW.md Builds a tray icon with a custom menu, including items, separators, and quit actions. Requires RGBA icon data and dimensions. ```rust use tray_icon::{TrayIconBuilder, Icon, menu::{Menu, MenuItem, PredefinedMenuItem}}; let menu = Menu::new(); menu.append(&MenuItem::new("Open", true, Some("Ctrl+O")))?; menu.append(&PredefinedMenuItem::separator())?; menu.append(&PredefinedMenuItem::quit(Default::default()))?; let icon = Icon::from_rgba(rgba_data, 32, 32)?; let tray = TrayIconBuilder::new() .with_icon(icon) .with_menu(Box::new(menu)) .with_tooltip("My App") .build()?; ``` -------------------------------- ### Get Tray Icon Rectangle Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon.md Retrieves the position and size of the tray icon on the screen. Returns `None` if the information is unavailable. This functionality is not supported on Linux. ```rust use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; if let Some(rect) = tray_icon.rect() { println!("Icon position: {:?}", rect.position); println!("Icon size: {:?}", rect.size); } ``` -------------------------------- ### Create Icon from File Path (Windows) Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/icon.md Loads an icon from a file path on Windows. Specify an optional size or use the default. Windows may scale the icon if the exact size is not available. ```rust #[cfg(windows)] { use tray_icon::Icon; use std::path::Path; let icon = Icon::from_path("resources/app.ico", Some((32, 32)))?; // Or load default size let icon = Icon::from_path("resources/app.ico", None)?; } ``` -------------------------------- ### Get Tray Icon Rectangle Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/rect.md Retrieves the current position and size of the tray icon. This method is supported on Windows and macOS, returning `None` on Linux. ```APIDOC ## TrayIcon::rect() ### Description Get the current position and size of a tray icon. ### Method ```rust fn rect(&self) -> Option ``` ### Platform-specific - Supported on: Windows, macOS - Returns `None` on: Linux ### Request Example ```rust use tray_icon::TrayIconBuilder; let tray = TrayIconBuilder::new().build()?; if let Some(rect) = tray.rect() { println!("Tray icon bounds:"); println!(" X: {}", rect.position.x); println!(" Y: {}", rect.position.y); println!(" Width: {}", rect.size.width); println!(" Height: {}", rect.size.height); // Calculate bottom-right corner let right = rect.position.x + rect.size.width as f64; let bottom = rect.position.y + rect.size.height as f64; println!(" Bottom-right: ({}, {})", right, bottom); } ``` ### Coordinate System - **Origin:** Top-left corner of the primary display is (0, 0) - **X-axis:** Increases to the right - **Y-axis:** Increases downward - **Units:** Physical screen pixels (not DPI-adjusted) - **Fractional values:** Possible on high-DPI displays (e.g., 1920x1080 rendered at 2x scaling) ### Example Calculation ```rust use tray_icon::TrayIconBuilder; let tray = TrayIconBuilder::new().build()?; if let Some(rect) = tray.rect() { // Center of the icon let center_x = rect.position.x + (rect.size.width as f64 / 2.0); let center_y = rect.position.y + (rect.size.height as f64 / 2.0); println!("Icon center: ({}, {})", center_x, center_y); // Check if point is within icon bounds fn is_in_icon(x: f64, y: f64, rect: &tray_icon::Rect) -> bool { x >= rect.position.x && x <= rect.position.x + rect.size.width as f64 && y >= rect.position.y && y <= rect.position.y + rect.size.height as f64 } let click_x = 150.0; let click_y = 210.0; if is_in_icon(click_x, click_y, &rect) { println!("Click was within icon bounds"); } } ``` ``` -------------------------------- ### Create Basic Tray Icon Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/INDEX.md Use `TrayIconBuilder` to create a tray icon with a specified icon. Requires RGBA data and dimensions. ```rust use tray_icon::{TrayIconBuilder, Icon}; let icon = Icon::from_rgba(rgba_data, 32, 32)?; let tray = TrayIconBuilder::new() .with_icon(icon) .build()?; ``` -------------------------------- ### Menu Integration with winit Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md Demonstrates how to set up a menu event handler to send custom events through a winit EventLoopProxy when a menu item is clicked. ```APIDOC ## Menu Integration with winit ### Description This example shows how to integrate tray icon menu events with a `winit` event loop. A custom `UserEvent` enum is used to capture `MenuEvent`s, which are then sent to the `winit` event loop via an `EventLoopProxy`. ### Code Example ```rust use tray_icon::menu::MenuEvent; use winit::event_loop::EventLoopProxy; enum UserEvent { MenuItemClicked(tray_icon::menu::MenuEvent), } let proxy = event_loop.create_proxy(); MenuEvent::set_event_handler(Some(move |event| { proxy.send_event(UserEvent::MenuItemClicked(event)).ok(); })); ``` ``` -------------------------------- ### Retrieve Tray Icon ID Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-id.md Get the ID of an existing tray icon using the `id()` method. The ID can be accessed as a string reference using `as_ref()`. ```rust use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; let id = tray_icon.id(); println!("Icon ID: {}", id.as_ref()); ``` -------------------------------- ### Iterate Over Tray Icon Events Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/types.md Example of how to block and iterate over incoming tray icon events using `TrayIconEvent::receiver().iter()`. This is generally not recommended for the UI thread. ```rust use tray_icon::TrayIconEvent; // Or iterate over receiver (blocking) for event in TrayIconEvent::receiver().iter() { println!("Tray event: {:?}", event); } ``` -------------------------------- ### Configure TrayIcon using Builder Pattern Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-attributes.md Recommended method for creating and configuring a TrayIcon. Simplifies attribute setting and requires importing TrayIconBuilder, Icon, and Menu. ```rust use tray_icon::{TrayIconBuilder, Icon, menu::Menu}; let icon = Icon::from_rgba(vec![/* RGBA */], 32, 32)?; let menu = Menu::new(); let tray = TrayIconBuilder::new() .with_icon(icon) .with_menu(Box::new(menu)) .with_tooltip("My Application") .with_title("0") .with_menu_on_left_click(true) .with_menu_on_right_click(true) .build()?; ``` -------------------------------- ### Minimal Dependencies Build Configuration Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/INDEX.md Specifies the minimal dependencies required for a build of the tray-icon crate, disabling default features for both 'tray-icon' and 'muda'. Note that GTK is still a system-level requirement on Linux. ```toml [dependencies] tray-icon = { version = "0.24", default-features = false } muda = { version = "0.19", default-features = false } ``` -------------------------------- ### Get AppIndicator on Linux/BSD Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon.md Retrieves a raw pointer to the underlying AppIndicator for a tray icon on Linux and BSD systems. This is an unsafe operation and the pointer is only valid while the TrayIcon exists. ```rust #[cfg(all(unix, not(target_os = "macos")))] pub unsafe fn app_indicator(&self) -> *const libappindicator::AppIndicator ``` ```rust #[cfg(all(unix, not(target_os = "macos")))] { use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; let indicator = unsafe { tray_icon.app_indicator() }; println!("Got AppIndicator: {:?}", indicator); } ``` -------------------------------- ### Handle OsError when loading icons Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/errors.md Catch OsError when loading an icon from a file path or resource. This example shows how to differentiate between file not found, permission denied, and other OS-related issues. ```rust use tray_icon::Icon; match Icon::from_path("icon.ico", Some((32, 32))) { Ok(icon) => println!("Icon loaded"), Err(tray_icon::BadIcon::OsError(e)) => { eprintln!("Failed to load icon: {}", e); match e.kind() { std::io::ErrorKind::NotFound => println!("File not found"), std::io::ErrorKind::PermissionDenied => println!("Permission denied"), _ => println!("Other OS error: {}", e), } } Err(e) => eprintln!("Invalid icon data: {}", e), } ``` -------------------------------- ### Icon Lifecycle - Configuration Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/INDEX.md Functions for configuring tray icons during their creation. ```APIDOC ## Icon Lifecycle - Configuration ### Description Functions for configuring tray icons during their creation. ### Functions - `TrayIconBuilder::with_icon()` - `TrayIconBuilder::with_menu()` - `TrayIconBuilder::with_tooltip()` - `TrayIconBuilder::with_title()` - `TrayIconBuilder::with_id()` - `TrayIconBuilder::with_icon_as_template()` - `TrayIconBuilder::with_menu_on_left_click()` - `TrayIconBuilder::with_menu_on_right_click()` - `TrayIconBuilder::with_temp_dir_path()` ``` -------------------------------- ### Import Menu Module Items Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md Import necessary components from the tray_icon::menu module for creating menus. ```rust use tray_icon::menu::{ Menu, MenuItem, Submenu, CheckMenuItem, PredefinedMenuItem, AboutMetadata, MenuEvent, }; ``` -------------------------------- ### Get Window Handle (Windows) Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon.md Retrieves the Windows window handle (HWND) associated with the tray icon. The handle remains valid as long as the tray icon exists. This is a Windows-specific feature. ```rust #[cfg(windows)] { use tray_icon::TrayIconBuilder; let tray_icon = TrayIconBuilder::new().build()?; let hwnd = tray_icon.window_handle(); println!("Window handle: {:?}", hwnd); } ``` -------------------------------- ### Icon Lifecycle - Building Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/INDEX.md Functions for finalizing the creation and building of a tray icon. ```APIDOC ## Icon Lifecycle - Building ### Description Functions for finalizing the creation and building of a tray icon. ### Functions - `TrayIconBuilder::build()` - `TrayIconBuilder::id()` ``` -------------------------------- ### Menu Configuration Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-attributes.md Configures the context menu that is displayed when interacting with the tray icon. ```APIDOC ## menu ### Description Context menu shown on tray icon interaction. ### Type `Option>` ### Default `None` ### Platform Support All ### Platform-specific Linux: Cannot be removed or replaced once set (content can be modified) ### Example (Direct Attributes) ```rust use tray_icon::{TrayIconAttributes, menu::Menu}; let attrs = TrayIconAttributes { menu: Some(Box::new(Menu::new())), ..Default::default() }; ``` ### Example (TrayIconBuilder) ```rust use tray_icon::{TrayIconBuilder, menu::Menu}; let menu = Menu::new(); let builder = TrayIconBuilder::new() .with_menu(Box::new(menu)); ``` ``` -------------------------------- ### Create TrayIcon with Default Attributes Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-attributes.md Demonstrates creating a TrayIcon using the default attributes. Ensure TrayIconAttributes and TrayIcon are in scope. ```rust use tray_icon::{TrayIcon, TrayIconAttributes}; let attrs = TrayIconAttributes::default(); let tray = TrayIcon::new(attrs)?; ``` -------------------------------- ### Menu Integration with tao Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md Shows how to set up a menu event handler to send custom events through a tao EventLoopProxy when a menu item is clicked. ```APIDOC ## Menu Integration with tao ### Description This example demonstrates integrating tray icon menu events with a `tao` event loop. Similar to `winit`, a `UserEvent` enum is defined to handle `MenuEvent`s, which are then forwarded to the `tao` event loop using an `EventLoopProxy`. ### Code Example ```rust use tray_icon::menu::MenuEvent; enum UserEvent { MenuItemClicked(tray_icon::menu::MenuEvent), } let proxy = event_loop.create_proxy(); MenuEvent::set_event_handler(Some(move |event| { proxy.send_event(UserEvent::MenuItemClicked(event)).ok(); })); ``` ``` -------------------------------- ### Receive Tray Icon Events via Channel Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-event.md Listen for tray icon events using a channel receiver. This method is suitable for polling-based event handling. Note that this receiver will not get events if a custom handler is set. ```rust use tray_icon::TrayIconEvent; loop { if let Ok(event) = TrayIconEvent::receiver().try_recv() { match event { TrayIconEvent::Click { id, button, .. } => { println!("Clicked icon {} with {:?}", id.as_ref(), button); } _ => {} } } } ``` -------------------------------- ### Menu on Left Click Configuration Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-attributes.md Configures whether the context menu should be displayed when the tray icon is clicked with the left mouse button. ```APIDOC ## menu_on_left_click ### Description Determines if the context menu should appear when the tray icon is clicked with the left mouse button. ### Type `bool` ### Default `false` ``` -------------------------------- ### TrayIconBuilder::with_menu() Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-builder.md Sets a context menu for the tray icon. Platform-specific notes apply. ```APIDOC ## TrayIconBuilder::with_menu() ### Description Sets a context menu for the tray icon. ### Parameters #### Path Parameters - **menu** (`Box`) - Required - The context menu to display on interaction ### Returns `Self` - Builder for chaining ### Platform-specific On Linux, once a menu is set, it cannot be removed or replaced, but you can change its content. ### Example ```rust use tray_icon::{TrayIconBuilder, menu::Menu}; let menu = Menu::new(); let builder = TrayIconBuilder::new() .with_menu(Box::new(menu)); ``` ``` -------------------------------- ### Get Tray Icon Position and Size Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/rect.md Retrieves the current position and size of a tray icon. This method is supported on Windows and macOS; it returns None on Linux. The output includes the icon's bounds, allowing for calculations like the bottom-right corner. ```rust use tray_icon::TrayIconBuilder; let tray = TrayIconIconBuilder::new().build()?; // Get icon position and size if let Some(rect) = tray.rect() { println!("Tray icon bounds:"); println!(" X: {}", rect.position.x); println!(" Y: {}", rect.position.y); println!(" Width: {}", rect.size.width); println!(" Height: {}", rect.size.height); // Calculate bottom-right corner let right = rect.position.x + rect.size.width as f64; let bottom = rect.position.y + rect.size.height as f64; println!(" Bottom-right: ({}, {})", right, bottom); } ``` -------------------------------- ### Icon Creation and Loading Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/README.md APIs for creating and loading `Icon` instances, including support for various formats and platforms. ```APIDOC ## Icon and BadIcon ### Description APIs for creating and loading `Icon` instances. ### Methods - `from_rgba(width, height, rgba)`: Creates an icon from raw RGBA pixel data. - `from_path(path)`: Loads an icon from a file path. - `from_resource(resource_path)`: Loads an icon from application resources. ### Error Handling - `BadIcon` enum: Represents errors encountered during icon loading or creation. - Specific variants detail the cause of the error (e.g., invalid format, file not found). ``` -------------------------------- ### Icon Lifecycle - Creation Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/INDEX.md Functions for creating new tray icons. ```APIDOC ## Icon Lifecycle - Creation ### Description Functions for creating new tray icons. ### Functions - `TrayIconBuilder::new()` - `TrayIcon::new()` - `TrayIcon::with_id()` ``` -------------------------------- ### Menu on Right Click Configuration Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-attributes.md Configures whether the context menu should be displayed when the tray icon is clicked with the right mouse button. ```APIDOC ## menu_on_right_click ### Description Determines if the context menu should appear when the tray icon is clicked with the right mouse button. ### Type `bool` ### Default `false` ``` -------------------------------- ### Create an Icon Menu Item Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/menu-module.md Create a menu item that displays an icon alongside its text. Requires the 'icon' feature to be enabled. ```rust use tray_icon::menu::{Menu, IconMenuItem}; use tray_icon::Icon; let menu = Menu::new(); let icon = Icon::from_rgba(vec![/* RGBA */], 32, 32)?; let open = IconMenuItem::new("Open", true, Some(icon), Some("Ctrl+O")); menu.append(&open)?; ``` -------------------------------- ### TrayIconBuilder::with_tooltip() Source: https://github.com/tauri-apps/tray-icon/blob/dev/_autodocs/api-reference/tray-icon-builder.md Sets a tooltip string for the tray icon. Tooltips are not supported on Linux. ```APIDOC ## TrayIconBuilder::with_tooltip() ### Description Sets a tooltip string for the tray icon. ### Parameters #### Path Parameters - **s** (`S: AsRef`) - Required - Tooltip text to display on hover ### Returns `Self` - Builder for chaining ### Platform-specific Tooltips are not supported on Linux. ### Example ```rust use tray_icon::TrayIconBuilder; let builder = TrayIconBuilder::new() .with_tooltip("My App - Click to open"); ``` ```