Compare commits

...

105 Commits

73 changed files with 3124 additions and 1790 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
@@ -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

74
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,74 @@
name: Test CI
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
RUST_BACKTRACE: short
jobs:
release:
runs-on: ${{ github.event.inputs.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@v1
with:
working-directory: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Dependencies (ubuntu only)
if: github.event.inputs.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@0e558392ccadcb49bcc89e7df15a400e8f0c954d
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}

1
.gitignore vendored
View File

@@ -4,3 +4,4 @@ dist
dist-ssr
*.local
update.json
scripts/_env.sh

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,57 @@
## v1.0.4
### Features
- update clash core and clash meta version
- support switch clash mode on system tray
- theme mode support follows system
### Bug Fixes
- config load error on first use
---
## 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
- adjust default theme settings
- reduce gpu usage of traffic graph when hidden
- supports more remote profile response header setting
- check remote profile data format when imported
### Bug Fixes
- service mode install and start issue (Windows)
- fix launch panic (Some Windows)
---
## v1.0.0
### Features

View File

@@ -1,14 +1,16 @@
{
"name": "clash-verge",
"version": "1.0.0",
"version": "1.0.4",
"license": "GPL-3.0",
"scripts": {
"dev": "tauri dev",
"dev:diff": "tauri dev -f verge-dev",
"build": "tauri build",
"tauri": "tauri",
"web:dev": "vite",
"web:build": "tsc && vite build",
"web:serve": "vite preview",
"aarch": "node scripts/aarch.mjs",
"check": "node scripts/check.mjs",
"updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs",
@@ -16,45 +18,47 @@
"prepare": "husky install"
},
"dependencies": {
"@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.6.1",
"@mui/material": "^5.6.1",
"@tauri-apps/api": "^1.0.0-rc.3",
"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.4",
"@mui/material": "^5.9.0",
"@tauri-apps/api": "^1.0.2",
"ahooks": "^3.5.2",
"axios": "^0.27.2",
"dayjs": "^1.11.3",
"i18next": "^21.8.12",
"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",
"recoil": "^0.6.1",
"react-i18next": "^11.17.4",
"react-router-dom": "^6.3.0",
"react-virtuoso": "^2.16.1",
"recoil": "^0.7.4",
"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.8",
"@actions/github": "^5.0.3",
"@tauri-apps/cli": "^1.0.4",
"@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",
"vite-plugin-monaco-editor": "^1.0.10",
"vite-plugin-svgr": "^1.1.0"
"sass": "^1.53.0",
"typescript": "^4.7.4",
"vite": "^2.9.13",
"vite-plugin-monaco-editor": "^1.1.0",
"vite-plugin-svgr": "^2.2.0"
},
"prettier": {
"tabWidth": 2,
@@ -62,4 +66,4 @@
"singleQuote": false,
"endOfLine": "lf"
}
}
}

104
scripts/aarch.mjs Normal file
View File

