Compare commits
29 Commits
8
.github/workflows/release.yml
vendored
@@ -10,7 +10,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform: [windows-latest]
|
||||
platform: [windows-latest, macos-latest]
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -54,6 +54,6 @@ jobs:
|
||||
with:
|
||||
tagName: v__VERSION__
|
||||
releaseName: "Clash Verge v__VERSION__"
|
||||
releaseBody: "This is a release."
|
||||
releaseDraft: true
|
||||
prerelease: false
|
||||
releaseBody: "Clash Verge now supports Windows and macos(intel)."
|
||||
releaseDraft: false
|
||||
prerelease: true
|
||||
|
||||
1
.gitignore
vendored
@@ -3,3 +3,4 @@ node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
update.json
|
||||
|
||||
10
README.md
@@ -26,7 +26,7 @@ yarn install
|
||||
Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/en/docs/api/config#tauri.bundle.externalBin).
|
||||
|
||||
```shell
|
||||
yarn run predev
|
||||
yarn run check
|
||||
```
|
||||
|
||||
Then run
|
||||
@@ -42,8 +42,12 @@ yarn dev
|
||||
## Screenshots
|
||||
|
||||
<div align="center">
|
||||
<img src="./docs/demo1.png" alt="demo1" width="42%" />
|
||||
<img src="./docs/demo2.png" alt="demo2" width="42%" />
|
||||
<img src="./docs/demo1.png" alt="demo1" width="32%" />
|
||||
<img src="./docs/demo2.png" alt="demo2" width="32%" />
|
||||
<img src="./docs/demo3.png" alt="demo3" width="32%" />
|
||||
<img src="./docs/demo4.png" alt="demo4" width="32%" />
|
||||
<img src="./docs/demo5.png" alt="demo5" width="32%" />
|
||||
<img src="./docs/demo6.png" alt="demo6" width="32%" />
|
||||
</div>
|
||||
|
||||
## Disclaimer
|
||||
|
||||
BIN
docs/demo1.png
|
Before Width: | Height: | Size: 52 KiB After Width: | Height: | Size: 21 KiB |
BIN
docs/demo2.png
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 20 KiB |
BIN
docs/demo3.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
BIN
docs/demo4.png
Normal file
|
After Width: | Height: | Size: 18 KiB |
BIN
docs/demo5.png
Normal file
|
After Width: | Height: | Size: 19 KiB |
BIN
docs/demo6.png
Normal file
|
After Width: | Height: | Size: 25 KiB |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "0.0.5",
|
||||
"version": "0.0.10",
|
||||
"license": "GPL-3.0",
|
||||
"scripts": {
|
||||
"dev": "cargo tauri dev",
|
||||
|
||||
@@ -11,10 +11,16 @@ async function resolvePublish() {
|
||||
|
||||
let [a, b, c] = packageJson.version.split(".").map(Number);
|
||||
|
||||
if (flag === "major") a += 1;
|
||||
else if (flag === "minor") b += 1;
|
||||
else if (flag === "patch") c += 1;
|
||||
else throw new Error(`invalid flag "${flag}"`);
|
||||
if (flag === "major") {
|
||||
a += 1;
|
||||
b = 0;
|
||||
c = 0;
|
||||
} else if (flag === "minor") {
|
||||
b += 1;
|
||||
c = 0;
|
||||
} else if (flag === "patch") {
|
||||
c += 1;
|
||||
} else throw new Error(`invalid flag "${flag}"`);
|
||||
|
||||
const nextVersion = `${a}.${b}.${c}`;
|
||||
packageJson.version = nextVersion;
|
||||
|
||||
752
src-tauri/Cargo.lock
generated
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
description = "clash verge"
|
||||
authors = ["zzzgydi"]
|
||||
license = "GPL-3.0"
|
||||
repository = ""
|
||||
repository = "https://github.com/zzzgydi/clash-verge.git"
|
||||
default-run = "app"
|
||||
edition = "2021"
|
||||
build = "build.rs"
|
||||
@@ -19,7 +19,10 @@ serde_json = "1.0"
|
||||
serde_yaml = "0.8"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
# tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
|
||||
tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
|
||||
# tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
|
||||
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all", "system-tray", "updater"] }
|
||||
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
|
||||
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }
|
||||
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
@@ -8,7 +8,7 @@ use crate::{
|
||||
},
|
||||
};
|
||||
use serde_yaml::Mapping;
|
||||
use tauri::State;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
|
||||
/// get all profiles from `profiles.yaml`
|
||||
/// do not acquire the lock of ProfileLock
|
||||
@@ -107,13 +107,23 @@ pub fn select_profile(
|
||||
}
|
||||
}
|
||||
|
||||
/// todo: need to check
|
||||
/// delete profile item
|
||||
#[tauri::command]
|
||||
pub fn delete_profile(index: usize, profiles: State<'_, ProfilesState>) -> Result<(), String> {
|
||||
match profiles.0.lock() {
|
||||
Ok(mut profiles) => profiles.delete_item(index),
|
||||
Err(_) => Err("can not get profiles lock".into()),
|
||||
pub fn delete_profile(
|
||||
index: usize,
|
||||
clash_state: State<'_, ClashState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut profiles = profiles_state.0.lock().unwrap();
|
||||
match profiles.delete_item(index) {
|
||||
Ok(change) => match change {
|
||||
true => {
|
||||
let clash = clash_state.0.lock().unwrap();
|
||||
profiles.activate(clash.info.clone())
|
||||
}
|
||||
false => Ok(()),
|
||||
},
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -132,10 +142,27 @@ pub fn patch_profile(
|
||||
|
||||
/// restart the sidecar
|
||||
#[tauri::command]
|
||||
pub fn restart_sidecar(clash_state: State<'_, ClashState>) {
|
||||
let mut clash_arc = clash_state.0.lock().unwrap();
|
||||
if let Err(err) = clash_arc.restart_sidecar() {
|
||||
log::error!("{}", err);
|
||||
pub fn restart_sidecar(
|
||||
clash_state: State<'_, ClashState>,
|
||||
profiles_state: State<'_, ProfilesState>,
|
||||
) -> Result<(), String> {
|
||||
let mut clash = clash_state.0.lock().unwrap();
|
||||
|
||||
match clash.restart_sidecar() {
|
||||
Ok(_) => {
|
||||
let profiles = profiles_state.0.lock().unwrap();
|
||||
match profiles.activate(clash.info.clone()) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("{}", err);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,24 +193,7 @@ pub fn patch_clash_config(payload: Mapping) -> Result<(), String> {
|
||||
save_clash(&config)
|
||||
}
|
||||
|
||||
/// set the system proxy
|
||||
/// Tips: only support windows now
|
||||
#[tauri::command]
|
||||
pub fn set_sys_proxy(enable: bool, verge_state: State<'_, VergeState>) -> Result<(), String> {
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
|
||||
if let Some(mut sysproxy) = verge.cur_sysproxy.take() {
|
||||
sysproxy.enable = enable;
|
||||
if sysproxy.set_sys().is_err() {
|
||||
log::error!("failed to set system proxy");
|
||||
}
|
||||
verge.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get the system proxy
|
||||
/// Tips: only support windows now
|
||||
#[tauri::command]
|
||||
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||
match SysProxyConfig::get_sys() {
|
||||
@@ -192,6 +202,8 @@ pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// get the current proxy config
|
||||
/// which may not the same as system proxy
|
||||
#[tauri::command]
|
||||
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
|
||||
match verge_state.0.lock() {
|
||||
@@ -217,22 +229,27 @@ pub async fn patch_verge_config(
|
||||
verge_state: State<'_, VergeState>,
|
||||
) -> Result<(), String> {
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
|
||||
if payload.theme_mode.is_some() {
|
||||
verge.config.theme_mode = payload.theme_mode;
|
||||
}
|
||||
|
||||
if payload.enable_self_startup.is_some() {
|
||||
verge.config.enable_self_startup = payload.enable_self_startup;
|
||||
}
|
||||
|
||||
if payload.enable_system_proxy.is_some() {
|
||||
verge.config.enable_system_proxy = payload.enable_system_proxy;
|
||||
}
|
||||
|
||||
if payload.system_proxy_bypass.is_some() {
|
||||
verge.config.system_proxy_bypass = payload.system_proxy_bypass;
|
||||
}
|
||||
|
||||
verge.config.save_file()
|
||||
verge.patch_config(payload)
|
||||
}
|
||||
|
||||
/// start dragging window
|
||||
#[tauri::command]
|
||||
pub fn win_drag(app_handle: AppHandle) {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.start_dragging().unwrap();
|
||||
}
|
||||
|
||||
/// hide the window
|
||||
#[tauri::command]
|
||||
pub fn win_hide(app_handle: AppHandle) {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
window.hide().unwrap();
|
||||
}
|
||||
|
||||
/// mini the window
|
||||
#[tauri::command]
|
||||
pub fn win_mini(app_handle: AppHandle) {
|
||||
let window = app_handle.get_window("main").unwrap();
|
||||
// todo: these methods still has bug on Windows
|
||||
window.minimize().unwrap();
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ impl ProfilesConfig {
|
||||
}
|
||||
|
||||
/// delete the item
|
||||
pub fn delete_item(&mut self, index: usize) -> Result<(), String> {
|
||||
pub fn delete_item(&mut self, index: usize) -> Result<bool, String> {
|
||||
let mut current = self.current.clone().unwrap_or(0);
|
||||
let mut items = self.items.clone().unwrap_or(vec![]);
|
||||
|
||||
@@ -205,13 +205,22 @@ impl ProfilesConfig {
|
||||
|
||||
items.remove(index);
|
||||
|
||||
let mut should_change = false;
|
||||
|
||||
if current == index {
|
||||
current = 0;
|
||||
should_change = true;
|
||||
} else if current > index {
|
||||
current = current - 1;
|
||||
}
|
||||
|
||||
self.current = Some(current);
|
||||
self.save_file()
|
||||
self.items = Some(items);
|
||||
|
||||
match self.save_file() {
|
||||
Ok(_) => Ok(should_change),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// activate current profile
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use crate::utils::{config, dirs, sysopt::SysProxyConfig};
|
||||
use crate::utils::{config, dirs, startup, sysopt::SysProxyConfig};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use tauri::api::path::resource_dir;
|
||||
|
||||
/// ### `verge.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
@@ -7,6 +9,10 @@ pub struct VergeConfig {
|
||||
/// `light` or `dark`
|
||||
pub theme_mode: Option<String>,
|
||||
|
||||
/// enable blur mode
|
||||
/// maybe be able to set the alpha
|
||||
pub theme_blur: Option<bool>,
|
||||
|
||||
/// can the app auto startup
|
||||
pub enable_self_startup: Option<bool>,
|
||||
|
||||
@@ -34,6 +40,7 @@ impl VergeConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Verge App abilities
|
||||
#[derive(Debug)]
|
||||
pub struct Verge {
|
||||
pub config: VergeConfig,
|
||||
@@ -41,6 +48,8 @@ pub struct Verge {
|
||||
pub old_sysproxy: Option<SysProxyConfig>,
|
||||
|
||||
pub cur_sysproxy: Option<SysProxyConfig>,
|
||||
|
||||
pub exe_path: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for Verge {
|
||||
@@ -55,6 +64,7 @@ impl Verge {
|
||||
config: VergeConfig::new(),
|
||||
old_sysproxy: None,
|
||||
cur_sysproxy: None,
|
||||
exe_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,4 +100,98 @@ impl Verge {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// set the exe_path
|
||||
pub fn set_exe_path(&mut self, package_info: &tauri::PackageInfo) {
|
||||
let exe = if cfg!(target_os = "windows") {
|
||||
"clash-verge.exe"
|
||||
} else {
|
||||
"clash-verge"
|
||||
};
|
||||
let path = resource_dir(package_info).unwrap().join(exe);
|
||||
self.exe_path = Some(path);
|
||||
}
|
||||
|
||||
/// sync the startup when run the app
|
||||
pub fn sync_startup(&self) -> Result<(), String> {
|
||||
let enable = self.config.enable_self_startup.clone().unwrap_or(false);
|
||||
|
||||
if !enable {
|
||||
return Ok(());
|
||||
}
|
||||
if self.exe_path.is_none() {
|
||||
return Err("should init the exe_path first".into());
|
||||
}
|
||||
|
||||
let exe_path = self.exe_path.clone().unwrap();
|
||||
match startup::get_startup(&exe_path) {
|
||||
Ok(sys_enable) => {
|
||||
if sys_enable || (!sys_enable && startup::set_startup(true, &exe_path).is_ok()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("failed to sync startup".into())
|
||||
}
|
||||
}
|
||||
Err(_) => Err("failed to get system startup info".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// update the startup
|
||||
fn update_startup(&mut self, enable: bool) -> Result<(), String> {
|
||||
let conf_enable = self.config.enable_self_startup.clone().unwrap_or(false);
|
||||
|
||||
if enable == conf_enable {
|
||||
return Ok(());
|
||||
}
|
||||
if self.exe_path.is_none() {
|
||||
return Err("should init the exe_path first".into());
|
||||
}
|
||||
let exe_path = self.exe_path.clone().unwrap();
|
||||
match startup::set_startup(enable, &exe_path) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(_) => Err("failed to set system startup info".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// patch verge config
|
||||
/// There should be only one update at a time here
|
||||
/// so call the save_file at the end is savely
|
||||
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<(), String> {
|
||||
// only change it
|
||||
if patch.theme_mode.is_some() {
|
||||
self.config.theme_mode = patch.theme_mode;
|
||||
}
|
||||
if patch.theme_blur.is_some() {
|
||||
self.config.theme_blur = patch.theme_blur;
|
||||
}
|
||||
|
||||
// should update system startup
|
||||
if patch.enable_self_startup.is_some() {
|
||||
let enable = patch.enable_self_startup.unwrap();
|
||||
self.update_startup(enable)?;
|
||||
self.config.enable_self_startup = Some(enable);
|
||||
}
|
||||
|
||||
// should update system proxy
|
||||
if patch.enable_system_proxy.is_some() {
|
||||
let enable = patch.enable_system_proxy.unwrap();
|
||||
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
|
||||
sysproxy.enable = enable;
|
||||
if sysproxy.set_sys().is_err() {
|
||||
log::error!("failed to set system proxy");
|
||||
return Err("failed to set system proxy".into());
|
||||
}
|
||||
self.cur_sysproxy = Some(sysproxy);
|
||||
}
|
||||
self.config.enable_system_proxy = Some(enable);
|
||||
}
|
||||
|
||||
// todo
|
||||
// should update system proxt too
|
||||
if patch.system_proxy_bypass.is_some() {
|
||||
self.config.system_proxy_bypass = patch.system_proxy_bypass;
|
||||
}
|
||||
|
||||
self.config.save_file()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,10 +22,10 @@ fn main() -> std::io::Result<()> {
|
||||
}
|
||||
|
||||
let menu = SystemTrayMenu::new()
|
||||
.add_item(CustomMenuItem::new("open_window", "显示应用"))
|
||||
.add_item(CustomMenuItem::new("restart_clash", "重启clash"))
|
||||
.add_item(CustomMenuItem::new("open_window", "Show"))
|
||||
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
|
||||
.add_native_item(SystemTrayMenuItem::Separator)
|
||||
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"));
|
||||
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
|
||||
|
||||
tauri::Builder::default()
|
||||
.manage(states::VergeState::default())
|
||||
@@ -42,9 +42,16 @@ fn main() -> std::io::Result<()> {
|
||||
}
|
||||
"restart_clash" => {
|
||||
let clash_state = app_handle.state::<states::ClashState>();
|
||||
let mut clash_arc = clash_state.0.lock().unwrap();
|
||||
if let Err(err) = clash_arc.restart_sidecar() {
|
||||
log::error!("{}", err);
|
||||
let mut clash = clash_state.0.lock().unwrap();
|
||||
match clash.restart_sidecar() {
|
||||
Ok(_) => {
|
||||
let profiles = app_handle.state::<states::ProfilesState>();
|
||||
let profiles = profiles.0.lock().unwrap();
|
||||
if let Err(err) = profiles.activate(clash.info.clone()) {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
Err(err) => log::error!("{}", err),
|
||||
}
|
||||
}
|
||||
"quit" => {
|
||||
@@ -62,14 +69,20 @@ fn main() -> std::io::Result<()> {
|
||||
_ => {}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
// common
|
||||
cmds::restart_sidecar,
|
||||
cmds::set_sys_proxy,
|
||||
cmds::get_sys_proxy,
|
||||
cmds::get_cur_proxy,
|
||||
cmds::win_drag,
|
||||
cmds::win_hide,
|
||||
cmds::win_mini,
|
||||
// clash
|
||||
cmds::get_clash_info,
|
||||
cmds::patch_clash_config,
|
||||
// verge
|
||||
cmds::get_verge_config,
|
||||
cmds::patch_verge_config,
|
||||
// profile
|
||||
cmds::import_profile,
|
||||
cmds::update_profile,
|
||||
cmds::delete_profile,
|
||||
@@ -86,10 +99,7 @@ fn main() -> std::io::Result<()> {
|
||||
api.prevent_close();
|
||||
app_handle.get_window(&label).unwrap().hide().unwrap();
|
||||
}
|
||||
tauri::Event::ExitRequested { api, .. } => {
|
||||
api.prevent_exit();
|
||||
}
|
||||
tauri::Event::Exit => {
|
||||
tauri::Event::ExitRequested { .. } => {
|
||||
resolve::resolve_reset(app_handle);
|
||||
api::process::kill_children();
|
||||
}
|
||||
|
||||
@@ -4,4 +4,5 @@ pub mod fetch;
|
||||
pub mod init;
|
||||
pub mod resolve;
|
||||
pub mod server;
|
||||
pub mod startup;
|
||||
pub mod sysopt;
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
use super::{init, server};
|
||||
use crate::{core::ProfilesConfig, states};
|
||||
use tauri::{App, AppHandle, Manager};
|
||||
use tauri_plugin_shadows::Shadows;
|
||||
|
||||
/// handle something when start app
|
||||
pub fn resolve_setup(app: &App) {
|
||||
// set shadow when window decorations
|
||||
let window = app.get_window("main").unwrap();
|
||||
window.set_shadow(true);
|
||||
|
||||
use tauri_plugin_vibrancy::Vibrancy;
|
||||
#[cfg(target_os = "windows")]
|
||||
window.apply_blur();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
use tauri_plugin_vibrancy::MacOSVibrancy;
|
||||
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
|
||||
}
|
||||
|
||||
// setup a simple http server for singleton
|
||||
server::embed_server(&app.handle());
|
||||
|
||||
@@ -28,13 +42,17 @@ pub fn resolve_setup(app: &App) {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
verge.set_exe_path(app.package_info());
|
||||
verge.init_sysproxy(clash.info.port.clone());
|
||||
if let Err(err) = verge.sync_startup() {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
}
|
||||
|
||||
/// reset system proxy
|
||||
pub fn resolve_reset(app_handle: &AppHandle) {
|
||||
let verge_state = app_handle.state::<states::VergeState>();
|
||||
let mut verge_arc = verge_state.0.lock().unwrap();
|
||||
let mut verge = verge_state.0.lock().unwrap();
|
||||
|
||||
verge_arc.reset_sysproxy();
|
||||
verge.reset_sysproxy();
|
||||
}
|
||||
|
||||
74
src-tauri/src/utils/startup.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use std::io;
|
||||
use std::path::PathBuf;
|
||||
|
||||
static APP_KEY: &str = "ClashVerge";
|
||||
|
||||
/// get the startup value
|
||||
/// whether as same as the exe_path
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn get_startup(exe_path: &PathBuf) -> io::Result<bool> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let cur_var = hkcu.open_subkey_with_flags(
|
||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
|
||||
KEY_READ,
|
||||
)?;
|
||||
|
||||
match cur_var.get_value::<String, _>(APP_KEY) {
|
||||
Ok(path) => {
|
||||
let exe_path = exe_path.clone();
|
||||
let exe_path = exe_path.as_os_str().to_str().unwrap();
|
||||
Ok(path == exe_path)
|
||||
}
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// set the startup on windows
|
||||
/// delete the reg key if disabled
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn set_startup(enable: bool, exe_path: &PathBuf) -> io::Result<()> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
let cur_var = hkcu.open_subkey_with_flags(
|
||||
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run",
|
||||
KEY_SET_VALUE,
|
||||
)?;
|
||||
|
||||
match enable {
|
||||
true => {
|
||||
let exe_path = exe_path.clone();
|
||||
let exe_path = exe_path.as_os_str().to_str().unwrap();
|
||||
cur_var.set_value::<&str, _>(APP_KEY, &exe_path)
|
||||
}
|
||||
false => cur_var.delete_value(APP_KEY),
|
||||
}
|
||||
}
|
||||
|
||||
/// todo
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn get_startup(exe_path: &PathBuf) -> io::Result<bool> {
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// todo
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_startup(enable: bool, exe_path: &PathBuf) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[test]
|
||||
fn test() {
|
||||
let path = PathBuf::from(r"D:\Software\Clash Verge\clash-verge.exe");
|
||||
|
||||
assert!(set_startup(true, &path).is_ok());
|
||||
assert_eq!(get_startup(&path).unwrap(), true);
|
||||
|
||||
assert!(set_startup(false, &path).is_ok());
|
||||
assert_eq!(get_startup(&path).unwrap(), false);
|
||||
}
|
||||
156
src-tauri/src/utils/sysopt.rs
Normal file → Executable file
@@ -1,7 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::io;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
|
||||
#[cfg(target_os = "macos")]
|
||||
static DEFAULT_BYPASS: &str =
|
||||
"192.168.0.0/16\n10.0.0.0/8\n172.16.0.0/12\n127.0.0.1\nlocalhost\n*.local\ntimestamp.apple.com\n";
|
||||
#[cfg(target_os = "macos")]
|
||||
static MACOS_SERVICE: &str = "Wi-Fi";
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize, Clone)]
|
||||
pub struct SysProxyConfig {
|
||||
@@ -29,8 +35,8 @@ impl SysProxyConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the windows system proxy config
|
||||
#[cfg(target_os = "windows")]
|
||||
/// Get the windows system proxy config
|
||||
pub fn get_sys() -> io::Result<Self> {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
@@ -48,6 +54,43 @@ impl SysProxyConfig {
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
/// Get the macos system proxy config
|
||||
pub fn get_sys() -> io::Result<Self> {
|
||||
use std::process::Command;
|
||||
|
||||
let http = macproxy::get_proxy(&["-getwebproxy", MACOS_SERVICE])?;
|
||||
let https = macproxy::get_proxy(&["-getsecurewebproxy", MACOS_SERVICE])?;
|
||||
let sock = macproxy::get_proxy(&["-getsocksfirewallproxy", MACOS_SERVICE])?;
|
||||
|
||||
let mut enable = false;
|
||||
let mut server = "".into();
|
||||
|
||||
if sock.0 == "Yes" {
|
||||
enable = true;
|
||||
server = sock.1;
|
||||
}
|
||||
if https.0 == "Yes" {
|
||||
enable = true;
|
||||
server = https.1;
|
||||
}
|
||||
if http.0 == "Yes" || !enable {
|
||||
enable = http.0 == "Yes";
|
||||
server = http.1;
|
||||
}
|
||||
|
||||
let bypass_output = Command::new("networksetup")
|
||||
.args(["-getproxybypassdomains", MACOS_SERVICE])
|
||||
.output()?;
|
||||
let bypass = std::str::from_utf8(&bypass_output.stdout).unwrap_or(DEFAULT_BYPASS);
|
||||
|
||||
Ok(SysProxyConfig {
|
||||
enable,
|
||||
server,
|
||||
bypass: bypass.into(),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
/// Set the windows system proxy config
|
||||
pub fn set_sys(&self) -> io::Result<()> {
|
||||
@@ -65,21 +108,104 @@ impl SysProxyConfig {
|
||||
cur_var.set_value("ProxyServer", &self.server)?;
|
||||
cur_var.set_value("ProxyOverride", &self.bypass)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
/// Set the macos system proxy config
|
||||
pub fn set_sys(&self) -> io::Result<()> {
|
||||
let enable = self.enable;
|
||||
let server = self.server.as_str();
|
||||
macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?;
|
||||
macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?;
|
||||
macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server)
|
||||
}
|
||||
}
|
||||
|
||||
// #[cfg(target_os = "macos")]
|
||||
// mod macos {
|
||||
// use super::*;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macproxy {
|
||||
use super::*;
|
||||
use std::process::Command;
|
||||
|
||||
// pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
|
||||
// Ok(SysProxyConfig {
|
||||
// enable: false,
|
||||
// server: "server".into(),
|
||||
// bypass: "bypass".into(),
|
||||
// })
|
||||
// }
|
||||
/// use networksetup
|
||||
/// get the target proxy config
|
||||
pub(super) fn get_proxy(args: &[&str; 2]) -> io::Result<(String, String)> {
|
||||
let output = Command::new("networksetup").args(args).output()?;
|
||||
match std::str::from_utf8(&output.stdout) {
|
||||
Ok(stdout) => {
|
||||
let enable = parse(stdout, "Enabled:");
|
||||
let server = parse(stdout, "Server:");
|
||||
let port = parse(stdout, "Port:");
|
||||
let server = format!("{}:{}", server, port);
|
||||
Ok((enable.into(), server))
|
||||
}
|
||||
Err(_) => Err(io::Error::from_raw_os_error(1)),
|
||||
}
|
||||
}
|
||||
|
||||
// pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
|
||||
// Ok(())
|
||||
// }
|
||||
// }
|
||||
/// use networksetup
|
||||
/// set the target proxy config
|
||||
pub(super) fn set_proxy(
|
||||
target: &str, // like: -setwebproxy
|
||||
device: &str,
|
||||
enable: bool,
|
||||
server: &str,
|
||||
) -> io::Result<()> {
|
||||
let mut split = server.split(":");
|
||||
let domain = split.next();
|
||||
let port = split.next();
|
||||
|
||||
// can not parse the field
|
||||
if domain.is_none() || port.is_none() {
|
||||
return Err(io::Error::from_raw_os_error(1));
|
||||
}
|
||||
|
||||
let args = vec![target, device, domain.unwrap(), port.unwrap()];
|
||||
Command::new("networksetup").args(&args).status()?;
|
||||
|
||||
let target_state = String::from(target) + "state";
|
||||
let enable = if enable { "on" } else { "off" };
|
||||
let args = vec![target_state.as_str(), device, enable];
|
||||
Command::new("networksetup").args(&args).status()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// parse the networksetup output
|
||||
pub(super) fn parse<'a>(target: &'a str, key: &'a str) -> &'a str {
|
||||
match target.find(key) {
|
||||
Some(idx) => {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
let value = match value.find("\n") {
|
||||
Some(end) => &value[..end],
|
||||
None => value,
|
||||
};
|
||||
value.trim()
|
||||
}
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_get() {
|
||||
use std::process::Command;
|
||||
|
||||
let output = Command::new("networksetup")
|
||||
.args(["-getwebproxy", "Wi-Fi"])
|
||||
.output();
|
||||
|
||||
let output = output.unwrap();
|
||||
let stdout = std::str::from_utf8(&output.stdout).unwrap();
|
||||
let enable = parse(stdout, "Enabled:");
|
||||
let server = parse(stdout, "Server:");
|
||||
let port = parse(stdout, "Port:");
|
||||
|
||||
println!("enable: {}, server: {}, port: {}", enable, server, port);
|
||||
|
||||
dbg!(SysProxyConfig::get_sys().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set() {
|
||||
let sysproxy = SysProxyConfig::new(true, "7890".into(), None);
|
||||
dbg!(sysproxy.set_sys().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"package": {
|
||||
"productName": "clash-verge",
|
||||
"version": "0.0.5"
|
||||
"version": "0.0.10"
|
||||
},
|
||||
"build": {
|
||||
"distDir": "../dist",
|
||||
"devPath": "http://localhost:3000/proxy",
|
||||
"devPath": "http://localhost:3000/",
|
||||
"beforeDevCommand": "yarn run web:dev",
|
||||
"beforeBuildCommand": "yarn run web:build"
|
||||
},
|
||||
@@ -50,7 +50,11 @@
|
||||
}
|
||||
},
|
||||
"updater": {
|
||||
"active": false
|
||||
"active": true,
|
||||
"endpoints": [
|
||||
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
|
||||
],
|
||||
"dialog": false
|
||||
},
|
||||
"allowlist": {
|
||||
"all": true
|
||||
@@ -62,8 +66,8 @@
|
||||
"height": 600,
|
||||
"resizable": true,
|
||||
"fullscreen": false,
|
||||
"decorations": true,
|
||||
"transparent": false,
|
||||
"decorations": false,
|
||||
"transparent": true,
|
||||
"minWidth": 600,
|
||||
"minHeight": 520
|
||||
}
|
||||
|
||||
@@ -1,46 +1,80 @@
|
||||
.layout {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
|
||||
&__sidebar {
|
||||
position: relative;
|
||||
&__left {
|
||||
flex: 1 0 25%;
|
||||
height: 100vh;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
max-width: 225px;
|
||||
min-width: 125px;
|
||||
overflow: hidden auto;
|
||||
padding: 8px 0;
|
||||
flex-direction: column;
|
||||
box-sizing: border-box;
|
||||
user-select: none;
|
||||
overflow: hidden;
|
||||
|
||||
.the-logo {
|
||||
position: relative;
|
||||
flex: 0 1 180px;
|
||||
width: 100%;
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
margin: 0 auto;
|
||||
padding: 0 8px;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
|
||||
.the-newbtn {
|
||||
position: absolute;
|
||||
right: 20px;
|
||||
bottom: 12px;
|
||||
transform: scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
.the-menu {
|
||||
flex: 1 1 75%;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.the-traffic {
|
||||
flex: 0 0 60px;
|
||||
|
||||
> div {
|
||||
margin: 0 auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&__content {
|
||||
&__right {
|
||||
position: relative;
|
||||
flex: 1 1 75%;
|
||||
height: 100vh;
|
||||
overflow: auto;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 2px 0;
|
||||
box-sizing: border-box;
|
||||
scrollbar-gutter: "stable";
|
||||
}
|
||||
|
||||
&__logo {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
margin: 0 auto;
|
||||
padding: 8px 8px 0;
|
||||
user-select: none;
|
||||
text-align: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
.the-bar {
|
||||
flex: 0 0 30px;
|
||||
width: 100%;
|
||||
height: 30px;
|
||||
padding: 0 16px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
&__traffic {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 8px;
|
||||
|
||||
> div {
|
||||
margin: 0 auto;
|
||||
.the-content {
|
||||
flex: 1 1 100%;
|
||||
overflow: auto;
|
||||
box-sizing: border-box;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,13 +8,15 @@ import {
|
||||
LinearProgress,
|
||||
IconButton,
|
||||
keyframes,
|
||||
MenuItem,
|
||||
Menu,
|
||||
} from "@mui/material";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { RefreshRounded } from "@mui/icons-material";
|
||||
import { CmdType } from "../services/types";
|
||||
import { updateProfile, deleteProfile } from "../services/cmds";
|
||||
import parseTraffic from "../utils/parse-traffic";
|
||||
import relativeTime from "dayjs/plugin/relativeTime";
|
||||
import { updateProfile } from "../services/cmds";
|
||||
|
||||
dayjs.extend(relativeTime);
|
||||
|
||||
@@ -46,6 +48,8 @@ const ProfileItemComp: React.FC<Props> = (props) => {
|
||||
|
||||
const { mutate } = useSWRConfig();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [anchorEl, setAnchorEl] = useState<any>(null);
|
||||
const [position, setPosition] = useState({ left: 0, top: 0 });
|
||||
|
||||
const { name = "Profile", extra, updated = 0 } = itemData;
|
||||
const { upload = 0, download = 0, total = 0 } = extra ?? {};
|
||||
@@ -55,6 +59,7 @@ const ProfileItemComp: React.FC<Props> = (props) => {
|
||||
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
|
||||
|
||||
const onUpdate = async () => {
|
||||
setAnchorEl(null);
|
||||
if (loading) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
@@ -67,98 +72,135 @@ const ProfileItemComp: React.FC<Props> = (props) => {
|
||||
}
|
||||
};
|
||||
|
||||
const onDelete = async () => {
|
||||
setAnchorEl(null);
|
||||
try {
|
||||
await deleteProfile(index);
|
||||
mutate("getProfiles");
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleContextMenu = (
|
||||
event: React.MouseEvent<HTMLDivElement, MouseEvent>
|
||||
) => {
|
||||
const { clientX, clientY } = event;
|
||||
setPosition({ top: clientY, left: clientX });
|
||||
setAnchorEl(event.currentTarget);
|
||||
event.preventDefault();
|
||||
};
|
||||
|
||||
return (
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
const { mode, primary, text, grey } = palette;
|
||||
const isDark = mode === "dark";
|
||||
<>
|
||||
<Wrapper
|
||||
sx={({ palette }) => {
|
||||
const { mode, primary, text, grey } = palette;
|
||||
const key = `${mode}-${selected}`;
|
||||
|
||||
if (selected) {
|
||||
const bgcolor = isDark
|
||||
? alpha(primary.main, 0.35)
|
||||
: alpha(primary.main, 0.15);
|
||||
const bgcolor = {
|
||||
"light-true": alpha(primary.main, 0.15),
|
||||
"light-false": palette.background.paper,
|
||||
"dark-true": alpha(primary.main, 0.35),
|
||||
"dark-false": alpha(grey[700], 0.35),
|
||||
}[key]!;
|
||||
|
||||
return {
|
||||
bgcolor,
|
||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
||||
"& h2": {
|
||||
color: isDark ? primary.light : primary.main,
|
||||
},
|
||||
};
|
||||
}
|
||||
const bgcolor = isDark
|
||||
? alpha(grey[700], 0.35)
|
||||
: palette.background.paper;
|
||||
return {
|
||||
bgcolor,
|
||||
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
|
||||
"& h2": {
|
||||
color: isDark ? text.primary : text.primary,
|
||||
},
|
||||
};
|
||||
}}
|
||||
onClick={onClick}
|
||||
>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography
|
||||
width="calc(100% - 40px)"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
noWrap
|
||||
title={name}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
const color = {
|
||||
"light-true": text.secondary,
|
||||
"light-false": text.secondary,
|
||||
"dark-true": alpha(text.secondary, 0.6),
|
||||
"dark-false": alpha(text.secondary, 0.6),
|
||||
}[key]!;
|
||||
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdate();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
const h2color = {
|
||||
"light-true": primary.main,
|
||||
"light-false": text.primary,
|
||||
"dark-true": primary.light,
|
||||
"dark-false": text.primary,
|
||||
}[key]!;
|
||||
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
my: 0.5,
|
||||
fontSize: 14,
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
return { bgcolor, color, "& h2": { color: h2color } };
|
||||
}}
|
||||
onClick={onClick}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
<Box display="flex" justifyContent="space-between">
|
||||
<Typography
|
||||
width="calc(100% - 40px)"
|
||||
variant="h6"
|
||||
component="h2"
|
||||
noWrap
|
||||
title={name}
|
||||
>
|
||||
{name}
|
||||
</Typography>
|
||||
|
||||
<LinearProgress variant="determinate" value={progress} color="inherit" />
|
||||
</Wrapper>
|
||||
<IconButton
|
||||
sx={{
|
||||
width: 30,
|
||||
height: 30,
|
||||
animation: loading ? `1s linear infinite ${round}` : "none",
|
||||
}}
|
||||
color="inherit"
|
||||
disabled={loading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onUpdate();
|
||||
}}
|
||||
>
|
||||
<RefreshRounded />
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Box display="flex" justifyContent="space-between" alignItems="center">
|
||||
<Typography noWrap title={`From: ${from}`}>
|
||||
{from}
|
||||
</Typography>
|
||||
|
||||
<Typography
|
||||
noWrap
|
||||
flex="1 0 auto"
|
||||
fontSize={14}
|
||||
textAlign="right"
|
||||
title="updated time"
|
||||
>
|
||||
{fromnow}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
my: 0.5,
|
||||
fontSize: 14,
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<span title="used / total">
|
||||
{parseTraffic(upload + download)} / {parseTraffic(total)}
|
||||
</span>
|
||||
<span title="expire time">{expire}</span>
|
||||
</Box>
|
||||
|
||||
<LinearProgress
|
||||
variant="determinate"
|
||||
value={progress}
|
||||
color="inherit"
|
||||
/>
|
||||
</Wrapper>
|
||||
|
||||
<Menu
|
||||
open={!!anchorEl}
|
||||
anchorEl={anchorEl}
|
||||
onClose={() => setAnchorEl(null)}
|
||||
anchorPosition={position}
|
||||
anchorReference="anchorPosition"
|
||||
>
|
||||
<MenuItem onClick={onUpdate}>Update</MenuItem>
|
||||
<MenuItem onClick={onDelete}>Delete</MenuItem>
|
||||
{/* <MenuItem>Update(proxy)</MenuItem> */}
|
||||
</Menu>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { useState } from "react";
|
||||
import { Virtuoso } from "react-virtuoso";
|
||||
import {
|
||||
alpha,
|
||||
Box,
|
||||
Collapse,
|
||||
Divider,
|
||||
IconButton,
|
||||
List,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
@@ -18,53 +15,11 @@ import {
|
||||
ExpandMoreRounded,
|
||||
MyLocationRounded,
|
||||
NetworkCheckRounded,
|
||||
CheckCircleOutlineRounded,
|
||||
} from "@mui/icons-material";
|
||||
import { updateProxy } from "../services/api";
|
||||
import { ApiType } from "../services/types";
|
||||
import { getProfiles, patchProfile } from "../services/cmds";
|
||||
|
||||
interface ItemProps {
|
||||
proxy: ApiType.ProxyItem;
|
||||
selected: boolean;
|
||||
onClick?: (name: string) => void;
|
||||
}
|
||||
|
||||
const Item = ({ proxy, selected, onClick }: ItemProps) => {
|
||||
return (
|
||||
<ListItem sx={{ py: 0, pl: 4 }}>
|
||||
<ListItemButton
|
||||
dense
|
||||
selected={selected}
|
||||
onClick={() => onClick?.(proxy.name)}
|
||||
sx={[
|
||||
{
|
||||
borderRadius: 1,
|
||||
},
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor =
|
||||
mode === "light"
|
||||
? alpha(primary.main, 0.15)
|
||||
: alpha(primary.main, 0.35);
|
||||
const color = mode === "light" ? primary.main : primary.light;
|
||||
|
||||
return {
|
||||
"&.Mui-selected": { bgcolor },
|
||||
"&.Mui-selected .MuiListItemText-secondary": { color },
|
||||
};
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText title={proxy.name} secondary={proxy.name} />
|
||||
<ListItemIcon
|
||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
||||
>
|
||||
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
|
||||
</ListItemIcon>
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
import ProxyItem from "./proxy-item";
|
||||
|
||||
interface Props {
|
||||
group: ApiType.ProxyGroupItem;
|
||||
@@ -146,9 +101,10 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
style={{ height: "400px", marginBottom: "4px" }}
|
||||
totalCount={proxies.length}
|
||||
itemContent={(index) => (
|
||||
<Item
|
||||
<ProxyItem
|
||||
proxy={proxies[index]}
|
||||
selected={proxies[index].name === now}
|
||||
sx={{ py: 0, pl: 4 }}
|
||||
onClick={onUpdate}
|
||||
/>
|
||||
)}
|
||||
@@ -160,10 +116,11 @@ const ProxyGroup = ({ group }: Props) => {
|
||||
sx={{ maxHeight: "400px", overflow: "auto", mb: "4px" }}
|
||||
>
|
||||
{proxies.map((proxy) => (
|
||||
<Item
|
||||
<ProxyItem
|
||||
key={proxy.name}
|
||||
proxy={proxy}
|
||||
selected={proxy.name === now}
|
||||
sx={{ py: 0, pl: 4 }}
|
||||
onClick={onUpdate}
|
||||
/>
|
||||
))}
|
||||
|
||||
58
src/components/proxy-item.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import { CheckCircleOutlineRounded } from "@mui/icons-material";
|
||||
import {
|
||||
alpha,
|
||||
ListItem,
|
||||
ListItemButton,
|
||||
ListItemIcon,
|
||||
ListItemText,
|
||||
SxProps,
|
||||
Theme,
|
||||
} from "@mui/material";
|
||||
import { ApiType } from "../services/types";
|
||||
|
||||
interface Props {
|
||||
proxy: ApiType.ProxyItem;
|
||||
selected: boolean;
|
||||
sx?: SxProps<Theme>;
|
||||
onClick?: (name: string) => void;
|
||||
}
|
||||
|
||||
const ProxyItem = (props: Props) => {
|
||||
const { proxy, selected, sx, onClick } = props;
|
||||
|
||||
return (
|
||||
<ListItem sx={sx}>
|
||||
<ListItemButton
|
||||
dense
|
||||
selected={selected}
|
||||
onClick={() => onClick?.(proxy.name)}
|
||||
sx={[
|
||||
{
|
||||
borderRadius: 1,
|
||||
},
|
||||
({ palette: { mode, primary } }) => {
|
||||
const bgcolor =
|
||||
mode === "light"
|
||||
? alpha(primary.main, 0.15)
|
||||
: alpha(primary.main, 0.35);
|
||||
const color = mode === "light" ? primary.main : primary.light;
|
||||
|
||||
return {
|
||||
"&.Mui-selected": { bgcolor },
|
||||
"&.Mui-selected .MuiListItemText-secondary": { color },
|
||||
};
|
||||
},
|
||||
]}
|
||||
>
|
||||
<ListItemText title={proxy.name} secondary={proxy.name} />
|
||||
<ListItemIcon
|
||||
sx={{ justifyContent: "flex-end", color: "primary.main" }}
|
||||
>
|
||||
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
|
||||
</ListItemIcon>
|
||||
</ListItemButton>
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProxyItem;
|
||||
@@ -43,11 +43,11 @@ const SettingClash = ({ onError }: Props) => {
|
||||
return (
|
||||
<List>
|
||||
<ListSubheader sx={{ background: "transparent" }}>
|
||||
Clash设置
|
||||
Clash Setting
|
||||
</ListSubheader>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="局域网连接" />
|
||||
<ListItemText primary="Allow Lan" />
|
||||
<GuardState
|
||||
value={allowLan}
|
||||
valueProps="checked"
|
||||
@@ -75,7 +75,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="日志等级" />
|
||||
<ListItemText primary="Log Level" />
|
||||
<GuardState
|
||||
value={logLevel}
|
||||
onCatch={onError}
|
||||
@@ -94,7 +94,7 @@ const SettingClash = ({ onError }: Props) => {
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="混合代理端口" />
|
||||
<ListItemText primary="Mixed Port" />
|
||||
<TextField
|
||||
size="small"
|
||||
value={mixedPort!}
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import {
|
||||
Box,
|
||||
List,
|
||||
ListItemText,
|
||||
ListSubheader,
|
||||
Switch,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import {
|
||||
getVergeConfig,
|
||||
patchVergeConfig,
|
||||
setSysProxy,
|
||||
} from "../services/cmds";
|
||||
import { getVergeConfig, patchVergeConfig } from "../services/cmds";
|
||||
import { CmdType } from "../services/types";
|
||||
import { version } from "../../package.json";
|
||||
import GuardState from "./guard-state";
|
||||
import SettingItem from "./setting-item";
|
||||
import PaletteSwitch from "./palette-switch";
|
||||
import { version } from "../../package.json";
|
||||
import SysproxyTooltip from "./sysproxy-tooltip";
|
||||
|
||||
interface Props {
|
||||
onError?: (err: Error) => void;
|
||||
@@ -27,64 +25,82 @@ const SettingVerge = ({ onError }: Props) => {
|
||||
|
||||
const {
|
||||
theme_mode: mode = "light",
|
||||
theme_blur: blur = false,
|
||||
enable_self_startup: startup = false,
|
||||
enable_system_proxy: proxy = false,
|
||||
} = vergeConfig ?? {};
|
||||
|
||||
const onSwitchFormat = (_e: any, value: boolean) => value;
|
||||
|
||||
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
|
||||
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
|
||||
};
|
||||
|
||||
return (
|
||||
<List>
|
||||
<ListSubheader sx={{ background: "transparent" }}>通用设置</ListSubheader>
|
||||
<ListSubheader sx={{ background: "transparent" }}>
|
||||
Common Setting
|
||||
</ListSubheader>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="外观主题" />
|
||||
<ListItemText primary="Theme Mode" />
|
||||
<GuardState
|
||||
value={mode === "dark"}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
|
||||
onGuard={async (c) => {
|
||||
await patchVergeConfig({ theme_mode: c ? "dark" : "light" });
|
||||
}}
|
||||
onGuard={(c) =>
|
||||
patchVergeConfig({ theme_mode: c ? "dark" : "light" })
|
||||
}
|
||||
>
|
||||
<PaletteSwitch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="开机自启" />
|
||||
<ListItemText primary="Theme Blur" />
|
||||
<GuardState
|
||||
value={startup}
|
||||
value={blur}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_self_startup: e })}
|
||||
onGuard={async (e) => {
|
||||
await patchVergeConfig({ enable_self_startup: e });
|
||||
}}
|
||||
onChange={(e) => onChangeData({ theme_blur: e })}
|
||||
onGuard={(e) => patchVergeConfig({ theme_blur: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText primary="设置系统代理" />
|
||||
<ListItemText primary="Self Startup" />
|
||||
<GuardState
|
||||
value={startup}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_self_startup: e })}
|
||||
onGuard={(e) => patchVergeConfig({ enable_self_startup: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
</SettingItem>
|
||||
|
||||
<SettingItem>
|
||||
<ListItemText
|
||||
primary={
|
||||
<Box sx={{ display: "flex", alignItems: "center" }}>
|
||||
System Proxy
|
||||
<SysproxyTooltip />
|
||||
</Box>
|
||||
}
|
||||
/>
|
||||
<GuardState
|
||||
value={proxy}
|
||||
valueProps="checked"
|
||||
onCatch={onError}
|
||||
onFormat={onSwitchFormat}
|
||||
onChange={(e) => onChangeData({ enable_system_proxy: e })}
|
||||
onGuard={async (e) => {
|
||||
await setSysProxy(e);
|
||||
await patchVergeConfig({ enable_system_proxy: e });
|
||||
}}
|
||||
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })}
|
||||
>
|
||||
<Switch edge="end" />
|
||||
</GuardState>
|
||||
|
||||
53
src/components/sysproxy-tooltip.tsx
Normal file
@@ -0,0 +1,53 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { InfoRounded } from "@mui/icons-material";
|
||||
import { ClickAwayListener, Tooltip } from "@mui/material";
|
||||
import { getSystemProxy } from "../services/cmds";
|
||||
|
||||
const SysproxyTooltip = () => {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [info, setInfo] = useState<any>({});
|
||||
|
||||
const onShow = async () => {
|
||||
const data = await getSystemProxy();
|
||||
console.log(data);
|
||||
setInfo(data ?? {});
|
||||
setOpen(true);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const timer = setTimeout(() => setOpen(false), 2000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [open]);
|
||||
|
||||
// todo: add error info
|
||||
const showTitle = (
|
||||
<div>
|
||||
<div>Enable: {(!!info.enable).toString()}</div>
|
||||
<div>Server: {info.server}</div>
|
||||
<div>Bypass: {info.bypass}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<ClickAwayListener onClickAway={() => setOpen(false)}>
|
||||
<Tooltip
|
||||
PopperProps={{
|
||||
disablePortal: true,
|
||||
}}
|
||||
onClose={() => setOpen(false)}
|
||||
open={open}
|
||||
disableFocusListener
|
||||
disableHoverListener
|
||||
disableTouchListener
|
||||
placement="top"
|
||||
title={showTitle}
|
||||
arrow
|
||||
>
|
||||
<InfoRounded fontSize="small" onClick={onShow} />
|
||||
</Tooltip>
|
||||
</ClickAwayListener>
|
||||
);
|
||||
};
|
||||
|
||||
export default SysproxyTooltip;
|
||||
66
src/components/update-dialog.tsx
Normal file
@@ -0,0 +1,66 @@
|
||||
import useSWR from "swr";
|
||||
import { useState } from "react";
|
||||
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
|
||||
import { relaunch } from "@tauri-apps/api/process";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogActions,
|
||||
DialogContent,
|
||||
DialogContentText,
|
||||
DialogTitle,
|
||||
} from "@mui/material";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
let uploadingState = false;
|
||||
|
||||
const UpdateDialog = (props: Props) => {
|
||||
const { open, onClose } = props;
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
});
|
||||
const [uploading, setUploading] = useState(uploadingState);
|
||||
|
||||
const onUpdate = async () => {
|
||||
try {
|
||||
setUploading(true);
|
||||
uploadingState = true;
|
||||
await installUpdate();
|
||||
await relaunch();
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
window.alert("Failed to upload, please try again.");
|
||||
} finally {
|
||||
setUploading(true);
|
||||
uploadingState = true;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose}>
|
||||
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
|
||||
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
|
||||
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>Cancel</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
autoFocus
|
||||
onClick={onUpdate}
|
||||
disabled={uploading}
|
||||
>
|
||||
Update
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default UpdateDialog;
|
||||
@@ -1,85 +1,97 @@
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import useSWR, { SWRConfig } from "swr";
|
||||
import { Route, Routes } from "react-router-dom";
|
||||
import { useRecoilState } from "recoil";
|
||||
import { createTheme, List, Paper, ThemeProvider } from "@mui/material";
|
||||
import { atomPaletteMode } from "../states/setting";
|
||||
import { getVergeConfig } from "../services/cmds";
|
||||
import {
|
||||
alpha,
|
||||
Button,
|
||||
createTheme,
|
||||
IconButton,
|
||||
List,
|
||||
Paper,
|
||||
ThemeProvider,
|
||||
} from "@mui/material";
|
||||
import { HorizontalRuleRounded, CloseRounded } from "@mui/icons-material";
|
||||
import { checkUpdate } from "@tauri-apps/api/updater";
|
||||
import { atomPaletteMode, atomThemeBlur } from "../states/setting";
|
||||
import { getVergeConfig, windowDrag, windowHide } from "../services/cmds";
|
||||
import LogoSvg from "../assets/image/logo.svg";
|
||||
import LogPage from "./log";
|
||||
import HomePage from "./home";
|
||||
import ProfilePage from "./profile";
|
||||
import ProxyPage from "./proxy";
|
||||
import SettingPage from "./setting";
|
||||
import ConnectionsPage from "./connections";
|
||||
import LayoutItem from "../components/layout-item";
|
||||
import Traffic from "../components/traffic";
|
||||
import UpdateDialog from "../components/update-dialog";
|
||||
|
||||
const routers = [
|
||||
{
|
||||
label: "代理",
|
||||
link: "/proxy",
|
||||
label: "Proxy",
|
||||
link: "/",
|
||||
ele: ProxyPage,
|
||||
},
|
||||
{
|
||||
label: "配置",
|
||||
label: "Profile",
|
||||
link: "/profile",
|
||||
ele: ProfilePage,
|
||||
},
|
||||
{
|
||||
label: "连接",
|
||||
label: "Connections",
|
||||
link: "/connections",
|
||||
ele: ConnectionsPage,
|
||||
},
|
||||
{
|
||||
label: "日志",
|
||||
label: "Log",
|
||||
link: "/log",
|
||||
ele: LogPage,
|
||||
},
|
||||
{
|
||||
label: "设置",
|
||||
label: "Setting",
|
||||
link: "/setting",
|
||||
ele: SettingPage,
|
||||
},
|
||||
];
|
||||
|
||||
const Layout = () => {
|
||||
const [mode, setMode] = useRecoilState(atomPaletteMode);
|
||||
const [blur, setBlur] = useRecoilState(atomThemeBlur);
|
||||
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
|
||||
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
});
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMode(vergeConfig?.theme_mode ?? "light");
|
||||
}, [vergeConfig?.theme_mode]);
|
||||
window.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape") windowHide();
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!vergeConfig) return;
|
||||
setBlur(!!vergeConfig.theme_blur);
|
||||
setMode(vergeConfig.theme_mode ?? "light");
|
||||
}, [vergeConfig]);
|
||||
|
||||
const theme = useMemo(() => {
|
||||
if (mode === "light") {
|
||||
document.documentElement.style.background = "#f5f5f5";
|
||||
document.documentElement.style.setProperty(
|
||||
"--selection-color",
|
||||
"#f5f5f5"
|
||||
);
|
||||
} else {
|
||||
document.documentElement.style.background = "#000";
|
||||
document.documentElement.style.setProperty(
|
||||
"--selection-color",
|
||||
"#d5d5d5"
|
||||
);
|
||||
}
|
||||
// const background = mode === "light" ? "#f5f5f5" : "#000";
|
||||
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
|
||||
|
||||
const rootEle = document.documentElement;
|
||||
rootEle.style.background = "transparent";
|
||||
rootEle.style.setProperty("--selection-color", selectColor);
|
||||
|
||||
return createTheme({
|
||||
breakpoints: {
|
||||
values: {
|
||||
xs: 0,
|
||||
sm: 650,
|
||||
md: 900,
|
||||
lg: 1200,
|
||||
xl: 1536,
|
||||
},
|
||||
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
|
||||
},
|
||||
palette: {
|
||||
mode,
|
||||
primary: {
|
||||
main: "#5b5c9d",
|
||||
},
|
||||
text: {
|
||||
primary: "#637381",
|
||||
secondary: "#909399",
|
||||
},
|
||||
primary: { main: "#5b5c9d" },
|
||||
text: { primary: "#637381", secondary: "#909399" },
|
||||
},
|
||||
});
|
||||
}, [mode]);
|
||||
@@ -87,13 +99,42 @@ const Layout = () => {
|
||||
return (
|
||||
<SWRConfig value={{}}>
|
||||
<ThemeProvider theme={theme}>
|
||||
<Paper square elevation={0} className="layout">
|
||||
<div className="layout__sidebar">
|
||||
<div className="layout__logo">
|
||||
<img src={LogoSvg} width="100%" alt="" />
|
||||
<Paper
|
||||
square
|
||||
elevation={0}
|
||||
className="layout"
|
||||
sx={[
|
||||
(theme) => ({
|
||||
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
|
||||
}),
|
||||
]}
|
||||
>
|
||||
<div className="layout__left">
|
||||
<div className="the-logo">
|
||||
<img
|
||||
src={LogoSvg}
|
||||
width="100%"
|
||||
alt=""
|
||||
onPointerDown={(e) => {
|
||||
windowDrag();
|
||||
e.preventDefault();
|
||||
}}
|
||||
/>
|
||||
|
||||
{updateInfo?.shouldUpdate && (
|
||||
<Button
|
||||
color="error"
|
||||
variant="contained"
|
||||
size="small"
|
||||
className="the-newbtn"
|
||||
onClick={() => setDialogOpen(true)}
|
||||
>
|
||||
New
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<List sx={{ userSelect: "none" }}>
|
||||
<List className="the-menu">
|
||||
{routers.map((router) => (
|
||||
<LayoutItem key={router.label} to={router.link}>
|
||||
{router.label}
|
||||
@@ -101,22 +142,38 @@ const Layout = () => {
|
||||
))}
|
||||
</List>
|
||||
|
||||
<div className="layout__traffic">
|
||||
<div className="the-traffic">
|
||||
<Traffic />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="layout__content">
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/proxy" element={<ProxyPage />} />
|
||||
<Route path="/profile" element={<ProfilePage />} />
|
||||
<Route path="/log" element={<LogPage />} />
|
||||
<Route path="/connections" element={<ConnectionsPage />} />
|
||||
<Route path="/setting" element={<SettingPage />} />
|
||||
</Routes>
|
||||
<div className="layout__right">
|
||||
<div
|
||||
className="the-bar"
|
||||
onPointerDown={(e) =>
|
||||
e.target === e.currentTarget && windowDrag()
|
||||
}
|
||||
>
|
||||
{/* todo: onClick = windowMini */}
|
||||
<IconButton size="small" sx={{ mx: 1 }} onClick={windowHide}>
|
||||
<HorizontalRuleRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
|
||||
<IconButton size="small" onClick={windowHide}>
|
||||
<CloseRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
<div className="the-content">
|
||||
<Routes>
|
||||
{routers.map(({ label, link, ele: Ele }) => (
|
||||
<Route key={label} path={link} element={<Ele />} />
|
||||
))}
|
||||
</Routes>
|
||||
</div>
|
||||
</div>
|
||||
</Paper>
|
||||
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
|
||||
</ThemeProvider>
|
||||
</SWRConfig>
|
||||
);
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { Typography } from "@mui/material";
|
||||
|
||||
const HomePage = () => {
|
||||
return (
|
||||
<Typography variant="h1" textAlign="center" mt={10}>
|
||||
Hello Clash!
|
||||
</Typography>
|
||||
);
|
||||
};
|
||||
|
||||
export default HomePage;
|
||||
@@ -24,16 +24,20 @@ const ProfilePage = () => {
|
||||
if (profiles.current == null) return;
|
||||
if (!profiles.items) profiles.items = [];
|
||||
|
||||
const profile = profiles.items![profiles.current];
|
||||
const current = profiles.current;
|
||||
const profile = profiles.items![current];
|
||||
if (!profile) return;
|
||||
|
||||
getProxies().then((proxiesData) => {
|
||||
setTimeout(async () => {
|
||||
const proxiesData = await getProxies();
|
||||
mutate("getProxies", proxiesData);
|
||||
|
||||
// init selected array
|
||||
const { selected = [] } = profile;
|
||||
const selectedMap = Object.fromEntries(
|
||||
selected.map((each) => [each.name!, each.now!])
|
||||
);
|
||||
|
||||
// todo: enhance error handle
|
||||
let hasChange = false;
|
||||
proxiesData.groups.forEach((group) => {
|
||||
@@ -52,10 +56,10 @@ const ProfilePage = () => {
|
||||
name,
|
||||
now,
|
||||
}));
|
||||
patchProfile(profiles.current!, profile).catch(console.error);
|
||||
patchProfile(current!, profile).catch(console.error);
|
||||
// update proxies cache
|
||||
if (hasChange) mutate("getProxies", getProxies());
|
||||
});
|
||||
}, 100);
|
||||
}, [profiles]);
|
||||
|
||||
const onImport = async () => {
|
||||
|
||||
@@ -1,27 +1,51 @@
|
||||
import useSWR from "swr";
|
||||
import useSWR, { useSWRConfig } from "swr";
|
||||
import { useEffect } from "react";
|
||||
import { Box, List, Paper, Typography } from "@mui/material";
|
||||
import { getProxies } from "../services/api";
|
||||
import ProxyGroup from "../components/proxy-group";
|
||||
import ProxyItem from "../components/proxy-item";
|
||||
|
||||
const ProxyPage = () => {
|
||||
const { mutate } = useSWRConfig();
|
||||
const { data: proxiesData } = useSWR("getProxies", getProxies);
|
||||
const { groups = [] } = proxiesData ?? {};
|
||||
const { groups = [], proxies = [] } = proxiesData ?? {};
|
||||
|
||||
useEffect(() => {
|
||||
// fix the empty proxies on the first sight
|
||||
// this bud only show on the build version
|
||||
// call twice to avoid something unknown or the delay of the clash startup
|
||||
setTimeout(() => mutate("getProxies"), 250);
|
||||
setTimeout(() => mutate("getProxies"), 1000);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
|
||||
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
|
||||
Proxy Groups
|
||||
{groups.length ? "Proxy Groups" : "Proxies"}
|
||||
</Typography>
|
||||
|
||||
{groups.length > 0 && (
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
|
||||
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
|
||||
{groups.length > 0 && (
|
||||
<List>
|
||||
{groups.map((group) => (
|
||||
<ProxyGroup key={group.name} group={group} />
|
||||
))}
|
||||
</List>
|
||||
</Paper>
|
||||
)}
|
||||
)}
|
||||
|
||||
{!groups.length && (
|
||||
<List>
|
||||
{Object.values(proxies).map((proxy) => (
|
||||
<ProxyItem
|
||||
key={proxy.name}
|
||||
proxy={proxy}
|
||||
selected={false}
|
||||
sx={{ py: 0, px: 2 }}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
)}
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -36,6 +36,18 @@ export async function restartSidecar() {
|
||||
return invoke<void>("restart_sidecar");
|
||||
}
|
||||
|
||||
export async function windowDrag() {
|
||||
return invoke<void>("win_drag");
|
||||
}
|
||||
|
||||
export async function windowHide() {
|
||||
return invoke<void>("win_hide");
|
||||
}
|
||||
|
||||
export async function windowMini() {
|
||||
return invoke<void>("win_mini");
|
||||
}
|
||||
|
||||
export async function getClashInfo() {
|
||||
return invoke<CmdType.ClashInfo | null>("get_clash_info");
|
||||
}
|
||||
@@ -44,10 +56,6 @@ export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
|
||||
return invoke<void>("patch_clash_config", { payload });
|
||||
}
|
||||
|
||||
export async function setSysProxy(enable: boolean) {
|
||||
return invoke<void>("set_sys_proxy", { enable });
|
||||
}
|
||||
|
||||
export async function getVergeConfig() {
|
||||
return invoke<CmdType.VergeConfig>("get_verge_config");
|
||||
}
|
||||
@@ -55,3 +63,7 @@ export async function getVergeConfig() {
|
||||
export async function patchVergeConfig(payload: CmdType.VergeConfig) {
|
||||
return invoke<void>("patch_verge_config", { payload });
|
||||
}
|
||||
|
||||
export async function getSystemProxy() {
|
||||
return invoke<any>("get_sys_proxy");
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ export namespace CmdType {
|
||||
|
||||
export interface VergeConfig {
|
||||
theme_mode?: "light" | "dark";
|
||||
theme_blur?: boolean;
|
||||
enable_self_startup?: boolean;
|
||||
enable_system_proxy?: boolean;
|
||||
}
|
||||
|
||||
@@ -4,3 +4,8 @@ export const atomPaletteMode = atom<"light" | "dark">({
|
||||
key: "atomPaletteMode",
|
||||
default: "light",
|
||||
});
|
||||
|
||||
export const atomThemeBlur = atom<boolean>({
|
||||
key: "atomThemeBlur",
|
||||
default: false,
|
||||
});
|
||||
|
||||