Compare commits

...

61 Commits

48 changed files with 2052 additions and 1219 deletions

84
.github/workflows/alpha.yml vendored Normal file
View File

@@ -0,0 +1,84 @@
name: Alpha CI
on:
push:
branches: [alpha]
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
strategy:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
if: startsWith(github.repository, 'zzzgydi')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@743a37fd53cbdd122910b818b9bef7b7aa019134
# enable cache even though failed
continue-on-error: true
env:
VITE_MULTI_CORE: 1
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
tagName: alpha
releaseName: "Clash Verge Alpha"
releaseBody: "Alpha Version"
releaseDraft: true
prerelease: true
# - name: Portable Bundle
# if: matrix.os == 'windows-latest'
# run: |
# yarn run portable
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -28,6 +28,8 @@ jobs:
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
@@ -38,7 +40,7 @@ jobs:
if: matrix.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
- name: Get yarn cache dir path
id: yarn-cache-dir-path
@@ -61,7 +63,7 @@ jobs:
- name: Tauri build
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
# enable cache even though failed
continue-on-error: true
# continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
@@ -73,7 +75,7 @@ jobs:
releaseDraft: false
prerelease: true
- name: Green zip bundle
- name: Portable Bundle
if: matrix.os == 'windows-latest'
run: |
yarn run portable

View File

@@ -1,6 +1,17 @@
name: Test CI
on: workflow_dispatch
on:
workflow_dispatch:
inputs:
os:
description: "Runs on OS"
required: true
default: windows-latest
type: choice
options:
- windows-latest
- ubuntu-latest
- macos-latest
env:
CARGO_INCREMENTAL: 0
@@ -8,10 +19,7 @@ env:
jobs:
release:
strategy:
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
runs-on: ${{ github.event.inputs.os }}
if: startsWith(github.repository, 'zzzgydi')
steps:
- name: Checkout repository
@@ -24,16 +32,21 @@ jobs:
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@v1
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: matrix.os == 'ubuntu-latest'
if: github.event.inputs.os == 'ubuntu-latest'
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
sudo apt-get install -y libwebkit2gtk-4.0-dev build-essential curl wget libssl-dev libgtk-3-dev libappindicator3-dev librsvg2-dev libayatana-appindicator3-dev
- name: Get yarn cache dir path
id: yarn-cache-dir-path
@@ -55,8 +68,6 @@ jobs:
- name: Tauri build
uses: tauri-apps/tauri-action@0e558392ccadcb49bcc89e7df15a400e8f0c954d
# enable cache even though failed
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}

View File

