Compare commits

...
105 Commits
Author SHA1 Message Date
GyDi 9b56233938 v1.0.4 2022-07-17 17:56:07 +08:00
GyDi 65074264b8 chore: update log 2022-07-17 17:52:41 +08:00
GyDi 4f6fceb87f feat: improve log rule 2022-07-17 17:39:44 +08:00
GyDi 659fdd1d37 fix: import mod 2022-07-17 16:51:54 +08:00
GyDi 8bce2ce040 feat: theme mode support follows system 2022-07-17 16:02:17 +08:00
GyDi 55cc83a5d4 chore: update deps 2022-07-17 14:54:09 +08:00
GyDi 6a51e93ded refactor: mode manage on tray 2022-07-13 02:26:54 +08:00
GyDi fcf570e96e chore: rm code 2022-07-13 01:07:29 +08:00
GyDi cbc184e953 fix: add tray separator 2022-07-13 01:05:53 +08:00
GyDi 98f9063352 Merge pull request #128 from Limsanity/main
feat: support switch proxy mode
2022-07-13 01:02:14 +08:00
limsanity c278f1af00 style: resolve formatting problem 2022-07-13 00:54:47 +08:00
limsanity fbb17a0ba5 feat(system tray): support switch rule/global/direct/script mode in system tray 2022-07-13 00:43:27 +08:00
GyDi 8637a9823e chore: update deps 2022-07-11 00:41:21 +08:00
GyDi d717fe7e8c chore: update clash version 2022-07-08 01:42:14 +08:00
GyDi 5e8dfe7267 chore: update aarch rule 2022-07-07 02:54:20 +08:00
GyDi aaa4fbcdbd chore: aarch upload script 2022-07-07 02:53:53 +08:00
GyDi 150f0cf486 fix: instantiate core after init app, close #122 2022-07-06 15:14:33 +08:00
GyDi 711b220a05 chore: update clash version 2022-07-06 00:54:01 +08:00
GyDi b615c485f7 chore: update deps 2022-07-06 00:49:09 +08:00
GyDi 2f3b6b29ae fix: rm macOS transition props 2022-07-05 01:24:23 +08:00
GyDi 7aecd83c4a chore: update deps 2022-07-05 00:52:22 +08:00
GyDi 3b460ab91f chore: change tray icon 2022-06-22 01:26:25 +08:00
GyDi 661c0eb970 v1.0.3 2022-06-20 02:09:12 +08:00
GyDi f4a1f1fdc8 chore: update log 2022-06-20 02:06:46 +08:00
GyDi b5432c3728 chore: update clash version 2022-06-20 01:47:15 +08:00
GyDi 6d0625c409 fix: improve external-controller parse and log 2022-06-20 01:36:56 +08:00
GyDi 2f1ea08b8a chore: update macos icon 2022-06-18 18:41:53 +08:00
GyDi a092da1943 fix: show windows on click 2022-06-18 17:28:37 +08:00
GyDi 43ef3cc562 chore: new logo for mac 2022-06-18 17:28:05 +08:00
GyDi 047774475c chore: update alpha ci 2022-06-17 01:18:19 +08:00
GyDi 91b8504df5 chore: update tauri 2022-06-17 01:16:46 +08:00
GyDi a4fb2dfcf8 fix: adjust update profile notice error 2022-06-15 02:42:04 +08:00
GyDi ba16ec02e5 fix: style issue on mac 2022-06-15 02:41:37 +08:00
GyDi 55b7af2623 chore: update version 2022-06-15 01:15:05 +08:00
GyDi b428eff10e feat: improve yaml file error log 2022-06-14 01:40:02 +08:00
GyDi 35aee15b6d chore: update deps 2022-06-14 01:23:58 +08:00
GyDi 6f53c1bfde Merge pull request #104 from FoundTheWOUT/main
fix: check script run on all OS
2022-06-12 22:25:05 +08:00
FoundTheWOUT db0230ed75 fix: check script run on all OS 2022-06-05 23:55:41 +08:00
GyDi 7fa3c1e12a feat: save proxy page state 2022-06-04 18:55:39 +08:00
GyDi 3b5993652f chore: portable script 2022-06-02 00:56:05 +08:00
GyDi be4ad8947f chore: updater script 2022-06-01 10:06:08 +08:00
GyDi 2ead15e78e v1.0.2 2022-06-01 01:26:05 +08:00
GyDi aa0740ff94 chore: update log 2022-06-01 01:25:39 +08:00
GyDi 6d3f837820 fix: macOS disable transparent 2022-06-01 01:04:46 +08:00
GyDi 359b82c29c chore: rm some files 2022-06-01 00:49:52 +08:00
GyDi b54171bc2c chore: rust cache 2022-06-01 00:47:04 +08:00
GyDi 936b2131e0 chore: adjust ci and script 2022-06-01 00:43:57 +08:00
GyDi aaef6a9e9c chore: enable meta by default 2022-06-01 00:31:12 +08:00
GyDi 9327006e61 chore: rm file 2022-05-30 00:58:48 +08:00
GyDi 5225c841ae chore: adjust code 2022-05-30 00:57:31 +08:00
GyDi 8464e319fd chore: update deps 2022-05-29 23:35:22 +08:00
GyDi 98b8bd90ea fix: window transparent and can not get hwnd 2022-05-25 19:06:06 +08:00
GyDi ae94993b09 fix: create main window 2022-05-25 16:45:18 +08:00
GyDi 72f10aaed1 chore: update deps 2022-05-25 16:12:48 +08:00
GyDi 4a74bae8c7 chore: update clash core 2022-05-25 16:08:58 +08:00
ctaoist 5164aec37b feat: light mode wip (#96)
* 关闭窗口释放UI资源

* windows 还有左键点击事件

* 兼容enhance profile

* bug 修复
2022-05-25 16:06:39 +08:00
GyDi 1581e9b1cd chore: update clash version 2022-05-18 14:14:37 +08:00
GyDi 536e3ffb11 chore: alpha ci 2022-05-18 14:07:41 +08:00
GyDi d6103191ba chore: error text 2022-05-18 09:58:20 +08:00
GyDi 49e37a19a5 chore: ci 2022-05-17 12:35:42 +08:00
GyDi d02431e260 chore: fix alpha ci 2022-05-17 12:34:30 +08:00
GyDi f24f6ead92 chore: alpha ci 2022-05-17 11:41:45 +08:00
GyDi b7bdb7ae50 chore: meta 2022-05-17 02:46:15 +08:00
GyDi 2dcf8ac96f chore: fix ci 2022-05-17 02:21:58 +08:00
GyDi 5421c94853 chore: test ci 2022-05-17 02:17:02 +08:00
GyDi 10f6bc092a chore: alpha 2022-05-17 02:11:29 +08:00
GyDi be9ea4ea8e feat: clash meta core supports 2022-05-17 01:59:49 +08:00
GyDi f5c6fa842a fix: adjust notice 2022-05-17 00:51:37 +08:00
GyDi e0943ce905 fix: label text 2022-05-16 20:26:13 +08:00
GyDi 61e7df77a7 feat: script mode 2022-05-16 20:18:56 +08:00
GyDi a5434360bc chore: test ci 2022-05-16 17:55:14 +08:00
GyDi ba29c66e3b chore: update deps 2022-05-16 17:54:21 +08:00
GyDi b3a72d55ae feat: clash meta core support (wip) 2022-05-16 01:52:50 +08:00
GyDi c382ad1cc8 fix: icon path 2022-05-13 12:28:36 +08:00
GyDi 363e28f323 fix: icon issue 2022-05-13 02:46:06 +08:00
GyDi d695656b8c fix: notice ui blocking 2022-05-13 02:29:43 +08:00
GyDi 31c6cbc0a2 fix: service mode error 2022-05-13 02:11:03 +08:00
GyDi b93284bc2f chore: fix linux build ci 2022-05-11 12:39:41 +08:00
GyDi 99c855b01b chore: test ci 2022-05-11 12:20:20 +08:00
GyDi c2eaedc959 chore: test ci 2022-05-11 12:12:55 +08:00
GyDi a631cd67ec chore: test ci fix deps 2022-05-11 11:30:19 +08:00
GyDi 66fccd3c68 chore: test ci 2022-05-11 11:22:09 +08:00
GyDi 9a4ebf4daa chore: test ci 2022-05-11 10:51:28 +08:00
GyDi 91c14211c6 chore: continue on error 2022-05-11 01:26:11 +08:00
GyDi 1ea07c458b chore: test linux 2022-05-11 00:52:20 +08:00
GyDi 591add6e0c chore: test ci 2022-05-11 00:31:19 +08:00
GyDi b99fff66df v1.0.1 2022-05-10 21:40:33 +08:00
GyDi f54ba05b00 chore: update log 2022-05-10 21:40:07 +08:00
GyDi 6596fb00c7 fix: win11 drag lag 2022-05-09 14:41:26 +08:00
GyDi df0b5a80dc chore: change default height 2022-05-09 14:01:46 +08:00
GyDi 8cdbb31dbe fix: rm unwrap 2022-05-09 14:01:14 +08:00
GyDi 0be4b1222d feat: reduce gpu usage when hidden 2022-05-07 14:43:52 +08:00
GyDi 18a6bfd73a feat: interval update from now field 2022-05-07 14:43:08 +08:00
GyDi 5e2271b237 feat: adjust theme 2022-05-06 14:04:39 +08:00
GyDi 798999d490 fix: edit profile info 2022-05-06 12:46:27 +08:00
GyDi 0e68c5e8bc feat: supports more remote headers close #81 2022-05-06 10:52:59 +08:00
GyDi 9694af82f4 feat: check the remote profile 2022-05-06 01:26:24 +08:00
GyDi 28a4386975 fix: change window default size 2022-05-06 01:15:15 +08:00
GyDi a238f7beba chore: update deps 2022-05-06 01:14:13 +08:00
GyDi 75ba16281b chore: change default user agent 2022-05-06 00:42:20 +08:00
GyDi ad65a278d4 chore: merge
feat: remove outdated config
2022-04-28 16:28:18 +08:00
tianyoulan a2320b3f8d feat: fix typo 2022-04-28 15:35:17 +08:00
tianyoulan ae12853ad0 feat: remove trailing comma 2022-04-28 15:05:10 +08:00
tianyoulan 68adf6dc2f feat: remove outdated config 2022-04-28 15:02:37 +08:00
GyDi f88989bd4b fix: change service installer and uninstaller 2022-04-27 15:46:44 +08:00
73 changed files with 3124 additions and 1790 deletions
+84
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 }}
+4 -2
View File
@@ -28,6 +28,8 @@ jobs:
- name: Rust Cache - name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72 uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
with:
working-directory: src-tauri
- name: Install Node - name: Install Node
uses: actions/setup-node@v1 uses: actions/setup-node@v1
@@ -38,7 +40,7 @@ jobs:
if: matrix.os == 'ubuntu-latest' if: matrix.os == 'ubuntu-latest'
run: | run: |
sudo apt-get update 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 - name: Get yarn cache dir path
id: yarn-cache-dir-path id: yarn-cache-dir-path
@@ -73,7 +75,7 @@ jobs:
releaseDraft: false releaseDraft: false
prerelease: true prerelease: true
- name: Green zip bundle - name: Portable Bundle
if: matrix.os == 'windows-latest' if: matrix.os == 'windows-latest'
run: | run: |
yarn run portable yarn run portable
+74
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
View File
@@ -4,3 +4,4 @@ dist
dist-ssr dist-ssr
*.local *.local
update.json update.json
scripts/_env.sh
+3 -1
View File
@@ -12,8 +12,9 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
## Features ## Features
- Full `clash` config supported, Partial `clash premium` config supported. - 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. - Simple UI and supports custom theme color.
- Built-in support [Clash.Meta](https://github.com/MetaCubeX/Clash.Meta) core.
- System proxy setting and guard. - System proxy setting and guard.
## Install ## 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. - [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. - [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. - [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! - [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
+54
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 ## v1.0.0
### Features ### Features
+29 -25
View File
@@ -1,14 +1,16 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "1.0.0", "version": "1.0.4",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "tauri dev", "dev": "tauri dev",
"dev:diff": "tauri dev -f verge-dev",
"build": "tauri build", "build": "tauri build",
"tauri": "tauri", "tauri": "tauri",
"web:dev": "vite", "web:dev": "vite",
"web:build": "tsc && vite build", "web:build": "tsc && vite build",
"web:serve": "vite preview", "web:serve": "vite preview",
"aarch": "node scripts/aarch.mjs",
"check": "node scripts/check.mjs", "check": "node scripts/check.mjs",
"updater": "node scripts/updater.mjs", "updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs", "publish": "node scripts/publish.mjs",
@@ -16,45 +18,47 @@
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.8.2", "@emotion/react": "^11.9.3",
"@emotion/styled": "^11.8.1", "@emotion/styled": "^11.9.3",
"@mui/icons-material": "^5.6.1", "@mui/icons-material": "^5.8.4",
"@mui/material": "^5.6.1", "@mui/material": "^5.9.0",
"@tauri-apps/api": "^1.0.0-rc.3", "@tauri-apps/api": "^1.0.2",
"ahooks": "^3.2.0", "ahooks": "^3.5.2",
"axios": "^0.26.0", "axios": "^0.27.2",
"dayjs": "^1.11.0", "dayjs": "^1.11.3",
"i18next": "^21.6.14", "i18next": "^21.8.12",
"monaco-editor": "^0.33.0", "monaco-editor": "^0.33.0",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"react-i18next": "^11.15.6", "react-i18next": "^11.17.4",
"react-router-dom": "^6.2.2", "react-router-dom": "^6.3.0",
"react-virtuoso": "~2.7.2", "react-virtuoso": "^2.16.1",
"recoil": "^0.6.1", "recoil": "^0.7.4",
"snarkdown": "^2.0.0", "snarkdown": "^2.0.0",
"swr": "^1.2.2" "swr": "^1.3.0"
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^5.0.0", "@actions/github": "^5.0.3",
"@tauri-apps/cli": "^1.0.0-rc.8", "@tauri-apps/cli": "^1.0.4",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1", "@types/js-cookie": "^3.0.2",
"@types/lodash": "^4.14.180", "@types/lodash": "^4.14.180",
"@types/react": "^17.0.0", "@types/react": "^17.0.0",
"@types/react-dom": "^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", "adm-zip": "^0.5.9",
"cross-env": "^7.0.3",
"fs-extra": "^10.0.0", "fs-extra": "^10.0.0",
"https-proxy-agent": "^5.0.1", "https-proxy-agent": "^5.0.1",
"husky": "^7.0.0", "husky": "^7.0.0",
"node-fetch": "^3.2.0", "node-fetch": "^3.2.6",
"prettier": "^2.6.2",
"pretty-quick": "^3.1.3", "pretty-quick": "^3.1.3",
"sass": "^1.49.7", "sass": "^1.53.0",
"typescript": "^4.5.5", "typescript": "^4.7.4",
"vite": "^2.8.6", "vite": "^2.9.13",
"vite-plugin-monaco-editor": "^1.0.10", "vite-plugin-monaco-editor": "^1.1.0",
"vite-plugin-svgr": "^1.1.0" "vite-plugin-svgr": "^2.2.0"
}, },
"prettier": { "prettier": {
"tabWidth": 2, "tabWidth": 2,
+104
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);
}
+141 -47
View File
@@ -10,6 +10,7 @@ const cwd = process.cwd();
const TEMP_DIR = path.join(cwd, "node_modules/.verge"); const TEMP_DIR = path.join(cwd, "node_modules/.verge");
const FORCE = process.argv.includes("--force"); const FORCE = process.argv.includes("--force");
const NO_META = process.argv.includes("--no-meta") || false;
/** /**
* get the correct clash release infomation * get the correct clash release infomation
@@ -19,7 +20,7 @@ function resolveClash() {
const CLASH_URL_PREFIX = const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/"; "https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.04.17"; const CLASH_LATEST_DATE = "2022.07.07";
// todo // todo
const map = { const map = {
@@ -44,55 +45,142 @@ function resolveClash() {
return { url, zip, exefile, zipfile }; 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 * get the sidecar bin
* clash and Clash Meta
*/ */
async function resolveSidecar() { async function resolveSidecar() {
const sidecarDir = path.join(cwd, "src-tauri", "sidecar"); 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 ext = process.platform === "win32" ? ".exe" : "";
const sidecarFile = `clash-${host}${ext}`;
const sidecarPath = path.join(sidecarDir, sidecarFile);
await fs.mkdirp(sidecarDir); await clash();
if (!FORCE && (await fs.pathExists(sidecarPath))) return; if (!NO_META) await clashMeta();
// download sidecar async function clash() {
const binInfo = resolveClash(); const sidecarFile = `clash-${host}${ext}`;
const tempDir = path.join(TEMP_DIR, "clash"); const sidecarPath = path.join(sidecarDir, sidecarFile);
const tempZip = path.join(tempDir, binInfo.zipfile);
const tempExe = path.join(tempDir, binInfo.exefile);
await fs.mkdirp(tempDir); await fs.mkdirp(sidecarDir);
if (!(await fs.pathExists(tempZip))) await downloadFile(binInfo.url, tempZip); if (!FORCE && (await fs.pathExists(sidecarPath))) return;
if (binInfo.zip === "zip") { // download sidecar
const zip = new AdmZip(tempZip); const binInfo = resolveClash();
zip.getEntries().forEach((entry) => { const tempDir = path.join(TEMP_DIR, "clash");
console.log("[INFO]: entry name", entry.entryName); const tempZip = path.join(tempDir, binInfo.zipfile);
}); const tempExe = path.join(tempDir, binInfo.exefile);
zip.extractAllTo(tempDir, true);
// save as sidecar await fs.mkdirp(tempDir);
await fs.rename(tempExe, sidecarPath); if (!(await fs.pathExists(tempZip)))
console.log(`[INFO]: unzip finished`); await downloadFile(binInfo.url, tempZip);
} else {
// gz if (binInfo.zip === "zip") {
const readStream = fs.createReadStream(tempZip); const zip = new AdmZip(tempZip);
const writeStream = fs.createWriteStream(sidecarPath); zip.getEntries().forEach((entry) => {
readStream console.log("[INFO]: entry name", entry.entryName);
.pipe(zlib.createGunzip()) });
.pipe(writeStream) zip.extractAllTo(tempDir, true);
.on("finish", () => { // save as sidecar
console.log(`[INFO]: gunzip finished`); await fs.rename(tempExe, sidecarPath);
execSync(`chmod 755 ${sidecarPath}`); console.log(`[INFO]: unzip finished`);
console.log(`[INFO]: chmod binary finished`); } else {
}) // gz
.on("error", (error) => console.error(error)); 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 async function clashMeta() {
await fs.remove(tempDir); 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; 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 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 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() { async function resolveMmdb() {
const url = 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 resDir = path.join(cwd, "src-tauri", "resources");
const resPath = path.join(resDir, "Country.mmdb"); const resPath = path.join(resDir, "Country.mmdb");
+54 -1
View File
@@ -4,6 +4,8 @@ import AdmZip from "adm-zip";
import { createRequire } from "module"; import { createRequire } from "module";
import { getOctokit, context } from "@actions/github"; import { getOctokit, context } from "@actions/github";
const META = process.argv.includes("--meta"); // use Clash.Meta
/// Script for ci /// Script for ci
/// 打包绿色版/便携版 (only Windows) /// 打包绿色版/便携版 (only Windows)
async function resolvePortable() { async function resolvePortable() {
@@ -19,6 +21,7 @@ async function resolvePortable() {
zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe")); zip.addLocalFile(path.join(releaseDir, "Clash Verge.exe"));
zip.addLocalFile(path.join(releaseDir, "clash.exe")); zip.addLocalFile(path.join(releaseDir, "clash.exe"));
zip.addLocalFile(path.join(releaseDir, "clash-meta.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources"); zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
const require = createRequire(import.meta.url); 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);
+10 -4
View File
@@ -53,12 +53,18 @@ async function resolveUpdater() {
const { name, browser_download_url } = asset; const { name, browser_download_url } = asset;
// win64 url // 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.win64.url = browser_download_url;
updateData.platforms["windows-x86_64"].url = browser_download_url; updateData.platforms["windows-x86_64"].url = browser_download_url;
} }
// win64 signature // 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); const sig = await getSignature(browser_download_url);
updateData.platforms.win64.signature = sig; updateData.platforms.win64.signature = sig;
updateData.platforms["windows-x86_64"].signature = sig; updateData.platforms["windows-x86_64"].signature = sig;
@@ -77,11 +83,11 @@ async function resolveUpdater() {
} }
// darwin url (aarch) // 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; updateData.platforms["darwin-aarch64"].url = browser_download_url;
} }
// darwin signature (aarch) // 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); const sig = await getSignature(browser_download_url);
updateData.platforms["darwin-aarch64"].signature = sig; updateData.platforms["darwin-aarch64"].signature = sig;
} }
+741 -819
View File
File diff suppressed because it is too large Load Diff
+14 -14
View File
@@ -10,37 +10,37 @@ edition = "2021"
build = "build.rs" build = "build.rs"
[build-dependencies] [build-dependencies]
tauri-build = { version = "1.0.0-rc.5", features = [] } tauri-build = { version = "1.0.0", features = [] }
[dependencies] [dependencies]
warp = "0.3"
which = "4.2.2"
anyhow = "1.0" anyhow = "1.0"
dirs = "4.0.0" dirs = "4.0.0"
open = "2.1.1" open = "2.1.1"
log = "0.4.14"
dunce = "1.0.2" dunce = "1.0.2"
log4rs = "1.0.0"
nanoid = "0.4.0" nanoid = "0.4.0"
chrono = "0.4.19" chrono = "0.4.19"
serde_json = "1.0" serde_json = "1.0"
serde_yaml = "0.8" 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" auto-launch = "0.2"
port_scanner = "0.1.5" 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] [target.'cfg(windows)'.dependencies]
runas = "0.2.1" runas = "0.2.1"
deelevate = "0.2.0" deelevate = "0.2.0"
winreg = { version = "0.10", features = ["transactions"] } winreg = { version = "0.10", features = ["transactions"] }
windows-sys = { version = "0.36", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
[features] [features]
default = ["custom-protocol"] 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

+19 -9
View File
@@ -178,8 +178,12 @@ pub fn get_clash_info(core: State<'_, Core>) -> CmdResult<ClashInfo> {
/// after putting the change to the clash core /// after putting the change to the clash core
/// then we should save the latest config /// then we should save the latest config
#[tauri::command] #[tauri::command]
pub fn patch_clash_config(payload: Mapping, core: State<'_, Core>) -> CmdResult { pub fn patch_clash_config(
wrap_err!(core.patch_clash(payload)) payload: Mapping,
app_handle: tauri::AppHandle,
core: State<'_, Core>,
) -> CmdResult {
wrap_err!(core.patch_clash(payload, &app_handle))
} }
/// get the verge config /// get the verge config
@@ -196,10 +200,16 @@ pub fn patch_verge_config(
payload: Verge, payload: Verge,
app_handle: tauri::AppHandle, app_handle: tauri::AppHandle,
core: State<'_, Core>, core: State<'_, Core>,
) -> Result<(), String> { ) -> CmdResult {
wrap_err!(core.patch_verge(payload, &app_handle)) 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 /// restart the sidecar
#[tauri::command] #[tauri::command]
pub fn restart_sidecar(core: State<'_, Core>) -> CmdResult { pub fn restart_sidecar(core: State<'_, Core>) -> CmdResult {
@@ -258,20 +268,20 @@ pub mod service {
#[tauri::command] #[tauri::command]
pub async fn check_service() -> Result<JsonResponse, String> { 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] #[tauri::command]
pub async fn install_service() -> Result<(), String> { pub async fn install_service() -> Result<(), String> {
log_if_err!(crate::core::Service::install_service().await); wrap_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
} }
#[tauri::command] #[tauri::command]
pub async fn uninstall_service() -> Result<(), String> { pub async fn uninstall_service() -> Result<(), String> {
log_if_err!(crate::core::Service::stop_service().await);
wrap_err!(crate::core::Service::uninstall_service().await) wrap_err!(crate::core::Service::uninstall_service().await)
} }
} }
+18 -11
View File
@@ -49,15 +49,16 @@ impl ClashInfo {
// `external-controller` could be // `external-controller` could be
// "127.0.0.1:9090" or ":9090" // "127.0.0.1:9090" or ":9090"
// "9090" or 9090 (clash do not support this)
let server = match config.get(&key_server) { let server = match config.get(&key_server) {
Some(value) => match value { Some(value) => {
Value::String(val_str) => match val_str.starts_with(":") { let val_str = value.as_str().unwrap_or("");
true => Some(format!("127.0.0.1{val_str}")),
false => Some(val_str.clone()), if val_str.starts_with(":") {
}, Some(format!("127.0.0.1{val_str}"))
_ => None, } else {
}, Some(val_str.into())
}
}
_ => None, _ => None,
}; };
@@ -112,20 +113,26 @@ impl Clash {
/// patch update the clash config /// patch update the clash config
/// if the port is changed then return true /// 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 port_key = Value::from("mixed-port");
let server_key = Value::from("external-controller"); let server_key = Value::from("external-controller");
let secret_key = Value::from("secret"); let secret_key = Value::from("secret");
let mode_key = Value::from("mode");
let mut change_port = false; let mut change_port = false;
let mut change_info = false; let mut change_info = false;
let mut change_mode = false;
for (key, value) in patch.into_iter() { for (key, value) in patch.into_iter() {
if key == port_key { if key == port_key {
change_port = true; 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; change_info = true;
} }
@@ -138,7 +145,7 @@ impl Clash {
self.save_config()?; self.save_config()?;
Ok(change_port) Ok((change_port, change_mode))
} }
/// revise the `tun` and `dns` config /// revise the `tun` and `dns` config
+119 -20
View File
@@ -3,10 +3,11 @@ use self::sysopt::Sysopt;
use self::timer::Timer; use self::timer::Timer;
use crate::core::enhance::PrfEnhancedResult; use crate::core::enhance::PrfEnhancedResult;
use crate::log_if_err; use crate::log_if_err;
use crate::utils::{dirs, help}; use crate::utils::help;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use parking_lot::Mutex; use parking_lot::Mutex;
use serde_yaml::Mapping; use serde_yaml::Mapping;
use serde_yaml::Value;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
use tauri::{AppHandle, Manager, Window}; use tauri::{AppHandle, Manager, Window};
@@ -28,6 +29,10 @@ pub use self::profiles::*;
pub use self::service::*; pub use self::service::*;
pub use self::verge::*; pub use self::verge::*;
/// close the window for slient start
/// after enhance mode
static mut WINDOW_CLOSABLE: bool = true;
#[derive(Clone)] #[derive(Clone)]
pub struct Core { pub struct Core {
pub clash: Arc<Mutex<Clash>>, pub clash: Arc<Mutex<Clash>>,
@@ -65,22 +70,21 @@ impl Core {
/// initialize the core state /// initialize the core state
pub fn init(&self, app_handle: tauri::AppHandle) { 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)] #[cfg(windows)]
{ {
let verge = self.verge.lock();
let enable = verge.enable_service_mode.clone(); let enable = verge.enable_service_mode.clone();
let mut service = self.service.lock();
service.set_mode(enable.unwrap_or(false)); service.set_mode(enable.unwrap_or(false));
log_if_err!(service.start());
} }
#[cfg(not(windows))] log_if_err!(service.start());
{ drop(verge);
let mut service = self.service.lock(); drop(service);
log_if_err!(service.start());
}
log_if_err!(self.activate()); log_if_err!(self.activate());
@@ -108,6 +112,7 @@ impl Core {
log_if_err!(sysopt.init_launch(auto_launch)); log_if_err!(sysopt.init_launch(auto_launch));
log_if_err!(self.update_systray(&app_handle)); log_if_err!(self.update_systray(&app_handle));
log_if_err!(self.update_systray_clash(&app_handle));
// wait the window setup during resolve app // wait the window setup during resolve app
let core = self.clone(); let core = self.clone();
@@ -138,17 +143,42 @@ impl Core {
self.activate_enhanced(true) 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 /// Patch Clash
/// handle the clash config changed /// handle the clash config changed
pub fn patch_clash(&self, patch: Mapping) -> Result<()> { pub fn patch_clash(&self, patch: Mapping, app_handle: &AppHandle) -> Result<()> {
let (changed, port) = { let ((changed_port, changed_mode), port) = {
let mut clash = self.clash.lock(); let mut clash = self.clash.lock();
(clash.patch_config(patch)?, clash.info.port.clone()) (clash.patch_config(patch)?, clash.info.port.clone())
}; };
// todo: port check // todo: port check
if changed { if changed_port {
let mut service = self.service.lock(); let mut service = self.service.lock();
service.restart()?; service.restart()?;
drop(service); drop(service);
@@ -161,6 +191,10 @@ impl Core {
sysopt.init_sysproxy(port, &verge); sysopt.init_sysproxy(port, &verge);
} }
if changed_mode {
self.update_systray_clash(app_handle)?;
}
Ok(()) Ok(())
} }
@@ -207,7 +241,7 @@ impl Core {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
if tun_mode.is_some() && *tun_mode.as_ref().unwrap_or(&false) { 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() { if !wintun_dll.exists() {
bail!("failed to enable TUN for missing `wintun.dll`"); bail!("failed to enable TUN for missing `wintun.dll`");
} }
@@ -229,7 +263,32 @@ impl Core {
Ok(()) 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<()> { pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
let verge = self.verge.lock(); let verge = self.verge.lock();
let tray = app_handle.tray_handle(); let tray = app_handle.tray_handle();
@@ -252,6 +311,33 @@ impl Core {
Ok(()) 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 /// activate the profile
/// auto activate enhanced profile /// auto activate enhanced profile
pub fn activate(&self) -> Result<()> { pub fn activate(&self) -> Result<()> {
@@ -332,7 +418,7 @@ impl Core {
let result = event.payload(); let result = event.payload();
if result.is_none() { if result.is_none() {
log::warn!("event payload result is none"); log::warn!(target: "app", "event payload result is none");
return; return;
} }
@@ -352,13 +438,26 @@ impl Core {
let service = service.lock(); let service = service.lock();
log_if_err!(service.set_config(info, config, notice)); 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(()) Ok(())
} }
+33 -6
View File
@@ -1,6 +1,7 @@
use crate::utils::{dirs, help, tmpl}; use crate::utils::{dirs, help, tmpl};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml::Mapping;
use std::fs; use std::fs;
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
@@ -15,13 +16,13 @@ pub struct PrfItem {
/// profile name /// profile name
pub name: Option<String>, pub name: Option<String>,
/// profile file
pub file: Option<String>,
/// profile description /// profile description
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub desc: Option<String>, pub desc: Option<String>,
/// profile file
pub file: Option<String>,
/// source url /// source url
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>, pub url: Option<String>,
@@ -155,7 +156,7 @@ impl PrfItem {
let desc = item.desc.unwrap_or("".into()); let desc = item.desc.unwrap_or("".into());
PrfItem::from_script(name, desc) 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.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 resp = builder.build()?.get(url).send().await?;
let header = resp.headers(); let header = resp.headers();
@@ -223,11 +224,37 @@ impl PrfItem {
None => None, 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 uid = help::get_uid("r");
let file = format!("{uid}.yaml"); 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?; 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 { Ok(PrfItem {
uid: Some(uid), uid: Some(uid),
itype: Some("remote".into()), itype: Some("remote".into()),
+123 -67
View File
@@ -3,12 +3,13 @@ use crate::log_if_err;
use crate::utils::{config, dirs}; use crate::utils::{config, dirs};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use reqwest::header::HeaderMap; use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use serde_yaml::Mapping; use serde_yaml::Mapping;
use std::{collections::HashMap, time::Duration}; use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent}; use tauri::api::process::{Command, CommandChild, CommandEvent};
use tokio::time::sleep; use tokio::time::sleep;
static mut CLASH_CORE: &str = "clash";
#[derive(Debug)] #[derive(Debug)]
pub struct Service { pub struct Service {
sidecar: Option<CommandChild>, 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)] #[allow(unused)]
pub fn set_mode(&mut self, enable: bool) { pub fn set_mode(&mut self, enable: bool) {
self.service_mode = enable; self.service_mode = enable;
@@ -46,12 +53,10 @@ impl Service {
Ok(status) => { Ok(status) => {
// 未启动clash // 未启动clash
if status.code != 0 { if status.code != 0 {
if let Err(err) = Self::start_clash_by_service().await { log_if_err!(Self::start_clash_by_service().await);
log::error!("{err}");
}
} }
} }
Err(err) => log::error!("{err}"), Err(err) => log::error!(target: "app", "{err}"),
} }
}); });
@@ -70,9 +75,7 @@ impl Service {
} }
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
if let Err(err) = Self::stop_clash_by_service().await { log_if_err!(Self::stop_clash_by_service().await);
log::error!("{err}");
}
}); });
Ok(()) Ok(())
@@ -92,7 +95,8 @@ impl Service {
let app_dir = dirs::app_home_dir(); let app_dir = dirs::app_home_dir();
let app_dir = app_dir.as_os_str().to_str().unwrap(); 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()?; let (mut rx, cmd_child) = cmd.args(["-d", app_dir]).spawn()?;
self.sidecar = Some(cmd_child); self.sidecar = Some(cmd_child);
@@ -101,8 +105,11 @@ impl Service {
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
while let Some(event) = rx.recv().await { while let Some(event) = rx.recv().await {
match event { match event {
CommandEvent::Stdout(line) => log::info!("[clash]: {}", line), CommandEvent::Stdout(line) => {
CommandEvent::Stderr(err) => log::error!("[clash]: {}", err), 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(); let temp_path = dirs::profiles_temp_path();
config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?; config::save_yaml(temp_path.clone(), &config, Some("# Clash Verge Temp File"))?;
if info.server.is_none() { let (server, headers) = Self::clash_client_info(info)?;
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);
}
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let mut data = HashMap::new(); let mut data = HashMap::new();
@@ -157,7 +151,7 @@ impl Service {
match builder.send().await { match builder.send().await {
Ok(resp) => { Ok(resp) => {
if resp.status() != 204 { 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(); notice.refresh_clash();
@@ -165,10 +159,10 @@ impl Service {
// do not retry // do not retry
break; 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; sleep(Duration::from_millis(500)).await;
} }
@@ -176,6 +170,52 @@ impl Service {
Ok(()) 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 { impl Drop for Service {
@@ -191,8 +231,10 @@ pub mod win_service {
use super::*; use super::*;
use anyhow::Context; use anyhow::Context;
use deelevate::{PrivilegeLevel, Token}; use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommond; use runas::Command as RunasCommand;
use std::{env::current_exe, process::Command as StdCommond}; 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"; const SERVICE_NAME: &str = "clash_verge_service";
@@ -217,61 +259,63 @@ pub mod win_service {
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程 /// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn install_service() -> Result<()> { pub async fn install_service() -> Result<()> {
let binary_path = dirs::service_path(); 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 token = Token::with_current_process()?;
let level = token.privilege_level()?; 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 { let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?, PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).status()?,
_ => StdCommond::new("sc").args(&args).status()?, _ => StdCommand::new(install_path)
.creation_flags(0x08000000)
.status()?,
}; };
if status.success() { if !status.success() {
return Ok(()); bail!(
"failed to install service with status {}",
status.code().unwrap()
);
} }
if status.code() == Some(1073i32) { Ok(())
bail!("clash verge service is installed");
}
bail!(
"failed to install service with status {}",
status.code().unwrap()
)
} }
/// Uninstall the Clash Verge Service /// Uninstall the Clash Verge Service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程 /// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn uninstall_service() -> Result<()> { 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 token = Token::with_current_process()?;
let level = token.privilege_level()?; let level = token.privilege_level()?;
let args = ["delete", SERVICE_NAME];
let status = match level { let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?, PrivilegeLevel::NotPrivileged => RunasCommand::new(uninstall_path).status()?,
_ => StdCommond::new("sc").args(&args).status()?, _ => StdCommand::new(uninstall_path)
.creation_flags(0x08000000)
.status()?,
}; };
match status.success() { if !status.success() {
true => Ok(()), bail!(
false => bail!(
"failed to uninstall service with status {}", "failed to uninstall service with status {}",
status.code().unwrap() status.code().unwrap()
), );
} }
Ok(())
} }
/// [deprecated]
/// start service /// start service
/// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程 /// 该函数应该在协程或者线程中执行,避免UAC弹窗阻塞主线程
pub async fn start_service() -> Result<()> { pub async fn start_service() -> Result<()> {
@@ -281,8 +325,8 @@ pub mod win_service {
let args = ["start", SERVICE_NAME]; let args = ["start", SERVICE_NAME];
let status = match level { let status = match level {
PrivilegeLevel::NotPrivileged => RunasCommond::new("sc").args(&args).status()?, PrivilegeLevel::NotPrivileged => RunasCommand::new("sc").args(&args).status()?,
_ => StdCommond::new("sc").args(&args).status()?, _ => StdCommand::new("sc").args(&args).status()?,
}; };
match status.success() { match status.success() {
@@ -297,7 +341,9 @@ pub mod win_service {
/// stop service /// stop service
pub async fn stop_service() -> Result<()> { pub async fn stop_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_service"); let url = format!("{SERVICE_URL}/stop_service");
let res = reqwest::Client::new() let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url) .post(url)
.send() .send()
.await? .await?
@@ -315,7 +361,11 @@ pub mod win_service {
/// check the windows service status /// check the windows service status
pub async fn check_service() -> Result<JsonResponse> { pub async fn check_service() -> Result<JsonResponse> {
let url = format!("{SERVICE_URL}/get_clash"); let url = format!("{SERVICE_URL}/get_clash");
let response = reqwest::get(url) let response = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.get(url)
.send()
.await? .await?
.json::<JsonResponse>() .json::<JsonResponse>()
.await .await
@@ -333,7 +383,9 @@ pub mod win_service {
sleep(Duration::from_secs(1)).await; 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 bin_path = bin_path.as_os_str().to_str().unwrap();
let config_dir = dirs::app_home_dir(); let config_dir = dirs::app_home_dir();
@@ -348,7 +400,9 @@ pub mod win_service {
map.insert("log_file", log_path); map.insert("log_file", log_path);
let url = format!("{SERVICE_URL}/start_clash"); let url = format!("{SERVICE_URL}/start_clash");
let res = reqwest::Client::new() let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url) .post(url)
.json(&map) .json(&map)
.send() .send()
@@ -367,7 +421,9 @@ pub mod win_service {
/// stop the clash by service /// stop the clash by service
pub(super) async fn stop_clash_by_service() -> Result<()> { pub(super) async fn stop_clash_by_service() -> Result<()> {
let url = format!("{SERVICE_URL}/stop_clash"); let url = format!("{SERVICE_URL}/stop_clash");
let res = reqwest::Client::new() let res = reqwest::ClientBuilder::new()
.no_proxy()
.build()?
.post(url) .post(url)
.send() .send()
.await? .await?
+4 -5
View File
@@ -2,7 +2,6 @@ use super::{Clash, Verge};
use crate::{log_if_err, utils::sysopt::SysProxyConfig}; use crate::{log_if_err, utils::sysopt::SysProxyConfig};
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use auto_launch::{AutoLaunch, AutoLaunchBuilder}; use auto_launch::{AutoLaunch, AutoLaunchBuilder};
// use parking_lot::Mutex;
use std::sync::Arc; use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe}; use tauri::{async_runtime::Mutex, utils::platform::current_exe};
@@ -46,7 +45,7 @@ impl Sysopt {
if enable { if enable {
if let Err(err) = sysproxy.set_sys() { 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() { if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() { match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None, 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; break;
} }
log::debug!("try to guard the system proxy"); log::debug!(target: "app", "try to guard the system proxy");
let clash = Clash::new(); let clash = Clash::new();
@@ -194,7 +193,7 @@ impl Sysopt {
log_if_err!(sysproxy.set_sys()); log_if_err!(sysproxy.set_sys());
} }
None => log::error!("failed to parse clash port"), None => log::error!(target: "app", "failed to parse clash port"),
} }
} }
+1 -1
View File
@@ -139,7 +139,7 @@ impl Timer {
/// the task runner /// the task runner
async fn async_task(core: Core, uid: String) { 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); log_if_err!(Core::update_profile_item(core, uid, None).await);
} }
} }
+7
View File
@@ -45,6 +45,10 @@ pub struct Verge {
/// theme setting /// theme setting
pub theme_setting: Option<VergeTheme>, 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)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -96,6 +100,9 @@ impl Verge {
if patch.traffic_graph.is_some() { if patch.traffic_graph.is_some() {
self.traffic_graph = patch.traffic_graph; self.traffic_graph = patch.traffic_graph;
} }
if patch.clash_core.is_some() {
self.clash_core = patch.clash_core;
}
// system setting // system setting
if patch.enable_silent_start.is_some() { if patch.enable_silent_start.is_some() {
+18 -22
View File
@@ -30,6 +30,12 @@ fn main() -> std::io::Result<()> {
let tray_menu = SystemTrayMenu::new() let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show")) .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("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode")) .add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash")) .add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
@@ -38,16 +44,17 @@ fn main() -> std::io::Result<()> {
#[allow(unused_mut)] #[allow(unused_mut)]
let mut builder = tauri::Builder::default() let mut builder = tauri::Builder::default()
.manage(core::Core::new())
.setup(|app| Ok(resolve::resolve_setup(app))) .setup(|app| Ok(resolve::resolve_setup(app)))
.system_tray(SystemTray::new().with_menu(tray_menu)) .system_tray(SystemTray::new().with_menu(tray_menu))
.on_system_tray_event(move |app_handle, event| match event { .on_system_tray_event(move |app_handle, event| match event {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() { SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"open_window" => { "open_window" => {
let window = app_handle.get_window("main").unwrap(); resolve::create_window(app_handle);
window.unminimize().unwrap(); }
window.show().unwrap(); mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => {
window.set_focus().unwrap(); 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" => { "system_proxy" => {
let core = app_handle.state::<core::Core>(); let core = app_handle.state::<core::Core>();
@@ -91,24 +98,22 @@ fn main() -> std::io::Result<()> {
}, },
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
SystemTrayEvent::LeftClick { .. } => { SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap(); resolve::create_window(app_handle);
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
} }
_ => {} _ => {}
}) })
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
// common // common
cmds::restart_sidecar,
cmds::get_sys_proxy, cmds::get_sys_proxy,
cmds::get_cur_proxy, cmds::get_cur_proxy,
cmds::kill_sidecar,
cmds::open_app_dir, cmds::open_app_dir,
cmds::open_logs_dir, cmds::open_logs_dir,
cmds::kill_sidecar,
cmds::restart_sidecar,
// clash // clash
cmds::get_clash_info, cmds::get_clash_info,
cmds::patch_clash_config, cmds::patch_clash_config,
cmds::change_clash_core,
// verge // verge
cmds::get_verge_config, cmds::get_verge_config,
cmds::patch_verge_config, cmds::patch_verge_config,
@@ -155,17 +160,8 @@ fn main() -> std::io::Result<()> {
.build(tauri::generate_context!()) .build(tauri::generate_context!())
.expect("error while running tauri application") .expect("error while running tauri application")
.run(|app_handle, e| match e { .run(|app_handle, e| match e {
tauri::RunEvent::WindowEvent { label, event, .. } => match event { tauri::RunEvent::ExitRequested { api, .. } => {
tauri::WindowEvent::CloseRequested { api, .. } => { api.prevent_exit();
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::Exit => { tauri::RunEvent::Exit => {
resolve::resolve_reset(app_handle); resolve::resolve_reset(app_handle);
+14 -2
View File
@@ -4,8 +4,20 @@ use std::{fs, path::PathBuf};
/// read data from yaml as struct T /// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T { pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
let yaml_str = fs::read_to_string(path).unwrap_or("".into()); if !path.exists() {
serde_yaml::from_str::<T>(&yaml_str).unwrap_or(T::default()) 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 /// save the data to the file
+2 -2
View File
@@ -80,7 +80,7 @@ pub fn open_file(path: PathBuf) -> Result<()> {
macro_rules! log_if_err { macro_rules! log_if_err {
($result: expr) => { ($result: expr) => {
if let Err(err) = $result { if let Err(err) = $result {
log::error!("{err}"); log::error!(target: "app", "{err}");
} }
}; };
} }
@@ -93,7 +93,7 @@ macro_rules! wrap_err {
match $stat { match $stat {
Ok(a) => Ok(a), Ok(a) => Ok(a),
Err(err) => { Err(err) => {
log::error!("{}", err.to_string()); log::error!(target: "app", "{}", err.to_string());
Err(format!("{}", err.to_string())) Err(format!("{}", err.to_string()))
} }
} }
+8 -6
View File
@@ -3,7 +3,7 @@ use chrono::Local;
use log::LevelFilter; use log::LevelFilter;
use log4rs::append::console::ConsoleAppender; use log4rs::append::console::ConsoleAppender;
use log4rs::append::file::FileAppender; use log4rs::append::file::FileAppender;
use log4rs::config::{Appender, Config, Root}; use log4rs::config::{Appender, Config, Logger, Root};
use log4rs::encode::pattern::PatternEncoder; use log4rs::encode::pattern::PatternEncoder;
use std::fs; use std::fs;
use std::io::Write; use std::io::Write;
@@ -28,11 +28,13 @@ fn init_log(log_dir: &PathBuf) {
let config = Config::builder() let config = Config::builder()
.appender(Appender::builder().build("stdout", Box::new(stdout))) .appender(Appender::builder().build("stdout", Box::new(stdout)))
.appender(Appender::builder().build("file", Box::new(tofile))) .appender(Appender::builder().build("file", Box::new(tofile)))
.build( .logger(
Root::builder() Logger::builder()
.appenders(["stdout", "file"]) .appenders(["file", "stdout"])
.build(LevelFilter::Info), .additive(false)
.build("app", LevelFilter::Info),
) )
.build(Root::builder().appender("stdout").build(LevelFilter::Info))
.unwrap(); .unwrap();
log4rs::init_config(config).unwrap(); log4rs::init_config(config).unwrap();
@@ -78,7 +80,7 @@ pub fn init_app(package_info: &PackageInfo) {
init_log(&log_dir); init_log(&log_dir);
if let Err(err) = init_config(&app_dir) { if let Err(err) = init_config(&app_dir) {
log::error!("{err}"); log::error!(target: "app", "{err}");
} }
// copy the resource file // copy the resource file
+1
View File
@@ -6,3 +6,4 @@ pub mod resolve;
pub mod server; pub mod server;
pub mod sysopt; pub mod sysopt;
pub mod tmpl; pub mod tmpl;
mod winhelp;
+81 -15
View File
@@ -9,12 +9,16 @@ pub fn resolve_setup(app: &App) {
// init app config // init app config
init::init_app(app.package_info()); init::init_app(app.package_info());
// init states // init core
let core = app.state::<Core>(); // should be initialized after init_app fix #122
let core = Core::new();
core.set_win(app.get_window("main")); core.set_win(app.get_window("main"));
core.init(app.app_handle()); core.init(app.app_handle());
// fix #122
app.manage(core);
resolve_window(app); resolve_window(app);
} }
@@ -35,27 +39,89 @@ fn resolve_window(app: &App) {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
use crate::utils::winhelp;
use window_shadows::set_shadow; use window_shadows::set_shadow;
use window_vibrancy::apply_blur; use window_vibrancy::apply_blur;
window.set_decorations(false).unwrap(); let _ = window.set_decorations(false);
set_shadow(&window, true).unwrap(); let _ = set_shadow(&window, true);
apply_blur(&window, None).unwrap();
// todo
// win11 disable this feature temporarily due to lag
if !winhelp::is_win11() {
let _ = apply_blur(&window, None);
}
} }
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
{ {
use tauri::LogicalSize; use tauri::LogicalSize;
use tauri::Size::Logical; use tauri::Size::Logical;
window.set_decorations(true).unwrap();
window let _ = window.set_decorations(true);
.set_size(Logical(LogicalSize { let _ = window.set_size(Logical(LogicalSize {
width: 800.0, width: 800.0,
height: 610.0, height: 620.0,
})) }));
.unwrap();
// use tauri_plugin_vibrancy::MacOSVibrancy;
// #[allow(deprecated)]
// window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
} }
} }
/// 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());
}
+69
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());
}
+19 -10
View File
@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "Clash Verge", "productName": "Clash Verge",
"version": "1.0.0" "version": "1.0.4"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -11,7 +11,7 @@
}, },
"tauri": { "tauri": {
"systemTray": { "systemTray": {
"iconPath": "icons/icon.png", "iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true "iconAsTemplate": true
}, },
"bundle": { "bundle": {
@@ -22,23 +22,26 @@
"icons/32x32.png", "icons/32x32.png",
"icons/128x128.png", "icons/128x128.png",
"icons/128x128@2x.png", "icons/128x128@2x.png",
"icons/icon.icns", "icons/icon-new.icns",
"icons/icon.ico" "icons/icon.ico"
], ],
"resources": ["resources"], "resources": [
"externalBin": ["sidecar/clash"], "resources"
],
"externalBin": [
"sidecar/clash",
"sidecar/clash-meta"
],
"copyright": "© 2022 zzzgydi All Rights Reserved", "copyright": "© 2022 zzzgydi All Rights Reserved",
"category": "DeveloperTool", "category": "DeveloperTool",
"shortDescription": "A Clash GUI based on tauri.", "shortDescription": "A Clash GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.", "longDescription": "A Clash GUI based on tauri.",
"deb": { "deb": {
"depends": [], "depends": []
"useBootstrapper": false
}, },
"macOS": { "macOS": {
"frameworks": [], "frameworks": [],
"minimumSystemVersion": "", "minimumSystemVersion": "",
"useBootstrapper": false,
"exceptionDomain": "", "exceptionDomain": "",
"signingIdentity": null, "signingIdentity": null,
"entitlements": null "entitlements": null
@@ -46,7 +49,13 @@
"windows": { "windows": {
"certificateThumbprint": null, "certificateThumbprint": null,
"digestAlgorithm": "sha256", "digestAlgorithm": "sha256",
"timestampUrl": "" "timestampUrl": "",
"wix": {
"language": [
"zh-CN",
"en-US"
]
}
} }
}, },
"updater": { "updater": {
@@ -73,7 +82,7 @@
{ {
"title": "Clash Verge", "title": "Clash Verge",
"width": 800, "width": 800,
"height": 600, "height": 636,
"resizable": true, "resizable": true,
"fullscreen": false, "fullscreen": false,
"decorations": false, "decorations": false,
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

+2 -1
View File
@@ -11,6 +11,7 @@ body {
--primary-main: #5b5c9d; --primary-main: #5b5c9d;
--text-primary: #637381; --text-primary: #637381;
--selection-color: #f5f5f5; --selection-color: #f5f5f5;
--scroller-color: #90939980;
} }
::selection { ::selection {
@@ -25,7 +26,7 @@ body {
} }
*::-webkit-scrollbar-thumb { *::-webkit-scrollbar-thumb {
border-radius: 6px; border-radius: 6px;
background-color: rgba(#909399, 0.5); background-color: var(--scroller-color);
} }
@import "./layout.scss"; @import "./layout.scss";
+5 -5
View File
@@ -10,7 +10,7 @@
height: 100%; height: 100%;
max-width: 225px; max-width: 225px;
min-width: 125px; min-width: 125px;
padding: 8px 0; padding: 16px 0 8px;
flex-direction: column; flex-direction: column;
box-sizing: border-box; box-sizing: border-box;
user-select: none; user-select: none;
@@ -23,14 +23,14 @@
max-width: 168px; max-width: 168px;
max-height: 168px; max-height: 168px;
margin: 0 auto; margin: 0 auto;
padding: 0 8px; padding: 0 16px;
text-align: center; text-align: center;
box-sizing: border-box; box-sizing: border-box;
img, img,
svg { svg {
width: 100%; width: 96%;
height: 100%; height: 96%;
pointer-events: none; pointer-events: none;
} }
@@ -43,7 +43,7 @@
} }
.the-menu { .the-menu {
flex: 1 1 75%; flex: 1 1 80%;
overflow-y: auto; overflow-y: auto;
margin-bottom: 8px; margin-bottom: 8px;
} }
+8 -5
View File
@@ -11,7 +11,7 @@ interface InnerProps {
} }
const NoticeInner = (props: 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 [visible, setVisible] = useState(true);
const onBtnClose = () => { const onBtnClose = () => {
@@ -26,12 +26,13 @@ const NoticeInner = (props: InnerProps) => {
type === "info" ? ( type === "info" ? (
message message
) : ( ) : (
<Box sx={{ display: "flex", alignItems: "center" }}> <Box sx={{ width: 328, display: "flex", alignItems: "center" }}>
{type === "error" && <ErrorRounded color="error" />} {type === "error" && <ErrorRounded color="error" />}
{type === "success" && <CheckCircleRounded color="success" />} {type === "success" && <CheckCircleRounded color="success" />}
<Typography <Typography
sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }} component="span"
sx={{ ml: 1, wordWrap: "break-word", width: "calc(100% - 35px)" }}
> >
{message} {message}
</Typography> </Typography>
@@ -79,14 +80,16 @@ const Notice: NoticeInstance = (props) => {
const onUnmount = () => { const onUnmount = () => {
const result = ReactDOM.unmountComponentAtNode(container); 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); ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
}; };
(["info", "error", "success"] as const).forEach((type) => { (["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; export default Notice;
+1 -1
View File
@@ -30,7 +30,7 @@ const LayoutControl = () => {
<Button <Button
size="small" size="small"
sx={{ minWidth, svg: { transform: "scale(1.05)" } }} sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
onClick={() => appWindow.hide()} onClick={() => appWindow.close()}
> >
<CloseRounded fontSize="small" /> <CloseRounded fontSize="small" />
</Button> </Button>
+2 -2
View File
@@ -5,7 +5,7 @@ import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material"; import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api"; import { getInformation } from "../../services/api";
import { getVergeConfig } from "../../services/cmds"; import { getVergeConfig } from "../../services/cmds";
import { atomClashPort } from "../../services/states"; import { atomClashPort } from "../../services/states";
import TrafficGraph from "./traffic-graph"; import TrafficGraph from "./traffic-graph";
@@ -41,7 +41,7 @@ const LayoutTraffic = () => {
useEffect(() => { useEffect(() => {
let ws: WebSocket | null = null; let ws: WebSocket | null = null;
getInfomation().then((result) => { getInformation().then((result) => {
const { server = "", secret = "" } = result; const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/traffic?token=${secret}`); ws = new WebSocket(`ws://${server}/traffic?token=${secret}`);
+25 -2
View File
@@ -1,5 +1,7 @@
import { useEffect, useRef } from "react"; import { useEffect, useRef, useState } from "react";
import { useTheme } from "@mui/material"; import { useTheme } from "@mui/material";
import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";
const maxPoint = 30; const maxPoint = 30;
@@ -70,7 +72,28 @@ const TrafficGraph = (props: Props) => {
}; };
}, []); }, []);
// reduce the GPU usage when hidden
const [enablePaint, setEnablePaint] = useState(true);
useEffect(() => { 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; let raf = 0;
const canvas = canvasRef.current!; const canvas = canvasRef.current!;
@@ -193,7 +216,7 @@ const TrafficGraph = (props: Props) => {
return () => { return () => {
cancelAnimationFrame(raf); cancelAnimationFrame(raf);
}; };
}, [palette]); }, [enablePaint, palette]);
return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />; return <canvas ref={canvasRef} style={{ width: "100%", height: "100%" }} />;
}; };
+32 -11
View File
@@ -1,8 +1,11 @@
import useSWR from "swr"; import useSWR from "swr";
import { useMemo } from "react"; import { useEffect, useMemo } from "react";
import { useRecoilState } from "recoil";
import { createTheme } from "@mui/material"; import { createTheme } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window";
import { getVergeConfig } from "../../services/cmds"; 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 * custome theme
@@ -10,17 +13,25 @@ import { defaultTheme as dt } from "../../pages/_theme";
export default function useCustomTheme() { export default function useCustomTheme() {
const { data } = useSWR("getVergeConfig", getVergeConfig); const { data } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode, theme_setting } = data ?? {}; 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 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 setting = theme_setting || {};
const dt = mode === "light" ? defaultTheme : defaultDarkTheme;
const theme = createTheme({ const theme = createTheme({
breakpoints: { 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 // inject css
let style = document.querySelector("style#verge-theme"); let style = document.querySelector("style#verge-theme");
if (!style) { if (!style) {
@@ -73,7 +94,7 @@ export default function useCustomTheme() {
}, 0); }, 0);
return theme; return theme;
}, [theme_mode, theme_setting]); }, [mode, theme_setting]);
return { theme }; return { theme };
} }
+2 -2
View File
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { getInfomation } from "../../services/api"; import { getInformation } from "../../services/api";
import { atomLogData } from "../../services/states"; import { atomLogData } from "../../services/states";
const MAX_LOG_NUM = 1000; const MAX_LOG_NUM = 1000;
@@ -25,7 +25,7 @@ export default function useLogSetup() {
}); });
}; };
getInfomation().then((info) => { getInformation().then((info) => {
const { server = "", secret = "" } = info; const { server = "", secret = "" } = info;
ws = new WebSocket(`ws://${server}/logs?token=${secret}`); ws = new WebSocket(`ws://${server}/logs?token=${secret}`);
ws.addEventListener("message", handler); ws.addEventListener("message", handler);
+1 -7
View File
@@ -26,7 +26,6 @@ import {
changeProfileValid, changeProfileValid,
} from "../../services/cmds"; } from "../../services/cmds";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import getSystem from "../../utils/get-system";
import ProfileMore from "./profile-more"; import ProfileMore from "./profile-more";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
@@ -35,8 +34,6 @@ interface Props {
chain: string[]; chain: string[];
} }
const OS = getSystem();
const EnhancedMode = (props: Props) => { const EnhancedMode = (props: Props) => {
const { items, chain } = props; const { items, chain } = props;
@@ -49,7 +46,7 @@ const EnhancedMode = (props: Props) => {
const onEnhance = useLockFn(async () => { const onEnhance = useLockFn(async () => {
try { try {
await enhanceProfiles(); await enhanceProfiles();
Notice.success("Refresh clash config", 2000); Notice.success("Refresh clash config", 1000);
} catch (err: any) { } catch (err: any) {
Notice.error(err.message || err.toString()); Notice.error(err.message || err.toString());
} }
@@ -147,9 +144,6 @@ const EnhancedMode = (props: Props) => {
anchorEl={anchorEl} anchorEl={anchorEl}
onClose={() => setAnchorEl(null)} onClose={() => setAnchorEl(null)}
transitionDuration={225} transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
MenuListProps={{ MenuListProps={{
dense: true, dense: true,
"aria-labelledby": "profile-use-button", "aria-labelledby": "profile-use-button",
+5 -9
View File
@@ -1,6 +1,6 @@
import useSWR from "swr";
import { useEffect, useRef } from "react"; import { useEffect, useRef } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useRecoilValue } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
Button, Button,
@@ -9,11 +9,8 @@ import {
DialogContent, DialogContent,
DialogTitle, DialogTitle,
} from "@mui/material"; } from "@mui/material";
import { import { atomThemeMode } from "../../services/states";
getVergeConfig, import { readProfileFile, saveProfileFile } from "../../services/cmds";
readProfileFile,
saveProfileFile,
} from "../../services/cmds";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js"; import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
@@ -35,8 +32,7 @@ const FileEditor = (props: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const editorRef = useRef<any>(); const editorRef = useRef<any>();
const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null); const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const themeMode = useRecoilValue(atomThemeMode);
const { theme_mode } = vergeConfig ?? {};
useEffect(() => { useEffect(() => {
if (!open) return; if (!open) return;
@@ -50,7 +46,7 @@ const FileEditor = (props: Props) => {
instanceRef.current = editor.create(editorRef.current, { instanceRef.current = editor.create(editorRef.current, {
value: data, value: data,
language: mode, language: mode,
theme: theme_mode === "light" ? "vs" : "vs-dark", theme: themeMode === "light" ? "vs" : "vs-dark",
minimap: { enabled: false }, minimap: { enabled: false },
}); });
}); });
+34 -24
View File
@@ -1,6 +1,7 @@
import { mutate } from "swr"; import { mutate } from "swr";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useLockFn, useSetState } from "ahooks"; import { useLockFn, useSetState } from "ahooks";
import { useTranslation } from "react-i18next";
import { import {
Button, Button,
Dialog, Dialog,
@@ -25,6 +26,8 @@ interface Props {
// remote / local file / merge / script // remote / local file / merge / script
const ProfileEdit = (props: Props) => { const ProfileEdit = (props: Props) => {
const { open, itemData, onClose } = props; const { open, itemData, onClose } = props;
const { t } = useTranslation();
const [form, setForm] = useSetState({ ...itemData }); const [form, setForm] = useSetState({ ...itemData });
const [option, setOption] = useSetState(itemData.option ?? {}); const [option, setOption] = useSetState(itemData.option ?? {});
const [showOpt, setShowOpt] = useState(!!itemData.option); const [showOpt, setShowOpt] = useState(!!itemData.option);
@@ -33,7 +36,10 @@ const ProfileEdit = (props: Props) => {
if (itemData) { if (itemData) {
setForm({ ...itemData }); setForm({ ...itemData });
setOption(itemData.option ?? {}); setOption(itemData.option ?? {});
setShowOpt(!!itemData.option?.user_agent); setShowOpt(
itemData.type === "remote" &&
(!!itemData.option?.user_agent || !!itemData.option?.update_interval)
);
} }
}, [itemData]); }, [itemData]);
@@ -41,7 +47,10 @@ const ProfileEdit = (props: Props) => {
try { try {
const { uid } = itemData; const { uid } = itemData;
const { name, desc, url } = form; 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) { if (itemData.type === "remote" && !url) {
throw new Error("Remote URL should not be null"); throw new Error("Remote URL should not be null");
@@ -65,11 +74,11 @@ const ProfileEdit = (props: Props) => {
const type = const type =
form.type || form.type ||
(form.url ? "remote" : form.file?.endsWith("js") ? "script" : "local"); (form.url ? "remote" : form.file?.endsWith(".js") ? "script" : "local");
return ( return (
<Dialog open={open} onClose={onClose}> <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 }}> <DialogContent sx={{ width: 336, pb: 1 }}>
<TextField <TextField
@@ -100,7 +109,7 @@ const ProfileEdit = (props: Props) => {
{type === "remote" && ( {type === "remote" && (
<TextField <TextField
{...textFieldProps} {...textFieldProps}
label="Subscription Url" label="Subscription URL"
value={form.url} value={form.url}
onChange={(e) => setForm({ url: e.target.value })} onChange={(e) => setForm({ url: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()} onKeyDown={(e) => e.key === "Enter" && onUpdate()}
@@ -108,26 +117,27 @@ const ProfileEdit = (props: Props) => {
)} )}
{showOpt && ( {showOpt && (
<> <TextField
<TextField {...textFieldProps}
{...textFieldProps} label="User Agent"
label="User Agent" value={option.user_agent}
value={option.user_agent} placeholder="clash-verge/v1.0.0"
onChange={(e) => setOption({ user_agent: e.target.value })} onChange={(e) => setOption({ user_agent: e.target.value })}
onKeyDown={(e) => e.key === "Enter" && onUpdate()} onKeyDown={(e) => e.key === "Enter" && onUpdate()}
/> />
)}
<TextField {((type === "remote" && showOpt) || type === "local") && (
{...textFieldProps} <TextField
label="Update Interval (mins)" {...textFieldProps}
value={option.update_interval} label="Update Interval (mins)"
onChange={(e) => { value={option.update_interval}
const str = e.target.value?.replace(/\D/, ""); onChange={(e) => {
setOption({ update_interval: str != null ? +str : str }); const str = e.target.value?.replace(/\D/, "");
}} setOption({ update_interval: str != null ? +str : str });
onKeyDown={(e) => e.key === "Enter" && onUpdate()} }}
/> onKeyDown={(e) => e.key === "Enter" && onUpdate()}
</> />
)} )}
</DialogContent> </DialogContent>
+42 -16
View File
@@ -1,5 +1,5 @@
import dayjs from "dayjs"; import dayjs from "dayjs";
import { useState } from "react"; import { useEffect, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
@@ -20,7 +20,6 @@ import { CmdType } from "../../services/types";
import { atomLoadingCache } from "../../services/states"; import { atomLoadingCache } from "../../services/states";
import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds"; import { updateProfile, deleteProfile, viewProfile } from "../../services/cmds";
import parseTraffic from "../../utils/parse-traffic"; import parseTraffic from "../../utils/parse-traffic";
import getSystem from "../../utils/get-system";
import ProfileEdit from "./profile-edit"; import ProfileEdit from "./profile-edit";
import FileEditor from "./file-editor"; import FileEditor from "./file-editor";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
@@ -41,8 +40,6 @@ const round = keyframes`
to { transform: rotate(360deg); } to { transform: rotate(360deg); }
`; `;
const OS = getSystem();
interface Props { interface Props {
selected: boolean; selected: boolean;
itemData: CmdType.ProfileItem; itemData: CmdType.ProfileItem;
@@ -59,11 +56,6 @@ const ProfileItem = (props: Props) => {
const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache); const [loadingCache, setLoadingCache] = useRecoilState(atomLoadingCache);
const { uid, name = "Profile", extra, updated = 0 } = itemData; 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 // local file mode
// remote file mode // remote file mode
@@ -71,8 +63,42 @@ const ProfileItem = (props: Props) => {
const hasUrl = !!itemData.url; const hasUrl = !!itemData.url;
const hasExtra = !!extra; // only subscription url has extra info 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; 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 [editOpen, setEditOpen] = useState(false);
const [fileOpen, setFileOpen] = useState(false); const [fileOpen, setFileOpen] = useState(false);
@@ -108,7 +134,10 @@ const ProfileItem = (props: Props) => {
await updateProfile(itemData.uid, { with_proxy: withProxy }); await updateProfile(itemData.uid, { with_proxy: withProxy });
mutate("getProfiles"); mutate("getProfiles");
} catch (err: any) { } 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 { } finally {
setLoadingCache((cache) => ({ ...cache, [itemData.uid]: false })); setLoadingCache((cache) => ({ ...cache, [itemData.uid]: false }));
} }
@@ -165,8 +194,8 @@ const ProfileItem = (props: Props) => {
const color = { const color = {
"light-true": text.secondary, "light-true": text.secondary,
"light-false": text.secondary, "light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6), "dark-true": alpha(text.secondary, 0.75),
"dark-false": alpha(text.secondary, 0.6), "dark-false": alpha(text.secondary, 0.75),
}[key]!; }[key]!;
const h2color = { const h2color = {
@@ -231,7 +260,7 @@ const ProfileItem = (props: Props) => {
textAlign="right" textAlign="right"
title="updated time" title="updated time"
> >
{fromnow} {updated > 0 ? dayjs(updated * 1000).fromNow() : ""}
</Typography> </Typography>
</Box> </Box>
) : ( ) : (
@@ -270,9 +299,6 @@ const ProfileItem = (props: Props) => {
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
transitionDuration={225} transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => { onContextMenu={(e) => {
setAnchorEl(null); setAnchorEl(null);
e.preventDefault(); e.preventDefault();
-6
View File
@@ -13,7 +13,6 @@ import {
} from "@mui/material"; } from "@mui/material";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { viewProfile } from "../../services/cmds"; import { viewProfile } from "../../services/cmds";
import getSystem from "../../utils/get-system";
import enhance from "../../services/enhance"; import enhance from "../../services/enhance";
import ProfileEdit from "./profile-edit"; import ProfileEdit from "./profile-edit";
import FileEditor from "./file-editor"; import FileEditor from "./file-editor";
@@ -30,8 +29,6 @@ const Wrapper = styled(Box)(({ theme }) => ({
boxSizing: "border-box", boxSizing: "border-box",
})); }));
const OS = getSystem();
interface Props { interface Props {
selected: boolean; selected: boolean;
itemData: CmdType.ProfileItem; itemData: CmdType.ProfileItem;
@@ -223,9 +220,6 @@ const ProfileMore = (props: Props) => {
anchorPosition={position} anchorPosition={position}
anchorReference="anchorPosition" anchorReference="anchorPosition"
transitionDuration={225} transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
onContextMenu={(e) => { onContextMenu={(e) => {
setAnchorEl(null); setAnchorEl(null);
e.preventDefault(); e.preventDefault();
+16 -13
View File
@@ -5,7 +5,8 @@ import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds"; 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 useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay"; import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head"; import ProxyHead from "./proxy-head";
@@ -24,13 +25,19 @@ const ProxyGlobal = (props: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT"); const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true); const [headState, setHeadState] = useHeadState(groupName);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>(); const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText); const filterProxies = useFilterProxy(
const sortedProxies = useSortProxy(filterProxies, groupName, sortType); proxies,
groupName,
headState.filterText
);
const sortedProxies = useSortProxy(
filterProxies,
groupName,
headState.sortType
);
const { data: profiles } = useSWR("getProfiles", getProfiles); const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -102,15 +109,11 @@ const ProxyGlobal = (props: Props) => {
<> <>
<ProxyHead <ProxyHead
sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }} sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={groupName} groupName={groupName}
filterText={filterText} headState={headState}
onLocation={onLocation} onLocation={onLocation}
onCheckDelay={onCheckAll} onCheckDelay={onCheckAll}
onShowType={setShowType} onHeadState={setHeadState}
onSortType={setSortType}
onFilterText={setFilterText}
/> />
<Virtuoso <Virtuoso
@@ -122,7 +125,7 @@ const ProxyGlobal = (props: Props) => {
groupName={groupName} groupName={groupName}
proxy={sortedProxies[index]} proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now} selected={sortedProxies[index].name === now}
showType={showType} showType={headState.showType}
onClick={onChangeProxy} onClick={onChangeProxy}
sx={{ py: 0, px: 2 }} sx={{ py: 0, px: 2 }}
/> />
+26 -20
View File
@@ -18,7 +18,8 @@ import {
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds"; 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 useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay"; import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head"; import ProxyHead from "./proxy-head";
@@ -30,16 +31,21 @@ interface Props {
const ProxyGroup = ({ group }: Props) => { const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now); const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false); const [headState, setHeadState] = useHeadState(group.name);
const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>(); const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(group.all, group.name, filterText); const filterProxies = useFilterProxy(
const sortedProxies = useSortProxy(filterProxies, group.name, sortType); group.all,
group.name,
headState.filterText
);
const sortedProxies = useSortProxy(
filterProxies,
group.name,
headState.sortType
);
const { data: profiles } = useSWR("getProfiles", getProfiles); const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -99,14 +105,18 @@ const ProxyGroup = ({ group }: Props) => {
// auto scroll to current index // auto scroll to current index
useEffect(() => { useEffect(() => {
if (open) { if (headState.open) {
setTimeout(() => onLocation(false), 5); setTimeout(() => onLocation(false), 5);
} }
}, [open]); }, [headState.open]);
return ( return (
<> <>
<ListItem button onClick={() => setOpen(!open)} dense> <ListItem
button
dense
onClick={() => setHeadState({ open: !headState.open })}
>
<ListItemText <ListItemText
primary={group.name} primary={group.name}
secondary={ secondary={
@@ -120,21 +130,17 @@ const ProxyGroup = ({ group }: Props) => {
}} }}
/> />
{open ? <ExpandLessRounded /> : <ExpandMoreRounded />} {headState.open ? <ExpandLessRounded /> : <ExpandMoreRounded />}
</ListItem> </ListItem>
<Collapse in={open} timeout="auto" unmountOnExit> <Collapse in={headState.open} timeout="auto" unmountOnExit>
<ProxyHead <ProxyHead
sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }} sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
showType={showType}
sortType={sortType}
groupName={group.name} groupName={group.name}
filterText={filterText} headState={headState}
onLocation={onLocation} onLocation={onLocation}
onCheckDelay={onCheckAll} onCheckDelay={onCheckAll}
onShowType={setShowType} onHeadState={setHeadState}
onSortType={setSortType}
onFilterText={setFilterText}
/> />
{!sortedProxies.length && ( {!sortedProxies.length && (
@@ -160,7 +166,7 @@ const ProxyGroup = ({ group }: Props) => {
groupName={group.name} groupName={group.name}
proxy={sortedProxies[index]} proxy={sortedProxies[index]}
selected={sortedProxies[index].name === now} selected={sortedProxies[index].name === now}
showType={showType} showType={headState.showType}
sx={{ py: 0, pl: 4 }} sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy} onClick={onChangeProxy}
/> />
@@ -178,7 +184,7 @@ const ProxyGroup = ({ group }: Props) => {
groupName={group.name} groupName={group.name}
proxy={proxy} proxy={proxy}
selected={proxy.name === now} selected={proxy.name === now}
showType={showType} showType={headState.showType}
sx={{ py: 0, pl: 4 }} sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy} onClick={onChangeProxy}
/> />
+29 -22
View File
@@ -1,4 +1,4 @@
import { useState } from "react"; import { useEffect, useState } from "react";
import { Box, IconButton, TextField, SxProps } from "@mui/material"; import { Box, IconButton, TextField, SxProps } from "@mui/material";
import { import {
AccessTimeRounded, AccessTimeRounded,
@@ -14,27 +14,33 @@ import {
SortRounded, SortRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import delayManager from "../../services/delay"; import delayManager from "../../services/delay";
import type { HeadState } from "./use-head-state";
import type { ProxySortType } from "./use-sort-proxy"; import type { ProxySortType } from "./use-sort-proxy";
interface Props { interface Props {
sx?: SxProps; sx?: SxProps;
groupName: string; groupName: string;
showType: boolean; headState: HeadState;
sortType: ProxySortType;
filterText: string;
onLocation: () => void; onLocation: () => void;
onCheckDelay: () => void; onCheckDelay: () => void;
onShowType: (val: boolean) => void; onHeadState: (val: Partial<HeadState>) => void;
onSortType: (val: ProxySortType) => void;
onFilterText: (val: string) => void;
} }
const ProxyHead = (props: Props) => { 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 ( return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}> <Box sx={{ display: "flex", alignItems: "center", ...sx }}>
@@ -54,7 +60,7 @@ const ProxyHead = (props: Props) => {
onClick={() => { onClick={() => {
// Remind the user that it is custom test url // Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") { if (testUrl?.trim() && textState !== "filter") {
setTextState("url"); onHeadState({ textState: "url" });
} }
props.onCheckDelay(); props.onCheckDelay();
}} }}
@@ -66,7 +72,9 @@ const ProxyHead = (props: Props) => {
size="small" size="small"
color="inherit" color="inherit"
title={["sort by default", "sort by delay", "sort by name"][sortType]} 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 === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />} {sortType === 1 && <AccessTimeRounded />}
@@ -77,7 +85,9 @@ const ProxyHead = (props: Props) => {
size="small" size="small"
color="inherit" color="inherit"
title="edit test url" title="edit test url"
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))} onClick={() =>
onHeadState({ textState: textState === "url" ? null : "url" })
}
> >
{textState === "url" ? ( {textState === "url" ? (
<WifiTetheringRounded /> <WifiTetheringRounded />
@@ -90,7 +100,7 @@ const ProxyHead = (props: Props) => {
size="small" size="small"
color="inherit" color="inherit"
title="proxy detail" title="proxy detail"
onClick={() => props.onShowType(!showType)} onClick={() => onHeadState({ showType: !showType })}
> >
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />} {showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton> </IconButton>
@@ -100,7 +110,7 @@ const ProxyHead = (props: Props) => {
color="inherit" color="inherit"
title="filter" title="filter"
onClick={() => onClick={() =>
setTextState((ts) => (ts === "filter" ? null : "filter")) onHeadState({ textState: textState === "filter" ? null : "filter" })
} }
> >
{textState === "filter" ? ( {textState === "filter" ? (
@@ -112,20 +122,20 @@ const ProxyHead = (props: Props) => {
{textState === "filter" && ( {textState === "filter" && (
<TextField <TextField
autoFocus autoFocus={autoFocus}
hiddenLabel hiddenLabel
value={filterText} value={filterText}
size="small" size="small"
variant="outlined" variant="outlined"
placeholder="Filter conditions" 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 } }} sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/> />
)} )}
{textState === "url" && ( {textState === "url" && (
<TextField <TextField
autoFocus autoFocus={autoFocus}
hiddenLabel hiddenLabel
autoSave="off" autoSave="off"
autoComplete="off" autoComplete="off"
@@ -133,10 +143,7 @@ const ProxyHead = (props: Props) => {
size="small" size="small"
variant="outlined" variant="outlined"
placeholder="Test url" placeholder="Test url"
onChange={(e) => { onChange={(e) => onHeadState({ testUrl: e.target.value })}
setTestUrl(e.target.value);
delayManager.setUrl(groupName, e.target.value);
}}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }} sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/> />
)} )}
+80
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;
}
+79
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;
@@ -1,5 +1,6 @@
import { styled, Switch } from "@mui/material"; import { styled, Switch } from "@mui/material";
// todo: deprecated
// From: https://mui.com/components/switches/ // From: https://mui.com/components/switches/
const PaletteSwitch = styled(Switch)(({ theme }) => ({ const PaletteSwitch = styled(Switch)(({ theme }) => ({
width: 62, width: 62,
+13
View File
@@ -65,6 +65,13 @@ const ServiceMode = (props: Props) => {
} }
}); });
// fix unhandle error of the service mode
const onDisable = useLockFn(async () => {
await patchVergeConfig({ enable_service_mode: false });
mutate("checkService");
onClose();
});
return ( return (
<Dialog open={open} onClose={onClose}> <Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Service Mode")}</DialogTitle> <DialogTitle>{t("Service Mode")}</DialogTitle>
@@ -84,6 +91,12 @@ const ServiceMode = (props: Props) => {
spacing={1} spacing={1}
sx={{ mt: 4, justifyContent: "flex-end" }} sx={{ mt: 4, justifyContent: "flex-end" }}
> >
{state === "uninstall" && enable && (
<Button variant="contained" onClick={onDisable}>
Disable Service Mode
</Button>
)}
{state === "uninstall" && ( {state === "uninstall" && (
<Button variant="contained" onClick={onInstall}> <Button variant="contained" onClick={onInstall}>
Install Install
+18 -2
View File
@@ -8,6 +8,7 @@ import {
Select, Select,
MenuItem, MenuItem,
Typography, Typography,
Box,
} from "@mui/material"; } from "@mui/material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { atomClashPort } from "../../services/states"; import { atomClashPort } from "../../services/states";
@@ -16,11 +17,15 @@ import { SettingList, SettingItem } from "./setting";
import { getClashConfig, getVersion, updateConfigs } from "../../services/api"; import { getClashConfig, getVersion, updateConfigs } from "../../services/api";
import Notice from "../base/base-notice"; import Notice from "../base/base-notice";
import GuardState from "./guard-state"; import GuardState from "./guard-state";
import CoreSwitch from "./core-switch";
interface Props { interface Props {
onError: (err: Error) => void; onError: (err: Error) => void;
} }
// const MULTI_CORE = !!import.meta.env.VITE_MULTI_CORE;
const MULTI_CORE = true;
const SettingClash = ({ onError }: Props) => { const SettingClash = ({ onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
@@ -54,7 +59,7 @@ const SettingClash = ({ onError }: Props) => {
} }
await patchClashConfig({ "mixed-port": port }); await patchClashConfig({ "mixed-port": port });
setGlobalClashPort(port); setGlobalClashPort(port);
Notice.success("Change Clash port successfully!"); Notice.success("Change Clash port successfully!", 1000);
// update the config // update the config
mutate("getClashConfig"); mutate("getClashConfig");
@@ -129,7 +134,18 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<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> <Typography sx={{ py: 1 }}>{clashVer}</Typography>
</SettingItem> </SettingItem>
</SettingList> </SettingList>
+12 -4
View File
@@ -13,9 +13,10 @@ import {
ListItemText, ListItemText,
styled, styled,
TextField, TextField,
useTheme,
} from "@mui/material"; } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds"; import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { defaultTheme } from "../../pages/_theme"; import { defaultTheme, defaultDarkTheme } from "../../pages/_theme";
interface Props { interface Props {
open: boolean; 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 ( return (
<Item> <Item>
<ListItemText primary={label} /> <ListItemText primary={label} />
<Round sx={{ background: theme[key] || defaultTheme[key] }} /> <Round sx={{ background: theme[key] || dt[key] }} />
<TextField <TextField
{...textProps} {...textProps}
value={theme[key] ?? ""} value={theme[key] ?? ""}
placeholder={defaultTheme[key]} placeholder={dt[key]}
onChange={handleChange(key)} onChange={handleChange(key)}
onKeyDown={(e) => e.key === "Enter" && onSave()} onKeyDown={(e) => e.key === "Enter" && onSave()}
/> />
+22 -26
View File
@@ -19,7 +19,7 @@ import { ArrowForward } from "@mui/icons-material";
import { SettingList, SettingItem } from "./setting"; import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import { version } from "../../../package.json"; import { version } from "../../../package.json";
import PaletteSwitch from "./palette-switch"; import ThemeModeSwitch from "./theme-mode-switch";
import GuardState from "./guard-state"; import GuardState from "./guard-state";
import SettingTheme from "./setting-theme"; import SettingTheme from "./setting-theme";
@@ -43,19 +43,31 @@ const SettingVerge = ({ onError }: Props) => {
return ( return (
<SettingList title={t("Verge Setting")}> <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> <SettingItem>
<ListItemText primary={t("Theme Mode")} /> <ListItemText primary={t("Theme Mode")} />
<GuardState <GuardState
value={theme_mode === "dark"} value={theme_mode}
valueProps="checked"
onCatch={onError} onCatch={onError}
onFormat={onSwitchFormat} onChange={(e) => onChangeData({ theme_mode: e })}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })} onGuard={(e) => patchVergeConfig({ theme_mode: e })}
onGuard={(e) =>
patchVergeConfig({ theme_mode: e ? "dark" : "light" })
}
> >
<PaletteSwitch edge="end" /> <ThemeModeSwitch />
</GuardState> </GuardState>
</SettingItem> </SettingItem>
@@ -87,22 +99,6 @@ const SettingVerge = ({ onError }: Props) => {
</GuardState> </GuardState>
</SettingItem> </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> <SettingItem>
<ListItemText primary={t("Theme Setting")} /> <ListItemText primary={t("Theme Setting")} />
<IconButton <IconButton
@@ -129,7 +125,7 @@ const SettingVerge = ({ onError }: Props) => {
</SettingItem> </SettingItem>
<SettingItem> <SettingItem>
<ListItemText primary={t("Version")} /> <ListItemText primary={t("Verge Version")} />
<Typography sx={{ py: "6px" }}>v{version}</Typography> <Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem> </SettingItem>
@@ -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;
+6 -2
View File
@@ -13,6 +13,7 @@
"rule": "rule", "rule": "rule",
"global": "global", "global": "global",
"direct": "direct", "direct": "direct",
"script": "script",
"Profiles": "Profiles", "Profiles": "Profiles",
"Profile URL": "Profile URL", "Profile URL": "Profile URL",
"Import": "Import", "Import": "Import",
@@ -39,7 +40,7 @@
"IPv6": "IPv6", "IPv6": "IPv6",
"Log Level": "Log Level", "Log Level": "Log Level",
"Mixed Port": "Mixed Port", "Mixed Port": "Mixed Port",
"Clash core": "Clash core", "Clash Core": "Clash Core",
"Tun Mode": "Tun Mode", "Tun Mode": "Tun Mode",
"Service Mode": "Service Mode", "Service Mode": "Service Mode",
"Auto Launch": "Auto Launch", "Auto Launch": "Auto Launch",
@@ -54,7 +55,10 @@
"Language": "Language", "Language": "Language",
"Open App Dir": "Open App Dir", "Open App Dir": "Open App Dir",
"Open Logs Dir": "Open Logs Dir", "Open Logs Dir": "Open Logs Dir",
"Version": "Version", "Verge Version": "Verge Version",
"theme.light": "Light",
"theme.dark": "Dark",
"theme.system": "System",
"Save": "Save", "Save": "Save",
"Cancel": "Cancel" "Cancel": "Cancel"
+7 -3
View File
@@ -13,6 +13,7 @@
"rule": "规则", "rule": "规则",
"global": "全局", "global": "全局",
"direct": "直连", "direct": "直连",
"script": "脚本",
"Profiles": "配置", "Profiles": "配置",
"Profile URL": "配置文件链接", "Profile URL": "配置文件链接",
"Import": "导入", "Import": "导入",
@@ -39,7 +40,7 @@
"IPv6": "IPv6", "IPv6": "IPv6",
"Log Level": "日志等级", "Log Level": "日志等级",
"Mixed Port": "端口设置", "Mixed Port": "端口设置",
"Clash core": "Clash 内核", "Clash Core": "Clash 内核",
"Tun Mode": "Tun 模式", "Tun Mode": "Tun 模式",
"Service Mode": "服务模式", "Service Mode": "服务模式",
"Auto Launch": "开机自启", "Auto Launch": "开机自启",
@@ -47,14 +48,17 @@
"System Proxy": "系统代理", "System Proxy": "系统代理",
"Proxy Guard": "系统代理守卫", "Proxy Guard": "系统代理守卫",
"Proxy Bypass": "Proxy Bypass", "Proxy Bypass": "Proxy Bypass",
"Theme Mode": "暗夜模式", "Theme Mode": "主题模式",
"Theme Blur": "背景模糊", "Theme Blur": "背景模糊",
"Theme Setting": "主题设置", "Theme Setting": "主题设置",
"Traffic Graph": "流量图显", "Traffic Graph": "流量图显",
"Language": "语言设置", "Language": "语言设置",
"Open App Dir": "应用目录", "Open App Dir": "应用目录",
"Open Logs Dir": "日志目录", "Open Logs Dir": "日志目录",
"Version": "版本", "Verge Version": "应用版本",
"theme.light": "浅色",
"theme.dark": "深色",
"theme.system": "系统",
"Save": "保存", "Save": "保存",
"Cancel": "取消" "Cancel": "取消"
+11 -4
View File
@@ -3,6 +3,7 @@ import i18next from "i18next";
import relativeTime from "dayjs/plugin/relativeTime"; import relativeTime from "dayjs/plugin/relativeTime";
import useSWR, { SWRConfig, useSWRConfig } from "swr"; import useSWR, { SWRConfig, useSWRConfig } from "swr";
import { useEffect } from "react"; import { useEffect } from "react";
import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { Route, Routes } from "react-router-dom"; import { Route, Routes } from "react-router-dom";
import { alpha, List, Paper, ThemeProvider } from "@mui/material"; 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 { appWindow } from "@tauri-apps/api/window";
import { routers } from "./_routers"; import { routers } from "./_routers";
import { getAxios } from "../services/api"; 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 { ReactComponent as LogoSvg } from "../assets/image/logo.svg";
import LayoutItem from "../components/layout/layout-item"; import LayoutItem from "../components/layout/layout-item";
import LayoutControl from "../components/layout/layout-control"; import LayoutControl from "../components/layout/layout-control";
@@ -33,9 +35,11 @@ const Layout = () => {
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig); const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_blur, language } = vergeConfig || {}; const { theme_blur, language } = vergeConfig || {};
const setCurrentProfile = useSetRecoilState(atomCurrentProfile);
useEffect(() => { useEffect(() => {
window.addEventListener("keydown", (e) => { window.addEventListener("keydown", (e) => {
if (e.key === "Escape") appWindow.hide(); if (e.key === "Escape") appWindow.close();
}); });
listen("verge://refresh-clash-config", async () => { listen("verge://refresh-clash-config", async () => {
@@ -47,6 +51,9 @@ const Layout = () => {
// update the verge config // update the verge config
listen("verge://refresh-verge-config", () => mutate("getVergeConfig")); listen("verge://refresh-verge-config", () => mutate("getVergeConfig"));
// set current profile uid
getProfiles().then((data) => setCurrentProfile(data.current ?? ""));
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -72,7 +79,7 @@ const Layout = () => {
}} }}
sx={[ sx={[
({ palette }) => ({ ({ 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" /> <UpdateButton className="the-newbtn" />
</div> </div>
<List className="the-menu" data-windrag> <List className="the-menu">
{routers.map((router) => ( {routers.map((router) => (
<LayoutItem key={router.label} to={router.link}> <LayoutItem key={router.label} to={router.link}>
{t(router.label)} {t(router.label)}
+7
View File
@@ -10,3 +10,10 @@ export const defaultTheme = {
success_color: "#2e7d32", success_color: "#2e7d32",
font_family: `"Roboto", "Helvetica", "Arial", sans-serif`, font_family: `"Roboto", "Helvetica", "Arial", sans-serif`,
}; };
// dark mode
export const defaultDarkTheme = {
...defaultTheme,
primary_text: "#757575",
secondary_text: "#637381",
};
+2 -2
View File
@@ -4,7 +4,7 @@ import { Box, Button, Paper, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ApiType } from "../services/types"; 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 BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item"; import ConnectionItem from "../components/connection/connection-item";
@@ -25,7 +25,7 @@ const ConnectionsPage = () => {
useEffect(() => { useEffect(() => {
let ws: WebSocket | null = null; let ws: WebSocket | null = null;
getInfomation().then((result) => { getInformation().then((result) => {
const { server = "", secret = "" } = result; const { server = "", secret = "" } = result;
ws = new WebSocket(`ws://${server}/connections?token=${secret}`); ws = new WebSocket(`ws://${server}/connections?token=${secret}`);
+9
View File
@@ -1,6 +1,7 @@
import useSWR, { useSWRConfig } from "swr"; import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { useSetRecoilState } from "recoil";
import { Box, Button, Grid, TextField } from "@mui/material"; import { Box, Button, Grid, TextField } from "@mui/material";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
@@ -10,6 +11,7 @@ import {
importProfile, importProfile,
} from "../services/cmds"; } from "../services/cmds";
import { getProxies, updateProxy } from "../services/api"; import { getProxies, updateProxy } from "../services/api";
import { atomCurrentProfile } from "../services/states";
import Notice from "../components/base/base-notice"; import Notice from "../components/base/base-notice";
import BasePage from "../components/base/base-page"; import BasePage from "../components/base/base-page";
import ProfileNew from "../components/profile/profile-new"; import ProfileNew from "../components/profile/profile-new";
@@ -24,6 +26,8 @@ const ProfilePage = () => {
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false); const [dialogOpen, setDialogOpen] = useState(false);
const setCurrentProfile = useSetRecoilState(atomCurrentProfile);
const { data: profiles = {} } = useSWR("getProfiles", getProfiles); const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
// distinguish type // distinguish type
@@ -52,6 +56,9 @@ const ProfilePage = () => {
const current = profiles.current; const current = profiles.current;
const profile = regularItems.find((p) => p.uid === current); const profile = regularItems.find((p) => p.uid === current);
setCurrentProfile(current);
if (!profile) return; if (!profile) return;
setTimeout(async () => { setTimeout(async () => {
@@ -121,7 +128,9 @@ const ProfilePage = () => {
try { try {
await selectProfile(uid); await selectProfile(uid);
setCurrentProfile(uid);
mutate("getProfiles", { ...profiles, current: uid }, true); mutate("getProfiles", { ...profiles, current: uid }, true);
if (force) Notice.success("Refresh clash config", 1000);
} catch (err: any) { } catch (err: any) {
Notice.error(err?.message || err.toString()); Notice.error(err?.message || err.toString());
} }
+4 -3
View File
@@ -16,7 +16,7 @@ const ProxyPage = () => {
const { data: proxiesData } = useSWR("getProxies", getProxies); const { data: proxiesData } = useSWR("getProxies", getProxies);
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig); const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const modeList = ["rule", "global", "direct"]; const modeList = ["rule", "global", "direct", "script"];
const curMode = clashConfig?.mode.toLowerCase(); const curMode = clashConfig?.mode.toLowerCase();
const { groups = [], proxies = [] } = proxiesData ?? {}; const { groups = [], proxies = [] } = proxiesData ?? {};
@@ -38,7 +38,8 @@ const ProxyPage = () => {
}); });
// difference style // difference style
const showGroup = curMode === "rule" && !!groups.length; const showGroup =
(curMode === "rule" || curMode === "script") && !!groups.length;
const pageStyle = showGroup ? {} : { height: "100%" }; const pageStyle = showGroup ? {} : { height: "100%" };
const paperStyle: any = showGroup const paperStyle: any = showGroup
? { mb: 0.5 } ? { mb: 0.5 }
@@ -64,7 +65,7 @@ const ProxyPage = () => {
} }
> >
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}> <Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
{curMode === "rule" && !!groups.length && ( {(curMode === "rule" || curMode === "script") && !!groups.length && (
<List> <List>
{groups.map((group) => ( {groups.map((group) => (
<ProxyGroup key={group.name} group={group} /> <ProxyGroup key={group.name} group={group} />
+2 -2
View File
@@ -32,8 +32,8 @@ export async function getAxios(force: boolean = false) {
return axiosIns; return axiosIns;
} }
/// get infomation /// get information
export async function getInfomation() { export async function getInformation() {
if (server) return { server, secret }; if (server) return { server, secret };
const info = await getClashInfo(); const info = await getClashInfo();
return info!; return info!;
+4
View File
@@ -86,6 +86,10 @@ export async function getSystemProxy() {
return invoke<any>("get_sys_proxy"); return invoke<any>("get_sys_proxy");
} }
export async function changeClashCore(clashCore: string) {
return invoke<any>("change_clash_core", { clashCore });
}
export async function restartSidecar() { export async function restartSidecar() {
return invoke<void>("restart_sidecar"); return invoke<void>("restart_sidecar");
} }
+19 -9
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 { CmdType } from "./types";
import ignoreCase from "../utils/ignore-case"; import ignoreCase from "../utils/ignore-case";
@@ -124,21 +125,30 @@ class Enhance {
return this.resultMap.get(uid); 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 the handler
setup() { setup() {
if (this.isSetup) return; if (this.isSetup) return;
this.isSetup = true; this.isSetup = true;
listen("script-handler", async (event) => { 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) => ({ listen("script-handler-close", async (event) => {
data: null, await this.enhanceHandler(event);
status: "error", appWindow.close();
error: err.message,
}));
emit(payload.callback, JSON.stringify(result)).catch(console.error);
}); });
} }
+11
View File
@@ -1,6 +1,11 @@
import { atom } from "recoil"; import { atom } from "recoil";
import { ApiType } from "./types"; import { ApiType } from "./types";
export const atomThemeMode = atom<"light" | "dark">({
key: "atomThemeMode",
default: "light",
});
export const atomClashPort = atom<number>({ export const atomClashPort = atom<number>({
key: "atomClashPort", key: "atomClashPort",
default: 0, default: 0,
@@ -22,3 +27,9 @@ export const atomUpdateState = atom<boolean>({
key: "atomUpdateState", key: "atomUpdateState",
default: false, default: false,
}); });
// current profile uid
export const atomCurrentProfile = atom<string>({
key: "atomCurrentProfile",
default: "",
});
+3 -2
View File
@@ -1,7 +1,7 @@
/** /**
* Some interface for clash api * Some interface for clash api
*/ */
export namespace ApiType { export namespace ApiType {
export interface ConfigData { export interface ConfigData {
port: number; port: number;
mode: string; mode: string;
@@ -125,7 +125,8 @@ export namespace CmdType {
export interface VergeConfig { export interface VergeConfig {
language?: string; language?: string;
theme_mode?: "light" | "dark"; clash_core?: string;
theme_mode?: "light" | "dark" | "system";
theme_blur?: boolean; theme_blur?: boolean;
traffic_graph?: boolean; traffic_graph?: boolean;
enable_tun_mode?: boolean; enable_tun_mode?: boolean;
+5 -1
View File
@@ -6,7 +6,11 @@ import monaco from "vite-plugin-monaco-editor";
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
root: "src", root: "src",
plugins: [svgr(), react(), monaco()], plugins: [
svgr(),
react(),
monaco({ languageWorkers: ["editorWorkerService", "typescript"] }),
],
build: { build: {
outDir: "../dist", outDir: "../dist",
emptyOutDir: true, emptyOutDir: true,
+590 -389
View File
File diff suppressed because it is too large Load Diff