@@ -0,0 +1,104 @@
/**
* Build and upload assets for macOS(aarch)
*/
import fs from "fs-extra";
import path from "path";
import { exit } from "process";
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
const require = createRequire(import.meta.url);
async function resolve() {
if (!process.env.GITHUB_TOKEN) {
throw new Error("GITHUB_TOKEN is required");
}
if (!process.env.GITHUB_REPOSITORY) {
throw new Error("GITHUB_REPOSITORY is required");
}
if (!process.env.TAURI_PRIVATE_KEY) {
throw new Error("TAURI_PRIVATE_KEY is required");
}
if (!process.env.TAURI_KEY_PASSWORD) {
throw new Error("TAURI_KEY_PASSWORD is required");
}
const { version } = require("../package.json");
const cwd = process.cwd();
const bundlePath = path.join(cwd, "src-tauri/target/release/bundle");
const join = (p) => path.join(bundlePath, p);
const appPathList = [
join("macos/Clash Verge.aarch64.app.tar.gz"),
join("macos/Clash Verge.aarch64.app.tar.gz.sig"),
];
for (const appPath of appPathList) {
if (fs.pathExistsSync(appPath)) {
fs.removeSync(appPath);
}
}
fs.copyFileSync(join("macos/Clash Verge.app.tar.gz"), appPathList[0]);
fs.copyFileSync(join("macos/Clash Verge.app.tar.gz.sig"), appPathList[1]);
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}`,
});
if (!release.id) throw new Error("failed to find the release");
await uploadAssets(release.id, [
join(`dmg/Clash Verge_${version}_aarch64.dmg`),
...appPathList,
]);
}
// From tauri-apps/tauri-action
// https://github.com/tauri-apps/tauri-action/blob/dev/packages/action/src/upload-release-assets.ts
async function uploadAssets(releaseId, assets) {
const github = getOctokit(process.env.GITHUB_TOKEN);
// Determine content-length for header to upload asset
const contentLength = (filePath) => fs.statSync(filePath).size;
for (const assetPath of assets) {
const headers = {
"content-type": "application/zip",
"content-length": contentLength(assetPath),
};
const ext = path.extname(assetPath);
const filename = path.basename(assetPath).replace(ext, "");
const assetName = path.dirname(assetPath).includes(`target${path.sep}debug`)
? `${filename}-debug${ext}`
: `${filename}${ext}`;
console.log(`[INFO]: Uploading ${assetName}...`);
try {
await github.rest.repos.uploadReleaseAsset({
headers,
name: assetName,
data: fs.readFileSync(assetPath),
owner: context.repo.owner,
repo: context.repo.repo,
release_id: releaseId,
});
} catch (error) {
console.log(error.message);
}
}
}
if (process.platform === "darwin" && process.arch === "arm64") {
resolve();
} else {
console.error("invalid");
exit(1);
}

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.07.07";
// 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.12.0";
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);
}
}
/**
@@ -143,20 +231,26 @@ async function resolveService() {
if (platform !== "win32") return;
const url =
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest/clash-verge-service.exe";
const binName = "clash-verge-service.exe";
const resDir = path.join(cwd, "src-tauri/resources");
const targetPath = path.join(resDir, binName);
if (!FORCE && (await fs.pathExists(targetPath))) return;
const repo =
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest";
async function help(bin) {
const targetPath = path.join(resDir, bin);
if (!FORCE && (await fs.pathExists(targetPath))) return;
const url = `${repo}/${bin}`;
await downloadFile(url, targetPath);
}
await fs.mkdirp(resDir);
await downloadFile(url, targetPath);
await help("clash-verge-service.exe");
await help("install-service.exe");
await help("uninstall-service.exe");
console.log(`[INFO]: resolve ${binName} finished`);
console.log(`[INFO]: resolve Service finished`);
}
/**
@@ -164,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;
@@ -77,11 +83,11 @@ async function resolveUpdater() {
}
// darwin url (aarch)
if (name.endsWith("aarch.app.tar.gz")) {
if (name.endsWith("aarch64.app.tar.gz")) {
updateData.platforms["darwin-aarch64"].url = browser_download_url;
}
// darwin signature (aarch)
if (name.endsWith("aarch.app.tar.gz.sig")) {
if (name.endsWith("aarch64.app.tar.gz.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms["darwin-aarch64"].signature = sig;
}

1560
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,37 +10,37 @@ edition = "2021"
build = "build.rs"
[build-dependencies]
tauri-build = { version = "1.0.0-rc.5", 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.6", 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"
winreg = { version = "0.10", features = ["transactions"] }
windows-sys = { version = "0.36", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
[features]
default = ["custom-protocol"]

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

@@ -178,8 +178,12 @@ pub fn get_clash_info(core: State<'_, Core>) -> CmdResult<ClashInfo> {
/// after putting the change to the clash core
/// then we should save the latest config
#[tauri::command]
pub fn patch_clash_config(payload: Mapping, core: State<'_, Core>) -> CmdResult {
wrap_err!(core.patch_clash(payload))
pub fn patch_clash_config(
payload: Mapping,
app_handle: tauri::AppHandle,
core: State<'_, Core>,
) -> CmdResult {
wrap_err!(core.patch_clash(payload, &app_handle))
}
/// get the verge config
@@ -196,10 +200,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 {
@@ -258,20 +268,20 @@ pub mod service {
#[tauri::command]
pub async fn check_service() -> Result<JsonResponse, String> {
wrap_err!(crate::core::Service::check_service().await)
// no log
match crate::core::Service::check_service().await {
Ok(res) => Ok(res),
Err(err) => Err(err.to_string()),
}
}
#[tauri::command]
pub async fn install_service() -> Result<(), String> {
log_if_err!(crate::core::Service::install_service().await);
let ret = wrap_err!(crate::core::Service::start_service().await);
log::info!("clash verge service started successfully");
ret
wrap_err!(crate::core::Service::install_service().await)
}
#[tauri::command]
pub async fn uninstall_service() -> Result<(), String> {
log_if_err!(crate::core::Service::stop_service().await);
wrap_err!(crate::core::Service::uninstall_service().await)
}
}

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,
};
@@ -112,20 +113,26 @@ impl Clash {
/// patch update the clash config
/// if the port is changed then return true
pub fn patch_config(&mut self, patch: Mapping) -> Result<bool> {
pub fn patch_config(&mut self, patch: Mapping) -> Result<(bool, bool)> {
let port_key = Value::from("mixed-port");
let server_key = Value::from("external-controller");
let secret_key = Value::from("secret");
let mode_key = Value::from("mode");
let mut change_port = false;
let mut change_info = false;
let mut change_mode = false;
for (key, value) in patch.into_iter() {
if key == port_key {
change_port = true;
}
if key == port_key || key == server_key || key == secret_key {
if key == mode_key {
change_mode = true;
}
if key == port_key || key == server_key || key == secret_key || key == mode_key {
change_info = true;
}
@@ -138,7 +145,7 @@ impl Clash {
self.save_config()?;
Ok(change_port)
Ok((change_port, change_mode))
}
/// revise the `tun` and `dns` config

View File

@@ -3,10 +3,11 @@ use self::sysopt::Sysopt;
use self::timer::Timer;
use crate::core::enhance::PrfEnhancedResult;
use crate::log_if_err;
use crate::utils::{dirs, help};
use crate::utils::help;
use anyhow::{bail, Result};
use parking_lot::Mutex;
use serde_yaml::Mapping;
use serde_yaml::Value;
use std::sync::Arc;
use std::time::Duration;
use tauri::{AppHandle, Manager, Window};
@@ -28,6 +29,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 +70,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());
@@ -108,6 +112,7 @@ impl Core {
log_if_err!(sysopt.init_launch(auto_launch));
log_if_err!(self.update_systray(&app_handle));
log_if_err!(self.update_systray_clash(&app_handle));
// wait the window setup during resolve app
let core = self.clone();
@@ -138,17 +143,42 @@ 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<()> {
let (changed, port) = {
pub fn patch_clash(&self, patch: Mapping, app_handle: &AppHandle) -> Result<()> {
let ((changed_port, changed_mode), port) = {
let mut clash = self.clash.lock();
(clash.patch_config(patch)?, clash.info.port.clone())
};
// todo: port check
if changed {
if changed_port {
let mut service = self.service.lock();
service.restart()?;
drop(service);
@@ -161,6 +191,10 @@ impl Core {
sysopt.init_sysproxy(port, &verge);
}
if changed_mode {
self.update_systray_clash(app_handle)?;
}
Ok(())
}
@@ -207,7 +241,7 @@ impl Core {
#[cfg(target_os = "windows")]
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) {
let wintun_dll = dirs::app_home_dir().join("wintun.dll");
let wintun_dll = crate::utils::dirs::app_home_dir().join("wintun.dll");
if !wintun_dll.exists() {
bail!("failed to enable TUN for missing `wintun.dll`");
}
@@ -229,7 +263,32 @@ impl Core {
Ok(())
}
/// update the system tray state
// update system tray state (clash config)
pub fn update_systray_clash(&self, app_handle: &AppHandle) -> Result<()> {
let clash = self.clash.lock();
let mode = clash
.config
.get(&Value::from("mode"))
.map(|val| val.as_str().unwrap_or("rule"))
.unwrap_or("rule");
let tray = app_handle.tray_handle();
tray.get_item("rule_mode").set_selected(mode == "rule")?;
tray
.get_item("global_mode")
.set_selected(mode == "global")?;
tray
.get_item("direct_mode")
.set_selected(mode == "direct")?;
tray
.get_item("script_mode")
.set_selected(mode == "script")?;
Ok(())
}
/// update the system tray state (verge config)
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
let verge = self.verge.lock();
let tray = app_handle.tray_handle();
@@ -252,6 +311,33 @@ impl Core {
Ok(())
}
// update rule/global/direct/script mode
pub fn update_mode(&self, app_handle: &AppHandle, mode: &str) -> Result<()> {
// save config to file
let mut clash = self.clash.lock();
clash.config.insert(Value::from("mode"), Value::from(mode));
clash.save_config()?;
let info = clash.info.clone();
drop(clash);
let notice = {
let window = self.window.lock();
Notice::from(window.clone())
};
let mut mapping = Mapping::new();
mapping.insert(Value::from("mode"), Value::from(mode));
let service = self.service.lock();
service.patch_config(info, mapping, notice)?;
// update tray
self.update_systray_clash(app_handle)?;
Ok(())
}
/// activate the profile
/// auto activate enhanced profile
pub fn activate(&self) -> Result<()> {
@@ -332,7 +418,7 @@ impl Core {
let result = event.payload();
if result.is_none() {
log::warn!("event payload result is none");
log::warn!(target: "app", "event payload result is none");
return;
}
@@ -352,13 +438,26 @@ impl Core {
let service = service.lock();
log_if_err!(service.set_config(info, config, notice));
log::info!("profile enhanced status {}", result.status);
log::info!(target: "app", "profile enhanced status {}", result.status);
}
result.error.map(|err| log::error!("{err}"));
result.error.map(|err| log::error!(target: "app", "{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

@@ -1,6 +1,7 @@
use crate::utils::{dirs, help, tmpl};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::fs;
#[derive(Debug, Clone, Deserialize, Serialize)]
@@ -15,13 +16,13 @@ pub struct PrfItem {
/// profile name
pub name: Option<String>,
/// profile file
pub file: Option<String>,
/// profile description
#[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>,
/// profile file
pub file: Option<String>,
/// source url
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
@@ -155,7 +156,7 @@ impl PrfItem {
let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc)
}
typ @ _ => bail!("invalid type \"{typ}\""),
typ @ _ => bail!("invalid profile item type \"{typ}\""),
}
}
@@ -203,7 +204,7 @@ impl PrfItem {
builder = builder.no_proxy();
}
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v0.1.0".into()));
builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v1.0.0".into()));
let resp = builder.build()?.get(url).send().await?;
let header = resp.headers();
@@ -223,11 +224,37 @@ impl PrfItem {
None => None,
};
// parse the Content-Disposition
let filename = match header.get("Content-Disposition") {
Some(value) => {
let filename = value.to_str().unwrap_or("");
help::parse_str::<String>(filename, "filename=")
}
None => None,
};
// parse the profile-update-interval
let option = match header.get("profile-update-interval") {
Some(value) => match value.to_str().unwrap_or("").parse::<u64>() {
Ok(val) => Some(PrfOption {
update_interval: Some(val * 60), // hour -> min
..PrfOption::default()
}),
Err(_) => None,
},
None => None,
};
let uid = help::get_uid("r");
let file = format!("{uid}.yaml");
let name = name.unwrap_or(uid.clone());
let name = name.unwrap_or(filename.unwrap_or("Remote File".into()));
let data = resp.text_with_charset("utf-8").await?;
// check the data whether the valid yaml format
if !serde_yaml::from_str::<Mapping>(&data).is_ok() {
bail!("the remote profile data is invalid yaml");
}
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),

View File

@@ -3,12 +3,13 @@ use crate::log_if_err;
use crate::utils::{config, dirs};
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
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 +26,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;
@@ -46,12 +53,10 @@ impl Service {
Ok(status) => {
// 未启动clash
if status.code != 0 {
if let Err(err) = Self::start_clash_by_service().await {
log::error!("{err}");
}
log_if_err!(Self::start_clash_by_service().await);
}
}
Err(err) => log::error!("{err}"),
Err(err) => log::error!(target: "app", "{err}"),
}
});
@@ -70,9 +75,7 @@ impl Service {
}
tauri::async_runtime::spawn(async move {
if let Err(err) = Self::stop_clash_by_service().await {
log::error!("{err}");
}
log_if_err!(Self::stop_clash_by_service().await);
});
Ok(())
@@ -92,7 +95,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);
@@ -101,8 +105,11 @@ impl Service {
tauri::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await {
match event {
CommandEvent::Stdout(line) => log::info!("[clash]: {}", line),
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err),
CommandEvent::Stdout(line) => {
let stdout = if line.len() > 33 { &line[33..] } else { &line };
log::info!(target: "app" ,"[clash]: {}", stdout);
}
CommandEvent::Stderr(err) => log::error!(target: "app" ,"[clash error]: {}", err),
_ => {}
}
}
@@ -129,20 +136,7 @@ impl Service {
let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
if info.server.is_none() {
bail!("failed to parse the server");
}
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
let (server, headers) = Self::clash_client_info(info)?;
tauri::async_runtime::spawn(async move {
let mut data = HashMap::new();
@@ -157,7 +151,7 @@ impl Service {
match builder.send().await {
Ok(resp) => {
if resp.status() != 204 {
log::error!("failed to activate clash with status \"{}\"", resp.status());
log::error!(target: "app", "failed to activate clash with status \"{}\"", resp.status());
}
notice.refresh_clash();
@@ -165,10 +159,10 @@ impl Service {
// do not retry
break;
}
Err(err) => log::error!("failed to activate for `{err}`"),
Err(err) => log::error!(target: "app", "failed to activate for `{err}`"),
}
}
Err(err) => log::error!("failed to activate for `{err}`"),
Err(err) => log::error!(target: "app", "failed to activate for `{err}`"),
}
sleep(Duration::from_millis(500)).await;
}
@@ -176,6 +170,52 @@ impl Service {
Ok(())
}
/// patch clash config
pub fn patch_config(&self, info: ClashInfo, config: Mapping, notice: Notice) -> Result<()> {
if !self.service_mode && self.sidecar.is_none() {
bail!("did not start sidecar");
}
let (server, headers) = Self::clash_client_info(info)?;
tauri::async_runtime::spawn(async move {
if let Ok(client) = reqwest::ClientBuilder::new().no_proxy().build() {
let builder = client.patch(&server).headers(headers.clone()).json(&config);
match builder.send().await {
Ok(_) => notice.refresh_clash(),
Err(err) => log::error!(target: "app", "{err}"),
}
}
});
Ok(())
}
/// get clash client url and headers from clash info
fn clash_client_info(info: ClashInfo) -> Result<(String, HeaderMap)> {
if info.server.is_none() {
if info.port.is_none() {
bail!("failed to parse config.yaml file");
} else {
bail!("failed to parse the server");
}
}
let server = info.server.unwrap();
let server = format!("http://{server}/configs");
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.as_ref() {
let secret = format!("Bearer {}", secret.clone()).parse().unwrap();
headers.insert("Authorization", secret);
}
Ok((server, headers))
}
}
impl Drop for Service {
@@ -191,8 +231,10 @@ pub mod win_service {
use super::*;
use anyhow::Context;
use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommond;
use std::{env::current_exe, process::Command as StdCommond};
use runas::Command as RunasCommand;
use serde::{Deserialize, Serialize};
use std::os::windows::process::CommandExt;
use std::{env::current_exe, process::Command as StdCommand};
const SERVICE_NAME: &str = "clash_verge_service";
@@ -217,61 +259,63 @@ pub mod win_service {
/// 该函数应该在协程或者线程中执行避免UAC弹窗阻塞主线程
pub async fn install_service() -> Result<()> {
let binary_path = dirs::service_path();
let arg = format!("binpath={}", binary_path.as_os_str().to_string_lossy());
let install_path = binary_path.with_file_name("install-service.exe");
if !install_path.exists() {
bail!("installer exe not found");
}
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let args = [
"create",
SERVICE_NAME,
arg.as_str(),
"type=own",
"start=AUTO",
"displayname=Clash Verge Service",
];
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?,
_ => StdCommond::new("sc").args(&args).status()?,
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
_ => StdCommand::new(install_path)
.creation_flags(0x08000000)
.status()?,
};
if status.success() {
return Ok(());
if !status.success() {
bail!(
"failed to install service with status {}",
status.code().unwrap()
);
}
if status.code() == Some(1073i32) {
bail!("clash verge service is installed");
}
bail!(
"failed to install service with status {}",
status.code().unwrap()
)
Ok(())
}
/// Uninstall the Clash Verge Service
/// 该函数应该在协程或者线程中执行避免UAC弹窗阻塞主线程
pub async fn uninstall_service() -> Result<()> {
let binary_path = dirs::service_path();
let uninstall_path = binary_path.with_file_name("uninstall-service.exe");
if !uninstall_path.exists() {
bail!("uninstaller exe not found");
}
let token = Token::with_current_process()?;
let level = token.privilege_level()?;
let args = ["delete", SERVICE_NAME];
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?,
_ => StdCommond::new("sc").args(&args).status()?,
PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
_ => StdCommand::new(uninstall_path)
.creation_flags(0x08000000)
.status()?,
};
match status.success() {
true => Ok(()),
false => bail!(
if !status.success() {
bail!(
"failed to uninstall service with status {}",
status.code().unwrap()
),
);
}
Ok(())
}
/// [deprecated]
/// start service
/// 该函数应该在协程或者线程中执行避免UAC弹窗阻塞主线程
pub async fn start_service() -> Result<()> {
@@ -281,8 +325,8 @@ pub mod win_service {
let args = ["start", SERVICE_NAME];
let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?,
_ => StdCommond::new("sc").args(&args).status()?,
PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
_ => StdCommand::new("sc").args(&args).status()?,
};
match status.success() {
@@ -297,7 +341,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?
@@ -315,7 +361,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
@@ -333,7 +383,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();
@@ -348,7 +400,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()
@@ -367,7 +421,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

@@ -2,7 +2,6 @@ use super::{Clash, Verge};
use crate::{log_if_err, utils::sysopt::SysProxyConfig};
use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
// use parking_lot::Mutex;
use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe};
@@ -46,7 +45,7 @@ impl Sysopt {
if enable {
if let Err(err) = sysproxy.set_sys() {
log::error!("failed to set system proxy for `{err}`");
log::error!(target: "app", "failed to set system proxy for `{err}`");
}
}
@@ -90,7 +89,7 @@ impl Sysopt {
if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy"),
Err(_) => log::error!(target: "app", "failed to reset proxy"),
}
}
}
@@ -183,7 +182,7 @@ impl Sysopt {
break;
}
log::debug!("try to guard the system proxy");
log::debug!(target: "app", "try to guard the system proxy");
let clash = Clash::new();
@@ -194,7 +193,7 @@ impl Sysopt {
log_if_err!(sysproxy.set_sys());
}
None => log::error!("failed to parse clash port"),
None => log::error!(target: "app", "failed to parse clash port"),
}
}

View File

@@ -139,7 +139,7 @@ impl Timer {
/// the task runner
async fn async_task(core: Core, uid: String) {
log::info!("running timer task `{uid}`");
log::info!(target: "app", "running timer task `{uid}`");
log_if_err!(Core::update_profile_item(core, uid, None).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

@@ -30,6 +30,12 @@ fn main() -> std::io::Result<()> {
let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("rule_mode", "Rule Mode"))
.add_item(CustomMenuItem::new("global_mode", "Global Mode"))
.add_item(CustomMenuItem::new("direct_mode", "Direct Mode"))
.add_item(CustomMenuItem::new("script_mode", "Script Mode"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
@@ -38,16 +44,17 @@ fn main() -> std::io::Result<()> {
#[allow(unused_mut)]
let mut builder = tauri::Builder::default()
.manage(core::Core::new())
.setup(|app| Ok(resolve::resolve_setup(app)))
.system_tray(SystemTray::new().with_menu(tray_menu))
.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);
}
mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => {
let mode = &mode[0..mode.len() - 5];
let core = app_handle.state::<core::Core>();
crate::log_if_err!(core.update_mode(app_handle, mode));
}
"system_proxy" => {
let core = app_handle.state::<core::Core>();
@@ -91,24 +98,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 +160,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!(target: "app", "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!(target: "app", "failed to read yaml file \"{}\"", path.display());
T::default()
}
}
}
/// save the data to the file

View File

@@ -80,7 +80,7 @@ pub fn open_file(path: PathBuf) -> Result<()> {
macro_rules! log_if_err {
($result: expr) => {
if let Err(err) = $result {
log::error!("{err}");
log::error!(target: "app", "{err}");
}
};
}
@@ -93,7 +93,7 @@ macro_rules! wrap_err {
match $stat {
Ok(a) => Ok(a),
Err(err) => {
log::error!("{}", err.to_string());
log::error!(target: "app", "{}", err.to_string());
Err(format!("{}", err.to_string()))
}
}

View File

@@ -3,7 +3,7 @@ use chrono::Local;
use log::LevelFilter;
use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root};
use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder;
use std::fs;
use std::io::Write;
@@ -28,11 +28,13 @@ fn init_log(log_dir: &PathBuf) {
let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("file", Box::new(tofile)))
.build(
Root::builder()
.appenders(["stdout", "file"])
.build(LevelFilter::Info),
.logger(
Logger::builder()
.appenders(["file", "stdout"])
.additive(false)
.build("app", LevelFilter::Info),
)
.build(Root::builder().appender("stdout").build(LevelFilter::Info))
.unwrap();
log4rs::init_config(config).unwrap();
@@ -78,7 +80,7 @@ pub fn init_app(package_info: &PackageInfo) {
init_log(&log_dir);
if let Err(err) = init_config(&app_dir) {
log::error!("{err}");
log::error!(target: "app", "{err}");
}
// copy the resource file

View File

@@ -6,3 +6,4 @@ pub mod resolve;
pub mod server;
pub mod sysopt;
pub mod tmpl;
mod winhelp;

View File

@@ -9,12 +9,16 @@ pub fn resolve_setup(app: &App) {
// init app config
init::init_app(app.package_info());
// init states
let core = app.state::<Core>();
// init core
// should be initialized after init_app fix #122
let core = Core::new();
core.set_win(app.get_window("main"));
core.init(app.app_handle());
// fix #122
app.manage(core);
resolve_window(app);
}
@@ -35,27 +39,89 @@ fn resolve_window(app: &App) {
#[cfg(target_os = "windows")]
{
use crate::utils::winhelp;
use window_shadows::set_shadow;
use window_vibrancy::apply_blur;
window.set_decorations(false).unwrap();
set_shadow(&window, true).unwrap();
apply_blur(&window, None).unwrap();
let _ = window.set_decorations(false);
let _ = set_shadow(&window, true);
// todo
// win11 disable this feature temporarily due to lag
if !winhelp::is_win11() {
let _ = apply_blur(&window, None);
}
}
#[cfg(target_os = "macos")]
{
use tauri::LogicalSize;
use tauri::Size::Logical;
window.set_decorations(true).unwrap();
window
.set_size(Logical(LogicalSize {
width: 800.0,
height: 610.0,
}))
.unwrap();
// use tauri_plugin_vibrancy::MacOSVibrancy;
// #[allow(deprecated)]
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
let _ = window.set_decorations(true);
let _ = window.set_size(Logical(LogicalSize {
width: 800.0,
height: 620.0,
}));
}
}
/// 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!(target: "app", "{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

@@ -0,0 +1,69 @@
#![cfg(target_os = "windows")]
#![allow(non_snake_case)]
#![allow(non_camel_case_types)]
//!
//! From https://github.com/tauri-apps/window-vibrancy/blob/dev/src/windows.rs
//!
use windows_sys::Win32::{
Foundation::*,
System::{LibraryLoader::*, SystemInformation::*},
};
fn get_function_impl(library: &str, function: &str) -> Option<FARPROC> {
assert_eq!(library.chars().last(), Some('\0'));
assert_eq!(function.chars().last(), Some('\0'));
let module = unsafe { LoadLibraryA(library.as_ptr()) };
if module == 0 {
return None;
}
Some(unsafe { GetProcAddress(module, function.as_ptr()) })
}
macro_rules! get_function {
($lib:expr, $func:ident) => {
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')).map(|f| unsafe {
std::mem::transmute::<::windows_sys::Win32::Foundation::FARPROC, $func>(f)
})
};
}
/// Returns a tuple of (major, minor, buildnumber)
fn get_windows_ver() -> Option<(u32, u32, u32)> {
type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
let handle = get_function!("ntdll.dll", RtlGetVersion);
if let Some(rtl_get_version) = handle {
unsafe {
let mut vi = OSVERSIONINFOW {
dwOSVersionInfoSize: 0,
dwMajorVersion: 0,
dwMinorVersion: 0,
dwBuildNumber: 0,
dwPlatformId: 0,
szCSDVersion: [0; 128],
};
let status = (rtl_get_version)(&mut vi as _);
if status >= 0 {
Some((vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber))
} else {
None
}
}
} else {
None
}
}
pub fn is_win11() -> bool {
let v = get_windows_ver().unwrap_or_default();
v.2 >= 22000
}
#[test]
fn test_version() {
dbg!(get_windows_ver().unwrap_or_default());
}

View File

@@ -1,7 +1,7 @@
{
"package": {
"productName": "Clash Verge",
"version": "1.0.0"
"version": "1.0.4"
},
"build": {
"distDir": "../dist",
@@ -11,7 +11,7 @@
},
"tauri": {
"systemTray": {
"iconPath": "icons/icon.png",
"iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true
},
"bundle": {
@@ -22,23 +22,26 @@
"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"],
"resources": [
"resources"
],
"externalBin": [
"sidecar/clash",
"sidecar/clash-meta"
],
"copyright": "© 2022 zzzgydi All Rights Reserved",
"category": "DeveloperTool",
"shortDescription": "A Clash GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.",
"deb": {
"depends": [],
"useBootstrapper": false
"depends": []
},
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"useBootstrapper": false,
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": null
@@ -46,7 +49,13 @@
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
"timestampUrl": "",
"wix": {
"language": [
"zh-CN",
"en-US"
]
}
}
},
"updater": {
@@ -73,7 +82,7 @@
{
"title": "Clash Verge",
"width": 800,
"height": 600,
"height": 636,
"resizable": true,
"fullscreen": false,
"decorations": false,
@@ -86,4 +95,4 @@
"csp": "script-src 'unsafe-eval' 'self'; default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self'; img-src data: 'self';"
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

View File

@@ -11,6 +11,7 @@ body {
--primary-main: #5b5c9d;
--text-primary: #637381;
--selection-color: #f5f5f5;
--scroller-color: #90939980;
}
::selection {
@@ -25,7 +26,7 @@ body {
}
*::-webkit-scrollbar-thumb {
border-radius: 6px;
background-color: rgba(#909399, 0.5);
background-color: var(--scroller-color);
}
@import "./layout.scss";

View File

@@ -10,7 +10,7 @@
height: 100%;
max-width: 225px;
min-width: 125px;
padding: 8px 0;
padding: 16px 0 8px;
flex-direction: column;
box-sizing: border-box;
user-select: none;
@@ -23,14 +23,14 @@
max-width: 168px;
max-height: 168px;
margin: 0 auto;
padding: 0 8px;
padding: 0 16px;
text-align: center;
box-sizing: border-box;
img,
svg {
width: 100%;
height: 100%;
width: 96%;
height: 96%;
pointer-events: none;
}
@@ -43,7 +43,7 @@
}
.the-menu {
flex: 1 1 75%;
flex: 1 1 80%;
overflow-y: auto;
margin-bottom: 8px;
}

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

@@ -5,7 +5,7 @@ import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { getInformation } from "../../services/api";
import { getVergeConfig } from "../../services/cmds";
import { atomClashPort } from "../../services/states";
import TrafficGraph from "./traffic-graph";
@@ -41,7 +41,7 @@ const LayoutTraffic = () => {
useEffect(() => {
let ws: WebSocket | null = null;
getInfomation().then((result) => {
getInformation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);

View File

@@ -1,5 +1,7 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { useTheme } from "@mui/material";
import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";
const maxPoint = 30;
@@ -70,7 +72,28 @@ const TrafficGraph = (props: Props) => {
};
}, []);
// reduce the GPU usage when hidden
const [enablePaint, setEnablePaint] = useState(true);
useEffect(() => {
appWindow.isVisible().then(setEnablePaint);
const unlistenBlur = listen("tauri://blur", async () => {
setEnablePaint(await appWindow.isVisible());
});
const unlistenFocus = listen("tauri://focus", async () => {
setEnablePaint(await appWindow.isVisible());
});
return () => {
unlistenBlur.then((fn) => fn());
unlistenFocus.then((fn) => fn());
};
}, []);
useEffect(() => {
if (!enablePaint) return;
let raf = 0;
const canvas = canvasRef.current!;
@@ -193,7 +216,7 @@ const TrafficGraph = (props: Props) => {
return () => {
cancelAnimationFrame(raf);
};
}, [palette]);
}, [enablePaint, palette]);
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
};

View File

@@ -1,8 +1,11 @@
import useSWR from "swr";
import { useMemo } from "react";
import { useEffect, useMemo } from "react";
import { useRecoilState } from "recoil";
import { createTheme } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window";
import { getVergeConfig } from "../../services/cmds";
import { defaultTheme as dt } from "../../pages/_theme";
import { atomThemeMode } from "../../services/states";
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
/**
* custome theme
@@ -10,17 +13,25 @@ import { defaultTheme as dt } from "../../pages/_theme";
export default function useCustomTheme() {
const { data } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode, theme_setting } = data ?? {};
const [mode, setMode] = useRecoilState(atomThemeMode);
useEffect(() => {
if (theme_mode !== "system") {
setMode(theme_mode ?? "light");
return;
}
appWindow.theme().then((m) => m && setMode(m));
const unlisten = appWindow.onThemeChanged((e) => setMode(e.payload));
return () => {
unlisten.then((fn) => fn());
};
}, [theme_mode]);
const theme = useMemo(() => {
const mode = theme_mode ?? "light";
// 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);
const setting = theme_setting || {};
const dt = mode === "light" ? defaultTheme : defaultDarkTheme;
const theme = createTheme({
breakpoints: {
@@ -47,6 +58,16 @@ export default function useCustomTheme() {
},
});
// css
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const scrollColor = mode === "light" ? "#90939980" : "#54545480";
const rootEle = document.documentElement;
rootEle.style.background = "transparent";
rootEle.style.setProperty("--selection-color", selectColor);
rootEle.style.setProperty("--scroller-color", scrollColor);
rootEle.style.setProperty("--primary-main", theme.palette.primary.main);
// inject css
let style = document.querySelector("style#verge-theme");
if (!style) {
@@ -73,7 +94,7 @@ export default function useCustomTheme() {
}, 0);
return theme;
}, [theme_mode, theme_setting]);
}, [mode, theme_setting]);
return { theme };
}

View File

@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api";
import { getInformation } from "../../services/api";
import { atomLogData } from "../../services/states";
const MAX_LOG_NUM = 1000;
@@ -25,7 +25,7 @@ export default function useLogSetup() {
});
};
getInfomation().then((info) => {
getInformation().then((info) => {
const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler);

View File

@@ -26,7 +26,6 @@ import {
changeProfileValid,
} from "../../services/cmds";
import { CmdType } from "../../services/types";
import getSystem from "../../utils/get-system";
import ProfileMore from "./profile-more";
import Notice from "../base/base-notice";
@@ -35,8 +34,6 @@ interface Props {
chain: string[];
}
const OS = getSystem();
const EnhancedMode = (props: Props) => {
const { items, chain } = props;
@@ -49,7 +46,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());
}
@@ -147,9 +144,6 @@ const EnhancedMode = (props: Props) => {
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
MenuListProps={{
dense: true,
"aria-labelledby": "profile-use-button",

View File

@@ -1,6 +1,6 @@
import useSWR from "swr";
import { useEffect, useRef } from "react";
import { useLockFn } from "ahooks";
import { useRecoilValue } from "recoil";
import { useTranslation } from "react-i18next";
import {
Button,
@@ -9,11 +9,8 @@ import {
DialogContent,
DialogTitle,
} from "@mui/material";
import {
getVergeConfig,
readProfileFile,
saveProfileFile,
} from "../../services/cmds";
import { atomThemeMode } from "../../services/states";
import { readProfileFile, saveProfileFile } from "../../services/cmds";
import Notice from "../base/base-notice";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
@@ -35,8 +32,7 @@ const FileEditor = (props: Props) => {
const { t } = useTranslation();
const editorRef = useRef<any>();
const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode } = vergeConfig ?? {};
const themeMode = useRecoilValue(atomThemeMode);
useEffect(() => {
if (!open) return;
@@ -50,7 +46,7 @@ const FileEditor = (props: Props) => {
instanceRef.current = editor.create(editorRef.current, {
value: data,
language: mode,
theme: theme_mode === "light" ? "vs" : "vs-dark",
theme: themeMode === "light" ? "vs" : "vs-dark",
minimap: { enabled: false },
});
});

View File

@@ -1,6 +1,7 @@
import { mutate } from "swr";
import { useEffect, useState } from "react";
import { useLockFn, useSetState } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
@@ -25,6 +26,8 @@ interface Props {
// remote / local file / merge / script
const ProfileEdit = (props: Props) => {
const { open, itemData, onClose } = props;
const { t } = useTranslation();
const [form, setForm] = useSetState({ ...itemData });
const [option, setOption] = useSetState(itemData.option ?? {});
const [showOpt, setShowOpt] = useState(!!itemData.option);
@@ -33,7 +36,10 @@ const ProfileEdit = (props: Props) => {
if (itemData) {
setForm({ ...itemData });
setOption(itemData.option ?? {});
setShowOpt(!!itemData.option?.user_agent);
setShowOpt(
itemData.type === "remote" &&
(!!itemData.option?.user_agent || !!itemData.option?.update_interval)
);
}
}, [itemData]);
@@ -41,7 +47,10 @@ const ProfileEdit = (props: Props) => {
try {
const { uid } = itemData;
const { name, desc, url } = form;
const option_ = itemData.type === "remote" ? option : undefined;
const option_ =
itemData.type === "remote" || itemData.type === "local"
? option
: undefined;
if (itemData.type === "remote" && !url) {
throw new Error("Remote URL should not be null");
@@ -65,11 +74,11 @@ const ProfileEdit = (props: Props) => {
const type =
form.type ||
(form.url ? "remote" : form.file?.endsWith("js") ? "script" : "local");
(form.url ? "remote" : form.file?.endsWith(".js") ? "script" : "local");
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle sx={{ pb: 0.5 }}>Edit Profile</DialogTitle>
<DialogTitle sx={{ pb: 0.5 }}>{t("Edit Info")}</DialogTitle>
<DialogContent sx={{ width: 336, pb: 1 }}>
<TextField
@@ -100,7 +109,7 @@ const ProfileEdit = (props: Props) => {
{type === "remote" && (
<TextField
{...textFieldProps}
label="Subscription Url"
label="Subscription URL"
value={form.url}
onChange={(e) => setForm({ url: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
@@ -108,26 +117,27 @@ const ProfileEdit = (props: Props) => {
)}
{showOpt && (
<>
<TextField
{...textFieldProps}
label="User Agent"
value={option.user_agent}
onChange={(e) => setOption({ user_agent: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
<TextField
{...textFieldProps}
label="User Agent"
value={option.user_agent}
placeholder="clash-verge/v1.0.0"
onChange={(e) => setOption({ user_agent: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
<TextField
{...textFieldProps}
label="Update Interval (mins)"
value={option.update_interval}
onChange={(e) => {
const str = e.target.value?.replace(/\D/, "");
setOption({ update_interval: str != null ? +str : str });
}}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
</>
{((type === "remote" && showOpt) || type === "local") && (
<TextField
{...textFieldProps}
label="Update Interval (mins)"
value={option.update_interval}
onChange={(e) => {
const str = e.target.value?.replace(/\D/, "");
setOption({ update_interval: str != null ? +str : str });
}}
onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/>
)}
</DialogContent>

View File

@@ -1,5 +1,5 @@
import dayjs from "dayjs";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr";
import { useRecoilState } from "recoil";
@@ -20,7 +20,6 @@ import { CmdType } from "../../services/types";
import { atomLoadingCache } from "../../services/states";
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import parseTraffic from "../../utils/parse-traffic";
import getSystem from "../../utils/get-system";
import ProfileEdit from "./profile-edit";
import FileEditor from "./file-editor";
import Notice from "../base/base-notice";
@@ -41,8 +40,6 @@ const round = keyframes`
to { transform: rotate(360deg); }
`;
const OS = getSystem();
interface Props {
selected: boolean;
itemData: CmdType.ProfileItem;
@@ -59,11 +56,6 @@ const ProfileItem = (props: Props) => {
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
const { uid, name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
// local file mode
// remote file mode
@@ -71,8 +63,42 @@ const ProfileItem = (props: Props) => {
const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info
const { upload = 0, download = 0, total = 0 } = extra ?? {};
const from = parseUrl(itemData.url);
const expire = parseExpire(extra?.expire);
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const loading = loadingCache[itemData.uid] ?? false;
// interval update from now field
const [, setRefresh] = useState({});
useEffect(() => {
if (!hasUrl) return;
let timer: any = null;
const handler = () => {
const now = Date.now();
const lastUpdate = updated * 1000;
// 大于一天的不管
if (now - lastUpdate >= 24 * 36e5) return;
const wait = now - lastUpdate >= 36e5 ? 30e5 : 5e4;
timer = setTimeout(() => {
setRefresh({});
handler();
}, wait);
};
handler();
return () => {
if (timer) clearTimeout(timer);
};
}, [hasUrl, updated]);
const [editOpen, setEditOpen] = useState(false);
const [fileOpen, setFileOpen] = useState(false);
@@ -108,7 +134,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 }));
}
@@ -165,8 +194,8 @@ const ProfileItem = (props: Props) => {
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
"dark-true": alpha(text.secondary, 0.75),
"dark-false": alpha(text.secondary, 0.75),
}[key]!;
const h2color = {
@@ -231,7 +260,7 @@ const ProfileItem = (props: Props) => {
textAlign="right"
title="updated time"
>
{fromnow}
{updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
</Typography>
</Box>
) : (
@@ -270,9 +299,6 @@ const ProfileItem = (props: Props) => {
anchorPosition={position}
anchorReference="anchorPosition"
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();

View File

@@ -13,7 +13,6 @@ import {
} from "@mui/material";
import { CmdType } from "../../services/types";
import { viewProfile } from "../../services/cmds";
import getSystem from "../../utils/get-system";
import enhance from "../../services/enhance";
import ProfileEdit from "./profile-edit";
import FileEditor from "./file-editor";
@@ -30,8 +29,6 @@ const Wrapper = styled(Box)(({ theme }) => ({
boxSizing: "border-box",
}));
const OS = getSystem();
interface Props {
selected: boolean;
itemData: CmdType.ProfileItem;
@@ -223,9 +220,6 @@ const ProfileMore = (props: Props) => {
anchorPosition={position}
anchorReference="anchorPosition"
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();

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,79 @@
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 { getVersion } from "../../services/api";
import Notice from "../base/base-notice";
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", 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}
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,5 +1,6 @@
import { styled, Switch } from "@mui/material";
// todo: deprecated
// From: https://mui.com/components/switches/
const PaletteSwitch = styled(Switch)(({ theme }) => ({
width: 62,

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,9 +13,10 @@ import {
ListItemText,
styled,
TextField,
useTheme,
} from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { defaultTheme } from "../../pages/_theme";
import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
interface Props {
open: boolean;
@@ -71,15 +72,22 @@ const SettingTheme = (props: Props) => {
}
});
const renderItem = (label: string, key: keyof typeof defaultTheme) => {
// default theme
const { palette } = useTheme();
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
type ThemeKey = keyof typeof theme & keyof typeof defaultTheme;
const renderItem = (label: string, key: ThemeKey) => {
return (
<Item>
<ListItemText primary={label} />
<Round sx={{ background: theme[key] || defaultTheme[key] }} />
<Round sx={{ background: theme[key] || dt[key] }} />
<TextField
{...textProps}
value={theme[key] ?? ""}
placeholder={defaultTheme[key]}
placeholder={dt[key]}
onChange={handleChange(key)}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>

View File

@@ -19,7 +19,7 @@ import { ArrowForward } from "@mui/icons-material";
import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types";
import { version } from "../../../package.json";
import PaletteSwitch from "./palette-switch";
import ThemeModeSwitch from "./theme-mode-switch";
import GuardState from "./guard-state";
import SettingTheme from "./setting-theme";
@@ -43,19 +43,31 @@ const SettingVerge = ({ onError }: Props) => {
return (
<SettingList title={t("Verge Setting")}>
<SettingItem>
<ListItemText primary={t("Language")} />
<GuardState
value={language ?? "en"}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ language: e })}
onGuard={(e) => patchVergeConfig({ language: e })}
>
<Select size="small" sx={{ width: 100 }}>
<MenuItem value="zh"></MenuItem>
<MenuItem value="en">English</MenuItem>
</Select>
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Theme Mode")} />
<GuardState
value={theme_mode === "dark"}
valueProps="checked"
value={theme_mode}
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
onGuard={(e) =>
patchVergeConfig({ theme_mode: e ? "dark" : "light" })
}
onChange={(e) => onChangeData({ theme_mode: e })}
onGuard={(e) => patchVergeConfig({ theme_mode: e })}
>
<PaletteSwitch edge="end" />
<ThemeModeSwitch />
</GuardState>
</SettingItem>
@@ -87,22 +99,6 @@ const SettingVerge = ({ onError }: Props) => {
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Language")} />
<GuardState
value={language ?? "en"}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ language: e })}
onGuard={(e) => patchVergeConfig({ language: e })}
>
<Select size="small" sx={{ width: 100 }}>
<MenuItem value="zh"></MenuItem>
<MenuItem value="en">English</MenuItem>
</Select>
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary={t("Theme Setting")} />
<IconButton
@@ -129,7 +125,7 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem>
<SettingItem>
<ListItemText primary={t("Version")} />
<ListItemText primary={t("Verge Version")} />
<Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem>

View File

@@ -0,0 +1,34 @@
import { useTranslation } from "react-i18next";
import { Button, ButtonGroup } from "@mui/material";
import { CmdType } from "../../services/types";
type ThemeValue = CmdType.VergeConfig["theme_mode"];
interface Props {
value?: ThemeValue;
onChange?: (value: ThemeValue) => void;
}
const ThemeModeSwitch = (props: Props) => {
const { value, onChange } = props;
const { t } = useTranslation();
const modes = ["light", "dark", "system"] as const;
return (
<ButtonGroup size="small">
{modes.map((mode) => (
<Button
key={mode}
variant={mode === value ? "contained" : "outlined"}
onClick={() => onChange?.(mode)}
sx={{ textTransform: "capitalize" }}
>
{t(`theme.${mode}`)}
</Button>
))}
</ButtonGroup>
);
};
export default ThemeModeSwitch;

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",
@@ -54,7 +55,10 @@
"Language": "Language",
"Open App Dir": "Open App Dir",
"Open Logs Dir": "Open Logs Dir",
"Version": "Version",
"Verge Version": "Verge Version",
"theme.light": "Light",
"theme.dark": "Dark",
"theme.system": "System",
"Save": "Save",
"Cancel": "Cancel"

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": "开机自启",
@@ -47,14 +48,17 @@
"System Proxy": "系统代理",
"Proxy Guard": "系统代理守卫",
"Proxy Bypass": "Proxy Bypass",
"Theme Mode": "暗夜模式",
"Theme Mode": "主题模式",
"Theme Blur": "背景模糊",
"Theme Setting": "主题设置",
"Traffic Graph": "流量图显",
"Language": "语言设置",
"Open App Dir": "应用目录",
"Open Logs Dir": "日志目录",
"Version": "版本",
"Verge Version": "应用版本",
"theme.light": "浅色",
"theme.dark": "深色",
"theme.system": "系统",
"Save": "保存",
"Cancel": "取消"

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(() => {
@@ -72,7 +79,7 @@ const Layout = () => {
}}
sx={[
({ palette }) => ({
bgcolor: alpha(palette.background.paper, theme_blur ? 0.85 : 1),
bgcolor: alpha(palette.background.paper, theme_blur ? 0.8 : 1),
}),
]}
>
@@ -83,7 +90,7 @@ const Layout = () => {
<UpdateButton className="the-newbtn" />
</div>
<List className="the-menu" data-windrag>
<List className="the-menu">
{routers.map((router) => (
<LayoutItem key={router.label} to={router.link}>
{t(router.label)}

View File

@@ -10,3 +10,10 @@ export const defaultTheme = {
success_color: "#2e7d32",
font_family: `"Roboto", "Helvetica", "Arial", sans-serif`,
};
// dark mode
export const defaultDarkTheme = {
...defaultTheme,
primary_text: "#757575",
secondary_text: "#637381",
};

View File

@@ -4,7 +4,7 @@ import { Box, Button, Paper, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next";
import { ApiType } from "../services/types";
import { closeAllConnections, getInfomation } from "../services/api";
import { closeAllConnections, getInformation } from "../services/api";
import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item";
@@ -25,7 +25,7 @@ const ConnectionsPage = () => {
useEffect(() => {
let ws: WebSocket | null = null;
getInfomation().then((result) => {
getInformation().then((result) => {
const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/connections?token=${secret}`);

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