@@ -12,8 +12,9 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
## Features
- Full `clash` config supported, Partial `clash premium` config supported.
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/issues/12)
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/wiki/%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97)
- Simple UI and supports custom theme color.
- Built-in support [Clash.Meta](https://github.com/MetaCubeX/Clash.Meta) core.
- System proxy setting and guard.
## Install
@@ -90,6 +91,7 @@ Clash Verge was based on or inspired by these projects and so on:
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
- [MetaCubeX/Clash.Meta](https://github.com/MetaCubeX/Clash.Meta): A rule-based tunnel in Go.
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!

View File

@@ -1,3 +1,27 @@
## v1.0.3
### Features
- save some states such as URL test, filter, etc
- update clash core and clash-meta core
- new icon for macOS
---
## v1.0.2
### Features
- supports for switching clash core
- supports release UI processes
- supports script mode setting
### Bug Fixes
- fix service mode bug (Windows)
---
## v1.0.1
### Features

View File

@@ -1,9 +1,10 @@
{
"name": "clash-verge",
"version": "1.0.1",
"version": "1.0.3",
"license": "GPL-3.0",
"scripts": {
"dev": "tauri dev",
"dev:diff": "tauri dev -f verge-dev",
"build": "tauri build",
"tauri": "tauri",
"web:dev": "vite",
@@ -16,45 +17,47 @@
"prepare": "husky install"
},
"dependencies": {
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.6.2",
"@mui/material": "^5.6.4",
"@tauri-apps/api": "^1.0.0-rc.4",
"ahooks": "^3.2.0",
"axios": "^0.26.0",
"dayjs": "^1.11.0",
"i18next": "^21.6.14",
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@mui/icons-material": "^5.8.3",
"@mui/material": "^5.8.3",
"@tauri-apps/api": "^1.0.1",
"ahooks": "^3.4.1",
"axios": "^0.27.2",
"dayjs": "^1.11.3",
"i18next": "^21.8.9",
"monaco-editor": "^0.33.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-i18next": "^11.15.6",
"react-router-dom": "^6.2.2",
"react-virtuoso": "~2.7.2",
"react-i18next": "^11.17.1",
"react-router-dom": "^6.3.0",
"react-virtuoso": "^2.13.2",
"recoil": "^0.6.1",
"snarkdown": "^2.0.0",
"swr": "^1.2.2"
"swr": "^1.3.0"
},
"devDependencies": {
"@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-rc.9",
"@actions/github": "^5.0.3",
"@tauri-apps/cli": "^1.0.0",
"@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1",
"@types/js-cookie": "^3.0.2",
"@types/lodash": "^4.14.180",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@vitejs/plugin-react": "^1.2.0",
"@vitejs/plugin-react": "^1.3.2",
"adm-zip": "^0.5.9",
"cross-env": "^7.0.3",
"fs-extra": "^10.0.0",
"https-proxy-agent": "^5.0.1",
"husky": "^7.0.0",
"node-fetch": "^3.2.0",
"node-fetch": "^3.2.6",
"prettier": "^2.6.2",
"pretty-quick": "^3.1.3",
"sass": "^1.49.7",
"typescript": "^4.5.5",
"vite": "^2.8.6",
"sass": "^1.52.3",
"typescript": "^4.7.3",
"vite": "^2.9.12",
"vite-plugin-monaco-editor": "^1.0.10",
"vite-plugin-svgr": "^1.1.0"
"vite-plugin-svgr": "^2.1.0"
},
"prettier": {
"tabWidth": 2,

View File

@@ -10,6 +10,7 @@ const cwd = process.cwd();
const TEMP_DIR = path.join(cwd, "node_modules/.verge");
const FORCE = process.argv.includes("--force");
const NO_META = process.argv.includes("--no-meta") || false;
/**
* get the correct clash release infomation
@@ -19,7 +20,7 @@ function resolveClash() {
const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.04.17";
const CLASH_LATEST_DATE = "2022.06.19";
// todo
const map = {
@@ -44,55 +45,142 @@ function resolveClash() {
return { url, zip, exefile, zipfile };
}
/**
* get the correct Clash.Meta release infomation
*/
async function resolveClashMeta() {
const { platform, arch } = process;
const urlPrefix = `https://github.com/MetaCubeX/Clash.Meta/releases/download/`;
const latestVersion = "v1.11.2";
const map = {
"win32-x64": "Clash.Meta-windows-amd64",
"darwin-x64": "Clash.Meta-darwin-amd64",
"darwin-arm64": "Clash.Meta-darwin-arm64",
"linux-x64": "Clash.Meta-linux-amd64",
};
const name = map[`${platform}-${arch}`];
if (!name) {
throw new Error(`unsupport platform "${platform}-${arch}"`);
}
const isWin = platform === "win32";
const ext = isWin ? "zip" : "gz";
const url = `${urlPrefix}${latestVersion}/${name}-${latestVersion}.${ext}`;
const exefile = `${name}${isWin ? ".exe" : ""}`;
const zipfile = `${name}-${latestVersion}.${ext}`;
return { url, zip: ext, exefile, zipfile };
}
/**
* get the sidecar bin
* clash and Clash Meta
*/
async function resolveSidecar() {
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
const host = execSync("rustc -vV | grep host").toString().slice(6).trim();
const host = execSync("rustc -vV")
.toString()
.match(/(?<=host: ).+(?=\s*)/g)[0];
const ext = process.platform === "win32" ? ".exe" : "";
const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(sidecarDir);
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
await clash();
if (!NO_META) await clashMeta();
// download sidecar
const binInfo = resolveClash();
const tempDir = path.join(TEMP_DIR, "clash");
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
async function clash() {
const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip);
await fs.mkdirp(sidecarDir);
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
if (binInfo.zip === "zip") {
const zip = new AdmZip(tempZip);
zip.getEntries().forEach((entry) => {
console.log("[INFO]: entry name", entry.entryName);
});
zip.extractAllTo(tempDir, true);
// save as sidecar
await fs.rename(tempExe, sidecarPath);
console.log(`[INFO]: unzip finished`);
} else {
// gz
const readStream = fs.createReadStream(tempZip);
const writeStream = fs.createWriteStream(sidecarPath);
readStream
.pipe(zlib.createGunzip())
.pipe(writeStream)
.on("finish", () => {
console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`);
})
.on("error", (error) => console.error(error));
// download sidecar
const binInfo = resolveClash();
const tempDir = path.join(TEMP_DIR, "clash");
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip)))
await downloadFile(binInfo.url, tempZip);
if (binInfo.zip === "zip") {
const zip = new AdmZip(tempZip);
zip.getEntries().forEach((entry) => {
console.log("[INFO]: entry name", entry.entryName);
});
zip.extractAllTo(tempDir, true);
// save as sidecar
await fs.rename(tempExe, sidecarPath);
console.log(`[INFO]: unzip finished`);
} else {
// gz
const readStream = fs.createReadStream(tempZip);
const writeStream = fs.createWriteStream(sidecarPath);
readStream
.pipe(zlib.createGunzip())
.pipe(writeStream)
.on("finish", () => {
console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`);
})
.on("error", (error) => console.error(error));
}
// delete temp dir
await fs.remove(tempDir);
}
// delete temp dir
await fs.remove(tempDir);
async function clashMeta() {
const sidecarFile = `clash-meta-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(sidecarDir);
if (!FORCE && (await fs.pathExists(sidecarPath))) return;
// download sidecar
const binInfo = await resolveClashMeta();
const tempDir = path.join(TEMP_DIR, "clash-meta");
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip)))
await downloadFile(binInfo.url, tempZip);
if (binInfo.zip === "zip") {
const zip = new AdmZip(tempZip);
zip.getEntries().forEach((entry) => {
console.log("[INFO]: entry name", entry.entryName);
});
zip.extractAllTo(tempDir, true);
// save as sidecar
await fs.rename(tempExe, sidecarPath);
console.log(`[INFO]: unzip finished`);
} else {
// gz
const readStream = fs.createReadStream(tempZip);
const writeStream = fs.createWriteStream(sidecarPath);
readStream
.pipe(zlib.createGunzip())
.pipe(writeStream)
.on("finish", () => {
console.log(`[INFO]: gunzip finished`);
execSync(`chmod 755 ${sidecarPath}`);
console.log(`[INFO]: chmod binary finished`);
})
.on("error", (error) => console.error(error));
}
// delete temp dir
await fs.remove(tempDir);
}
}
/**
@@ -170,7 +258,7 @@ async function resolveService() {
*/
async function resolveMmdb() {
const url =
"https://github.com/Dreamacro/maxmind-geoip/releases/latest/download/Country.mmdb";
"https://github.com/Dreamacro/maxmind-geoip/releases/download/20220512/Country.mmdb";
const resDir = path.join(cwd, "src-tauri", "resources");
const resPath = path.join(resDir, "Country.mmdb");

View File

@@ -4,6 +4,8 @@ import AdmZip from "adm-zip";
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
const META = process.argv.includes("--meta"); // use Clash.Meta
/// Script for ci
/// 打包绿色版/便携版 (only Windows)
async function resolvePortable() {
@@ -19,6 +21,7 @@ async function resolvePortable() {
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
zip.addLocalFile(path.join(releaseDir, "clash.exe"));
zip.addLocalFile(path.join(releaseDir, "clash-meta.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
const require = createRequire(import.meta.url);
@@ -53,4 +56,54 @@ async function resolvePortable() {
});
}
resolvePortable().catch(console.error);
/// 打包包含Clash.Meta的 (only Windows)
async function resolvePortableMeta() {
if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release";
if (!(await fs.pathExists(releaseDir))) {
throw new Error("could not found the release dir");
}
const zip = new AdmZip();
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
zip.addLocalFile(path.join(releaseDir, "clash.exe"));
zip.addLocalFile(path.join(releaseDir, "clash-meta.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
const require = createRequire(import.meta.url);
const packageJson = require("../package.json");
const { version } = packageJson;
const zipFile = `Clash.Verge.Meta_${version}_x64_portable.zip`;
zip.writeZip(zipFile);
console.log("[INFO]: create portable zip successfully");
// push release assets
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const options = { owner: context.repo.owner, repo: context.repo.repo };
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
...options,
tag: `v${version}`,
});
console.log(release.name);
await github.rest.repos.uploadReleaseAsset({
...options,
release_id: release.id,
name: zipFile,
data: zip.toBuffer(),
});
}
if (META) resolvePortableMeta().catch(console.error);
else resolvePortable().catch(console.error);

View File

@@ -53,12 +53,18 @@ async function resolveUpdater() {
const { name, browser_download_url } = asset;
// win64 url
if (name.endsWith(".msi.zip")) {
if (
name.endsWith(".msi.zip") &&
(!updateData.platforms.win64.url || name.includes("en-US"))
) {
updateData.platforms.win64.url = browser_download_url;
updateData.platforms["windows-x86_64"].url = browser_download_url;
}
// win64 signature
if (name.endsWith(".msi.zip.sig")) {
if (
name.endsWith(".msi.zip.sig") &&
(!updateData.platforms.win64.signature || name.includes("en-US"))
) {
const sig = await getSignature(browser_download_url);
updateData.platforms.win64.signature = sig;
updateData.platforms["windows-x86_64"].signature = sig;

1033
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,41 +10,40 @@ edition = "2021"
build = "build.rs"
[build-dependencies]
tauri-build = { version = "1.0.0-rc.7", features = [] }
tauri-build = { version = "1.0.0", features = [] }
[dependencies]
warp = "0.3"
which = "4.2.2"
anyhow = "1.0"
dirs = "4.0.0"
open = "2.1.1"
log = "0.4.14"
dunce = "1.0.2"
log4rs = "1.0.0"
nanoid = "0.4.0"
chrono = "0.4.19"
serde_json = "1.0"
serde_yaml = "0.8"
delay_timer = "0.11.1"
parking_lot = "0.12.0"
serde = { version = "1.0", features = ["derive"] }
tauri = { version = "1.0.0-rc.8", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
window-shadows = { git = "https://github.com/tauri-apps/window-shadows" }
window-vibrancy = { git = "https://github.com/tauri-apps/window-vibrancy" }
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
log = "0.4.14"
log4rs = "1.0.0"
warp = "0.3"
which = "4.2.2"
auto-launch = "0.2"
port_scanner = "0.1.5"
delay_timer = "0.11.1"
parking_lot = "0.12.0"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json"] }
tauri = { version = "1.0.0", features = ["process-all", "shell-all", "system-tray", "updater", "window-all"] }
window-shadows = { version = "0.1" }
window-vibrancy = { version = "0.1" }
[target.'cfg(windows)'.dependencies]
runas = "0.2.1"
deelevate = "0.2.0"
windows-sys = "0.36"
winreg = { version = "0.10", features = ["transactions"] }
windows-sys = { version = "0.36", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
[features]
default = ["custom-protocol", "tauri/ayatana-tray"]
default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"]
verge-dev = []
debug-yml = []

Binary file not shown.

Before

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -196,10 +196,16 @@ pub fn patch_verge_config(
payload: Verge,
app_handle: tauri::AppHandle,
core: State<'_, Core>,
) -> Result<(), String> {
) -> CmdResult {
wrap_err!(core.patch_verge(payload, &app_handle))
}
/// change clash core
#[tauri::command]
pub fn change_clash_core(core: State<'_, Core>, clash_core: Option<String>) -> CmdResult {
wrap_err!(core.change_core(clash_core))
}
/// restart the sidecar
#[tauri::command]
pub fn restart_sidecar(core: State<'_, Core>) -> CmdResult {

View File

@@ -49,15 +49,16 @@ impl ClashInfo {
// `external-controller` could be
// "127.0.0.1:9090" or ":9090"
// "9090" or 9090 (clash do not support this)
let server = match config.get(&key_server) {
Some(value) => match value {
Value::String(val_str) => match val_str.starts_with(":") {
true => Some(format!("127.0.0.1{val_str}")),
false => Some(val_str.clone()),
},
_ => None,
},
Some(value) => {
let val_str = value.as_str().unwrap_or("");
if val_str.starts_with(":") {
Some(format!("127.0.0.1{val_str}"))
} else {
Some(val_str.into())
}
}
_ => None,
};

View File

@@ -28,6 +28,10 @@ pub use self::profiles::*;
pub use self::service::*;
pub use self::verge::*;
/// close the window for slient start
/// after enhance mode
static mut WINDOW_CLOSABLE: bool = true;
#[derive(Clone)]
pub struct Core {
pub clash: Arc<Mutex<Clash>>,
@@ -65,22 +69,21 @@ impl Core {
/// initialize the core state
pub fn init(&self, app_handle: tauri::AppHandle) {
let verge = self.verge.lock();
let clash_core = verge.clash_core.clone();
let mut service = self.service.lock();
service.set_core(clash_core);
#[cfg(windows)]
{
let verge = self.verge.lock();
let enable = verge.enable_service_mode.clone();
let mut service = self.service.lock();
service.set_mode(enable.unwrap_or(false));
log_if_err!(service.start());
}
#[cfg(not(windows))]
{
let mut service = self.service.lock();
log_if_err!(service.start());
}
log_if_err!(service.start());
drop(verge);
drop(service);
log_if_err!(self.activate());
@@ -138,6 +141,31 @@ impl Core {
self.activate_enhanced(true)
}
/// change the clash core
pub fn change_core(&self, clash_core: Option<String>) -> Result<()> {
let clash_core = clash_core.unwrap_or("clash".into());
if &clash_core != "clash" && &clash_core != "clash-meta" {
bail!("invalid clash core name \"{clash_core}\"");
}
let mut verge = self.verge.lock();
verge.patch_config(Verge {
clash_core: Some(clash_core.clone()),
..Verge::default()
})?;
drop(verge);
let mut service = self.service.lock();
service.stop()?;
service.set_core(Some(clash_core));
service.start()?;
drop(service);
self.activate()?;
self.activate_enhanced(true)
}
/// Patch Clash
/// handle the clash config changed
pub fn patch_clash(&self, patch: Mapping) -> Result<()> {
@@ -358,7 +386,20 @@ impl Core {
result.error.map(|err| log::error!("{err}"));
});
window.emit("script-handler", payload).unwrap();
let verge = self.verge.lock();
let silent_start = verge.enable_silent_start.clone();
let closable = unsafe { WINDOW_CLOSABLE };
if silent_start.unwrap_or(false) && closable {
unsafe {
WINDOW_CLOSABLE = false;
}
window.emit("script-handler-close", payload).unwrap();
} else {
window.emit("script-handler", payload).unwrap();
}
Ok(())
}

View File

@@ -252,7 +252,7 @@ impl PrfItem {
// check the data whether the valid yaml format
if !serde_yaml::from_str::<Mapping>(&data).is_ok() {
bail!("the remote profile data is not valid yaml");
bail!("the remote profile data is invalid yaml");
}
Ok(PrfItem {

View File

@@ -9,6 +9,8 @@ use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent};
use tokio::time::sleep;
static mut CLASH_CORE: &str = "clash";
#[derive(Debug)]
pub struct Service {
sidecar: Option<CommandChild>,
@@ -25,6 +27,12 @@ impl Service {
}
}
pub fn set_core(&mut self, clash_core: Option<String>) {
unsafe {
CLASH_CORE = Box::leak(clash_core.unwrap_or("clash".into()).into_boxed_str());
}
}
#[allow(unused)]
pub fn set_mode(&mut self, enable: bool) {
self.service_mode = enable;
@@ -92,7 +100,8 @@ impl Service {
let app_dir = dirs::app_home_dir();
let app_dir = app_dir.as_os_str().to_str().unwrap();
let cmd = Command::new_sidecar("clash")?;
let clash_core = unsafe { CLASH_CORE };
let cmd = Command::new_sidecar(clash_core)?;
let (mut rx, cmd_child) = cmd.args(["-d", app_dir]).spawn()?;
self.sidecar = Some(cmd_child);
@@ -130,7 +139,11 @@ impl Service {
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
if info.server.is_none() {
bail!("failed to parse the server");
if info.port.is_none() {
bail!("failed to parse config.yaml file");
} else {
bail!("failed to parse the server");
}
}
let server = info.server.unwrap();
@@ -300,7 +313,9 @@ pub mod win_service {
/// stop service
pub async fn stop_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_service");
let res = reqwest::Client::new()
let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url)
.send()
.await?
@@ -318,7 +333,11 @@ pub mod win_service {
/// check the windows service status
pub async fn check_service() -> Result<JsonResponse> {
let url = format!("{SERVICE_URL}/get_clash");
let response = reqwest::get(url)
let response = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.get(url)
.send()
.await?
.json::<JsonResponse>()
.await
@@ -336,7 +355,9 @@ pub mod win_service {
sleep(Duration::from_secs(1)).await;
}
let bin_path = current_exe().unwrap().with_file_name("clash.exe");
let clash_core = unsafe { CLASH_CORE };
let clash_bin = format!("{clash_core}.exe");
let bin_path = current_exe().unwrap().with_file_name(clash_bin);
let bin_path = bin_path.as_os_str().to_str().unwrap();
let config_dir = dirs::app_home_dir();
@@ -351,7 +372,9 @@ pub mod win_service {
map.insert("log_file", log_path);
let url = format!("{SERVICE_URL}/start_clash");
let res = reqwest::Client::new()
let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url)
.json(&map)
.send()
@@ -370,7 +393,9 @@ pub mod win_service {
/// stop the clash by service
pub(super) async fn stop_clash_by_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_clash");
let res = reqwest::Client::new()
let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url)
.send()
.await?

View File

@@ -45,6 +45,10 @@ pub struct Verge {
/// theme setting
pub theme_setting: Option<VergeTheme>,
/// clash core path
#[serde(skip_serializing_if = "Option::is_none")]
pub clash_core: Option<String>,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -96,6 +100,9 @@ impl Verge {
if patch.traffic_graph.is_some() {
self.traffic_graph = patch.traffic_graph;
}
if patch.clash_core.is_some() {
self.clash_core = patch.clash_core;
}
// system setting
if patch.enable_silent_start.is_some() {

View File

@@ -44,10 +44,7 @@ fn main() -> std::io::Result<()> {
.on_system_tray_event(move |app_handle, event| match event {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"open_window" => {
let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
resolve::create_window(app_handle);
}
"system_proxy" => {
let core = app_handle.state::<core::Core>();
@@ -91,24 +88,22 @@ fn main() -> std::io::Result<()> {
},
#[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
resolve::create_window(app_handle);
}
_ => {}
})
.invoke_handler(tauri::generate_handler![
// common
cmds::restart_sidecar,
cmds::get_sys_proxy,
cmds::get_cur_proxy,
cmds::kill_sidecar,
cmds::open_app_dir,
cmds::open_logs_dir,
cmds::kill_sidecar,
cmds::restart_sidecar,
// clash
cmds::get_clash_info,
cmds::patch_clash_config,
cmds::change_clash_core,
// verge
cmds::get_verge_config,
cmds::patch_verge_config,
@@ -155,17 +150,8 @@ fn main() -> std::io::Result<()> {
.build(tauri::generate_context!())
.expect("error while running tauri application")
.run(|app_handle, e| match e {
tauri::RunEvent::WindowEvent { label, event, .. } => match event {
tauri::WindowEvent::CloseRequested { api, .. } => {
let app_handle = app_handle.clone();
api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap();
}
_ => {}
},
tauri::RunEvent::ExitRequested { .. } => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
tauri::RunEvent::ExitRequested { api, .. } => {
api.prevent_exit();
}
tauri::RunEvent::Exit => {
resolve::resolve_reset(app_handle);

View File

@@ -4,8 +4,20 @@ use std::{fs, path::PathBuf};
/// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
let yaml_str = fs::read_to_string(path).unwrap_or("".into());
serde_yaml::from_str::<T>(&yaml_str).unwrap_or(T::default())
if !path.exists() {
log::error!("file not found \"{}\"", path.display());
return T::default();
}
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
match serde_yaml::from_str::<T>(&yaml_str) {
Ok(val) => val,
Err(_) => {
log::error!("failed to read yaml file \"{}\"", path.display());
T::default()
}
}
}
/// save the data to the file

View File

@@ -61,3 +61,63 @@ fn resolve_window(app: &App) {
}));
}
}
/// create main window
pub fn create_window(app_handle: &AppHandle) {
if let Some(window) = app_handle.get_window("main") {
let _ = window.unminimize();
let _ = window.show();
let _ = window.set_focus();
return;
}
let builder = tauri::window::WindowBuilder::new(
app_handle,
"main".to_string(),
tauri::WindowUrl::App("index.html".into()),
)
.title("Clash Verge")
.center()
.fullscreen(false)
.min_inner_size(600.0, 520.0);
#[cfg(target_os = "windows")]
{
use crate::utils::winhelp;
use window_shadows::set_shadow;
use window_vibrancy::apply_blur;
match builder
.decorations(false)
.transparent(true)
.inner_size(800.0, 636.0)
.build()
{
Ok(_) => {
let app_handle = app_handle.clone();
tauri::async_runtime::spawn(async move {
if let Some(window) = app_handle.get_window("main") {
let _ = window.show();
let _ = set_shadow(&window, true);
if !winhelp::is_win11() {
let _ = apply_blur(&window, None);
}
}
});
}
Err(err) => log::error!("{err}"),
}
}
#[cfg(target_os = "macos")]
crate::log_if_err!(builder.decorations(true).inner_size(800.0, 620.0).build());
#[cfg(target_os = "linux")]
crate::log_if_err!(builder
.decorations(false)
.transparent(true)
.inner_size(800.0, 636.0)
.build());
}

View File

@@ -1,7 +1,7 @@
{
"package": {
"productName": "Clash Verge",
"version": "1.0.1"
"version": "1.0.3"
},
"build": {
"distDir": "../dist",
@@ -11,7 +11,7 @@
},
"tauri": {
"systemTray": {
"iconPath": "icons/icon.png",
"iconPath": "icons/tray-icon.png",
"iconAsTemplate": true
},
"bundle": {
@@ -22,11 +22,11 @@
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon-new.icns",
"icons/icon.ico"
],
"resources": ["resources"],
"externalBin": ["sidecar/clash"],
"externalBin": ["sidecar/clash", "sidecar/clash-meta"],
"copyright": "© 2022 zzzgydi All Rights Reserved",
"category": "DeveloperTool",
"shortDescription": "A Clash GUI based on tauri.",
@@ -44,7 +44,10 @@
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
"timestampUrl": "",
"wix": {
"language": ["zh-CN", "en-US"]
}
}
},
"updater": {

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

View File

@@ -11,7 +11,7 @@ interface InnerProps {
}
const NoticeInner = (props: InnerProps) => {
const { type, message, duration = 2000, onClose } = props;
const { type, message, duration = 1500, onClose } = props;
const [visible, setVisible] = useState(true);
const onBtnClose = () => {
@@ -26,12 +26,13 @@ const NoticeInner = (props: InnerProps) => {
type === "info" ? (
message
) : (
<Box sx={{ display: "flex", alignItems: "center" }}>
<Box sx={{ width: 328, display: "flex", alignItems: "center" }}>
{type === "error" && <ErrorRounded color="error" />}
{type === "success" && <CheckCircleRounded color="success" />}
<Typography
sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }}
component="span"
sx={{ ml: 1, wordWrap: "break-word", width: "calc(100% - 35px)" }}
>
{message}
</Typography>
@@ -79,14 +80,16 @@ const Notice: NoticeInstance = (props) => {
const onUnmount = () => {
const result = ReactDOM.unmountComponentAtNode(container);
if (result && parent) parent.removeChild(container);
if (result && parent) setTimeout(() => parent.removeChild(container), 500);
};
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
};
(["info", "error", "success"] as const).forEach((type) => {
Notice[type] = (message, duration) => Notice({ type, message, duration });
Notice[type] = (message, duration) => {
setTimeout(() => Notice({ type, message, duration }), 0);
};
});
export default Notice;

View File

@@ -30,7 +30,7 @@ const LayoutControl = () => {
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
onClick={() => appWindow.hide()}
onClick={() => appWindow.close()}
>
<CloseRounded fontSize="small" />
</Button>

View File

@@ -49,7 +49,7 @@ const EnhancedMode = (props: Props) => {
const onEnhance = useLockFn(async () => {
try {
await enhanceProfiles();
Notice.success("Refresh clash config", 2000);
Notice.success("Refresh clash config", 1000);
} catch (err: any) {
Notice.error(err.message || err.toString());
}

View File

@@ -137,7 +137,10 @@ const ProfileItem = (props: Props) => {
await updateProfile(itemData.uid, { with_proxy: withProxy });
mutate("getProfiles");
} catch (err: any) {
Notice.error(err?.message || err.toString());
const errmsg = err?.message || err.toString();
Notice.error(
errmsg.replace(/error sending request for url (\S+?): /, "")
);
} finally {
setLoadingCache((cache) => ({ ...cache, [itemData.uid]: false }));
}

View File

@@ -5,7 +5,8 @@ import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useSortProxy from "./use-sort-proxy";
import useHeadState from "./use-head-state";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
@@ -24,13 +25,19 @@ const ProxyGlobal = (props: Props) => {
const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const [headState, setHeadState] = useHeadState(groupName);
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText);
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
const filterProxies = useFilterProxy(
proxies,
groupName,
headState.filterText
);
const sortedProxies = useSortProxy(
filterProxies,
groupName,
headState.sortType
);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -102,15 +109,11 @@ const ProxyGlobal = (props: Props) => {
<>
<ProxyHead
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={groupName}
filterText={filterText}
headState={headState}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
onHeadState={setHeadState}
/>
<Virtuoso
@@ -122,7 +125,7 @@ const ProxyGlobal = (props: Props) => {
groupName={groupName}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
showType={headState.showType}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
/>

View File

@@ -18,7 +18,8 @@ import {
import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds";
import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useSortProxy from "./use-sort-proxy";
import useHeadState from "./use-head-state";
import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
@@ -30,16 +31,21 @@ interface Props {
const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const [headState, setHeadState] = useHeadState(group.name);
const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(group.all, group.name, filterText);
const sortedProxies = useSortProxy(filterProxies, group.name, sortType);
const filterProxies = useFilterProxy(
group.all,
group.name,
headState.filterText
);
const sortedProxies = useSortProxy(
filterProxies,
group.name,
headState.sortType
);
const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -99,14 +105,18 @@ const ProxyGroup = ({ group }: Props) => {
// auto scroll to current index
useEffect(() => {
if (open) {
if (headState.open) {
setTimeout(() => onLocation(false), 5);
}
}, [open]);
}, [headState.open]);
return (
<>
<ListItem button onClick={() => setOpen(!open)} dense>
<ListItem
button
dense
onClick={() => setHeadState({ open: !headState.open })}
>
<ListItemText
primary={group.name}
secondary={
@@ -120,21 +130,17 @@ const ProxyGroup = ({ group }: Props) => {
}}
/>
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
{headState.open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<Collapse in={headState.open} timeout="auto" unmountOnExit>
<ProxyHead
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={group.name}
filterText={filterText}
headState={headState}
onLocation={onLocation}
onCheckDelay={onCheckAll}
onShowType={setShowType}
onSortType={setSortType}
onFilterText={setFilterText}
onHeadState={setHeadState}
/>
{!sortedProxies.length && (
@@ -160,7 +166,7 @@ const ProxyGroup = ({ group }: Props) => {
groupName={group.name}
proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now}
showType={showType}
showType={headState.showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
/>
@@ -178,7 +184,7 @@ const ProxyGroup = ({ group }: Props) => {
groupName={group.name}
proxy={proxy}
selected={proxy.name === now}
showType={showType}
showType={headState.showType}
sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy}
/>

View File

@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { Box, IconButton, TextField, SxProps } from "@mui/material";
import {
AccessTimeRounded,
@@ -14,27 +14,33 @@ import {
SortRounded,
} from "@mui/icons-material";
import delayManager from "../../services/delay";
import type { HeadState } from "./use-head-state";
import type { ProxySortType } from "./use-sort-proxy";
interface Props {
sx?: SxProps;
groupName: string;
showType: boolean;
sortType: ProxySortType;
filterText: string;
headState: HeadState;
onLocation: () => void;
onCheckDelay: () => void;
onShowType: (val: boolean) => void;
onSortType: (val: ProxySortType) => void;
onFilterText: (val: string) => void;
onHeadState: (val: Partial<HeadState>) => void;
}
const ProxyHead = (props: Props) => {
const { sx = {}, groupName, showType, sortType, filterText } = props;
const { sx = {}, groupName, headState, onHeadState } = props;
const [textState, setTextState] = useState<"url" | "filter" | null>(null);
const { showType, sortType, filterText, textState, testUrl } = headState;
const [testUrl, setTestUrl] = useState(delayManager.getUrl(groupName) || "");
const [autoFocus, setAutoFocus] = useState(false);
useEffect(() => {
// fix the focus conflict
setTimeout(() => setAutoFocus(true), 100);
}, []);
useEffect(() => {
delayManager.setUrl(groupName, testUrl);
}, [groupName, headState.testUrl]);
return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
@@ -54,7 +60,7 @@ const ProxyHead = (props: Props) => {
onClick={() => {
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") {
setTextState("url");
onHeadState({ textState: "url" });
}
props.onCheckDelay();
}}
@@ -66,7 +72,9 @@ const ProxyHead = (props: Props) => {
size="small"
color="inherit"
title={["sort by default", "sort by delay", "sort by name"][sortType]}
onClick={() => props.onSortType(((sortType + 1) % 3) as ProxySortType)}
onClick={() =>
onHeadState({ sortType: ((sortType + 1) % 3) as ProxySortType })
}
>
{sortType === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />}
@@ -77,7 +85,9 @@ const ProxyHead = (props: Props) => {
size="small"
color="inherit"
title="edit test url"
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))}
onClick={() =>
onHeadState({ textState: textState === "url" ? null : "url" })
}
>
{textState === "url" ? (
<WifiTetheringRounded />
@@ -90,7 +100,7 @@ const ProxyHead = (props: Props) => {
size="small"
color="inherit"
title="proxy detail"
onClick={() => props.onShowType(!showType)}
onClick={() => onHeadState({ showType: !showType })}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
@@ -100,7 +110,7 @@ const ProxyHead = (props: Props) => {
color="inherit"
title="filter"
onClick={() =>
setTextState((ts) => (ts === "filter" ? null : "filter"))
onHeadState({ textState: textState === "filter" ? null : "filter" })
}
>
{textState === "filter" ? (
@@ -112,20 +122,20 @@ const ProxyHead = (props: Props) => {
{textState === "filter" && (
<TextField
autoFocus
autoFocus={autoFocus}
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => props.onFilterText(e.target.value)}
onChange={(e) => onHeadState({ filterText: e.target.value })}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
{textState === "url" && (
<TextField
autoFocus
autoFocus={autoFocus}
hiddenLabel
autoSave="off"
autoComplete="off"
@@ -133,10 +143,7 @@ const ProxyHead = (props: Props) => {
size="small"
variant="outlined"
placeholder="Test url"
onChange={(e) => {
setTestUrl(e.target.value);
delayManager.setUrl(groupName, e.target.value);
}}
onChange={(e) => onHeadState({ testUrl: e.target.value })}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}

View File

@@ -0,0 +1,80 @@
import { useCallback, useEffect, useState } from "react";
import { useRecoilValue } from "recoil";
import { atomCurrentProfile } from "../../services/states";
import { ProxySortType } from "./use-sort-proxy";
export interface HeadState {
open?: boolean;
showType: boolean;
sortType: ProxySortType;
filterText: string;
textState: "url" | "filter" | null;
testUrl: string;
}
type HeadStateStorage = Record<string, Record<string, HeadState>>;
const HEAD_STATE_KEY = "proxy-head-state";
const DEFAULT_STATE: HeadState = {
open: false,
showType: false,
sortType: 0,
filterText: "",
textState: null,
testUrl: "",
};
export default function useHeadState(groupName: string) {
const current = useRecoilValue(atomCurrentProfile);
const [state, setState] = useState<HeadState>(DEFAULT_STATE);
useEffect(() => {
if (!current) {
setState(DEFAULT_STATE);
return;
}
try {
const data = JSON.parse(
localStorage.getItem(HEAD_STATE_KEY)!
) as HeadStateStorage;
const value = data[current][groupName] || DEFAULT_STATE;
if (value && typeof value === "object") {
setState({ ...DEFAULT_STATE, ...value });
} else {
setState(DEFAULT_STATE);
}
} catch {}
}, [current, groupName]);
const setHeadState = useCallback(
(obj: Partial<HeadState>) => {
setState((old) => {
const ret = { ...old, ...obj };
setTimeout(() => {
try {
const item = localStorage.getItem(HEAD_STATE_KEY);
let data = (item ? JSON.parse(item) : {}) as HeadStateStorage;
if (!data || typeof data !== "object") data = {};
if (!data[current]) data[current] = {};
data[current][groupName] = ret;
localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data));
} catch {}
});
return ret;
});
},
[current, groupName]
);
return [state, setHeadState] as const;
}

View File

@@ -0,0 +1,84 @@
import useSWR, { useSWRConfig } from "swr";
import { useState } from "react";
import { useLockFn } from "ahooks";
import { Menu, MenuItem } from "@mui/material";
import { Settings } from "@mui/icons-material";
import { changeClashCore, getVergeConfig } from "../../services/cmds";
import getSystem from "../../utils/get-system";
import Notice from "../base/base-notice";
const OS = getSystem();
const VALID_CORE = [
{ name: "Clash", core: "clash" },
{ name: "Clash Meta", core: "clash-meta" },
];
const CoreSwitch = () => {
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 });
const { clash_core = "clash" } = vergeConfig ?? {};
const onCoreChange = useLockFn(async (core: string) => {
if (core === clash_core) return;
try {
await changeClashCore(core);
mutate("getVergeConfig");
mutate("getClashConfig");
mutate("getVersion");
setAnchorEl(null);
Notice.success(`Successfully switch to ${core}`, 1000);
} catch (err: any) {
Notice.error(err?.message || err.toString());
}
});
return (
<>
<Settings
fontSize="small"
style={{ cursor: "pointer" }}
onClick={(event) => {
const { clientX, clientY } = event;
setPosition({ top: clientY, left: clientX });
setAnchorEl(event.currentTarget);
}}
/>
<Menu
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
}}
>
{VALID_CORE.map((each) => (
<MenuItem
key={each.core}
sx={{ minWidth: 125 }}
selected={each.core === clash_core}
onClick={() => onCoreChange(each.core)}
>
{each.name}
</MenuItem>
))}
</Menu>
</>
);
};
export default CoreSwitch;

View File

@@ -1,104 +1,117 @@
import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogContent,
DialogTitle,
Stack,
Typography,
} from "@mui/material";
import {
checkService,
installService,
uninstallService,
patchVergeConfig,
} from "../../services/cmds";
import Notice from "../base/base-notice";
import noop from "../../utils/noop";
interface Props {
open: boolean;
enable: boolean;
onClose: () => void;
onError?: (err: Error) => void;
}
const ServiceMode = (props: Props) => {
const { open, enable, onClose, onError = noop } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: status } = useSWR("checkService", checkService, {
revalidateIfStale: true,
shouldRetryOnError: false,
});
const state = status != null ? status : "pending";
const onInstall = useLockFn(async () => {
try {
await installService();
mutate("checkService");
onClose();
Notice.success("Service installed successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
const onUninstall = useLockFn(async () => {
try {
if (state === "active" && enable) {
await patchVergeConfig({ enable_service_mode: false });
}
await uninstallService();
mutate("checkService");
onClose();
Notice.success("Service uninstalled successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Service Mode")}</DialogTitle>
<DialogContent sx={{ width: 360, userSelect: "text" }}>
<Typography>Current State: {state}</Typography>
{(state === "unknown" || state === "uninstall") && (
<Typography>
Infomation: Please make sure the Clash Verge Service is installed
and enabled
</Typography>
)}
<Stack
direction="row"
spacing={1}
sx={{ mt: 4, justifyContent: "flex-end" }}
>
{state === "uninstall" && (
<Button variant="contained" onClick={onInstall}>
Install
</Button>
)}
{(state === "active" || state === "installed") && (
<Button variant="outlined" onClick={onUninstall}>
Uninstall
</Button>
)}
</Stack>
</DialogContent>
</Dialog>
);
};
export default ServiceMode;
import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogContent,
DialogTitle,
Stack,
Typography,
} from "@mui/material";
import {
checkService,
installService,
uninstallService,
patchVergeConfig,
} from "../../services/cmds";
import Notice from "../base/base-notice";
import noop from "../../utils/noop";
interface Props {
open: boolean;
enable: boolean;
onClose: () => void;
onError?: (err: Error) => void;
}
const ServiceMode = (props: Props) => {
const { open, enable, onClose, onError = noop } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: status } = useSWR("checkService", checkService, {
revalidateIfStale: true,
shouldRetryOnError: false,
});
const state = status != null ? status : "pending";
const onInstall = useLockFn(async () => {
try {
await installService();
mutate("checkService");
onClose();
Notice.success("Service installed successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
const onUninstall = useLockFn(async () => {
try {
if (state === "active" && enable) {
await patchVergeConfig({ enable_service_mode: false });
}
await uninstallService();
mutate("checkService");
onClose();
Notice.success("Service uninstalled successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
// fix unhandle error of the service mode
const onDisable = useLockFn(async () => {
await patchVergeConfig({ enable_service_mode: false });
mutate("checkService");
onClose();
});
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Service Mode")}</DialogTitle>
<DialogContent sx={{ width: 360, userSelect: "text" }}>
<Typography>Current State: {state}</Typography>
{(state === "unknown" || state === "uninstall") && (
<Typography>
Infomation: Please make sure the Clash Verge Service is installed
and enabled
</Typography>
)}
<Stack
direction="row"
spacing={1}
sx={{ mt: 4, justifyContent: "flex-end" }}
>
{state === "uninstall" && enable && (
<Button variant="contained" onClick={onDisable}>
Disable Service Mode
</Button>
)}
{state === "uninstall" && (
<Button variant="contained" onClick={onInstall}>
Install
</Button>
)}
{(state === "active" || state === "installed") && (
<Button variant="outlined" onClick={onUninstall}>
Uninstall
</Button>
)}
</Stack>
</DialogContent>
</Dialog>
);
};
export default ServiceMode;

View File

@@ -8,6 +8,7 @@ import {
Select,
MenuItem,
Typography,
Box,
} from "@mui/material";
import { ApiType } from "../../services/types";
import { atomClashPort } from "../../services/states";
@@ -16,11 +17,15 @@ import { SettingList, SettingItem } from "./setting";
import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
import Notice from "../base/base-notice";
import GuardState from "./guard-state";
import CoreSwitch from "./core-switch";
interface Props {
onError: (err: Error) => void;
}
// const MULTI_CORE = !!import.meta.env.VITE_MULTI_CORE;
const MULTI_CORE = true;
const SettingClash = ({ onError }: Props) => {
const { t } = useTranslation();
const { mutate } = useSWRConfig();
@@ -54,7 +59,7 @@ const SettingClash = ({ onError }: Props) => {
}
await patchClashConfig({ "mixed-port": port });
setGlobalClashPort(port);
Notice.success("Change Clash port successfully!");
Notice.success("Change Clash port successfully!", 1000);
// update the config
mutate("getClashConfig");
@@ -129,7 +134,18 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem>
<SettingItem>
<ListItemText primary={t("Clash core")} />
<ListItemText
primary={
MULTI_CORE ? (
<Box sx={{ display: "flex", alignItems: "center" }}>
<span style={{ marginRight: 4 }}>{t("Clash Core")}</span>
<CoreSwitch />
</Box>
) : (
t("Clash Core")
)
}
/>
<Typography sx={{ py: 1 }}>{clashVer}</Typography>
</SettingItem>
</SettingList>

View File

@@ -13,6 +13,7 @@
"rule": "rule",
"global": "global",
"direct": "direct",
"script": "script",
"Profiles": "Profiles",
"Profile URL": "Profile URL",
"Import": "Import",
@@ -39,7 +40,7 @@
"IPv6": "IPv6",
"Log Level": "Log Level",
"Mixed Port": "Mixed Port",
"Clash core": "Clash core",
"Clash Core": "Clash Core",
"Tun Mode": "Tun Mode",
"Service Mode": "Service Mode",
"Auto Launch": "Auto Launch",

View File

@@ -13,6 +13,7 @@
"rule": "规则",
"global": "全局",
"direct": "直连",
"script": "脚本",
"Profiles": "配置",
"Profile URL": "配置文件链接",
"Import": "导入",
@@ -39,7 +40,7 @@
"IPv6": "IPv6",
"Log Level": "日志等级",
"Mixed Port": "端口设置",
"Clash core": "Clash 内核",
"Clash Core": "Clash 内核",
"Tun Mode": "Tun 模式",
"Service Mode": "服务模式",
"Auto Launch": "开机自启",

View File

@@ -3,6 +3,7 @@ import i18next from "i18next";
import relativeTime from "dayjs/plugin/relativeTime";
import useSWR, { SWRConfig, useSWRConfig } from "swr";
import { useEffect } from "react";
import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next";
import { Route, Routes } from "react-router-dom";
import { alpha, List, Paper, ThemeProvider } from "@mui/material";
@@ -10,7 +11,8 @@ import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";
import { routers } from "./_routers";
import { getAxios } from "../services/api";
import { getVergeConfig } from "../services/cmds";
import { atomCurrentProfile } from "../services/states";
import { getVergeConfig, getProfiles } from "../services/cmds";
import { ReactComponent as LogoSvg } from "../assets/image/logo.svg";
import LayoutItem from "../components/layout/layout-item";
import LayoutControl from "../components/layout/layout-control";
@@ -33,9 +35,11 @@ const Layout = () => {
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_blur, language } = vergeConfig || {};
const setCurrentProfile = useSetRecoilState(atomCurrentProfile);
useEffect(() => {
window.addEventListener("keydown", (e) => {
if (e.key === "Escape") appWindow.hide();
if (e.key === "Escape") appWindow.close();
});
listen("verge://refresh-clash-config", async () => {
@@ -47,6 +51,9 @@ const Layout = () => {
// update the verge config
listen("verge://refresh-verge-config", () => mutate("getVergeConfig"));
// set current profile uid
getProfiles().then((data) => setCurrentProfile(data.current ?? ""));
}, []);
useEffect(() => {

View File

@@ -1,6 +1,7 @@
import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
import { useEffect, useMemo, useState } from "react";
import { useSetRecoilState } from "recoil";
import { Box, Button, Grid, TextField } from "@mui/material";
import { useTranslation } from "react-i18next";
import {
@@ -10,6 +11,7 @@ import {
importProfile,
} from "../services/cmds";
import { getProxies, updateProxy } from "../services/api";
import { atomCurrentProfile } from "../services/states";
import Notice from "../components/base/base-notice";
import BasePage from "../components/base/base-page";
import ProfileNew from "../components/profile/profile-new";
@@ -24,6 +26,8 @@ const ProfilePage = () => {
const [disabled, setDisabled] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const setCurrentProfile = useSetRecoilState(atomCurrentProfile);
const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
// distinguish type
@@ -52,6 +56,9 @@ const ProfilePage = () => {
const current = profiles.current;
const profile = regularItems.find((p) => p.uid === current);
setCurrentProfile(current);
if (!profile) return;
setTimeout(async () => {
@@ -121,7 +128,9 @@ const ProfilePage = () => {
try {
await selectProfile(uid);
setCurrentProfile(uid);
mutate("getProfiles", { ...profiles, current: uid }, true);
if (force) Notice.success("Refresh clash config", 1000);
} catch (err: any) {
Notice.error(err?.message || err.toString());
}

View File

@@ -16,7 +16,7 @@ const ProxyPage = () => {
const { data: proxiesData } = useSWR("getProxies", getProxies);
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const modeList = ["rule", "global", "direct"];
const modeList = ["rule", "global", "direct", "script"];
const curMode = clashConfig?.mode.toLowerCase();
const { groups = [], proxies = [] } = proxiesData ?? {};
@@ -38,7 +38,8 @@ const ProxyPage = () => {
});
// difference style
const showGroup = curMode === "rule" && !!groups.length;
const showGroup =
(curMode === "rule" || curMode === "script") && !!groups.length;
const pageStyle = showGroup ? {} : { height: "100%" };
const paperStyle: any = showGroup
? { mb: 0.5 }
@@ -64,7 +65,7 @@ const ProxyPage = () => {
}
>
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
{curMode === "rule" && !!groups.length && (
{(curMode === "rule" || curMode === "script") && !!groups.length && (
<List>
{groups.map((group) => (
<ProxyGroup key={group.name} group={group} />

View File

@@ -86,6 +86,10 @@ export async function getSystemProxy() {
return invoke<any>("get_sys_proxy");
}
export async function changeClashCore(clashCore: string) {
return invoke<any>("change_clash_core", { clashCore });
}
export async function restartSidecar() {
return invoke<void>("restart_sidecar");
}

View File

@@ -1,4 +1,5 @@
import { emit, listen } from "@tauri-apps/api/event";
import { emit, listen, Event } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";
import { CmdType } from "./types";
import ignoreCase from "../utils/ignore-case";
@@ -124,21 +125,30 @@ class Enhance {
return this.resultMap.get(uid);
}
async enhanceHandler(event: Event<unknown>) {
const payload = event.payload as CmdType.EnhancedPayload;
const result = await this.runner(payload).catch((err: any) => ({
data: null,
status: "error",
error: err.message,
}));
emit(payload.callback, JSON.stringify(result)).catch(console.error);
}
// setup the handler
setup() {
if (this.isSetup) return;
this.isSetup = true;
listen("script-handler", async (event) => {
const payload = event.payload as CmdType.EnhancedPayload;
await this.enhanceHandler(event);
});
const result = await this.runner(payload).catch((err: any) => ({
data: null,
status: "error",
error: err.message,
}));
emit(payload.callback, JSON.stringify(result)).catch(console.error);
listen("script-handler-close", async (event) => {
await this.enhanceHandler(event);
appWindow.close();
});
}

View File

@@ -22,3 +22,9 @@ export const atomUpdateState = atom<boolean>({
key: "atomUpdateState",
default: false,
});
// current profile uid
export const atomCurrentProfile = atom<string>({
key: "atomCurrentProfile",
default: "",
});

View File

@@ -1,7 +1,7 @@
/**
* Some interface for clash api
*/
export namespace ApiType {
export namespace ApiType {
export interface ConfigData {
port: number;
mode: string;
@@ -125,6 +125,7 @@ export namespace CmdType {
export interface VergeConfig {
language?: string;
clash_core?: string;
theme_mode?: "light" | "dark";
theme_blur?: boolean;
traffic_graph?: boolean;

900
yarn.lock

File diff suppressed because it is too large Load Diff