From 2e10f735fad9b632c2fb93a2b44682e1d4e8cf51 Mon Sep 17 00:00:00 2001 From: hazre Date: Thu, 5 Mar 2026 16:29:58 +0100 Subject: [PATCH] feat(tauri): add desktop system tray and option to close to tray note that close to tray currently does nothing and it's intended for when notifications land --- src-tauri/src/desktop_tray.rs | 187 ++++++++++++++++++ src/app/features/settings/Settings.tsx | 15 ++ src/app/features/settings/desktop/Desktop.tsx | 61 ++++++ src/app/features/settings/desktop/index.ts | 1 + src/app/generated/tauri.ts | 161 +++++++-------- src/app/state/settings.ts | 4 + 6 files changed, 342 insertions(+), 87 deletions(-) create mode 100644 src-tauri/src/desktop_tray.rs create mode 100644 src/app/features/settings/desktop/Desktop.tsx create mode 100644 src/app/features/settings/desktop/index.ts diff --git a/src-tauri/src/desktop_tray.rs b/src-tauri/src/desktop_tray.rs new file mode 100644 index 000000000..021c65acb --- /dev/null +++ b/src-tauri/src/desktop_tray.rs @@ -0,0 +1,187 @@ +use std::sync::atomic::{AtomicBool, Ordering}; + +use tauri::{ + menu::{Menu, MenuItem}, + tray::{MouseButton, TrayIconBuilder, TrayIconEvent}, + AppHandle, Manager, RunEvent, WebviewUrl, WebviewWindow, WebviewWindowBuilder, +}; + +pub const MAIN_WINDOW_LABEL: &str = "main"; +const TRAY_MENU_SHOW_ID: &str = "tray_show"; +const TRAY_MENU_QUIT_ID: &str = "tray_quit"; + +pub struct DesktopSettingsState { + close_to_tray: AtomicBool, +} + +impl DesktopSettingsState { + pub fn new(close_to_tray: bool) -> Self { + Self { + close_to_tray: AtomicBool::new(close_to_tray), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum TrayDoubleClickAction { + Ignore, + ShowOrCreateMainWindow, + CloseMainWindow, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ExitRequestAction { + AllowExit, + CloseWindowsToTray, +} + +fn tray_double_click_action(window_exists: bool, event: &TrayIconEvent) -> TrayDoubleClickAction { + match event { + TrayIconEvent::DoubleClick { + button: MouseButton::Left, + .. + } => { + if window_exists { + TrayDoubleClickAction::CloseMainWindow + } else { + TrayDoubleClickAction::ShowOrCreateMainWindow + } + } + _ => TrayDoubleClickAction::Ignore, + } +} + +fn exit_request_action(close_to_tray: bool, code: Option) -> ExitRequestAction { + match (close_to_tray, code) { + (_, Some(_)) => ExitRequestAction::AllowExit, + (true, None) => ExitRequestAction::CloseWindowsToTray, + (false, None) => ExitRequestAction::AllowExit, + } +} + +#[tauri::command] +#[specta::specta] +pub fn set_close_to_tray_enabled(app: AppHandle, enabled: bool) { + app.state::() + .close_to_tray + .store(enabled, Ordering::Relaxed); +} + +fn close_to_tray_enabled(app: &AppHandle) -> bool { + app.state::() + .close_to_tray + .load(Ordering::Relaxed) +} + +fn main_window_exists(app: &AppHandle) -> bool { + app.get_webview_window(MAIN_WINDOW_LABEL).is_some() +} + +fn close_main_window(app: &AppHandle) { + if let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) { + let _ = window.close(); + } +} + +fn close_all_windows(app: &AppHandle) { + for (_label, window) in app.webview_windows() { + let _ = window.close(); + } +} + +fn handle_exit_request( + app: &AppHandle, + code: Option, + api: &tauri::ExitRequestApi, +) { + if exit_request_action(close_to_tray_enabled(app), code) + == ExitRequestAction::CloseWindowsToTray + { + api.prevent_exit(); + close_all_windows(app); + } +} + +fn handle_tray_double_click(app: &AppHandle, event: &TrayIconEvent) { + match tray_double_click_action(main_window_exists(app), event) { + TrayDoubleClickAction::ShowOrCreateMainWindow => { + let _ = show_or_create_main_window(app); + } + TrayDoubleClickAction::CloseMainWindow => { + close_main_window(app); + } + TrayDoubleClickAction::Ignore => {} + } +} + +pub fn configure_main_window(window: &WebviewWindow) { + #[cfg(target_os = "windows")] + { + let _ = window.set_decorations(false); + } +} + +pub fn handle_run_event(app: &AppHandle, event: RunEvent) { + if let RunEvent::ExitRequested { code, api, .. } = event { + handle_exit_request(app, code, &api); + } +} + +pub fn show_or_create_main_window(app: &AppHandle) -> tauri::Result<()> { + if let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) { + let _ = window.unminimize(); + let _ = window.show(); + let _ = window.set_focus(); + return Ok(()); + } + + if let Some(window_config) = app + .config() + .app + .windows + .iter() + .find(|window| window.label == MAIN_WINDOW_LABEL) + .or_else(|| app.config().app.windows.first()) + { + let window = WebviewWindowBuilder::from_config(app, window_config)?.build()?; + configure_main_window(&window); + return Ok(()); + } + + let window = WebviewWindowBuilder::new(app, MAIN_WINDOW_LABEL, WebviewUrl::default()) + .title("sable") + .build()?; + configure_main_window(&window); + + Ok(()) +} + +pub fn create_system_tray(app: &AppHandle) -> tauri::Result<()> { + let show_item = MenuItem::with_id(app, TRAY_MENU_SHOW_ID, "Show", true, None::<&str>)?; + let quit_item = MenuItem::with_id(app, TRAY_MENU_QUIT_ID, "Quit", true, None::<&str>)?; + let tray_menu = Menu::with_items(app, &[&show_item, &quit_item])?; + + let mut tray_builder = TrayIconBuilder::new() + .menu(&tray_menu) + .show_menu_on_left_click(false) + .on_menu_event(|app, event| match event.id().as_ref() { + TRAY_MENU_SHOW_ID => { + let _ = show_or_create_main_window(app); + } + TRAY_MENU_QUIT_ID => { + app.exit(0); + } + _ => {} + }) + .on_tray_icon_event(|tray, event| { + let app = tray.app_handle(); + handle_tray_double_click(app, &event); + }); + + if let Some(icon) = app.default_window_icon() { + tray_builder = tray_builder.icon(icon.clone()); + } + + tray_builder.build(app)?; + Ok(()) +} diff --git a/src/app/features/settings/Settings.tsx b/src/app/features/settings/Settings.tsx index 34f350b3d..9f1781f5a 100644 --- a/src/app/features/settings/Settings.tsx +++ b/src/app/features/settings/Settings.tsx @@ -14,6 +14,7 @@ import { OverlayCenter, Text, } from 'folds'; +import { isTauri } from '@tauri-apps/api/core'; import FocusTrap from 'focus-trap-react'; import { PageNav, PageNavContent, PageNavHeader, PageRoot } from '$components/page'; import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize'; @@ -36,12 +37,14 @@ import { General } from './general'; import { Cosmetics } from './cosmetics/Cosmetics'; import { Experimental } from './experimental/Experimental'; import { KeyboardShortcuts } from './keyboard-shortcuts'; +import { Desktop } from './desktop'; export enum SettingsPages { GeneralPage, AccountPage, NotificationPage, DevicesPage, + DesktopPage, EmojisStickersPage, CosmeticsPage, DeveloperToolsPage, @@ -86,6 +89,15 @@ const useSettingsMenuItems = (): SettingsMenuItem[] => name: 'Devices', icon: Icons.Monitor, }, + ...(isTauri() + ? [ + { + page: SettingsPages.DesktopPage, + name: 'Desktop', + icon: Icons.Monitor, + }, + ] + : []), { page: SettingsPages.EmojisStickersPage, name: 'Emojis & Stickers', @@ -256,6 +268,9 @@ export function Settings({ initialPage, requestClose }: SettingsProps) { {activePage === SettingsPages.DevicesPage && ( )} + {activePage === SettingsPages.DesktopPage && ( + + )} {activePage === SettingsPages.EmojisStickersPage && ( )} diff --git a/src/app/features/settings/desktop/Desktop.tsx b/src/app/features/settings/desktop/Desktop.tsx new file mode 100644 index 000000000..0efaf3cf4 --- /dev/null +++ b/src/app/features/settings/desktop/Desktop.tsx @@ -0,0 +1,61 @@ +import { isTauri } from '@tauri-apps/api/core'; +import { Box, Text, IconButton, Icon, Icons, Scroll, Switch } from 'folds'; +import { Page, PageContent, PageHeader } from '$components/page'; +import { SequenceCard } from '$components/sequence-card'; +import { SettingTile } from '$components/setting-tile'; +import { useSetting } from '$state/hooks/settings'; +import { settingsAtom } from '$state/settings'; +import { SequenceCardStyle } from '$features/settings/styles.css'; + +type DesktopProps = { + requestClose: () => void; +}; + +export function Desktop({ requestClose }: DesktopProps) { + const [closeToTray, setCloseToTray] = useSetting(settingsAtom, 'closeToTray'); + + if (!isTauri()) return null; + + return ( + + + + + + Desktop + + + + + + + + + + + + + + + Window + + + } + /> + + + + + + + + ); +} diff --git a/src/app/features/settings/desktop/index.ts b/src/app/features/settings/desktop/index.ts new file mode 100644 index 000000000..71f2ecc9f --- /dev/null +++ b/src/app/features/settings/desktop/index.ts @@ -0,0 +1 @@ +export * from './Desktop'; diff --git a/src/app/generated/tauri.ts b/src/app/generated/tauri.ts index 049233e2d..43edaea73 100644 --- a/src/app/generated/tauri.ts +++ b/src/app/generated/tauri.ts @@ -3,111 +3,98 @@ /** user-defined commands **/ - export const commands = { -async setCloseToTrayEnabled(enabled: boolean) : Promise { - await TAURI_INVOKE("set_close_to_tray_enabled", { enabled }); -}, -async showSnapOverlay() : Promise { - await TAURI_INVOKE("show_snap_overlay"); -}, -async hideSnapOverlay() : Promise { - await TAURI_INVOKE("hide_snap_overlay"); -}, -async startWindowTrackingWithTarget(target: WindowTarget) : Promise> { + async setCloseToTrayEnabled(enabled: boolean): Promise { + await TAURI_INVOKE('set_close_to_tray_enabled', { enabled }); + }, + async showSnapOverlay(): Promise { + await TAURI_INVOKE('show_snap_overlay'); + }, + async hideSnapOverlay(): Promise { + await TAURI_INVOKE('hide_snap_overlay'); + }, + async startWindowTrackingWithTarget(target: WindowTarget): Promise> { try { - return { status: "ok", data: await TAURI_INVOKE("start_window_tracking_with_target", { target }) }; -} catch (e) { - if(e instanceof Error) throw e; - else return { status: "error", error: e as any }; -} -}, -async stopWindowTracking() : Promise> { + return { + status: 'ok', + data: await TAURI_INVOKE('start_window_tracking_with_target', { target }), + }; + } catch (e) { + if (e instanceof Error) throw e; + else return { status: 'error', error: e as any }; + } + }, + async stopWindowTracking(): Promise> { try { - return { status: "ok", data: await TAURI_INVOKE("stop_window_tracking") }; -} catch (e) { - if(e instanceof Error) throw e; - else return { status: "error", error: e as any }; -} -}, -async isWindowTrackingActive() : Promise> { + return { status: 'ok', data: await TAURI_INVOKE('stop_window_tracking') }; + } catch (e) { + if (e instanceof Error) throw e; + else return { status: 'error', error: e as any }; + } + }, + async isWindowTrackingActive(): Promise> { try { - return { status: "ok", data: await TAURI_INVOKE("is_window_tracking_active") }; -} catch (e) { - if(e instanceof Error) throw e; - else return { status: "error", error: e as any }; -} -} -} + return { status: 'ok', data: await TAURI_INVOKE('is_window_tracking_active') }; + } catch (e) { + if (e instanceof Error) throw e; + else return { status: 'error', error: e as any }; + } + }, +}; /** user-defined events **/ - - /** user-defined constants **/ - - /** user-defined types **/ -export type WindowTarget = { window_class: string | null; exe_name: string | null } +export type WindowTarget = { window_class: string | null; exe_name: string | null }; /** tauri-specta globals **/ -import { - invoke as TAURI_INVOKE, - Channel as TAURI_CHANNEL, -} from "@tauri-apps/api/core"; -import * as TAURI_API_EVENT from "@tauri-apps/api/event"; -import { type WebviewWindow as __WebviewWindow__ } from "@tauri-apps/api/webviewWindow"; +import { invoke as TAURI_INVOKE, Channel as TAURI_CHANNEL } from '@tauri-apps/api/core'; +import * as TAURI_API_EVENT from '@tauri-apps/api/event'; +import { type WebviewWindow as __WebviewWindow__ } from '@tauri-apps/api/webviewWindow'; type __EventObj__ = { - listen: ( - cb: TAURI_API_EVENT.EventCallback, - ) => ReturnType>; - once: ( - cb: TAURI_API_EVENT.EventCallback, - ) => ReturnType>; - emit: null extends T - ? (payload?: T) => ReturnType - : (payload: T) => ReturnType; + listen: (cb: TAURI_API_EVENT.EventCallback) => ReturnType>; + once: (cb: TAURI_API_EVENT.EventCallback) => ReturnType>; + emit: null extends T + ? (payload?: T) => ReturnType + : (payload: T) => ReturnType; }; -export type Result = - | { status: "ok"; data: T } - | { status: "error"; error: E }; +export type Result = { status: 'ok'; data: T } | { status: 'error'; error: E }; -function __makeEvents__>( - mappings: Record, -) { - return new Proxy( - {} as unknown as { - [K in keyof T]: __EventObj__ & { - (handle: __WebviewWindow__): __EventObj__; - }; - }, - { - get: (_, event) => { - const name = mappings[event as keyof T]; +function __makeEvents__>(mappings: Record) { + return new Proxy( + {} as unknown as { + [K in keyof T]: __EventObj__ & { + (handle: __WebviewWindow__): __EventObj__; + }; + }, + { + get: (_, event) => { + const name = mappings[event as keyof T]; - return new Proxy((() => {}) as any, { - apply: (_, __, [window]: [__WebviewWindow__]) => ({ - listen: (arg: any) => window.listen(name, arg), - once: (arg: any) => window.once(name, arg), - emit: (arg: any) => window.emit(name, arg), - }), - get: (_, command: keyof __EventObj__) => { - switch (command) { - case "listen": - return (arg: any) => TAURI_API_EVENT.listen(name, arg); - case "once": - return (arg: any) => TAURI_API_EVENT.once(name, arg); - case "emit": - return (arg: any) => TAURI_API_EVENT.emit(name, arg); - } - }, - }); - }, - }, - ); + return new Proxy((() => {}) as any, { + apply: (_, __, [window]: [__WebviewWindow__]) => ({ + listen: (arg: any) => window.listen(name, arg), + once: (arg: any) => window.once(name, arg), + emit: (arg: any) => window.emit(name, arg), + }), + get: (_, command: keyof __EventObj__) => { + switch (command) { + case 'listen': + return (arg: any) => TAURI_API_EVENT.listen(name, arg); + case 'once': + return (arg: any) => TAURI_API_EVENT.once(name, arg); + case 'emit': + return (arg: any) => TAURI_API_EVENT.emit(name, arg); + } + }, + }); + }, + } + ); } diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index ab4d6ef18..2d6b09260 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -96,6 +96,8 @@ export interface Settings { // furry stuff renderAnimals: boolean; + + closeToTray: boolean; } const defaultSettings: Settings = { @@ -172,6 +174,8 @@ const defaultSettings: Settings = { // furry stuff renderAnimals: true, + + closeToTray: true, }; export const getSettings = () => {