@@ -32,8 +32,8 @@ export async function getAxios(force: boolean = false) {
return axiosIns;
}
/// get infomation
export async function getInfomation() {
/// get information
export async function getInformation() {
if (server) return { server, secret };
const info = await getClashInfo();
return info!;

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

@@ -1,6 +1,11 @@
import { atom } from "recoil";
import { ApiType } from "./types";
export const atomThemeMode = atom<"light" | "dark">({
key: "atomThemeMode",
default: "light",
});
export const atomClashPort = atom<number>({
key: "atomClashPort",
default: 0,
@@ -22,3 +27,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,7 +125,8 @@ export namespace CmdType {
export interface VergeConfig {
language?: string;
theme_mode?: "light" | "dark";
clash_core?: string;
theme_mode?: "light" | "dark" | "system";
theme_blur?: boolean;
traffic_graph?: boolean;
enable_tun_mode?: boolean;

View File

@@ -6,7 +6,11 @@ import monaco from "vite-plugin-monaco-editor";
// https://vitejs.dev/config/
export default defineConfig({
root: "src",
plugins: [svgr(), react(), monaco()],
plugins: [
svgr(),
react(),
monaco({ languageWorkers: ["editorWorkerService", "typescript"] }),
],
build: {
outDir: "../dist",
emptyOutDir: true,

979
yarn.lock

File diff suppressed because it is too large Load Diff