mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-26 03:46:25 -08:00
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
This commit is contained in:
6 files changed
+342
-87
No files matched your search
@@ -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<i32>) -> 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::<DesktopSettingsState>()
|
||||
.close_to_tray
|
||||
.store(enabled, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn close_to_tray_enabled<R: tauri::Runtime>(app: &AppHandle<R>) -> bool {
|
||||
app.state::<DesktopSettingsState>()
|
||||
.close_to_tray
|
||||
.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn main_window_exists<R: tauri::Runtime>(app: &AppHandle<R>) -> bool {
|
||||
app.get_webview_window(MAIN_WINDOW_LABEL).is_some()
|
||||
}
|
||||
|
||||
fn close_main_window<R: tauri::Runtime>(app: &AppHandle<R>) {
|
||||
if let Some(window) = app.get_webview_window(MAIN_WINDOW_LABEL) {
|
||||
let _ = window.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn close_all_windows<R: tauri::Runtime>(app: &AppHandle<R>) {
|
||||
for (_label, window) in app.webview_windows() {
|
||||
let _ = window.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_exit_request<R: tauri::Runtime>(
|
||||
app: &AppHandle<R>,
|
||||
code: Option<i32>,
|
||||
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<R: tauri::Runtime>(app: &AppHandle<R>, 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<R: tauri::Runtime>(window: &WebviewWindow<R>) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let _ = window.set_decorations(false);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_run_event<R: tauri::Runtime>(app: &AppHandle<R>, event: RunEvent) {
|
||||
if let RunEvent::ExitRequested { code, api, .. } = event {
|
||||
handle_exit_request(app, code, &api);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show_or_create_main_window<R: tauri::Runtime>(app: &AppHandle<R>) -> 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<R: tauri::Runtime>(app: &AppHandle<R>) -> 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(())
|
||||
}
|
||||
@@ -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 && (
|
||||
<Devices requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
{activePage === SettingsPages.DesktopPage && (
|
||||
<Desktop requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
{activePage === SettingsPages.EmojisStickersPage && (
|
||||
<EmojisStickers requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
|
||||
@@ -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 (
|
||||
<Page>
|
||||
<PageHeader outlined={false}>
|
||||
<Box grow="Yes" gap="200">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<Text size="H3" truncate>
|
||||
Desktop
|
||||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</PageHeader>
|
||||
<Box grow="Yes">
|
||||
<Scroll hideTrack visibility="Hover">
|
||||
<PageContent>
|
||||
<Box direction="Column" gap="700">
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Window</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
>
|
||||
<SettingTile
|
||||
title="Close to Tray"
|
||||
description="Keep the app running in the system tray when the main window closes. Disable this to fully exit on close."
|
||||
after={
|
||||
<Switch variant="Primary" value={closeToTray} onChange={setCloseToTray} />
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
</Box>
|
||||
</PageContent>
|
||||
</Scroll>
|
||||
</Box>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './Desktop';
|
||||
+74
-87
@@ -3,111 +3,98 @@
|
||||
|
||||
/** user-defined commands **/
|
||||
|
||||
|
||||
export const commands = {
|
||||
async setCloseToTrayEnabled(enabled: boolean) : Promise<void> {
|
||||
await TAURI_INVOKE("set_close_to_tray_enabled", { enabled });
|
||||
},
|
||||
async showSnapOverlay() : Promise<void> {
|
||||
await TAURI_INVOKE("show_snap_overlay");
|
||||
},
|
||||
async hideSnapOverlay() : Promise<void> {
|
||||
await TAURI_INVOKE("hide_snap_overlay");
|
||||
},
|
||||
async startWindowTrackingWithTarget(target: WindowTarget) : Promise<Result<null, string>> {
|
||||
async setCloseToTrayEnabled(enabled: boolean): Promise<void> {
|
||||
await TAURI_INVOKE('set_close_to_tray_enabled', { enabled });
|
||||
},
|
||||
async showSnapOverlay(): Promise<void> {
|
||||
await TAURI_INVOKE('show_snap_overlay');
|
||||
},
|
||||
async hideSnapOverlay(): Promise<void> {
|
||||
await TAURI_INVOKE('hide_snap_overlay');
|
||||
},
|
||||
async startWindowTrackingWithTarget(target: WindowTarget): Promise<Result<null, string>> {
|
||||
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<Result<null, string>> {
|
||||
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<Result<null, string>> {
|
||||
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<Result<boolean, string>> {
|
||||
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<Result<boolean, string>> {
|
||||
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__<T> = {
|
||||
listen: (
|
||||
cb: TAURI_API_EVENT.EventCallback<T>,
|
||||
) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
|
||||
once: (
|
||||
cb: TAURI_API_EVENT.EventCallback<T>,
|
||||
) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
|
||||
emit: null extends T
|
||||
? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
|
||||
: (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
|
||||
listen: (cb: TAURI_API_EVENT.EventCallback<T>) => ReturnType<typeof TAURI_API_EVENT.listen<T>>;
|
||||
once: (cb: TAURI_API_EVENT.EventCallback<T>) => ReturnType<typeof TAURI_API_EVENT.once<T>>;
|
||||
emit: null extends T
|
||||
? (payload?: T) => ReturnType<typeof TAURI_API_EVENT.emit>
|
||||
: (payload: T) => ReturnType<typeof TAURI_API_EVENT.emit>;
|
||||
};
|
||||
|
||||
export type Result<T, E> =
|
||||
| { status: "ok"; data: T }
|
||||
| { status: "error"; error: E };
|
||||
export type Result<T, E> = { status: 'ok'; data: T } | { status: 'error'; error: E };
|
||||
|
||||
function __makeEvents__<T extends Record<string, any>>(
|
||||
mappings: Record<keyof T, string>,
|
||||
) {
|
||||
return new Proxy(
|
||||
{} as unknown as {
|
||||
[K in keyof T]: __EventObj__<T[K]> & {
|
||||
(handle: __WebviewWindow__): __EventObj__<T[K]>;
|
||||
};
|
||||
},
|
||||
{
|
||||
get: (_, event) => {
|
||||
const name = mappings[event as keyof T];
|
||||
function __makeEvents__<T extends Record<string, any>>(mappings: Record<keyof T, string>) {
|
||||
return new Proxy(
|
||||
{} as unknown as {
|
||||
[K in keyof T]: __EventObj__<T[K]> & {
|
||||
(handle: __WebviewWindow__): __EventObj__<T[K]>;
|
||||
};
|
||||
},
|
||||
{
|
||||
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__<any>) => {
|
||||
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__<any>) => {
|
||||
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);
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -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 = () => {
|
||||
|
||||
Reference in new issue
Block a user