Skip to content

Commit

Permalink
feat(backend): allow to hide tray selector (#626)
Browse files Browse the repository at this point in the history
* feat(backend): allow to hide tray selector

* feat(frontend): enable clash tray selector switch
  • Loading branch information
greenhat616 authored Mar 17, 2024
1 parent 94d3863 commit 4e45b98
Show file tree
Hide file tree
Showing 9 changed files with 64 additions and 17 deletions.
5 changes: 5 additions & 0 deletions backend/tauri/src/config/nyanpasu/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ pub struct IVerge {

/// Clash 相关策略
pub clash_strategy: Option<ClashStrategy>,

/// 是否启用代理托盘选择
pub clash_tray_selector: Option<bool>,
}

#[derive(Default, Debug, Clone, Deserialize, Serialize)]
Expand Down Expand Up @@ -227,6 +230,7 @@ impl IVerge {
// auto_log_clean: Some(60 * 24 * 7), // 7 days 自动清理日记
max_log_files: Some(7), // 7 days
disable_auto_check_update: Some(true),
clash_tray_selector: Some(true),
..Self::default()
}
}
Expand Down Expand Up @@ -281,5 +285,6 @@ impl IVerge {
patch!(max_log_files);
patch!(window_size_state);
patch!(clash_strategy);
patch!(clash_tray_selector);
}
}
1 change: 0 additions & 1 deletion backend/tauri/src/core/tray/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ impl Tray {

SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", t!("tray.dashboard")))
.add_native_item(SystemTrayMenuItem::Separator)
.setup_proxies() // Setup the proxies menu
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("rule_mode", t!("tray.rule_mode")))
Expand Down
39 changes: 29 additions & 10 deletions backend/tauri/src/core/tray/proxies.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use crate::core::{
clash::proxies::{Proxies, ProxiesGuard, ProxiesGuardExt},
handle::Handle,
use crate::{
config::Config,
core::{
clash::proxies::{Proxies, ProxiesGuard, ProxiesGuardExt},
handle::Handle,
},
};
use anyhow::Context;
use base64::{engine::general_purpose::STANDARD as base64_standard, Engine as _};
Expand Down Expand Up @@ -65,18 +68,17 @@ fn to_tray_proxies(mode: &str, raw_proxies: &Proxies) -> TrayProxies {
all: raw_proxies
.global
.all
.clone()
.into_iter()
.map(|x| x.name)
.iter()
.map(|x| x.name.to_owned())
.collect(),
r#type: "Selector".to_owned(),
r#type: "Selector".to_string(),
};
tray_proxies.insert("global".to_owned(), global);
}
for raw_group in raw_proxies.groups.iter() {
let group = TrayProxyItem {
current: raw_group.now.clone(),
all: raw_group.all.clone().into_iter().map(|x| x.name).collect(),
all: raw_group.all.iter().map(|x| x.name.to_owned()).collect(),
r#type: raw_group.r#type.clone(),
};
tray_proxies.insert(raw_group.name.to_owned(), group);
Expand Down Expand Up @@ -159,6 +161,13 @@ pub async fn proxies_updated_receiver() {
continue;
}
Handle::mutate_proxies();
{
let is_tray_selector_enabled =
Config::verge().latest().clash_tray_selector.unwrap_or(true);
if !is_tray_selector_enabled {
continue;
}
}
// Do diff check
let mode = crate::utils::config::get_current_clash_mode();
let current_tray_proxies =
Expand Down Expand Up @@ -202,7 +211,7 @@ mod platform_impl {
use super::{ProxySelectAction, TrayProxyItem};
use crate::core::{clash::proxies::ProxiesGuard, handle::Handle};
use base64::{engine::general_purpose::STANDARD as base64_standard, Engine as _};
use tauri::{CustomMenuItem, SystemTrayMenu, SystemTraySubmenu};
use tauri::{CustomMenuItem, SystemTrayMenu, SystemTrayMenuItem, SystemTraySubmenu};
use tracing::warn;

pub fn generate_group_selector(group_name: &str, group: &TrayProxyItem) -> SystemTraySubmenu {
Expand Down Expand Up @@ -247,10 +256,20 @@ mod platform_impl {
}

pub fn setup_tray(menu: &mut SystemTrayMenu) -> SystemTrayMenu {
let mut menu = menu.to_owned();
let is_tray_selector_enabled = crate::config::Config::verge()
.latest()
.clash_tray_selector
.unwrap_or(true);
if !is_tray_selector_enabled {
return menu;
}
// TODO: support submenu
menu = menu.add_native_item(SystemTrayMenuItem::Separator);
let proxies = ProxiesGuard::global().read().inner().to_owned();
let mode = crate::utils::config::get_current_clash_mode();
let tray_proxies = super::to_tray_proxies(mode.as_str(), &proxies);
generate_selectors(menu, &tray_proxies)
generate_selectors(&menu, &tray_proxies)
}

pub fn update_selected_proxies(actions: &[ProxySelectAction]) {
Expand Down
11 changes: 8 additions & 3 deletions backend/tauri/src/feat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,16 +265,16 @@ pub async fn patch_clash(patch: Mapping) -> Result<()> {
/// 一般都是一个个的修改
pub async fn patch_verge(patch: IVerge) -> Result<()> {
Config::verge().draft().patch_config(patch.clone());

let tun_mode = patch.enable_tun_mode;
let auto_launch = patch.enable_auto_launch;
let system_proxy = patch.enable_system_proxy;
let proxy_bypass = patch.system_proxy_bypass;
let language = patch.language;
let log_level = patch.app_log_level;
let log_max_files = patch.max_log_files;
let enable_tray_selector = patch.clash_tray_selector;

let res = {
let res = || async move {
#[cfg(target_os = "windows")]
{
let service_mode = patch.enable_service_mode;
Expand Down Expand Up @@ -321,9 +321,14 @@ pub async fn patch_verge(patch: IVerge) -> Result<()> {
utils::init::refresh_logger((log_level, log_max_files))?;
}

if enable_tray_selector.is_some() {
handle::Handle::update_systray()?;
}

<Result<()>>::Ok(())
};
match res {

match res().await {
Ok(()) => {
Config::verge().apply();
Config::verge().data().save_file()?;
Expand Down
14 changes: 14 additions & 0 deletions src/components/setting/mods/misc-viewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
autoCloseConnection: false,
enableClashFields: true,
enableBuiltinEnhanced: true,
clashTraySelector: true,
proxyLayoutColumn: 6,
defaultLatencyTest: "",
});
Expand All @@ -36,6 +37,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
autoCloseConnection: verge?.auto_close_connection ?? false,
enableClashFields: verge?.enable_clash_fields ?? true,
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
clashTraySelector: verge?.clash_tray_selector ?? true,
proxyLayoutColumn: verge?.proxy_layout_column || 6,
defaultLatencyTest: verge?.default_latency_test || "",
});
Expand All @@ -52,6 +54,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
enable_builtin_enhanced: values.enableBuiltinEnhanced,
proxy_layout_column: values.proxyLayoutColumn,
default_latency_test: values.defaultLatencyTest,
clash_tray_selector: values.clashTraySelector,
});
setOpen(false);
} catch (err: any) {
Expand Down Expand Up @@ -129,6 +132,17 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
/>
</ListItem>

<ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary={t("Enable Tray Proxies Selector")} />
<MDYSwitch
edge="end"
checked={values.clashTraySelector}
onChange={(_, c) =>
setValues((v) => ({ ...v, clashTraySelector: c }))
}
/>
</ListItem>

<ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary={t("Proxy Layout Column")} />
<Select
Expand Down
3 changes: 2 additions & 1 deletion src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,6 @@
"Rule Set rules": "{{rule}} rules",
"Last Update": "Last Updated: {{fromNow}}",
"Update Rules Providers Success": "Update Rules Providers Success",
"Portable Update Error": "Portable Update is not supported, please download the latest version from the official website."
"Portable Update Error": "Portable Update is not supported, please download the latest version from the official website.",
"Enable Tray Proxies Selector": "Enable Tray Proxies Selector"
}
3 changes: 2 additions & 1 deletion src/locales/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,5 +139,6 @@
"Last Update": "Последнее обновление {{fromNow}}",
"Update Rules Providers Success": "Провайдеры правил успешно обновлены",

"Portable Update Error": "Обновление портативной версии не поддерживается"
"Portable Update Error": "Обновление портативной версии не поддерживается",
"Enable Tray Proxies Selector": "Включить выбор прокси в трее"
}
4 changes: 3 additions & 1 deletion src/locales/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -161,5 +161,7 @@
"Last Update": "{{fromNow}}更新",
"Update Rules Providers Success": "更新规则集成功",

"Portable Update Error": "便携版无法自动更新,请到 Github 下载最新版本"
"Portable Update Error": "便携版无法自动更新,请到 Github 下载最新版本",

"Enable Tray Proxies Selector": "开启托盘代理选择"
}
1 change: 1 addition & 0 deletions src/services/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ interface IVergeConfig {
enable_clash_fields?: boolean;
enable_builtin_enhanced?: boolean;
proxy_layout_column?: number;
clash_tray_selector?: boolean;

clash_strategy?: {
external_controller_port_strategy: "fixed" | "random" | "allow_fallback";
Expand Down

0 comments on commit 4e45b98

Please sign in to comment.