Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-taurisrctray.rs

1.4.2Released Nov 21, 2026

tray.rs

160 lines6.5 KBRust
//! Closing the window keeps the app running in the system tray (the owner, 2026-11-21: "when people close juicewrld.io//! app it should really jus like minimize to tray yk and the rpc shi should all still work"). The window's Close (the//! bar's X, Alt+F4, the taskbar's Close window) hides it instead: the music in it keeps playing, and Discord keeps//! showing what plays here or in the member's other browsers (presence.rs, site.js's poll; the webviews run hidden at//! full speed, main.rs's BROWSER_ARGS). The tray icon brings it back (a left click, or Open juicewrld.io in its menu),//! as does a second launch; its menu's Quit is the one way out, which clears the Discord status as the app closes.//!//! The first close to the tray says so once, in a Windows notification (where the app went and how to quit), and never//! again: remembered in tray.json in the app's config folder.use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};use tauri::{AppHandle, Manager};use tauri_plugin_notification::NotificationExt;const FILE: &str = "tray.json";pub const OPEN: &str = "tray:open";pub const QUIT: &str = "tray:quit";const NOTICE_TITLE: &str = "juicewrld.io is still running";const NOTICE_BODY: &str = "It's in the tray by the clock, and your Discord status keeps showing what you play. To quit, right-click its icon there and choose Quit.";/// Whether the tray icon is up (closing hides the window only then: with no icon, nothing could bring it back), and/// whether the first close's notice went up in this run (so a settings folder that can't be written doesn't repeat it).#[derive(Default)]pub struct Tray {    up: AtomicBool,    told: AtomicBool,}/// The tray icon: the app's icon, "juicewrld.io" on hover, a left click opens the window, a right click the menu (Open/// juicewrld.io, Quit; main.rs's menu handler answers both through `on_menu`).pub fn create(app: &AppHandle) -> tauri::Result<()> {    let open = MenuItem::with_id(app, OPEN, "Open juicewrld.io", true, None::<&str>)?;    let line = PredefinedMenuItem::separator(app)?;    let quit = MenuItem::with_id(app, QUIT, "Quit", true, None::<&str>)?;    let menu = Menu::with_items(app, &[&open, &line, &quit])?;    let mut tray = TrayIconBuilder::with_id("main")        .tooltip("juicewrld.io")        .menu(&menu)        .show_menu_on_left_click(false)        .on_tray_icon_event(|tray, event| {            if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event {                crate::focus(tray.app_handle());            }        });    if let Some(icon) = app.default_window_icon() {        tray = tray.icon(icon.clone());    }    tray.build(app)?;    app.state::<Tray>().up.store(true, Ordering::SeqCst);    Ok(())}/// The tray menu's items; false for any other menu's.pub fn on_menu(app: &AppHandle, id: &str) -> bool {    match id {        OPEN => crate::focus(app),        // RunEvent::Exit then stops the Discord status (cleared before the app goes), the plugins and an update's install.        QUIT => app.exit(0),        _ => return false,    }    true}/// The window's Close: hidden to the tray, the app running on; the first time, a notification says so. With no tray/// icon (it couldn't be made), the app quits as before.pub fn close_to_tray(app: &AppHandle) {    let tray = app.state::<Tray>();    if !tray.up.load(Ordering::SeqCst) {        app.exit(0);        return;    }    if let Some(window) = app.get_window("main") {        let _ = window.hide();    }    eprintln!("[tray] closed to the tray");    if tray.told.swap(true, Ordering::SeqCst) {        return;    }    let Some(path) = saved_path(app) else { return };    if !first_close(&path) {        return;    }    if let Err(e) = app.notification().builder().title(NOTICE_TITLE).body(NOTICE_BODY).show() {        eprintln!("[tray] the first close's notice didn't go up ({e})");    }}/// Where the flag is kept: the app's config folder, or a debug test run's own (JW_APP_CONFIG, as the like shortcut's).fn saved_path(app: &AppHandle) -> Option<PathBuf> {    #[cfg(debug_assertions)]    if let Some(dir) = std::env::var_os("JW_APP_CONFIG") {        return Some(PathBuf::from(dir).join(FILE));    }    app.path().app_config_dir().ok().map(|d| d.join(FILE))}/// Whether the saved file says the first close's notice already went up.fn told(saved: Option<&str>) -> bool {    saved        .and_then(|text| serde_json::from_str::<serde_json::Value>(text).ok())        .and_then(|v| v.get("told").and_then(|t| t.as_bool()))        .unwrap_or(false)}/// True the first time (and remembers it at `path`), false ever after.fn first_close(path: &Path) -> bool {    if told(std::fs::read_to_string(path).ok().as_deref()) {        return false;    }    if let Some(dir) = path.parent() {        let _ = std::fs::create_dir_all(dir);    }    // Written whole to a temporary name, then moved into place: never half a file.    let tmp = path.with_extension("json.tmp");    if std::fs::write(&tmp, r#"{"told":true}"#).is_ok() {        let _ = std::fs::rename(&tmp, path);    }    true}#[cfg(test)]mod tests {    use super::*;    #[test]    fn only_a_saved_yes_counts_as_told() {        assert!(told(Some(r#"{"told":true}"#)));        assert!(!told(Some(r#"{"told":false}"#)));        assert!(!told(Some(r#"{"told":"yes"}"#)));        assert!(!told(Some("{}")));        assert!(!told(Some("not json")));        assert!(!told(Some("")));        assert!(!told(None));    }    #[test]    fn the_first_close_is_told_once() {        let dir = std::env::temp_dir().join(format!("juicewrld-tray-test-{}", std::process::id()));        let _ = std::fs::remove_dir_all(&dir);        let path = dir.join(FILE);        assert!(first_close(&path), "the first close");        assert!(!first_close(&path), "and never again");        assert!(!first_close(&path));        assert!(told(std::fs::read_to_string(&path).ok().as_deref()));        // A broken file is told again (once), then fixed.        std::fs::write(&path, "{").unwrap();        assert!(first_close(&path));        assert!(!first_close(&path));        let _ = std::fs::remove_dir_all(&dir);    }    #[test]    fn the_menus_items_are_its_own() {        assert!(OPEN.starts_with("tray:") && QUIT.starts_with("tray:"));        assert!(NOTICE_BODY.contains("Quit"));    }}