Compare commits

...
117 Commits
Author SHA1 Message Date
MystiPanda 99740c1324 fix patch error 2024-01-11 14:47:25 +08:00
MystiPanda c04b20d1fa Release v1.4.7 2024-01-11 13:19:05 +08:00
MystiPanda e127067878 feat: Disable updater for portable 2024-01-11 12:44:30 +08:00
MystiPanda 6f03b72368 feat: Support hide group
#214
2024-01-11 12:34:05 +08:00
Morris Li 7bd3ee9340 Fix expired Tauri domain (#222) 2024-01-11 10:17:56 +08:00
MystiPanda c94db606e5 build: Use old sysproxy 2024-01-10 19:24:14 +08:00
MystiPanda 4d2474226b refactor: cargo clippy 2024-01-10 17:36:35 +08:00
MystiPanda 1ffc4f538b refactor: Optimizing the implementation of Linux URL Scheme registration 2024-01-10 16:34:35 +08:00
MystiPanda 6702ac957b fix: resolve scheme error 2024-01-10 15:37:40 +08:00
MystiPanda ba42b2e77d fix: linux build error 2024-01-10 15:22:08 +08:00
MystiPanda fba18ca40a feat: Support URL Scheme for MacOS 2024-01-10 14:04:06 +08:00
MystiPanda 3a2a7a1476 feat: Support URL Scheme for Linux 2024-01-10 13:03:34 +08:00
MystiPanda 3c6d6b90bc build: fix macos build script 2024-01-09 22:49:11 +08:00
MystiPanda 47dc9ee304 fix patch error 2024-01-09 22:25:25 +08:00
MystiPanda 0045bf206c Release v1.4.6 2024-01-09 22:17:29 +08:00
MystiPanda 669a1a6953 feat: Support URL Scheme for Windows
#165
2024-01-09 21:57:06 +08:00
MystiPanda e28452cc7b feat: Optimize control button style 2024-01-09 16:04:56 +08:00
MystiPanda 5ceac03db1 feat: Add pin button 2024-01-09 15:13:59 +08:00
MystiPanda 96215e5950 fix: Fix some compile error 2024-01-09 14:52:43 +08:00
wonfen 7a030b9224 Style: UI improvement & 1.4.6 ready 2024-01-09 13:57:53 +08:00
wonfen e743478a4d chore: UI adjustment 2024-01-08 19:32:21 +08:00
MystiPanda bc29c80d44 chore: Use Latest and compatible core 2023-12-23 12:09:19 +08:00
MystiPanda 82b8a474d7 fix: Cargo clippy 2023-12-21 16:49:21 +08:00
MystiPanda 99851b297d fix: Get filename error
#165
2023-12-19 19:52:13 +08:00
MystiPanda e3a500e12c fix: portable flag 2023-12-15 21:39:34 +08:00
MystiPanda 378666e3cc chore: update service url 2023-12-15 20:38:17 +08:00
MystiPanda b65ad1ebd7 fix: user-agent version error 2023-12-15 15:18:01 +08:00
MystiPanda 933a821b5f fix: Subinfo parse error 2023-12-15 11:35:10 +08:00
MystiPanda 159337ddbd Release 1.4.5 2023-12-14 17:40:48 +08:00
MystiPanda 2e25a4333a fix: Window control button icon issue
#136
2023-12-14 14:59:55 +08:00
MystiPanda 64fafb0795 chore: Remove unsafe function 2023-12-14 13:56:51 +08:00
MystiPanda 5927e0bb3b fix: icon size 2023-12-14 13:20:01 +08:00
MystiPanda e21596db83 feat: Update MacOS tray icon 2023-12-14 13:11:46 +08:00
MystiPanda 8a608c3c3e chore: Optimize service path 2023-12-14 13:03:52 +08:00
MystiPanda 76f9db8516 chore: Optimize upgrade process 2023-12-14 11:24:26 +08:00
MystiPanda 90f4809b7c chore: default enable clash field filter 2023-12-14 10:49:58 +08:00
MystiPanda 3ff1af9fd6 chore: Delete unnecessary drag area 2023-12-13 11:09:19 +08:00
MystiPanda 711dd520f7 chore: Change service path 2023-12-13 10:59:07 +08:00
MystiPanda 99503c836a fix: Save wrong window size 2023-12-12 16:42:19 +08:00
MystiPanda 2c8bc51862 Revert "fix: Change PID file path"
This reverts commit d64bdf02de.
2023-12-12 15:59:00 +08:00
MystiPanda 5e7aa15232 fix: Can't switch env type 2023-12-11 10:51:59 +08:00
MystiPanda d0761869b6 build: fix update issue 2023-12-10 22:24:46 +08:00
MystiPanda bb99b89228 build: fix patch 2023-12-10 21:40:57 +08:00
MystiPanda 7b88beb0b5 v1.4.4 2023-12-10 21:36:22 +08:00
MystiPanda 82c630bd0e feat: Support windows aarch64 (#112) 2023-12-10 20:45:27 +08:00
MystiPanda bb4f11e1b8 feat: Patch for windows aarch64 2023-12-10 19:50:01 +08:00
MystiPanda 3182d20b7c build: Update Depends 2023-12-10 17:14:48 +08:00
MystiPanda a6f15e2474 chore: Hide script mode for alpha core 2023-12-10 16:31:55 +08:00
MystiPanda 0c3f03680c Support upgrade alpha core 2023-12-10 15:57:10 +08:00
MystiPanda a66e8dfc9f feat: Support update geodata
#37
2023-12-10 15:22:04 +08:00
zclkkk 556232aac4 chore: Allow user to choose where to install (#110) 2023-12-10 09:50:43 +08:00
MystiPanda 7fcfaadd91 chore: Remove script mode 2023-12-09 17:04:03 +08:00
MystiPanda 18d388e1e2 docs: Update ISSUE_TEMPLATE 2023-12-09 12:00:01 +08:00
MystiPanda 7de6622d74 feat: Support different tray icon for macos 2023-12-09 11:22:02 +08:00
MystiPanda 9af1f90990 feat: Support different tray icon for linux 2023-12-09 11:03:19 +08:00
Pylogmon 15ab43963d feat: Optimize copy environment variable logic (#106) 2023-12-08 22:16:42 +08:00
MystiPanda 6b7465a4b0 perf: Improves window creation speed 2023-12-08 13:10:35 +08:00
MystiPanda d64bdf02de fix: Change PID file path
#99
2023-12-08 11:59:40 +08:00
MystiPanda 4a2c94993a docs: Update README 2023-12-07 16:49:59 +08:00
MystiPanda 86c318d86b feat: Add AppImage for x86 linux 2023-12-07 16:38:39 +08:00
MystiPanda bffc1ad41d ci: fix build script 2023-12-07 16:17:34 +08:00
MystiPanda 2a685c116f chore: Fix build error 2023-12-07 16:02:29 +08:00
MystiPanda 0e271d2924 ci: Fix Linux CI Script 2023-12-07 15:57:53 +08:00
MystiPanda 7127c4d590 ci: Fix Linux Build Script 2023-12-07 15:34:49 +08:00
MystiPanda a82929996b chore: change default port to 7897 2023-12-07 14:52:14 +08:00
MystiPanda 3f01f52c7b refactor: fix depends 2023-12-07 14:44:44 +08:00
MystiPanda 9c94494622 refactor: Remove unnecessary changes 2023-12-07 13:43:53 +08:00
MystiPanda c8a508f35c Revert "chore: change default port to 7897"
This reverts commit 4ec73ef1c3.
2023-12-07 13:32:49 +08:00
wonfen 4ec73ef1c3 chore: change default port to 7897 2023-12-06 03:37:16 +08:00
MystiPanda 3465b79e5b docs: Update README 2023-12-05 17:02:54 +08:00
MystiPanda 726a0a33ae docs: UPDATELOG 2023-12-05 16:47:42 +08:00
MystiPanda ba05810d80 Release 1.4.3 2023-12-05 16:28:50 +08:00
MystiPanda 10bb53e7de chore: fix appid 2023-12-05 15:41:13 +08:00
MystiPanda dd8a083546 refactor: Change app_home to standard locations of app_data 2023-12-05 15:39:44 +08:00
MystiPanda 84131a71c9 fix: Stop core before install update 2023-12-05 15:01:15 +08:00
MystiPanda 4909a11896 docs: Update README 2023-12-05 13:33:23 +08:00
MystiPanda 4069357b81 refactor: Remove page animation 2023-12-05 13:30:55 +08:00
MystiPanda e6e87bcc40 refactor: Change Tun Icon Color 2023-12-05 13:23:54 +08:00
MystiPanda 7ba22045e8 build: Dependency downgrade 2023-12-05 12:55:20 +08:00
Pylogmon d4040b61c4 refactor: Change Portable Config Path (#66) 2023-12-05 12:52:26 +08:00
Pylogmon 7534f8fc37 refactor: Hide Clash Field Option when Disable Filter (#63) 2023-12-05 08:34:57 +08:00
MystiPanda 7ced009e92 Update README.md 2023-12-04 14:51:46 +08:00
MystiPanda cc13c71e40 ci: fix updater 2023-12-04 13:51:46 +08:00
MystiPanda d2f09209a7 chore: Use Nsis 2023-12-04 13:45:28 +08:00
Pylogmon a241b04d99 fix: Open File (#56) 2023-12-04 12:15:12 +08:00
Pylogmon 4f35d907cb fix: Get Profile Filename (#54) 2023-12-04 12:15:01 +08:00
MystiPanda 9e50d144a3 chore: change linux meta core to compatible 2023-12-04 11:38:54 +08:00
wonfen 8514bb48c4 chore: change windows meta core to compatible 2023-12-04 06:00:31 +08:00
WhizPanda 3ae633a2a1 fix: alpha core can't display memory 2023-12-03 18:55:38 +08:00
WhizPanda 2799cb9118 style: fix icon size 2023-12-03 18:28:41 +08:00
WhizPanda d20346b6ac docs: Update README.md 2023-12-03 16:42:49 +08:00
Pylogmon 2f00666a68 style: improve drag icon style (#51) 2023-12-03 16:27:13 +08:00
WhizPanda 80f4570093 ci: Fix Portable Script 2023-12-03 15:36:39 +08:00
wonfen 3f0a2ba48f docs: update readme 2023-12-03 15:25:33 +08:00
WhizPanda fc90094e8a feat: Support Both Stable and Alpha Version (#47) 2023-12-03 14:26:03 +08:00
wonfen 20d580ade8 release: 1.4.2, tweak UI, fix emoji on mac 2023-12-03 14:01:53 +08:00
WhizPanda 290a024a9e chore: Adjust style 2023-12-02 23:20:04 +08:00
WhizPanda 64a283c3a6 chore: Replace Repo Name 2023-12-02 23:04:04 +08:00
WhizPanda 3e93f0ecbc build: Update Depends 2023-12-02 22:36:04 +08:00
WhizPanda b12bcc1c49 style: Improve Style 2023-12-02 16:23:53 +08:00
WhizPanda 05d7313dcc feat: Support New Clash Field
#46
2023-12-02 15:18:54 +08:00
WhizPanda c0b6e549f0 build: Update Cargo Depends 2023-12-01 15:52:49 +08:00
WhizPanda 31f9bf219e build: Update Depends 2023-12-01 14:49:32 +08:00
WhizPanda 4906ca7059 feat: support random mixed port 2023-12-01 12:56:18 +08:00
WhizPanda b963a7a0e5 fix: Fix Updater Script 2023-12-01 11:19:49 +08:00
WhizPanda 5d6dadda76 Remove unnecessary conditions 2023-12-01 11:11:20 +08:00
Pylogmon 77f69fd223 feat: Add Windows x86 and Linux armv7 Support (#44)
* feat: Add Windows x86 and Linux armv7 Support

* ci: Remove Linux armv7 Support
2023-12-01 11:03:18 +08:00
Pylogmon 7f5052bc87 feat: Use Latest Meta Core mihomo (#41) 2023-12-01 02:44:18 +08:00
Pylogmon 3009c1f4f6 feat: Support cross-compiling to aarch64 (#40)
#19
2023-11-30 22:46:09 +08:00
Pylogmon 5425872bba feat: Support Disable Tray Click Event (#38)
#21
2023-11-30 22:45:02 +08:00
Pylogmon 0759e17295 feat: Set different tray icon on tun mode (#33)
好看!
2023-11-30 01:29:11 +08:00
Pylogmon 56a59d25df feat: Add Download Progress for Updater (#34) 2023-11-30 01:28:46 +08:00
Pylogmon 887f92babe feat: Support Drag to Reorder the Profile (#29)
* feat: Support Drag to Reorder the Profile

* style: Remove unnecessary styles
2023-11-29 08:54:02 +08:00
wonfen 197f942b3f Merge pull request #27 from Pylogmon/emoji-font
feat: Embed Emoji fonts
2023-11-28 10:41:35 +08:00
Pylogmon a5be7a35e9 feat: Embed Emoji fonts 2023-11-28 10:36:32 +08:00
wonfen e347675265 fix: Adjust font order 2023-11-28 10:03:01 +08:00
wonfen 02a084d571 chore: update preview gif 2023-11-28 08:49:22 +08:00
107 changed files with 3378 additions and 2433 deletions
-33
View File
@@ -1,33 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: "[BUG]"
labels: bug
assignees: ""
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Information**
- OS: [e.g. macOS]
- Clash Verge Version: [e.g. 1.3.4]
- Clash Core: [e.g. Clash or Clash Meta]
**Additional context**
Add any other context about the problem here.
+45
View File
@@ -0,0 +1,45 @@
name: Bug report
description: Create a report to help us improve
title: "[BUG]"
labels: ["bug"]
body:
- type: textarea
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
validations:
required: true
- type: textarea
attributes:
label: To Reproduce
description: Steps to reproduce the behavior.
validations:
required: true
- type: dropdown
attributes:
label: Platform
options:
- Windows
- Linux
- MacOS
validations:
required: true
- type: input
attributes:
label: System Version
placeholder: "e.g. macOS 10.15.7"
validations:
required: true
- type: input
attributes:
label: Software Version
placeholder: "e.g. 1.4.3"
validations:
required: true
- type: textarea
attributes:
label: Log
description: "Log file content or screenshot"
- type: textarea
attributes:
label: Additional Information
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: "[Feature]"
labels: enhancement
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
@@ -0,0 +1,27 @@
name: Feature request
description: Suggest an idea for this project
title: "[Feature]"
labels: ["enhancement"]
body:
- type: textarea
attributes:
label: Is your feature request related to a problem? Please describe.
description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
validations:
required: true
- type: textarea
attributes:
label: Describe the solution you'd like
description: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
attributes:
label: Describe alternatives you've considered
description: A clear and concise description of any alternative solutions or features you've considered.
validations:
required: true
- type: textarea
attributes:
label: Additional context
description: Add any other context or screenshots about the feature request here.
+4
View File
@@ -0,0 +1,4 @@
FROM rust:buster
COPY entrypoint.sh /entrypoint.sh
RUN chmod a+x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
+14
View File
@@ -0,0 +1,14 @@
name: "Build for Linux"
branding:
icon: user-check
color: gray-dark
inputs:
target:
required: true
description: "Rust Target"
runs:
using: "docker"
image: "Dockerfile"
args:
- ${{ inputs.target }}
+9
View File
@@ -0,0 +1,9 @@
# pnpm install --resolution-only
pnpm install
pnpm check $INPUT_TARGET
sed -i "s/#openssl/openssl={version=\"0.10\",features=[\"vendored\"]}/g" src-tauri/Cargo.toml
if [ "$INPUT_TARGET" = "x86_64-unknown-linux-gnu" ] || [ "$INPUT_TARGET" = "i686-unknown-linux-gnu" ]; then
pnpm build --target $INPUT_TARGET
else
pnpm build --target $INPUT_TARGET -b deb
fi
+47
View File
@@ -0,0 +1,47 @@
#!/bin/bash
wget https://nodejs.org/dist/v20.10.0/node-v20.10.0-linux-x64.tar.xz
tar -Jxvf ./node-v20.10.0-linux-x64.tar.xz
export PATH=$(pwd)/node-v20.10.0-linux-x64/bin:$PATH
npm install pnpm -g
rustup target add "$INPUT_TARGET"
if [ "$INPUT_TARGET" = "x86_64-unknown-linux-gnu" ]; then
apt-get update
apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libayatana-appindicator3-dev librsvg2-dev patchelf
elif [ "$INPUT_TARGET" = "i686-unknown-linux-gnu" ]; then
dpkg --add-architecture i386
apt-get update
apt-get install -y libstdc++6:i386 libgdk-pixbuf2.0-dev:i386 libatomic1:i386 gcc-multilib g++-multilib libwebkit2gtk-4.0-dev:i386 libssl-dev:i386 libgtk-3-dev:i386 librsvg2-dev:i386 patchelf:i386 libayatana-appindicator3-dev:i386
export PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig/:$PKG_CONFIG_PATH
export PKG_CONFIG_SYSROOT_DIR=/
elif [ "$INPUT_TARGET" = "aarch64-unknown-linux-gnu" ]; then
sed 's/http:\/\/\(.*\).ubuntu.com\/ubuntu\//[arch-=amd64,i386] http:\/\/ports.ubuntu.com\/ubuntu-ports\//g' /etc/apt/sources.list | tee /etc/apt/sources.list.d/ports.list
sed -i 's/http:\/\/\(.*\).ubuntu.com\/ubuntu\//[arch=amd64,i386] http:\/\/\1.archive.ubuntu.com\/ubuntu\//g' /etc/apt/sources.list
dpkg --add-architecture arm64
apt-get update
apt-get install -y libncurses6:arm64 libtinfo6:arm64 linux-libc-dev:arm64 libncursesw6:arm64 libssl3:arm64 libcups2:arm64
apt-get install -y --no-install-recommends g++-aarch64-linux-gnu libc6-dev-arm64-cross libssl-dev:arm64 libwebkit2gtk-4.0-dev:arm64 libgtk-3-dev:arm64 patchelf:arm64 librsvg2-dev:arm64 libayatana-appindicator3-dev:arm64
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc
export CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc
export CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++
export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig
export PKG_CONFIG_ALLOW_CROSS=1
elif [ "$INPUT_TARGET" = "armv7-unknown-linux-gnueabihf" ]; then
sed 's/http:\/\/\(.*\).ubuntu.com\/ubuntu\//[arch-=amd64,i386] http:\/\/ports.ubuntu.com\/ubuntu-ports\//g' /etc/apt/sources.list | tee /etc/apt/sources.list.d/ports.list
sed -i 's/http:\/\/\(.*\).ubuntu.com\/ubuntu\//[arch=amd64,i386] http:\/\/\1.archive.ubuntu.com\/ubuntu\//g' /etc/apt/sources.list
dpkg --add-architecture armhf
apt-get update
apt-get install -y libncurses6:armhf libtinfo6:armhf linux-libc-dev:armhf libncursesw6:armhf libssl3:armhf libcups2:armhf
apt-get install -y --no-install-recommends g++-arm-linux-gnueabihf libc6-dev-armhf-cross libssl-dev:armhf libwebkit2gtk-4.0-dev:armhf libgtk-3-dev:armhf patchelf:armhf librsvg2-dev:armhf libayatana-appindicator3-dev:armhf
export CARGO_TARGET_ARMV7_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc
export CC_armv7_unknown_linux_gnueabihf=arm-linux-gnueabihf-gcc
export CXX_armv7_unknown_linux_gnueabihf=arm-linux-gnueabihf-g++
export PKG_CONFIG_PATH=/usr/lib/arm-linux-gnueabihf/pkgconfig
export PKG_CONFIG_ALLOW_CROSS=1
else
echo "Unknown target: $INPUT_TARGET" && exit 1
fi
bash .github/build-for-linux/build.sh
-102
View File
@@ -1,102 +0,0 @@
name: Compatible CI
on:
workflow_dispatch:
# push:
# tags:
# - v**
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
build:
strategy:
fail-fast: false
matrix:
targets:
- tag: macOS-10.15
os: macos-10.15
- tag: Ubuntu18
os: ubuntu-18.04
- tag: Ubuntu22
os: ubuntu-22.04
runs-on: ${{ matrix.targets.os }}
if: startsWith(github.repository, 'wonfen')
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@v2
with:
workspaces: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 16
# - name: Install Dependencies (ubuntu18 only)
# if: matrix.targets.os == 'ubuntu-18.04'
# 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: Install Dependencies (ubuntu22 only)
if: startsWith(matrix.targets.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf
- 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@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
tagName: ${{ matrix.targets.tag }}
releaseName: "Compatible For ${{ matrix.targets.tag }}"
releaseBody: "More new features are now supported."
releaseDraft: false
prerelease: false
# - name: Portable Bundle
# if: matrix.os == 'windows-latest'
# # rebuild with env settings
# run: |
# yarn build
# yarn run portable
# env:
# GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
# TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
# VITE_WIN_PORTABLE: 1
-98
View File
@@ -1,98 +0,0 @@
name: Dev Build
on:
workflow_dispatch:
push:
branches:
- dev
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, 'wonfen')
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
- name: Rust Cache
uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- name: Install Node
uses: actions/setup-node@v4
with:
node-version: "20"
- uses: pnpm/action-setup@v2
name: Install pnpm
with:
version: 8
run_install: false
- name: Delete current release assets
if: startsWith(matrix.os, 'ubuntu-')
uses: mknejp/delete-release-assets@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
tag: dev
fail-if-no-assets: false
fail-if-no-release: false
assets: |
*.zip
*.gz
*.AppImage
*.deb
*.dmg
*.msi
*.sig
*.exe
*.json
- name: Install Dependencies (Ubuntu Only)
if: startsWith(matrix.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf openssl
- name: Pnpm install and check
run: |
pnpm i
pnpm check
- name: Tauri build
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
tagName: dev
releaseName: "Clash Verge Dev"
releaseBody: "More new features are now supported."
releaseDraft: false
prerelease: true
tauriScript: pnpm
args: -f default-meta
- name: Portable Bundle
if: matrix.os == 'windows-latest'
run: |
pnpm portable
env:
TAG_NAME: dev
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
VITE_WIN_PORTABLE: 1
-107
View File
@@ -1,107 +0,0 @@
name: Meta CI
on:
workflow_dispatch:
push:
tags:
- v**
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest, macos-latest]
runs-on: ${{ matrix.os }}
if: startsWith(github.repository, 'wonfen')
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@v2
with:
workspaces: src-tauri
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 16
- name: Delete current release assets
if: matrix.os == 'ubuntu-latest'
uses: mknejp/delete-release-assets@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
tag: meta
fail-if-no-assets: false
fail-if-no-release: false
assets: |
*.zip
*.gz
*.AppImage
*.deb
*.dmg
*.msi
*.sig
- name: Install Dependencies (ubuntu only)
if: startsWith(matrix.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf openssl
- 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@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
tagName: meta
releaseName: "Clash Verge Meta"
releaseBody: ""
releaseDraft: false
prerelease: true
args: -f default-meta
- name: Portable Bundle
if: matrix.os == 'windows-latest'
run: |
yarn build -f default-meta
yarn run portable
env:
TAG_NAME: meta
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
VITE_WIN_PORTABLE: 1
+80 -19
View File
@@ -5,7 +5,7 @@ on:
push: push:
tags: tags:
- v** - v**
permissions: write-all
env: env:
CARGO_INCREMENTAL: 0 CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short RUST_BACKTRACE: short
@@ -15,17 +15,40 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-latest, ubuntu-latest, macos-latest] include:
- os: windows-latest
target: x86_64-pc-windows-msvc
- os: windows-latest
target: i686-pc-windows-msvc
- os: windows-latest
target: aarch64-pc-windows-msvc
- os: macos-latest
target: aarch64-apple-darwin
- os: macos-latest
target: x86_64-apple-darwin
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
if: startsWith(github.repository, 'wonfen')
steps: steps:
- name: Checkout repository - name: Checkout Repository
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: install Rust stable - name: Apply Patch
if: matrix.target == 'aarch64-pc-windows-msvc'
run: |
git config --global user.email "clash-verge-rev@github.io"
git config --global user.name "clash-verge-rev"
git am patches/support-windows-aarch64.patch
- name: Init Submodule
if: matrix.target == 'aarch64-pc-windows-msvc'
run: git submodule update --init --recursive
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable uses: dtolnay/rust-toolchain@stable
- name: Add Rust Target
run: rustup target add ${{ matrix.target }}
- name: Rust Cache - name: Rust Cache
uses: Swatinem/rust-cache@v2 uses: Swatinem/rust-cache@v2
with: with:
@@ -42,16 +65,10 @@ jobs:
version: 8 version: 8
run_install: false run_install: false
- name: Install Dependencies (Ubuntu Only)
if: startsWith(matrix.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev webkit2gtk-4.0 libappindicator3-dev librsvg2-dev patchelf openssl
- name: Pnpm install and check - name: Pnpm install and check
run: | run: |
pnpm i pnpm i
pnpm check pnpm check ${{ matrix.target }}
- name: Tauri build - name: Tauri build
uses: tauri-apps/tauri-action@v0 uses: tauri-apps/tauri-action@v0
@@ -66,24 +83,68 @@ jobs:
releaseDraft: false releaseDraft: false
prerelease: false prerelease: false
tauriScript: pnpm tauriScript: pnpm
args: -f default-meta args: --target ${{ matrix.target }}
- name: Portable Bundle - name: Portable Bundle
if: matrix.os == 'windows-latest' if: matrix.os == 'windows-latest'
run: | run: pnpm portable ${{ matrix.target }}
pnpm portable
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }} TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }} TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
VITE_WIN_PORTABLE: 1
release-for-linux:
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
target: x86_64-unknown-linux-gnu
- os: ubuntu-latest
target: i686-unknown-linux-gnu
- os: ubuntu-latest
target: aarch64-unknown-linux-gnu
# - os: ubuntu-latest
# target: armv7-unknown-linux-gnueabihf
runs-on: ${{ matrix.os }}
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Build for Linux
uses: ./.github/build-for-linux
env:
TAURI_PRIVATE_KEY: ${{ secrets.TAURI_PRIVATE_KEY }}
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
with:
target: ${{ matrix.target }}
- name: Get Version
run: |
sudo apt-get update
sudo apt-get install jq
echo "VERSION=$(cat package.json | jq '.version' | tr -d '"')" >> $GITHUB_ENV
- name: Upload Release
if: startsWith(matrix.target, 'x86_64') || startsWith(matrix.target, 'i686')
uses: softprops/action-gh-release@v1
with:
tag_name: v${{env.VERSION}}
name: "Clash Verge v${{env.VERSION}}"
body: "More new features are now supported."
token: ${{ secrets.GITHUB_TOKEN }}
files: src-tauri/target/${{ matrix.target }}/release/bundle/appimage/*.AppImage*
- name: Upload Release
uses: softprops/action-gh-release@v1
with:
tag_name: v${{env.VERSION}}
name: "Clash Verge v${{env.VERSION}}"
body: "More new features are now supported."
token: ${{ secrets.GITHUB_TOKEN }}
files: src-tauri/target/${{ matrix.target }}/release/bundle/deb/*.deb
release-update: release-update:
needs: [release] needs: [release]
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: | if: startsWith(github.ref, 'refs/tags/v')
startsWith(github.repository, 'wonfen') &&
startsWith(github.ref, 'refs/tags/v')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
-76
View File
@@ -1,76 +0,0 @@
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
- ubuntu-18.04
- ubuntu-20.04
- ubuntu-22.04
- macos-10.15
- macos-11
- macos-12
- windows-2019
- windows-2022
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
runs-on: ${{ github.event.inputs.os }}
if: startsWith(github.repository, 'wonfen')
steps:
- name: System Version
run: |
echo ${{ github.event.inputs.os }}
- name: Checkout repository
uses: actions/checkout@v4
- name: install Rust stable
uses: dtolnay/rust-toolchain@stable
- name: Rust Cache
uses: Swatinem/rust-cache@v2
with:
workspaces: src-tauri
- name: Install Node
uses: actions/setup-node@v4
with:
node-version: "16"
cache: "yarn"
- name: Install Dependencies (ubuntu only)
if: startsWith(github.event.inputs.os, 'ubuntu-')
run: |
sudo apt-get update
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.0-dev libappindicator3-dev librsvg2-dev patchelf
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000 --frozen-lockfile
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@v0
env:
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 (include debug)"
releaseDraft: false
includeUpdaterJson: false
+1 -3
View File
@@ -1,12 +1,10 @@
name: Updater CI name: Updater CI
on: workflow_dispatch on: workflow_dispatch
permissions: write-all
jobs: jobs:
release-update: release-update:
runs-on: ubuntu-latest runs-on: ubuntu-latest
if: |
startsWith(github.repository, 'wonfen')
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v3
+19 -13
View File
@@ -1,20 +1,20 @@
<h1 align="center"> <h1 align="center">
<img src="./src/assets/image/logo.png" alt="Clash" width="128" /> <img src="./src/assets/image/logo.png" alt="Clash" width="128" />
<br> <br>
Clash Verge Continuation of <a href="https://github.com/zzzgydi/clash-verge">Clash Verge</a>
<br> <br>
</h1> </h1>
<h3 align="center"> <h3 align="center">
A 接盘 Clash Meta GUI based on <a href="https://github.com/tauri-apps/tauri">tauri</a>. A Clash Meta GUI based on <a href="https://github.com/tauri-apps/tauri">Tauri</a>.
</h3> </h3>
## Features ## Features
- Since the clash core has been removed. The project no longer maintains the clash core, but only the Clash Meta core. - Since the clash core has been removed. The project no longer maintains the clash core, but only the Clash Meta core.
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/wonfen/clash-verge-rev/wiki/%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97) - Profiles management and enhancement (by yaml and Javascript). [Doc](https://clash-verge-rev.github.io)
- 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. - Built-in support [Clash.Meta(mihomo)](https://github.com/MetaCubeX/mihomo) core.
- System proxy setting and guard. - System proxy setting and guard.
#### TG Group: [@clash_verge_rev](https://t.me/clash_verge_rev) #### TG Group: [@clash_verge_rev](https://t.me/clash_verge_rev)
@@ -39,13 +39,20 @@ A 接盘 Clash Meta GUI based on <a href="https://github.com/tauri-apps/tauri">t
## Install ## Install
Download from [release](https://github.com/wonfen/clash-verge-rev/releases). Supports Windows x64, Linux x86_64 and macOS 11+ Download from [release](https://github.com/clash-verge-rev/clash-verge-rev/releases). Supports Windows (x64/x86), Linux (x64/arm64) and macOS 10.15+ (intel/apple).
- [Windows x64](https://github.com/wonfen/clash-verge-rev/releases/download/v1.4.0/Clash.Verge_1.4.0_x64_zh-CN.msi) - [Windows x64](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/Clash.Verge_1.4.7_x64-setup.exe)
- [macOS intel](https://github.com/wonfen/clash-verge-rev/releases/download/v1.4.0/Clash.Verge_1.4.0_x64.dmg) - [Windows x86](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/Clash.Verge_1.4.7_x86-setup.exe)
- [macOS arm](https://github.com/wonfen/clash-verge-rev/releases/download/v1.4.0/Clash.Verge_1.4.0_aarch64.dmg) - [Windows arm64](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/Clash.Verge_1.4.7_arm64-setup.exe)
- [Linux AppImage](https://github.com/wonfen/clash-verge-rev/releases/download/v1.4.0/clash-verge_1.4.0_amd64.AppImage)
- [Linux deb](https://github.com/wonfen/clash-verge-rev/releases/download/v1.4.0/clash-verge_1.4.0_amd64.deb) - [macOS intel](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/Clash.Verge_1.4.7_x64.dmg)
- [macOS apple](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/Clash.Verge_1.4.7_aarch64.dmg)
- [Linux x64 AppImage](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/clash-verge_1.4.7_amd64.AppImage)
- [Linux x64 deb](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/clash-verge_1.4.7_amd64.deb)
- [Linux x86 AppImage](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/clash-verge_1.4.7_i386.AppImage)
- [Linux x86 deb](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/clash-verge_1.4.7_i386.deb)
- [Linux arm64 deb](https://github.com/clash-verge-rev/clash-verge-rev/releases/download/v1.4.7/clash-verge_1.4.7_arm64.deb)
Or you can build it yourself. Supports Windows, Linux and macOS 10.15+ Or you can build it yourself. Supports Windows, Linux and macOS 10.15+
@@ -65,7 +72,7 @@ You should install Rust and Nodejs, see [here](https://tauri.app/v1/guides/getti
pnpm i pnpm i
``` ```
Then download the clash binary... Or you can download it from [clash meta release](https://github.com/MetaCubeX/Clash.Meta/releases) and rename it according to [tauri config](https://tauri.studio/docs/api/config/#tauri.bundle.externalBin). Then download the clash binary... Or you can download it from [clash meta release](https://github.com/MetaCubeX/Clash.Meta/releases) and rename it according to [tauri config](https://tauri.app/v1/api/config#bundleconfig.externalbin).
```shell ```shell
# force update to latest version # force update to latest version
@@ -105,11 +112,10 @@ Issue and PR welcome!
Clash Verge rev was based on or inspired by these projects and so on: Clash Verge rev was based on or inspired by these projects and so on:
- [keiko233/clash-nyanpasu](https://github.com/keiko233/clash-nyanpasu): A Clash Verge variant.
- [zzzgydi/clash-verge](https://github.com/zzzgydi/clash-verge): A Clash GUI based on tauri. Supports Windows, macOS and Linux. - [zzzgydi/clash-verge](https://github.com/zzzgydi/clash-verge): A Clash GUI based on tauri. Supports Windows, macOS and Linux.
- [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. - [MetaCubeX/mihomo](https://github.com/MetaCubeX/mihomo): 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!
+109
View File
@@ -1,3 +1,112 @@
## v1.4.7
### Features
- Windows 便携版禁用应用内更新
- 支持代理组 Hidden 选项
- 支持 URL Scheme(MacOS & Linux)
---
## v1.4.6
### Features
- 更新 Clash Meta(mihomo) 内核到 v1.18.0
- 支持 URL Scheme(暂时仅支持 Windows)
- 添加窗口置顶按钮
- UI 优化调整
### Bugs Fixes
- 修复一些编译错误
- 获取订阅名称错误
- 订阅信息解析错误
---
## v1.4.5
### Features
- 更新 MacOS 托盘图标样式(@gxx2778 贡献)
### Bugs Fixes
- Windows 下更新时无法覆盖`clash-verge-service.exe`的问题(需要卸载重装一次服务,下次更新生效)
- 窗口最大化按钮变化问题
- 窗口尺寸保存错误问题
- 复制环境变量类型无法切换问题
- 某些情况下闪退的问题
- 某些订阅无法导入的问题
---
## v1.4.4
### Features
- 支持 Windows aarch64(arm64) 版本
- 支持一键更新 GeoData
- 支持一键更新 Alpha 内核
- MacOS 支持在系统代理时显示不同的托盘图标
- Linux 支持在系统代理时显示不同的托盘图标
- 优化复制环境变量逻辑
### Bugs Fixes
- 修改 PID 文件的路径
### Performance
- 优化创建窗口的速度
---
## v1.4.3
### Break Changes
- 更改配置文件路径到标准目录(可以保证卸载时没有残留)
- 更改 appid 为 `io.github.clash-verge-rev.clash-verge-rev`
- 建议卸载旧版本后再安装新版本,该版本安装后不会使用旧版配置文件,你可以手动将旧版配置文件迁移到新版配置文件目录下
### Features
- 移除页面切换动画
- 更改 Tun 模式托盘图标颜色
- Portable 版本默认使用当前目录作为配置文件目录
- 禁用 Clash 字段过滤时隐藏 Clash 字段选项
- 优化拖拽时光标样式
### Bugs Fixes
- 修复 windows 下更新时没有关闭内核导致的更新失败的问题
- 修复打开文件报错的问题
- 修复 url 导入时无法获取中文配置名称的问题
- 修复 alpha 内核无法显示内存信息的问题
---
## v1.4.2
### Features
- update clash meta core to mihomo 1.17.0
- support both clash meta stable release and prerelease-alpha release
- fixed the problem of not being able to set the system proxy when there is a dial-up link on windows system [#833](https://github.com/zzzgydi/clash-verge/issues/833)
- support new clash field
- support random mixed port
- add windows x86 and linux armv7 support
- support disable tray click event
- add download progress for updater
- support drag to reorder the profile
- embed emoji fonts
- update depends
- improve UI style
---
## v1.4.1 ## v1.4.1
### Features ### Features
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 MiB

After

Width:  |  Height:  |  Size: 6.7 MiB

+36 -35
View File
@@ -1,74 +1,75 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "1.4.1", "version": "1.4.7",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "tauri dev -f default-meta", "dev": "tauri dev",
"dev:diff": "tauri dev -f verge-dev", "dev:diff": "tauri dev -f verge-dev",
"build": "tauri build -f default-meta", "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",
"portable": "node scripts/portable.mjs", "portable": "node scripts/portable.mjs",
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@dnd-kit/core": "^6.1.0",
"@dnd-kit/sortable": "^8.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@emotion/react": "^11.11.1", "@emotion/react": "^11.11.1",
"@emotion/styled": "^11.11.0", "@emotion/styled": "^11.11.0",
"@juggle/resize-observer": "^3.4.0", "@juggle/resize-observer": "^3.4.0",
"@mui/icons-material": "^5.14.14", "@mui/icons-material": "^5.14.19",
"@mui/lab": "5.0.0-alpha.149", "@mui/lab": "5.0.0-alpha.149",
"@mui/material": "^5.14.14", "@mui/material": "^5.14.19",
"@mui/x-data-grid": "^6.16.3", "@mui/x-data-grid": "^6.18.2",
"@tauri-apps/api": "^1.3.0", "@tauri-apps/api": "^1.5.1",
"ahooks": "^3.7.2", "ahooks": "^3.7.8",
"axios": "^1.1.3", "axios": "^1.6.2",
"dayjs": "1.11.5", "dayjs": "1.11.5",
"i18next": "^22.0.4", "i18next": "^23.7.7",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"monaco-editor": "^0.34.1", "monaco-editor": "^0.34.1",
"react": "^18.2.0", "react": "^18.2.0",
"react-dom": "^18.2.0", "react-dom": "^18.2.0",
"react-error-boundary": "^3.1.4", "react-error-boundary": "^3.1.4",
"react-hook-form": "^7.39.5", "react-hook-form": "^7.48.2",
"react-i18next": "^12.0.0", "react-i18next": "^13.5.0",
"react-router-dom": "^6.4.3", "react-router-dom": "^6.20.0",
"react-transition-group": "^4.4.5", "react-transition-group": "^4.4.5",
"react-virtuoso": "^3.1.3", "react-virtuoso": "^4.6.2",
"recoil": "^0.7.6", "recoil": "^0.7.7",
"snarkdown": "^2.0.0", "snarkdown": "^2.0.0",
"tar": "^6.2.0", "swr": "^1.3.0",
"swr": "^1.3.0" "tar": "^6.2.0"
}, },
"devDependencies": { "devDependencies": {
"@actions/github": "^5.0.3", "@actions/github": "^5.1.1",
"@tauri-apps/cli": "^1.3.1", "@tauri-apps/cli": "^1.5.6",
"@types/fs-extra": "^9.0.13", "@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.2", "@types/js-cookie": "^3.0.6",
"@types/lodash": "^4.14.180", "@types/lodash": "^4.14.202",
"@types/lodash-es": "^4.17.7", "@types/lodash-es": "^4.17.12",
"@types/react": "^18.2.37", "@types/react": "^18.2.39",
"@types/react-dom": "^18.0.11", "@types/react-dom": "^18.2.17",
"@types/react-transition-group": "^4.4.9", "@types/react-transition-group": "^4.4.9",
"@vitejs/plugin-react": "^4.1.0", "@vitejs/plugin-react": "^4.2.0",
"adm-zip": "^0.5.9", "adm-zip": "^0.5.10",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"fs-extra": "^10.0.0", "fs-extra": "^11.2.0",
"https-proxy-agent": "^5.0.1", "https-proxy-agent": "^5.0.1",
"husky": "^7.0.0", "husky": "^7.0.4",
"node-fetch": "^3.2.6", "node-fetch": "^3.3.2",
"prettier": "^2.7.1", "prettier": "^2.8.8",
"pretty-quick": "^3.1.3", "pretty-quick": "^3.1.3",
"sass": "^1.54.0", "sass": "^1.69.5",
"typescript": "^4.7.4", "typescript": "^5.3.2",
"vite": "^4.5.0", "vite": "^4.5.0",
"vite-plugin-monaco-editor": "^1.1.0", "vite-plugin-monaco-editor": "^1.1.0",
"vite-plugin-svgr": "^4.1.0" "vite-plugin-svgr": "^4.2.0"
}, },
"prettier": { "prettier": {
"tabWidth": 2, "tabWidth": 2,
+195
View File
@@ -0,0 +1,195 @@
From 8b085aea2f11e64f433244eda092c178a2bb50bc Mon Sep 17 00:00:00 2001
From: MystiPanda <mystipanda@proton.me>
Date: Sun, 10 Dec 2023 19:47:45 +0800
Subject: [PATCH] feat: Support windows aarch64
---
.gitmodules | 3 +
src-tauri/Cargo.toml | 2 +-
src-tauri/quick-rs | 1 +
src-tauri/src/enhance/script.rs | 130 +++++++++++++++++++-------------
4 files changed, 81 insertions(+), 55 deletions(-)
create mode 100644 .gitmodules
create mode 160000 src-tauri/quick-rs
diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..2eda7e4
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "src-tauri/quick-rs"]
+ path = src-tauri/quick-rs
+ url = https://github.com/clash-verge-rev/quick-rs.git
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 4c6dde5..5fd9ad8 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -25,7 +25,6 @@ log4rs = "1"
nanoid = "0.4"
chrono = "0.4"
sysinfo = "0.30"
-rquickjs = "0.3" # 高版本不支持 Linux aarch64
serde_json = "1.0"
serde_yaml = "0.9"
auto-launch = "0.5"
@@ -34,6 +33,7 @@ port_scanner = "0.1.5"
delay_timer = "0.11.5"
parking_lot = "0.12"
percent-encoding = "2.3.1"
+quick-rs = { path = "quick-rs" }
window-shadows = { version = "0.2" }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
diff --git a/src-tauri/quick-rs b/src-tauri/quick-rs
new file mode 160000
index 0000000..78277c4
--- /dev/null
+++ b/src-tauri/quick-rs
@@ -0,0 +1 @@
+Subproject commit 78277c4509c64f18c0fc5c9f2b84671de7c83343
diff --git a/src-tauri/src/enhance/script.rs b/src-tauri/src/enhance/script.rs
index 6c207d9..d47dc33 100644
--- a/src-tauri/src/enhance/script.rs
+++ b/src-tauri/src/enhance/script.rs
@@ -3,61 +3,83 @@ use anyhow::Result;
use serde_yaml::Mapping;
pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(String, String)>)> {
- use rquickjs::{function::Func, Context, Runtime};
- use std::sync::{Arc, Mutex};
-
- let runtime = Runtime::new().unwrap();
- let context = Context::full(&runtime).unwrap();
- let outputs = Arc::new(Mutex::new(vec![]));
-
- let copy_outputs = outputs.clone();
- let result = context.with(|ctx| -> Result<Mapping> {
- ctx.globals().set(
- "__verge_log__",
- Func::from(move |level: String, data: String| {
- let mut out = copy_outputs.lock().unwrap();
- out.push((level, data));
- }),
- )?;
-
- ctx.eval(
- r#"var console = Object.freeze({
- log(data){__verge_log__("log",JSON.stringify(data))},
- info(data){__verge_log__("info",JSON.stringify(data))},
- error(data){__verge_log__("error",JSON.stringify(data))},
- debug(data){__verge_log__("debug",JSON.stringify(data))},
- });"#,
- )?;
-
- let config = use_lowercase(config.clone());
- let config_str = serde_json::to_string(&config)?;
-
- let code = format!(
- r#"try{{
+ use quick_rs::{context::Context, function::Function, module::Module, runtime::Runtime};
+
+ let config = use_lowercase(config.clone());
+ let config_str = serde_json::to_string(&config)?;
+
+ let runtime = Runtime::new();
+ let context = Context::from(&runtime);
+
+ let code = format!(
+ r#"
+ let output = [];
+
+ function __verge_log__(type, data) {{
+ output.push([type, data]);
+ }}
+
+ var console = Object.freeze({{
+ log(data) {{ __verge_log__("log", JSON.stringify(data)) }},
+ info(data) {{ __verge_log__("info", JSON.stringify(data)) }},
+ error(data) {{ __verge_log__("error", JSON.stringify(data)) }},
+ debug(data) {{ __verge_log__("debug", JSON.stringify(data)) }},
+ }});
+
{script};
- JSON.stringify(main({config_str})||'')
- }} catch(err) {{
- `__error_flag__ ${{err.toString()}}`
- }}"#
- );
- let result: String = ctx.eval(code.as_str())?;
- if result.starts_with("__error_flag__") {
- anyhow::bail!(result[15..].to_owned());
- }
- if result == "\"\"" {
- anyhow::bail!("main function should return object");
- }
- Ok(serde_json::from_str::<Mapping>(result.as_str())?)
- });
-
- let mut out = outputs.lock().unwrap();
- match result {
- Ok(config) => Ok((use_lowercase(config), out.to_vec())),
- Err(err) => {
- out.push(("exception".into(), err.to_string()));
- Ok((config, out.to_vec()))
- }
- }
+
+ export function _main(){{
+ try{{
+ let result = JSON.stringify(main({config_str})||"");
+ return JSON.stringify({{result, output}});
+ }} catch(err) {{
+ output.push(["exception", err.toString()]);
+ return JSON.stringify({{result: "__error__", output}});
+ }}
+ }}
+ "#
+ );
+ let value = context.eval_module(&code, "_main")?;
+ let module = Module::new(value)?;
+ let value = module.get("_main")?;
+ let function = Function::new(value)?;
+ let value = function.call(vec![])?;
+ let result = serde_json::from_str::<serde_json::Value>(&value.to_string()?)?;
+ result
+ .as_object()
+ .map(|obj| {
+ let result = obj.get("result").unwrap().as_str().unwrap();
+ let output = obj.get("output").unwrap();
+
+ let mut out = output
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|item| {
+ let item = item.as_array().unwrap();
+ (
+ item[0].as_str().unwrap().into(),
+ item[1].as_str().unwrap().into(),
+ )
+ })
+ .collect::<Vec<_>>();
+ if result.is_empty() {
+ anyhow::bail!("main function should return object");
+ }
+ if result == "__error__" {
+ return Ok((config, out.to_vec()));
+ }
+ let result = serde_json::from_str::<Mapping>(result);
+
+ match result {
+ Ok(config) => Ok((use_lowercase(config), out.to_vec())),
+ Err(err) => {
+ out.push(("exception".into(), err.to_string()));
+ Ok((config, out.to_vec()))
+ }
+ }
+ })
+ .unwrap_or_else(|| anyhow::bail!("Unknown result"))
}
#[test]
--
2.43.0.windows.1
+634 -529
View File
File diff suppressed because it is too large Load Diff
-119
View File
@@ -1,119 +0,0 @@
/**
* Build and upload assets
* for macOS(aarch)
*/
import fs from "fs-extra";
import path from "path";
import { exit } from "process";
import { execSync } from "child_process";
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
// to `meta` tag
const META = process.argv.includes("--meta");
// to `alpha` tag
const ALPHA = process.argv.includes("--alpha");
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 tag = META ? "meta" : ALPHA ? "alpha" : `v${version}`;
const buildCmd = META ? `pnpm build -f default-meta` : `pnpm build`;
console.log(`[INFO]: Upload to tag "${tag}"`);
console.log(`[INFO]: Building app. "${buildCmd}"`);
execSync(buildCmd);
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,
});
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);
}
+156 -147
View File
@@ -11,122 +11,174 @@ 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 SIDECAR_HOST = execSync("rustc -vV") const PLATFORM_MAP = {
.toString() "x86_64-pc-windows-msvc": "win32",
.match(/(?<=host: ).+(?=\s*)/g)[0]; "i686-pc-windows-msvc": "win32",
"aarch64-pc-windows-msvc": "win32",
/* ======= clash ======= "x86_64-apple-darwin": "darwin",
const CLASH_STORAGE_PREFIX = "https://release.dreamacro.workers.dev/"; "aarch64-apple-darwin": "darwin",
const CLASH_URL_PREFIX = "x86_64-unknown-linux-gnu": "linux",
"https://github.com/Dreamacro/clash/releases/download/premium/"; "i686-unknown-linux-gnu": "linux",
const CLASH_LATEST_DATE = "latest"; "aarch64-unknown-linux-gnu": "linux",
"armv7-unknown-linux-gnueabihf": "linux",
const CLASH_BACKUP_URL_PREFIX =
"https://github.com/zhongfly/Clash-premium-backup/releases/download/";
const CLASH_BACKUP_LATEST_DATE = "2023-09-05-gdcc8d87";
//https://github.com/zhongfly/Clash-premium-backup/releases/download/2023-09-05-gdcc8d87/clash-windows-amd64-2023-09-05-gdcc8d87.zip
//https://github.com/zhongfly/Clash-premium-backup/releases/download/2023-09-05-gdcc8d87/clash-windows-amd64-n2023-09-05-gdcc8d87.zip
const CLASH_MAP = {
"win32-x64": "clash-windows-amd64",
"darwin-x64": "clash-darwin-amd64",
"darwin-arm64": "clash-darwin-arm64",
"linux-x64": "clash-linux-amd64",
"linux-arm64": "clash-linux-arm64",
}; };
*/ const ARCH_MAP = {
/* ======= clash meta ======= */ "x86_64-pc-windows-msvc": "x64",
const META_URL_PREFIX = `https://github.com/wonfen/Clash.Meta/releases/download/latest`; "i686-pc-windows-msvc": "ia32",
// const META_VERSION = "2023.11.23"; "aarch64-pc-windows-msvc": "arm64",
"x86_64-apple-darwin": "x64",
"aarch64-apple-darwin": "arm64",
"x86_64-unknown-linux-gnu": "x64",
"i686-unknown-linux-gnu": "ia32",
"aarch64-unknown-linux-gnu": "arm64",
"armv7-unknown-linux-gnueabihf": "arm",
};
const arg1 = process.argv.slice(2)[0];
const arg2 = process.argv.slice(2)[1];
const target = arg1 === "--force" ? arg2 : arg1;
const { platform, arch } = target
? { platform: PLATFORM_MAP[target], arch: ARCH_MAP[target] }
: process;
const SIDECAR_HOST = target
? target
: execSync("rustc -vV")
.toString()
.match(/(?<=host: ).+(?=\s*)/g)[0];
/* ======= clash meta alpha======= */
const META_ALPHA_VERSION_URL =
"https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha/version.txt";
const META_ALPHA_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download/Prerelease-Alpha`;
let META_ALPHA_VERSION;
const META_ALPHA_MAP = {
"win32-x64": "mihomo-windows-amd64-compatible",
"win32-ia32": "mihomo-windows-386",
"win32-arm64": "mihomo-windows-arm64",
"darwin-x64": "mihomo-darwin-amd64",
"darwin-arm64": "mihomo-darwin-arm64",
"linux-x64": "mihomo-linux-amd64-compatible",
"linux-ia32": "mihomo-linux-386",
"linux-arm64": "mihomo-linux-arm64",
"linux-arm": "mihomo-linux-armv7",
};
// Fetch the latest alpha release version from the version.txt file
async function getLatestAlphaVersion() {
const options = {};
const httpProxy =
process.env.HTTP_PROXY ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.https_proxy;
if (httpProxy) {
options.agent = proxyAgent(httpProxy);
}
try {
const response = await fetch(META_ALPHA_VERSION_URL, {
...options,
method: "GET",
});
let v = await response.text();
META_ALPHA_VERSION = v.trim(); // Trim to remove extra whitespaces
console.log(`Latest alpha version: ${META_ALPHA_VERSION}`);
} catch (error) {
console.error("Error fetching latest alpha version:", error.message);
process.exit(1);
}
}
/* ======= clash meta stable ======= */
const META_VERSION_URL =
"https://github.com/MetaCubeX/mihomo/releases/latest/download/version.txt";
const META_URL_PREFIX = `https://github.com/MetaCubeX/mihomo/releases/download`;
let META_VERSION;
const META_MAP = { const META_MAP = {
"win32-x64": "clash.meta-win-amd64", "win32-x64": "mihomo-windows-amd64-compatible",
"darwin-x64": "clash.meta-darwin-amd64", "win32-ia32": "mihomo-windows-386",
"darwin-arm64": "clash.meta-darwin-arm64", "win32-arm64": "mihomo-windows-arm64",
"linux-x64": "clash.meta-linux-amd64", "darwin-x64": "mihomo-darwin-amd64",
"linux-arm64": "clash.meta-linux-arm64", "darwin-arm64": "mihomo-darwin-arm64",
"linux-x64": "mihomo-linux-amd64-compatible",
"linux-ia32": "mihomo-linux-386",
"linux-arm64": "mihomo-linux-arm64",
"linux-arm": "mihomo-linux-armv7",
}; };
// Fetch the latest release version from the version.txt file
async function getLatestReleaseVersion() {
const options = {};
const httpProxy =
process.env.HTTP_PROXY ||
process.env.http_proxy ||
process.env.HTTPS_PROXY ||
process.env.https_proxy;
if (httpProxy) {
options.agent = proxyAgent(httpProxy);
}
try {
const response = await fetch(META_VERSION_URL, {
...options,
method: "GET",
});
let v = await response.text();
META_VERSION = v.trim(); // Trim to remove extra whitespaces
console.log(`Latest release version: ${META_VERSION}`);
} catch (error) {
console.error("Error fetching latest release version:", error.message);
process.exit(1);
}
}
/* /*
* check available * check available
*/ */
const { platform, arch } = process;
/*
if (!CLASH_MAP[`${platform}-${arch}`]) {
throw new Error(`clash unsupported platform "${platform}-${arch}"`);
}
*/
if (!META_MAP[`${platform}-${arch}`]) { if (!META_MAP[`${platform}-${arch}`]) {
throw new Error(`clash meta unsupported platform "${platform}-${arch}"`); throw new Error(
`clash meta alpha unsupported platform "${platform}-${arch}"`
);
} }
/*
function clash() {
const name = CLASH_MAP[`${platform}-${arch}`];
if (!META_ALPHA_MAP[`${platform}-${arch}`]) {
throw new Error(
`clash meta alpha unsupported platform "${platform}-${arch}"`
);
}
/**
* core info
*/
function clashMetaAlpha() {
const name = META_ALPHA_MAP[`${platform}-${arch}`];
const isWin = platform === "win32"; const isWin = platform === "win32";
const urlExt = isWin ? "zip" : "gz"; const urlExt = isWin ? "zip" : "gz";
const downloadURL = `${CLASH_URL_PREFIX}${name}-${CLASH_LATEST_DATE}.${urlExt}`; const downloadURL = `${META_ALPHA_URL_PREFIX}/${name}-${META_ALPHA_VERSION}.${urlExt}`;
const exeFile = `${name}${isWin ? ".exe" : ""}`; const exeFile = `${name}${isWin ? ".exe" : ""}`;
const zipFile = `${name}.${urlExt}`; const zipFile = `${name}-${META_ALPHA_VERSION}.${urlExt}`;
return { return {
name: "clash", name: "clash-meta-alpha",
targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`, targetFile: `clash-meta-alpha-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
exeFile, exeFile,
zipFile, zipFile,
downloadURL, downloadURL,
}; };
} }
function clashBackup() {
const name = CLASH_MAP[`${platform}-${arch}`];
const isWin = platform === "win32";
const urlExt = isWin ? "zip" : "gz";
const downloadURL = `${CLASH_BACKUP_URL_PREFIX}${CLASH_BACKUP_LATEST_DATE}/${name}-n${CLASH_BACKUP_LATEST_DATE}.${urlExt}`;
const exeFile = `${name}${isWin ? ".exe" : ""}`;
const zipFile = `${name}.${urlExt}`;
return {
name: "clash",
targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
exeFile,
zipFile,
downloadURL,
};
}
function clashS3() {
const name = CLASH_MAP[`${platform}-${arch}`];
const isWin = platform === "win32";
const urlExt = isWin ? "zip" : "gz";
const downloadURL = `${CLASH_STORAGE_PREFIX}${CLASH_LATEST_DATE}/${name}-${CLASH_LATEST_DATE}.${urlExt}`;
const exeFile = `${name}${isWin ? ".exe" : ""}`;
const zipFile = `${name}.${urlExt}`;
return {
name: "clash",
targetFile: `clash-${SIDECAR_HOST}${isWin ? ".exe" : ""}`,
exeFile,
zipFile,
downloadURL,
};
}
*/
function clashMeta() { function clashMeta() {
const name = META_MAP[`${platform}-${arch}`]; const name = META_MAP[`${platform}-${arch}`];
const isWin = platform === "win32"; const isWin = platform === "win32";
/* const urlExt = isWin ? "zip" : "gz"; const urlExt = isWin ? "zip" : "gz";
const downloadURL = `${META_URL_PREFIX}${META_VERSION}/${name}-${META_VERSION}.${urlExt}`; const downloadURL = `${META_URL_PREFIX}/${META_VERSION}/${name}-${META_VERSION}.${urlExt}`;
const exeFile = `${name}${isWin ? ".exe" : ""}`; const exeFile = `${name}${isWin ? ".exe" : ""}`;
const zipFile = `${name}-${META_VERSION}.${urlExt}`; */ const zipFile = `${name}-${META_VERSION}.${urlExt}`;
const urlExt = isWin ? "zip" : "tgz";
const downloadURL = `${META_URL_PREFIX}/${name}.${urlExt}`;
const exeFile = isWin ? "虚空终端-win-amd64.exe" : name;
const zipFile = `${name}.${urlExt}`;
return { return {
name: "clash-meta", name: "clash-meta",
@@ -136,7 +188,6 @@ function clashMeta() {
downloadURL, downloadURL,
}; };
} }
/** /**
* download sidecar and rename * download sidecar and rename
*/ */
@@ -218,58 +269,6 @@ async function resolveSidecar(binInfo) {
} }
} }
/**
* prepare clash core
* if the core version is not updated in time, use S3 storage as a backup.
*/
async function resolveClash() {
try {
return await resolveSidecar(clash());
} catch {
console.log(`[WARN]: clash core needs to be updated`);
return await resolveSidecar(clashS3());
}
}
/**
* only Windows
* get the wintun.dll (not required)
async function resolveWintun() {
const { platform } = process;
if (platform !== "win32") return;
const url = "https://www.wintun.net/builds/wintun-0.14.1.zip";
const tempDir = path.join(TEMP_DIR, "wintun");
const tempZip = path.join(tempDir, "wintun.zip");
const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll");
const targetPath = path.join(cwd, "src-tauri/resources", "wintun.dll");
if (!FORCE && (await fs.pathExists(targetPath))) return;
await fs.mkdirp(tempDir);
if (!(await fs.pathExists(tempZip))) {
await downloadFile(url, tempZip);
}
// unzip
const zip = new AdmZip(tempZip);
zip.extractAllTo(tempDir, true);
if (!(await fs.pathExists(wintunPath))) {
throw new Error(`path not found "${wintunPath}"`);
}
await fs.rename(wintunPath, targetPath);
await fs.remove(tempDir);
console.log(`[INFO]: resolve wintun.dll finished`);
}
*/
/** /**
* download the file to the resources dir * download the file to the resources dir
*/ */
@@ -317,8 +316,8 @@ async function downloadFile(url, path) {
/** /**
* main * main
*/ */
const SERVICE_URL =
"https://github.com/zzzgydi/clash-verge-service/releases/download/latest"; const SERVICE_URL = `https://github.com/clash-verge-rev/clash-verge-service/releases/download/${SIDECAR_HOST}`;
const resolveService = () => const resolveService = () =>
resolveResource({ resolveResource({
@@ -358,8 +357,18 @@ const resolveEnableLoopback = () =>
const tasks = [ const tasks = [
// { name: "clash", func: resolveClash, retry: 5 }, // { name: "clash", func: resolveClash, retry: 5 },
{ name: "clash-meta", func: () => resolveSidecar(clashMeta()), retry: 5 }, {
// { name: "wintun", func: resolveWintun, retry: 5, winOnly: true }, name: "clash-meta-alpha",
func: () =>
getLatestAlphaVersion().then(() => resolveSidecar(clashMetaAlpha())),
retry: 5,
},
{
name: "clash-meta",
func: () =>
getLatestReleaseVersion().then(() => resolveSidecar(clashMeta())),
retry: 5,
},
{ name: "service", func: resolveService, retry: 5, winOnly: true }, { name: "service", func: resolveService, retry: 5, winOnly: true },
{ name: "install", func: resolveInstall, retry: 5, winOnly: true }, { name: "install", func: resolveInstall, retry: 5, winOnly: true },
{ name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true }, { name: "uninstall", func: resolveUninstall, retry: 5, winOnly: true },
+18 -3
View File
@@ -4,29 +4,44 @@ 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 target = process.argv.slice(2)[0];
const ARCH_MAP = {
"i686-pc-windows-msvc": "x86",
"x86_64-pc-windows-msvc": "x64",
"aarch64-pc-windows-msvc": "arm64",
};
/// Script for ci /// Script for ci
/// 打包绿色版/便携版 (only Windows) /// 打包绿色版/便携版 (only Windows)
async function resolvePortable() { async function resolvePortable() {
if (process.platform !== "win32") return; if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release"; const releaseDir = target
? `./src-tauri/target/${target}/release`
: `./src-tauri/target/release`;
const configDir = path.join(releaseDir, ".config");
if (!(await fs.pathExists(releaseDir))) { if (!(await fs.pathExists(releaseDir))) {
throw new Error("could not found the release dir"); throw new Error("could not found the release dir");
} }
await fs.mkdir(configDir);
await fs.createFile(path.join(configDir, "PORTABLE"));
const zip = new AdmZip(); const zip = new AdmZip();
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-meta.exe")); zip.addLocalFile(path.join(releaseDir, "clash-meta.exe"));
zip.addLocalFile(path.join(releaseDir, "clash-meta-alpha.exe"));
zip.addLocalFolder(path.join(releaseDir, "resources"), "resources"); zip.addLocalFolder(path.join(releaseDir, "resources"), "resources");
zip.addLocalFolder(configDir, ".config");
const require = createRequire(import.meta.url); const require = createRequire(import.meta.url);
const packageJson = require("../package.json"); const packageJson = require("../package.json");
const { version } = packageJson; const { version } = packageJson;
const zipFile = `Clash.Verge_${version}_x64_portable.zip`; const zipFile = `Clash.Verge_${version}_${ARCH_MAP[target]}_portable.zip`;
zip.writeZip(zipFile); zip.writeZip(zipFile);
console.log("[INFO]: create portable zip successfully"); console.log("[INFO]: create portable zip successfully");
-53
View File
@@ -1,53 +0,0 @@
import fs from "fs-extra";
import { createRequire } from "module";
import { execSync } from "child_process";
import { resolveUpdateLog } from "./updatelog.mjs";
const require = createRequire(import.meta.url);
// publish
async function resolvePublish() {
const flag = process.argv[2] ?? "patch";
const packageJson = require("../package.json");
const tauriJson = require("../src-tauri/tauri.conf.json");
let [a, b, c] = packageJson.version.split(".").map(Number);
if (flag === "major") {
a += 1;
b = 0;
c = 0;
} else if (flag === "minor") {
b += 1;
c = 0;
} else if (flag === "patch") {
c += 1;
} else throw new Error(`invalid flag "${flag}"`);
const nextVersion = `${a}.${b}.${c}`;
packageJson.version = nextVersion;
tauriJson.package.version = nextVersion;
// 发布更新前先写更新日志
const nextTag = `v${nextVersion}`;
await resolveUpdateLog(nextTag);
await fs.writeFile(
"./package.json",
JSON.stringify(packageJson, undefined, 2)
);
await fs.writeFile(
"./src-tauri/tauri.conf.json",
JSON.stringify(tauriJson, undefined, 2)
);
execSync("git add ./package.json");
execSync("git add ./src-tauri/tauri.conf.json");
execSync(`git commit -m "v${nextVersion}"`);
execSync(`git tag -a v${nextVersion} -m "v${nextVersion}"`);
execSync(`git push`);
execSync(`git push origin v${nextVersion}`);
console.log(`Publish Successfully...`);
}
resolvePublish();
+47 -6
View File
@@ -45,7 +45,12 @@ async function resolveUpdater() {
"darwin-intel": { signature: "", url: "" }, "darwin-intel": { signature: "", url: "" },
"darwin-x86_64": { signature: "", url: "" }, "darwin-x86_64": { signature: "", url: "" },
"linux-x86_64": { signature: "", url: "" }, "linux-x86_64": { signature: "", url: "" },
"linux-i686": { signature: "", url: "" },
"linux-aarch64": { signature: "", url: "" },
"linux-armv7": { signature: "", url: "" },
"windows-x86_64": { signature: "", url: "" }, "windows-x86_64": { signature: "", url: "" },
"windows-i686": { signature: "", url: "" },
"windows-aarch64": { signature: "", url: "" },
}, },
}; };
@@ -53,17 +58,37 @@ async function resolveUpdater() {
const { name, browser_download_url } = asset; const { name, browser_download_url } = asset;
// win64 url // win64 url
if (name.endsWith(".msi.zip") && name.includes("en-US")) { if (name.endsWith("x64-setup.nsis.zip")) {
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") && name.includes("en-US")) { if (name.endsWith("x64-setup.nsis.zip.sig")) {
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;
} }
// win32 url
if (name.endsWith("x86-setup.nsis.zip")) {
updateData.platforms["windows-i686"].url = browser_download_url;
}
// win32 signature
if (name.endsWith("x86-setup.nsis.zip.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms["windows-i686"].signature = sig;
}
// win arm url
if (name.endsWith("arm64-setup.nsis.zip")) {
updateData.platforms["windows-aarch64"].url = browser_download_url;
}
// win arm signature
if (name.endsWith("arm64-setup.nsis.zip.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms["windows-aarch64"].signature = sig;
}
// darwin url (intel) // darwin url (intel)
if (name.endsWith(".app.tar.gz") && !name.includes("aarch")) { if (name.endsWith(".app.tar.gz") && !name.includes("aarch")) {
updateData.platforms.darwin.url = browser_download_url; updateData.platforms.darwin.url = browser_download_url;
@@ -88,16 +113,32 @@ async function resolveUpdater() {
updateData.platforms["darwin-aarch64"].signature = sig; updateData.platforms["darwin-aarch64"].signature = sig;
} }
// linux url // linux x64 url
if (name.endsWith(".AppImage.tar.gz")) { if (name.endsWith("amd64.AppImage.tar.gz")) {
updateData.platforms.linux.url = browser_download_url; updateData.platforms.linux.url = browser_download_url;
updateData.platforms["linux-x86_64"].url = browser_download_url; updateData.platforms["linux-x86_64"].url = browser_download_url;
// 暂时使用x64版本的url和sig,使得可以检查更新,但aarch64版本还不支持构建appimage
updateData.platforms["linux-aarch64"].url = browser_download_url;
updateData.platforms["linux-armv7"].url = browser_download_url;
} }
// linux signature // linux x64 signature
if (name.endsWith(".AppImage.tar.gz.sig")) { if (name.endsWith("amd64.AppImage.tar.gz.sig")) {
const sig = await getSignature(browser_download_url); const sig = await getSignature(browser_download_url);
updateData.platforms.linux.signature = sig; updateData.platforms.linux.signature = sig;
updateData.platforms["linux-x86_64"].signature = sig; updateData.platforms["linux-x86_64"].signature = sig;
// 暂时使用x64版本的url和sig,使得可以检查更新,但aarch64版本还不支持构建appimage
updateData.platforms["linux-aarch64"].signature = sig;
updateData.platforms["linux-armv7"].signature = sig;
}
// linux x86 url
if (name.endsWith("i386.AppImage.tar.gz")) {
updateData.platforms["linux-i686"].url = browser_download_url;
}
// linux x86 signature
if (name.endsWith("i386.AppImage.tar.gz.sig")) {
const sig = await getSignature(browser_download_url);
updateData.platforms["linux-i686"].signature = sig;
} }
}); });
+548 -189
View File
File diff suppressed because it is too large Load Diff
+25 -33
View File
@@ -1,10 +1,10 @@
[package] [package]
name = "clash-verge" name = "clash-verge"
version = "1.4.1" version = "1.4.7"
description = "clash verge" description = "clash verge"
authors = ["zzzgydi"] authors = ["zzzgydi", "wonfen", "MystiPanda"]
license = "GPL-3.0" license = "GPL-3.0"
repository = "https://github.com/wonfen/clash-verge-rev.git" repository = "https://github.com/clash-verge-rev/clash-verge-rev.git"
default-run = "clash-verge" default-run = "clash-verge"
edition = "2021" edition = "2021"
build = "build.rs" build = "build.rs"
@@ -14,53 +14,45 @@ tauri-build = { version = "1", features = [] }
[dependencies] [dependencies]
warp = "0.3" warp = "0.3"
which = "4.2.2" sysproxy = "0.3.0"
which = "5.0.0"
anyhow = "1.0" anyhow = "1.0"
dirs = "5.0.0" dirs = "5.0"
open = "4.0.1" open = "5.0"
log = "0.4.14" log = "0.4"
ctrlc = "3.2.3" ctrlc = "3.4"
dunce = "1.0.2" dunce = "1.0"
log4rs = "1.0.0" log4rs = "1"
nanoid = "0.4.0" nanoid = "0.4"
chrono = "0.4.19" chrono = "0.4"
sysinfo = "0.29" sysinfo = "0.30"
sysproxy = "0.3" rquickjs = "0.3" # 高版本不支持 Linux aarch64
rquickjs = "0.1.7"
serde_json = "1.0" serde_json = "1.0"
serde_yaml = "0.9" serde_yaml = "0.9"
auto-launch = "0.5" auto-launch = "0.5"
once_cell = "1.14.0" once_cell = "1.18"
port_scanner = "0.1.5" port_scanner = "0.1.5"
delay_timer = "0.11.1" delay_timer = "0.11.5"
parking_lot = "0.12.0" parking_lot = "0.12"
percent-encoding = "2.3.1"
window-shadows = { version = "0.2" }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.11", features = ["json", "rustls-tls"] } reqwest = { version = "0.11", features = ["json", "rustls-tls"] }
tauri = { version = "1.2.4", features = ["global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all"] } tauri = { version = "1.5", features = [ "notification-all", "icon-png", "clipboard-all", "global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all"] }
window-vibrancy = { version = "0.3.0" }
window-shadows = { version = "0.2.0" }
wry = { version = "0.24.3" }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
runas = "=1.0.0" runas = "=1.0.0" # 高版本会返回错误 Status
deelevate = "0.2.0" deelevate = "0.2.0"
winreg = { version = "0.50", features = ["transactions"] } winreg = "0.52.0"
windows-sys = { version = "0.48", features = ["Win32_System_LibraryLoader", "Win32_System_SystemInformation"] }
[target.'cfg(windows)'.dependencies.tauri]
features = ["global-shortcut-all", "icon-png", "process-all", "shell-all", "system-tray", "updater", "window-all"]
[target.'cfg(linux)'.dependencies.tauri]
features = ["global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all", "native-tls-vendored", "reqwest-native-tls-vendored"]
[target.'cfg(target_os = "linux")'.dependencies]
#openssl
[features] [features]
default = ["custom-protocol"] default = ["custom-protocol"]
custom-protocol = ["tauri/custom-protocol"] custom-protocol = ["tauri/custom-protocol"]
verge-dev = [] verge-dev = []
default-meta = []
[profile.release] [profile.release]
panic = "abort" panic = "abort"
+17
View File
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>io.github.clash-verge-rev.clash-verge-rev</string>
<key>CFBundleURLSchemes</key>
<array>
<string>clash</string>
</array>
</dict>
</array>
</dict>
</plist>
+9
View File
@@ -0,0 +1,9 @@
[Desktop Entry]
Categories={{{categories}}}
Comment={{{comment}}}
Exec={{{exec}}} %u
Icon={{{icon}}}
Name={{{name}}}
Terminal=false
Type=Application
MimeType=x-scheme-handler/clash;
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

+15 -6
View File
@@ -30,6 +30,11 @@ pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult
wrap_err!(Config::profiles().data().append_item(item)) wrap_err!(Config::profiles().data().append_item(item))
} }
#[tauri::command]
pub async fn reorder_profile(active_id: String, over_id: String) -> CmdResult {
wrap_err!(Config::profiles().data().reorder(active_id, over_id))
}
#[tauri::command] #[tauri::command]
pub async fn create_profile(item: PrfItem, file_data: Option<String>) -> CmdResult { pub async fn create_profile(item: PrfItem, file_data: Option<String>) -> CmdResult {
let item = wrap_err!(PrfItem::from(item, file_data).await)?; let item = wrap_err!(PrfItem::from(item, file_data).await)?;
@@ -80,7 +85,7 @@ pub fn patch_profile(index: String, profile: PrfItem) -> CmdResult {
} }
#[tauri::command] #[tauri::command]
pub fn view_profile(index: String) -> CmdResult { pub fn view_profile(app_handle: tauri::AppHandle, index: String) -> CmdResult {
let file = { let file = {
wrap_err!(Config::profiles().latest().get_item(&index))? wrap_err!(Config::profiles().latest().get_item(&index))?
.file .file
@@ -93,7 +98,7 @@ pub fn view_profile(index: String) -> CmdResult {
ret_err!("the file not found"); ret_err!("the file not found");
} }
wrap_err!(help::open_file(path)) wrap_err!(help::open_file(app_handle, path))
} }
#[tauri::command] #[tauri::command]
@@ -214,7 +219,7 @@ pub fn open_app_dir() -> CmdResult<()> {
#[tauri::command] #[tauri::command]
pub fn open_core_dir() -> CmdResult<()> { pub fn open_core_dir() -> CmdResult<()> {
let core_dir = wrap_err!(tauri::utils::platform::current_exe())?; let core_dir = wrap_err!(tauri::utils::platform::current_exe())?;
let core_dir = core_dir.parent().ok_or(format!("failed to get core dir"))?; let core_dir = core_dir.parent().ok_or("failed to get core dir")?;
wrap_err!(open::that(core_dir)) wrap_err!(open::that(core_dir))
} }
@@ -229,7 +234,6 @@ pub fn open_web_url(url: String) -> CmdResult<()> {
wrap_err!(open::that(url)) wrap_err!(open::that(url))
} }
#[cfg(windows)] #[cfg(windows)]
pub mod uwp { pub mod uwp {
use super::*; use super::*;
@@ -248,10 +252,15 @@ pub async fn clash_api_get_proxy_delay(
) -> CmdResult<clash_api::DelayRes> { ) -> CmdResult<clash_api::DelayRes> {
match clash_api::get_proxy_delay(name, url).await { match clash_api::get_proxy_delay(name, url).await {
Ok(res) => Ok(res), Ok(res) => Ok(res),
Err(err) => Err(format!("{}", err.to_string())), Err(err) => Err(err.to_string()),
} }
} }
#[tauri::command]
pub fn get_portable_flag() -> CmdResult<bool> {
Ok(*dirs::PORTABLE_FLAG.get().unwrap_or(&false))
}
#[cfg(windows)] #[cfg(windows)]
pub mod service { pub mod service {
use super::*; use super::*;
@@ -299,4 +308,4 @@ pub mod uwp {
pub async fn invoke_uwp_tool() -> CmdResult { pub async fn invoke_uwp_tool() -> CmdResult {
Ok(()) Ok(())
} }
} }
+14 -31
View File
@@ -24,29 +24,12 @@ impl IClashTemp {
pub fn template() -> Self { pub fn template() -> Self {
let mut map = Mapping::new(); let mut map = Mapping::new();
map.insert( map.insert("mixed-port".into(), 7897.into());
"mixed-port".into(),
match cfg!(feature = "default-meta") {
false => 7890.into(),
true => 7898.into(),
},
);
map.insert("log-level".into(), "info".into()); map.insert("log-level".into(), "info".into());
map.insert("allow-lan".into(), false.into()); map.insert("allow-lan".into(), false.into());
map.insert("mode".into(), "rule".into()); map.insert("mode".into(), "rule".into());
map.insert( map.insert("external-controller".into(), "127.0.0.1:9097".into());
"external-controller".into(),
match cfg!(feature = "default-meta") {
false => "127.0.0.1:9090".into(),
true => "127.0.0.1:9098".into(),
},
);
map.insert("secret".into(), "".into()); map.insert("secret".into(), "".into());
#[cfg(feature = "default-meta")]
map.insert("unified-delay".into(), true.into());
#[cfg(feature = "default-meta")]
map.insert("tcp-concurrent".into(), true.into());
// map.insert("ipv6".into(), false.into());
Self(map) Self(map)
} }
@@ -82,8 +65,8 @@ impl IClashTemp {
let config = &self.0; let config = &self.0;
ClashInfo { ClashInfo {
port: Self::guard_mixed_port(&config), port: Self::guard_mixed_port(config),
server: Self::guard_client_ctrl(&config), server: Self::guard_client_ctrl(config),
secret: config.get("secret").and_then(|value| match value { secret: config.get("secret").and_then(|value| match value {
Value::String(val_str) => Some(val_str.clone()), Value::String(val_str) => Some(val_str.clone()),
Value::Bool(val_bool) => Some(val_bool.to_string()), Value::Bool(val_bool) => Some(val_bool.to_string()),
@@ -101,9 +84,9 @@ impl IClashTemp {
Value::Number(val_num) => val_num.as_u64().map(|u| u as u16), Value::Number(val_num) => val_num.as_u64().map(|u| u as u16),
_ => None, _ => None,
}) })
.unwrap_or(7890); .unwrap_or(7897);
if port == 0 { if port == 0 {
port = 7890; port = 7897;
} }
port port
} }
@@ -115,7 +98,7 @@ impl IClashTemp {
Some(val_str) => { Some(val_str) => {
let val_str = val_str.trim(); let val_str = val_str.trim();
let val = match val_str.starts_with(":") { let val = match val_str.starts_with(':') {
true => format!("127.0.0.1{val_str}"), true => format!("127.0.0.1{val_str}"),
false => val_str.to_owned(), false => val_str.to_owned(),
}; };
@@ -126,7 +109,7 @@ impl IClashTemp {
} }
None => None, None => None,
}) })
.unwrap_or("127.0.0.1:9090".into()) .unwrap_or("127.0.0.1:9097".into())
} }
pub fn guard_client_ctrl(config: &Mapping) -> String { pub fn guard_client_ctrl(config: &Mapping) -> String {
@@ -138,7 +121,7 @@ impl IClashTemp {
} }
socket.to_string() socket.to_string()
} }
Err(_) => "127.0.0.1:9090".into(), Err(_) => "127.0.0.1:9097".into(),
} }
} }
} }
@@ -173,12 +156,12 @@ fn test_clash_info() {
assert_eq!( assert_eq!(
IClashTemp(IClashTemp::guard(Mapping::new())).get_client_info(), IClashTemp(IClashTemp::guard(Mapping::new())).get_client_info(),
get_result(7890, "127.0.0.1:9090") get_result(7897, "127.0.0.1:9097")
); );
assert_eq!(get_case("", ""), get_result(7890, "127.0.0.1:9090")); assert_eq!(get_case("", ""), get_result(7897, "127.0.0.1:9097"));
assert_eq!(get_case(65537, ""), get_result(1, "127.0.0.1:9090")); assert_eq!(get_case(65537, ""), get_result(1, "127.0.0.1:9097"));
assert_eq!( assert_eq!(
get_case(8888, "127.0.0.1:8888"), get_case(8888, "127.0.0.1:8888"),
@@ -187,7 +170,7 @@ fn test_clash_info() {
assert_eq!( assert_eq!(
get_case(8888, " :98888 "), get_case(8888, " :98888 "),
get_result(8888, "127.0.0.1:9090") get_result(8888, "127.0.0.1:9097")
); );
assert_eq!( assert_eq!(
@@ -212,7 +195,7 @@ fn test_clash_info() {
assert_eq!( assert_eq!(
get_case(8888, "192.168.1.1:80800"), get_case(8888, "192.168.1.1:80800"),
get_result(8888, "127.0.0.1:9090") get_result(8888, "127.0.0.1:9097")
); );
} }
+45 -47
View File
@@ -1,4 +1,4 @@
use crate::utils::{dirs, help, tmpl}; use crate::utils::{dirs, help, resolve::VERSION, tmpl};
use anyhow::{bail, Context, Result}; use anyhow::{bail, Context, Result};
use reqwest::StatusCode; use reqwest::StatusCode;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -8,7 +8,7 @@ use sysproxy::Sysproxy;
use super::Config; use super::Config;
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct PrfItem { pub struct PrfItem {
pub uid: Option<String>, pub uid: Option<String>,
@@ -96,25 +96,7 @@ impl PrfOption {
a.update_interval = b.update_interval.or(a.update_interval); a.update_interval = b.update_interval.or(a.update_interval);
Some(a) Some(a)
} }
t @ _ => t.0.or(t.1), t => t.0.or(t.1),
}
}
}
impl Default for PrfItem {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
} }
} }
} }
@@ -152,7 +134,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 profile item type \"{typ}\""), typ => bail!("invalid profile item type \"{typ}\""),
} }
} }
@@ -188,13 +170,16 @@ impl PrfItem {
let opt_ref = option.as_ref(); let opt_ref = option.as_ref();
let with_proxy = opt_ref.map_or(false, |o| o.with_proxy.unwrap_or(false)); let with_proxy = opt_ref.map_or(false, |o| o.with_proxy.unwrap_or(false));
let self_proxy = opt_ref.map_or(false, |o| o.self_proxy.unwrap_or(false)); let self_proxy = opt_ref.map_or(false, |o| o.self_proxy.unwrap_or(false));
let user_agent = opt_ref.map_or(None, |o| o.user_agent.clone()); let user_agent = opt_ref.and_then(|o| o.user_agent.clone());
let mut builder = reqwest::ClientBuilder::new().use_rustls_tls().no_proxy(); let mut builder = reqwest::ClientBuilder::new().use_rustls_tls().no_proxy();
// 使用软件自己的代理 // 使用软件自己的代理
if self_proxy { if self_proxy {
let port = Config::clash().data().get_mixed_port(); let port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
let proxy_scheme = format!("http://127.0.0.1:{port}"); let proxy_scheme = format!("http://127.0.0.1:{port}");
@@ -210,26 +195,26 @@ impl PrfItem {
} }
// 使用系统代理 // 使用系统代理
else if with_proxy { else if with_proxy {
match Sysproxy::get_system_proxy() { if let Ok(p @ Sysproxy { enable: true, .. }) = Sysproxy::get_system_proxy() {
Ok(p @ Sysproxy { enable: true, .. }) => { let proxy_scheme = format!("http://{}:{}", p.host, p.port);
let proxy_scheme = format!("http://{}:{}", p.host, p.port);
if let Ok(proxy) = reqwest::Proxy::http(&proxy_scheme) { if let Ok(proxy) = reqwest::Proxy::http(&proxy_scheme) {
builder = builder.proxy(proxy); builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::https(&proxy_scheme) {
builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::all(&proxy_scheme) {
builder = builder.proxy(proxy);
}
} }
_ => {} if let Ok(proxy) = reqwest::Proxy::https(&proxy_scheme) {
}; builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::all(&proxy_scheme) {
builder = builder.proxy(proxy);
}
}
} }
let version = unsafe { dirs::APP_VERSION }; let version = match VERSION.get() {
let version = format!("clash-verge/{version}"); Some(v) => format!("clash-verge/v{}", v),
None => "clash-verge/unknown".to_string(),
};
builder = builder.user_agent(user_agent.unwrap_or(version)); builder = builder.user_agent(user_agent.unwrap_or(version));
let resp = builder.build()?.get(url).send().await?; let resp = builder.build()?.get(url).send().await?;
@@ -245,12 +230,11 @@ impl PrfItem {
let extra = match header.get("Subscription-Userinfo") { let extra = match header.get("Subscription-Userinfo") {
Some(value) => { Some(value) => {
let sub_info = value.to_str().unwrap_or(""); let sub_info = value.to_str().unwrap_or("");
Some(PrfExtra { Some(PrfExtra {
upload: help::parse_str(sub_info, "upload=").unwrap_or(0), upload: help::parse_str(sub_info, "upload").unwrap_or(0),
download: help::parse_str(sub_info, "download=").unwrap_or(0), download: help::parse_str(sub_info, "download").unwrap_or(0),
total: help::parse_str(sub_info, "total=").unwrap_or(0), total: help::parse_str(sub_info, "total").unwrap_or(0),
expire: help::parse_str(sub_info, "expire=").unwrap_or(0), expire: help::parse_str(sub_info, "expire").unwrap_or(0),
}) })
} }
None => None, None => None,
@@ -259,8 +243,22 @@ impl PrfItem {
// parse the Content-Disposition // parse the Content-Disposition
let filename = match header.get("Content-Disposition") { let filename = match header.get("Content-Disposition") {
Some(value) => { Some(value) => {
let filename = value.to_str().unwrap_or(""); let filename = format!("{value:?}");
help::parse_str::<String>(filename, "filename=") let filename = filename.trim_matches('"');
match help::parse_str::<String>(filename, "filename*") {
Some(filename) => {
let iter = percent_encoding::percent_decode(filename.as_bytes());
let filename = iter.decode_utf8().unwrap_or_default();
filename.split("''").last().map(|s| s.to_string())
}
None => match help::parse_str::<String>(filename, "filename") {
Some(filename) => {
let filename = filename.trim_matches('"');
Some(filename.to_string())
}
None => None,
},
}
} }
None => None, None => None,
}; };
+42 -11
View File
@@ -37,13 +37,13 @@ impl IProfiles {
profiles.items = Some(vec![]); profiles.items = Some(vec![]);
} }
// compatible with the old old old version // compatible with the old old old version
profiles.items.as_mut().map(|items| { if let Some(items) = profiles.items.as_mut() {
for item in items.iter_mut() { for item in items.iter_mut() {
if item.uid.is_none() { if item.uid.is_none() {
item.uid = Some(help::get_uid("d")); item.uid = Some(help::get_uid("d"));
} }
} }
}); }
profiles profiles
} }
Err(err) => { Err(err) => {
@@ -55,7 +55,12 @@ impl IProfiles {
pub fn template() -> Self { pub fn template() -> Self {
Self { Self {
valid: Some(vec!["dns".into(), "sub-rules".into(), "unified-delay".into(), "tcp-concurrent".into()]), valid: Some(vec![
"dns".into(),
"sub-rules".into(),
"unified-delay".into(),
"tcp-concurrent".into(),
]),
items: Some(vec![]), items: Some(vec![]),
..Self::default() ..Self::default()
} }
@@ -147,13 +152,39 @@ impl IProfiles {
self.items = Some(vec![]); self.items = Some(vec![]);
} }
self.items.as_mut().map(|items| items.push(item)); if let Some(items) = self.items.as_mut() {
items.push(item)
}
self.save_file()
}
/// reorder items
pub fn reorder(&mut self, active_id: String, over_id: String) -> Result<()> {
let mut items = self.items.take().unwrap_or_default();
let mut old_index = None;
let mut new_index = None;
for (i, _) in items.iter().enumerate() {
if items[i].uid == Some(active_id.clone()) {
old_index = Some(i);
}
if items[i].uid == Some(over_id.clone()) {
new_index = Some(i);
}
}
if old_index.is_none() || new_index.is_none() {
return Ok(());
}
let item = items.remove(old_index.unwrap());
items.insert(new_index.unwrap(), item);
self.items = Some(items);
self.save_file() self.save_file()
} }
/// update the item value /// update the item value
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> { pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]); let mut items = self.items.take().unwrap_or_default();
for each in items.iter_mut() { for each in items.iter_mut() {
if each.uid == Some(uid.clone()) { if each.uid == Some(uid.clone()) {
@@ -226,11 +257,11 @@ impl IProfiles {
let current = self.current.as_ref().unwrap_or(&uid); let current = self.current.as_ref().unwrap_or(&uid);
let current = current.clone(); let current = current.clone();
let mut items = self.items.take().unwrap_or(vec![]); let mut items = self.items.take().unwrap_or_default();
let mut index = None; let mut index = None;
// get the index // get the index
for i in 0..items.len() { for (i, _) in items.iter().enumerate() {
if items[i].uid == Some(uid.clone()) { if items[i].uid == Some(uid.clone()) {
index = Some(i); index = Some(i);
break; break;
@@ -238,19 +269,19 @@ impl IProfiles {
} }
if let Some(index) = index { if let Some(index) = index {
items.remove(index).file.map(|file| { if let Some(file) = items.remove(index).file {
let _ = dirs::app_profiles_dir().map(|path| { let _ = dirs::app_profiles_dir().map(|path| {
let path = path.join(file); let path = path.join(file);
if path.exists() { if path.exists() {
let _ = fs::remove_file(path); let _ = fs::remove_file(path);
} }
}); });
}); }
} }
// delete the original uid // delete the original uid
if current == uid { if current == uid {
self.current = match items.len() > 0 { self.current = match !items.is_empty() {
true => items[0].uid.clone(), true => items[0].uid.clone(),
false => None, false => None,
}; };
@@ -270,7 +301,7 @@ impl IProfiles {
Some(file) => dirs::app_profiles_dir()?.join(file), Some(file) => dirs::app_profiles_dir()?.join(file),
None => bail!("failed to get the file field"), None => bail!("failed to get the file field"),
}; };
return Ok(help::read_merge_mapping(&file_path)?); return help::read_merge_mapping(&file_path);
} }
bail!("failed to find the current profile \"uid:{current}\""); bail!("failed to find the current profile \"uid:{current}\"");
} }
+21 -9
View File
@@ -26,6 +26,9 @@ pub struct IVerge {
/// tray click event /// tray click event
pub tray_event: Option<String>, pub tray_event: Option<String>,
/// copy env type
pub env_type: Option<String>,
/// enable traffic graph default is true /// enable traffic graph default is true
pub traffic_graph: Option<bool>, pub traffic_graph: Option<bool>,
@@ -77,7 +80,7 @@ pub struct IVerge {
/// 默认的延迟测试连接 /// 默认的延迟测试连接
pub default_latency_test: Option<String>, pub default_latency_test: Option<String>,
/// 支持关闭字段过滤,避免meta的新字段都被过滤掉,默认为真 /// 支持关闭字段过滤,避免meta的新字段都被过滤掉,默认为关闭
pub enable_clash_fields: Option<bool>, pub enable_clash_fields: Option<bool>,
/// 是否使用内部的脚本支持,默认为真 /// 是否使用内部的脚本支持,默认为真
@@ -93,6 +96,12 @@ pub struct IVerge {
/// window size and position /// window size and position
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub window_size_position: Option<Vec<f64>>, pub window_size_position: Option<Vec<f64>>,
/// 是否启用随机端口
pub enable_random_port: Option<bool>,
/// verge mixed port 用于覆盖 clash 的 mixed port
pub verge_mixed_port: Option<u16>,
} }
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -124,21 +133,21 @@ impl IVerge {
pub fn template() -> Self { pub fn template() -> Self {
Self { Self {
clash_core: match cfg!(feature = "default-meta") { clash_core: Some("clash-meta".into()),
false => Some("clash".into()), language: Some("zh".into()),
true => Some("clash-meta".into()),
},
language: match cfg!(feature = "default-meta") {
false => Some("en".into()),
true => Some("zh".into()),
},
theme_mode: Some("system".into()), theme_mode: Some("system".into()),
#[cfg(not(target_os = "windows"))]
env_type: Some("bash".into()),
#[cfg(target_os = "windows")]
env_type: Some("powershell".into()),
theme_blur: Some(false), theme_blur: Some(false),
traffic_graph: Some(true), traffic_graph: Some(true),
enable_memory_usage: Some(true), enable_memory_usage: Some(true),
enable_auto_launch: Some(false), enable_auto_launch: Some(false),
enable_silent_start: Some(false), enable_silent_start: Some(false),
enable_system_proxy: Some(false), enable_system_proxy: Some(false),
enable_random_port: Some(false),
verge_mixed_port: Some(7897),
enable_proxy_guard: Some(false), enable_proxy_guard: Some(false),
proxy_guard_duration: Some(30), proxy_guard_duration: Some(30),
auto_close_connection: Some(true), auto_close_connection: Some(true),
@@ -170,6 +179,7 @@ impl IVerge {
patch!(theme_mode); patch!(theme_mode);
patch!(theme_blur); patch!(theme_blur);
patch!(tray_event); patch!(tray_event);
patch!(env_type);
patch!(traffic_graph); patch!(traffic_graph);
patch!(enable_memory_usage); patch!(enable_memory_usage);
@@ -177,6 +187,8 @@ impl IVerge {
patch!(enable_service_mode); patch!(enable_service_mode);
patch!(enable_auto_launch); patch!(enable_auto_launch);
patch!(enable_silent_start); patch!(enable_silent_start);
patch!(enable_random_port);
patch!(verge_mixed_port);
patch!(enable_system_proxy); patch!(enable_system_proxy);
patch!(enable_proxy_guard); patch!(enable_proxy_guard);
patch!(system_proxy_bypass); patch!(system_proxy_bypass);
+6 -6
View File
@@ -20,7 +20,7 @@ pub async fn put_configs(path: &str) -> Result<()> {
match response.status().as_u16() { match response.status().as_u16() {
204 => Ok(()), 204 => Ok(()),
status @ _ => { status => {
bail!("failed to put configs with status \"{status}\"") bail!("failed to put configs with status \"{status}\"")
} }
} }
@@ -83,12 +83,12 @@ fn clash_client_info() -> Result<(String, HeaderMap)> {
/// 缩短clash的日志 /// 缩短clash的日志
pub fn parse_log(log: String) -> String { pub fn parse_log(log: String) -> String {
if log.starts_with("time=") && log.len() > 33 { if log.starts_with("time=") && log.len() > 33 {
return (&log[33..]).to_owned(); return (log[33..]).to_owned();
} }
if log.len() > 9 { if log.len() > 9 {
return (&log[9..]).to_owned(); return (log[9..]).to_owned();
} }
return log; log
} }
/// 缩短clash -t的错误输出 /// 缩短clash -t的错误输出
@@ -105,7 +105,7 @@ pub fn parse_check_output(log: String) -> String {
}; };
if mr > m { if mr > m {
return (&log[e..mr]).to_owned(); return (log[e..mr]).to_owned();
} }
} }
@@ -113,7 +113,7 @@ pub fn parse_check_output(log: String) -> String {
let r = log.find("path=").or(Some(log.len())); let r = log.find("path=").or(Some(log.len()));
if let (Some(l), Some(r)) = (l, r) { if let (Some(l), Some(r)) = (l, r) {
return (&log[(l + 6)..(r - 1)]).to_owned(); return (log[(l + 6)..(r - 1)]).to_owned();
} }
log log
+8 -6
View File
@@ -5,7 +5,7 @@ use anyhow::{bail, Context, Result};
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::{fs, io::Write, sync::Arc, time::Duration}; use std::{fs, io::Write, sync::Arc, time::Duration};
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt}; use sysinfo::{Pid, System};
use tauri::api::process::{Command, CommandChild, CommandEvent}; use tauri::api::process::{Command, CommandChild, CommandEvent};
use tokio::time::sleep; use tokio::time::sleep;
@@ -35,12 +35,12 @@ impl CoreManager {
.map(|pid| { .map(|pid| {
let mut system = System::new(); let mut system = System::new();
system.refresh_all(); system.refresh_all();
system.process(Pid::from_u32(pid)).map(|proc| { if let Some(proc) = system.process(Pid::from_u32(pid)) {
if proc.name().contains("clash") { if proc.name().contains("clash") {
log::debug!(target: "app", "kill old clash process"); log::debug!(target: "app", "kill old clash process");
proc.kill(); proc.kill();
} }
}); }
}); });
tauri::async_runtime::spawn(async { tauri::async_runtime::spawn(async {
@@ -68,7 +68,7 @@ impl CoreManager {
if !output.status.success() { if !output.status.success() {
let error = clash_api::parse_check_output(output.stdout.clone()); let error = clash_api::parse_check_output(output.stdout.clone());
let error = match error.len() > 0 { let error = match !error.is_empty() {
true => error, true => error,
false => output.stdout.clone(), false => output.stdout.clone(),
}; };
@@ -110,7 +110,7 @@ impl CoreManager {
use super::win_service; use super::win_service;
// 服务模式 // 服务模式
let enable = { Config::verge().latest().enable_service_mode.clone() }; let enable = { Config::verge().latest().enable_service_mode };
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
*self.use_service_mode.lock() = enable; *self.use_service_mode.lock() = enable;
@@ -147,6 +147,7 @@ impl CoreManager {
// fix #212 // fix #212
let args = match clash_core.as_str() { let args = match clash_core.as_str() {
"clash-meta" => vec!["-m", "-d", app_dir, "-f", config_path], "clash-meta" => vec!["-m", "-d", app_dir, "-f", config_path],
"clash-meta-alpha" => vec!["-m", "-d", app_dir, "-f", config_path],
_ => vec!["-d", app_dir, "-f", config_path], _ => vec!["-d", app_dir, "-f", config_path],
}; };
@@ -258,8 +259,9 @@ impl CoreManager {
/// 切换核心 /// 切换核心
pub async fn change_core(&self, clash_core: Option<String>) -> Result<()> { pub async fn change_core(&self, clash_core: Option<String>) -> Result<()> {
let clash_core = clash_core.ok_or(anyhow::anyhow!("clash core is null"))?; let clash_core = clash_core.ok_or(anyhow::anyhow!("clash core is null"))?;
const CLASH_CORES: [&str; 3] = ["clash", "clash-meta", "clash-meta-alpha"];
if &clash_core != "clash" && &clash_core != "clash-meta" { if !CLASH_CORES.contains(&clash_core.as_str()) {
bail!("invalid clash core name \"{clash_core}\""); bail!("invalid clash core name \"{clash_core}\"");
} }
+1 -1
View File
@@ -28,7 +28,7 @@ impl Handle {
self.app_handle self.app_handle
.lock() .lock()
.as_ref() .as_ref()
.map_or(None, |a| a.get_window("main")) .and_then(|a| a.get_window("main"))
} }
pub fn refresh_clash() { pub fn refresh_clash() {
+10 -26
View File
@@ -4,7 +4,6 @@ use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::{collections::HashMap, sync::Arc}; use std::{collections::HashMap, sync::Arc};
use tauri::{AppHandle, GlobalShortcutManager}; use tauri::{AppHandle, GlobalShortcutManager};
use wry::application::accelerator::Accelerator;
pub struct Hotkey { pub struct Hotkey {
current: Arc<Mutex<Vec<String>>>, // 保存当前的热键设置 current: Arc<Mutex<Vec<String>>>, // 保存当前的热键设置
@@ -35,7 +34,7 @@ impl Hotkey {
match (key, func) { match (key, func) {
(Some(key), Some(func)) => { (Some(key), Some(func)) => {
log_err!(Self::check_key(key).and_then(|_| self.register(key, func))); log_err!(self.register(key, func));
} }
_ => { _ => {
let key = key.unwrap_or("None"); let key = key.unwrap_or("None");
@@ -50,16 +49,6 @@ impl Hotkey {
Ok(()) Ok(())
} }
/// 检查一个键是否合法
fn check_key(hotkey: &str) -> Result<()> {
// fix #287
// tauri的这几个方法全部有Result expect,会panic,先检测一遍避免挂了
if hotkey.parse::<Accelerator>().is_err() {
bail!("invalid hotkey `{hotkey}`");
}
Ok(())
}
fn get_manager(&self) -> Result<impl GlobalShortcutManager> { fn get_manager(&self) -> Result<impl GlobalShortcutManager> {
let app_handle = self.app_handle.lock(); let app_handle = self.app_handle.lock();
if app_handle.is_none() { if app_handle.is_none() {
@@ -76,17 +65,17 @@ impl Hotkey {
} }
let f = match func.trim() { let f = match func.trim() {
"open_dashboard" => || feat::open_dashboard(), "open_dashboard" => feat::open_dashboard,
"clash_mode_rule" => || feat::change_clash_mode("rule".into()), "clash_mode_rule" => || feat::change_clash_mode("rule".into()),
"clash_mode_global" => || feat::change_clash_mode("global".into()), "clash_mode_global" => || feat::change_clash_mode("global".into()),
"clash_mode_direct" => || feat::change_clash_mode("direct".into()), "clash_mode_direct" => || feat::change_clash_mode("direct".into()),
"clash_mode_script" => || feat::change_clash_mode("script".into()), "clash_mode_script" => || feat::change_clash_mode("script".into()),
"toggle_system_proxy" => || feat::toggle_system_proxy(), "toggle_system_proxy" => feat::toggle_system_proxy,
"enable_system_proxy" => || feat::enable_system_proxy(), "enable_system_proxy" => feat::enable_system_proxy,
"disable_system_proxy" => || feat::disable_system_proxy(), "disable_system_proxy" => feat::disable_system_proxy,
"toggle_tun_mode" => || feat::toggle_tun_mode(), "toggle_tun_mode" => feat::toggle_tun_mode,
"enable_tun_mode" => || feat::enable_tun_mode(), "enable_tun_mode" => feat::enable_tun_mode,
"disable_tun_mode" => || feat::disable_tun_mode(), "disable_tun_mode" => feat::disable_tun_mode,
_ => bail!("invalid function \"{func}\""), _ => bail!("invalid function \"{func}\""),
}; };
@@ -97,7 +86,7 @@ impl Hotkey {
} }
fn unregister(&self, hotkey: &str) -> Result<()> { fn unregister(&self, hotkey: &str) -> Result<()> {
self.get_manager()?.unregister(&hotkey)?; self.get_manager()?.unregister(hotkey)?;
log::info!(target: "app", "unregister hotkey {hotkey}"); log::info!(target: "app", "unregister hotkey {hotkey}");
Ok(()) Ok(())
} }
@@ -109,11 +98,6 @@ impl Hotkey {
let (del, add) = Self::get_diff(old_map, new_map); let (del, add) = Self::get_diff(old_map, new_map);
// 先检查一遍所有新的热键是不是可以用的
for (hotkey, _) in add.iter() {
Self::check_key(hotkey)?;
}
del.iter().for_each(|key| { del.iter().for_each(|key| {
let _ = self.unregister(key); let _ = self.unregister(key);
}); });
@@ -126,7 +110,7 @@ impl Hotkey {
Ok(()) Ok(())
} }
fn get_map_from_vec<'a>(hotkeys: &'a Vec<String>) -> HashMap<&'a str, &'a str> { fn get_map_from_vec(hotkeys: &Vec<String>) -> HashMap<&str, &str> {
let mut map = HashMap::new(); let mut map = HashMap::new();
hotkeys.iter().for_each(|hotkey| { hotkeys.iter().for_each(|hotkey| {
-35
View File
@@ -1,5 +1,3 @@
use std::borrow::Cow;
/// 给clash内核的tun模式授权 /// 给clash内核的tun模式授权
#[cfg(any(target_os = "macos", target_os = "linux"))] #[cfg(any(target_os = "macos", target_os = "linux"))]
pub fn grant_permission(core: String) -> anyhow::Result<()> { pub fn grant_permission(core: String) -> anyhow::Result<()> {
@@ -13,9 +11,6 @@ pub fn grant_permission(core: String) -> anyhow::Result<()> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
let output = { let output = {
// the path of clash /Applications/Clash Verge.app/Contents/MacOS/clash
// https://apple.stackexchange.com/questions/82967/problem-with-empty-spaces-when-executing-shell-commands-in-applescript
// let path = escape(&path);
let path = path.replace(' ', "\\\\ "); let path = path.replace(' ', "\\\\ ");
let shell = format!("chown root:admin {path}\nchmod +sx {path}"); let shell = format!("chown root:admin {path}\nchmod +sx {path}");
let command = format!(r#"do shell script "{shell}" with administrator privileges"#); let command = format!(r#"do shell script "{shell}" with administrator privileges"#);
@@ -50,33 +45,3 @@ pub fn grant_permission(core: String) -> anyhow::Result<()> {
anyhow::bail!("{stderr}"); anyhow::bail!("{stderr}");
} }
} }
#[allow(unused)]
pub fn escape<'a>(text: &'a str) -> Cow<'a, str> {
let bytes = text.as_bytes();
let mut owned = None;
for pos in 0..bytes.len() {
let special = match bytes[pos] {
b' ' => Some(b' '),
_ => None,
};
if let Some(s) = special {
if owned.is_none() {
owned = Some(bytes[0..pos].to_owned());
}
owned.as_mut().unwrap().push(b'\\');
owned.as_mut().unwrap().push(b'\\');
owned.as_mut().unwrap().push(s);
} else if let Some(owned) = owned.as_mut() {
owned.push(bytes[pos]);
}
}
if let Some(owned) = owned {
unsafe { Cow::Owned(String::from_utf8_unchecked(owned)) }
} else {
unsafe { Cow::Borrowed(std::str::from_utf8_unchecked(bytes)) }
}
}
+20 -11
View File
@@ -27,7 +27,8 @@ static DEFAULT_BYPASS: &str = "localhost;127.*;192.168.*;10.*;172.16.*;<local>";
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
static DEFAULT_BYPASS: &str = "localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1"; static DEFAULT_BYPASS: &str = "localhost,127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,::1";
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
static DEFAULT_BYPASS: &str = "127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>"; static DEFAULT_BYPASS: &str =
"127.0.0.1,192.168.0.0/16,10.0.0.0/8,172.16.0.0/12,localhost,*.local,*.crashlytics.com,<local>";
impl Sysopt { impl Sysopt {
pub fn global() -> &'static Sysopt { pub fn global() -> &'static Sysopt {
@@ -43,13 +44,16 @@ impl Sysopt {
/// init the sysproxy /// init the sysproxy
pub fn init_sysproxy(&self) -> Result<()> { pub fn init_sysproxy(&self) -> Result<()> {
let port = { Config::clash().latest().get_mixed_port() }; let port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
let (enable, bypass) = { let (enable, bypass) = {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
( (
verge.enable_system_proxy.clone().unwrap_or(false), verge.enable_system_proxy.unwrap_or(false),
verge.system_proxy_bypass.clone(), verge.system_proxy_bypass.clone(),
) )
}; };
@@ -62,7 +66,7 @@ impl Sysopt {
}; };
if enable { if enable {
let old = Sysproxy::get_system_proxy().map_or(None, |p| Some(p)); let old = Sysproxy::get_system_proxy().ok();
current.set_system_proxy()?; current.set_system_proxy()?;
*self.old_sysproxy.lock() = old; *self.old_sysproxy.lock() = old;
@@ -89,7 +93,7 @@ impl Sysopt {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
( (
verge.enable_system_proxy.clone().unwrap_or(false), verge.enable_system_proxy.unwrap_or(false),
verge.system_proxy_bypass.clone(), verge.system_proxy_bypass.clone(),
) )
}; };
@@ -138,7 +142,7 @@ impl Sysopt {
/// init the auto launch /// init the auto launch
pub fn init_launch(&self) -> Result<()> { pub fn init_launch(&self) -> Result<()> {
let enable = { Config::verge().latest().enable_auto_launch.clone() }; let enable = { Config::verge().latest().enable_auto_launch };
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
let app_exe = current_exe()?; let app_exe = current_exe()?;
@@ -229,7 +233,7 @@ impl Sysopt {
drop(auto_launch); drop(auto_launch);
return self.init_launch(); return self.init_launch();
} }
let enable = { Config::verge().latest().enable_auto_launch.clone() }; let enable = { Config::verge().latest().enable_auto_launch };
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
let auto_launch = auto_launch.as_ref().unwrap(); let auto_launch = auto_launch.as_ref().unwrap();
@@ -267,9 +271,9 @@ impl Sysopt {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
( (
verge.enable_system_proxy.clone().unwrap_or(false), verge.enable_system_proxy.unwrap_or(false),
verge.enable_proxy_guard.clone().unwrap_or(false), verge.enable_proxy_guard.unwrap_or(false),
verge.proxy_guard_duration.clone().unwrap_or(10), verge.proxy_guard_duration.unwrap_or(10),
verge.system_proxy_bypass.clone(), verge.system_proxy_bypass.clone(),
) )
}; };
@@ -284,7 +288,12 @@ impl Sysopt {
log::debug!(target: "app", "try to guard the system proxy"); log::debug!(target: "app", "try to guard the system proxy");
let port = { Config::clash().latest().get_mixed_port() }; let port = {
Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port())
};
let sysproxy = Sysproxy { let sysproxy = Sysproxy {
enable: true, enable: true,
+2 -2
View File
@@ -40,7 +40,7 @@ impl Timer {
let timer_map = self.timer_map.lock(); let timer_map = self.timer_map.lock();
let delay_timer = self.delay_timer.lock(); let delay_timer = self.delay_timer.lock();
Config::profiles().latest().get_items().map(|items| { if let Some(items) = Config::profiles().latest().get_items() {
items items
.iter() .iter()
.filter_map(|item| { .filter_map(|item| {
@@ -61,7 +61,7 @@ impl Timer {
} }
} }
}) })
}); }
Ok(()) Ok(())
} }
+27 -33
View File
@@ -41,10 +41,6 @@ impl Tray {
"direct_mode", "direct_mode",
t!("Direct Mode", "直连模式"), t!("Direct Mode", "直连模式"),
)) ))
.add_item(CustomMenuItem::new(
"script_mode",
t!("Script Mode", "脚本模式"),
))
.add_native_item(SystemTrayMenuItem::Separator) .add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new(
"system_proxy", "system_proxy",
@@ -52,16 +48,8 @@ impl Tray {
)) ))
.add_item(CustomMenuItem::new("tun_mode", t!("TUN Mode", "Tun 模式"))) .add_item(CustomMenuItem::new("tun_mode", t!("TUN Mode", "Tun 模式")))
.add_item(CustomMenuItem::new( .add_item(CustomMenuItem::new(
"copy_env_sh", "copy_env",
t!("Copy Env (sh)", "复制环境变量(sh)"), t!("Copy Env", "复制环境变量"),
))
.add_item(CustomMenuItem::new(
"copy_env_cmd",
t!("Copy Env (CMD)", "复制环境变量(CMD)"),
))
.add_item(CustomMenuItem::new(
"copy_env_ps",
t!("Copy Env (PS)", "复制环境变量(PS)"),
)) ))
.add_submenu(SystemTraySubmenu::new( .add_submenu(SystemTraySubmenu::new(
t!("Open Dir", "打开目录"), t!("Open Dir", "打开目录"),
@@ -136,24 +124,36 @@ impl Tray {
let _ = tray.get_item("rule_mode").set_selected(mode == "rule"); let _ = tray.get_item("rule_mode").set_selected(mode == "rule");
let _ = tray.get_item("global_mode").set_selected(mode == "global"); let _ = tray.get_item("global_mode").set_selected(mode == "global");
let _ = tray.get_item("direct_mode").set_selected(mode == "direct"); let _ = tray.get_item("direct_mode").set_selected(mode == "direct");
let _ = tray.get_item("script_mode").set_selected(mode == "script");
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false); let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false);
let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false); let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false);
#[cfg(target_os = "windows")] let mut indication_icon = if *system_proxy {
{ #[cfg(not(target_os = "macos"))]
let indication_icon = if *system_proxy { let icon = include_bytes!("../../icons/tray-icon-sys.png").to_vec();
include_bytes!("../../icons/win-tray-icon-activated.png").to_vec() #[cfg(target_os = "macos")]
} else { let icon = include_bytes!("../../icons/mac-tray-icon-sys.png").to_vec();
include_bytes!("../../icons/win-tray-icon.png").to_vec() icon
}; } else {
#[cfg(not(target_os = "macos"))]
let icon = include_bytes!("../../icons/tray-icon.png").to_vec();
#[cfg(target_os = "macos")]
let icon = include_bytes!("../../icons/mac-tray-icon.png").to_vec();
icon
};
let _ = tray.set_icon(tauri::Icon::Raw(indication_icon)); if *tun_mode {
#[cfg(not(target_os = "macos"))]
let icon = include_bytes!("../../icons/tray-icon-tun.png").to_vec();
#[cfg(target_os = "macos")]
let icon = include_bytes!("../../icons/mac-tray-icon-tun.png").to_vec();
indication_icon = icon
} }
let _ = tray.set_icon(tauri::Icon::Raw(indication_icon));
let _ = tray.get_item("system_proxy").set_selected(*system_proxy); let _ = tray.get_item("system_proxy").set_selected(*system_proxy);
let _ = tray.get_item("tun_mode").set_selected(*tun_mode); let _ = tray.get_item("tun_mode").set_selected(*tun_mode);
@@ -164,7 +164,6 @@ impl Tray {
map map
}; };
#[cfg(not(target_os = "linux"))]
let _ = tray.set_tooltip(&format!( let _ = tray.set_tooltip(&format!(
"Clash Verge {version}\n{}: {}\n{}: {}", "Clash Verge {version}\n{}: {}\n{}: {}",
t!("System Proxy", "系统代理"), t!("System Proxy", "系统代理"),
@@ -182,28 +181,23 @@ impl Tray {
match tray_event.as_str() { match tray_event.as_str() {
"system_proxy" => feat::toggle_system_proxy(), "system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(), "tun_mode" => feat::toggle_tun_mode(),
_ => resolve::create_window(app_handle), "main_window" => resolve::create_window(app_handle),
_ => {}
} }
} }
pub fn on_system_tray_event(app_handle: &AppHandle, event: SystemTrayEvent) { pub fn on_system_tray_event(app_handle: &AppHandle, event: SystemTrayEvent) {
match event { match event {
#[cfg(not(target_os = "linux"))]
SystemTrayEvent::LeftClick { .. } => Tray::on_left_click(app_handle), SystemTrayEvent::LeftClick { .. } => Tray::on_left_click(app_handle),
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() { SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
mode @ ("rule_mode" | "global_mode" | "direct_mode" | "script_mode") => { mode @ ("rule_mode" | "global_mode" | "direct_mode") => {
let mode = &mode[0..mode.len() - 5]; let mode = &mode[0..mode.len() - 5];
feat::change_clash_mode(mode.into()); feat::change_clash_mode(mode.into());
} }
"open_window" => resolve::create_window(app_handle), "open_window" => resolve::create_window(app_handle),
"system_proxy" => feat::toggle_system_proxy(), "system_proxy" => feat::toggle_system_proxy(),
"tun_mode" => feat::toggle_tun_mode(), "tun_mode" => feat::toggle_tun_mode(),
"copy_env_sh" => feat::copy_clash_env("sh"), "copy_env" => feat::copy_clash_env(app_handle),
#[cfg(target_os = "windows")]
"copy_env_cmd" => feat::copy_clash_env("cmd"),
#[cfg(target_os = "windows")]
"copy_env_ps" => feat::copy_clash_env("ps"),
"open_app_dir" => crate::log_err!(cmds::open_app_dir()), "open_app_dir" => crate::log_err!(cmds::open_app_dir()),
"open_core_dir" => crate::log_err!(cmds::open_core_dir()), "open_core_dir" => crate::log_err!(cmds::open_core_dir()),
"open_logs_dir" => crate::log_err!(cmds::open_logs_dir()), "open_logs_dir" => crate::log_err!(cmds::open_logs_dir()),
+4 -5
View File
@@ -7,8 +7,8 @@ use runas::Command as RunasCommand;
use std::process::Command as StdCommand; use std::process::Command as StdCommand;
pub async fn invoke_uwptools() -> Result<()> { pub async fn invoke_uwptools() -> Result<()> {
let binary_path = dirs::service_path()?; let resource_dir = dirs::app_resources_dir()?;
let tool_path = binary_path.with_file_name("enableLoopback.exe"); let tool_path = resource_dir.join("enableLoopback.exe");
if !tool_path.exists() { if !tool_path.exists() {
bail!("enableLoopback exe not found"); bail!("enableLoopback exe not found");
@@ -17,10 +17,9 @@ pub async fn invoke_uwptools() -> Result<()> {
let token = Token::with_current_process()?; let token = Token::with_current_process()?;
let level = token.privilege_level()?; let level = token.privilege_level()?;
match level { match level {
PrivilegeLevel::NotPrivileged => RunasCommand::new(tool_path).status()?, PrivilegeLevel::NotPrivileged => RunasCommand::new(tool_path).status()?,
_ => StdCommand::new(tool_path) _ => StdCommand::new(tool_path).status()?,
.status()?,
}; };
Ok(()) Ok(())
+12
View File
@@ -21,6 +21,7 @@ pub enum ChainType {
pub enum ChainSupport { pub enum ChainSupport {
Clash, Clash,
ClashMeta, ClashMeta,
ClashMetaAlpha,
All, All,
} }
@@ -60,9 +61,19 @@ impl ChainItem {
let hy_alpn = let hy_alpn =
ChainItem::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js")); ChainItem::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js"));
// meta 的一些处理
let meta_guard_alpha =
ChainItem::to_script("verge_meta_guard", include_str!("./builtin/meta_guard.js"));
// meta 1.13.2 alpn string 转 数组
let hy_alpn_alpha =
ChainItem::to_script("verge_hy_alpn", include_str!("./builtin/meta_hy_alpn.js"));
vec![ vec![
(ChainSupport::ClashMeta, hy_alpn), (ChainSupport::ClashMeta, hy_alpn),
(ChainSupport::ClashMeta, meta_guard), (ChainSupport::ClashMeta, meta_guard),
(ChainSupport::ClashMetaAlpha, hy_alpn_alpha),
(ChainSupport::ClashMetaAlpha, meta_guard_alpha),
] ]
} }
@@ -81,6 +92,7 @@ impl ChainSupport {
(ChainSupport::All, _) => true, (ChainSupport::All, _) => true,
(ChainSupport::Clash, "clash") => true, (ChainSupport::Clash, "clash") => true,
(ChainSupport::ClashMeta, "clash-meta") => true, (ChainSupport::ClashMeta, "clash-meta") => true,
(ChainSupport::ClashMetaAlpha, "clash-meta-alpha") => true,
_ => false, _ => false,
}, },
None => true, None => true,
+7 -6
View File
@@ -21,7 +21,7 @@ pub const DEFAULT_FIELDS: [&str; 5] = [
"rule-providers", "rule-providers",
]; ];
pub const OTHERS_FIELDS: [&str; 30] = [ pub const OTHERS_FIELDS: [&str; 31] = [
"dns", "dns",
"tun", "tun",
"ebpf", "ebpf",
@@ -50,6 +50,7 @@ pub const OTHERS_FIELDS: [&str; 30] = [
"tcp-concurrent", // meta "tcp-concurrent", // meta
"enable-process", // meta "enable-process", // meta
"find-process-mode", // meta "find-process-mode", // meta
"skip-auth-prefixes", // meta
"external-controller-tls", // meta "external-controller-tls", // meta
"global-client-fingerprint", // meta "global-client-fingerprint", // meta
]; ];
@@ -113,9 +114,9 @@ pub fn use_sort(config: Mapping, enable_filter: bool) -> Mapping {
.chain(DEFAULT_FIELDS) .chain(DEFAULT_FIELDS)
.for_each(|key| { .for_each(|key| {
let key = Value::from(key); let key = Value::from(key);
config.get(&key).map(|value| { if let Some(value) = config.get(&key) {
ret.insert(key, value.clone()); ret.insert(key, value.clone());
}); }
}); });
if !enable_filter { if !enable_filter {
@@ -133,9 +134,9 @@ pub fn use_sort(config: Mapping, enable_filter: bool) -> Mapping {
config_keys.difference(&supported_keys).for_each(|&key| { config_keys.difference(&supported_keys).for_each(|&key| {
let key = Value::from(key); let key = Value::from(key);
config.get(&key).map(|value| { if let Some(value) = config.get(&key) {
ret.insert(key, value.clone()); ret.insert(key, value.clone());
}); }
}); });
} }
@@ -149,7 +150,7 @@ pub fn use_keys(config: &Mapping) -> Vec<String> {
.map(|s| { .map(|s| {
let mut s = s.to_string(); let mut s = s.to_string();
s.make_ascii_lowercase(); s.make_ascii_lowercase();
return s; s
}) })
.collect() .collect()
} }
+7 -8
View File
@@ -4,9 +4,8 @@ mod merge;
mod script; mod script;
mod tun; mod tun;
pub(self) use self::field::*;
use self::chain::*; use self::chain::*;
use self::field::*;
use self::merge::*; use self::merge::*;
use self::script::*; use self::script::*;
use self::tun::*; use self::tun::*;
@@ -28,9 +27,9 @@ pub fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
let verge = verge.latest(); let verge = verge.latest();
( (
verge.clash_core.clone(), verge.clash_core.clone(),
verge.enable_tun_mode.clone().unwrap_or(false), verge.enable_tun_mode.unwrap_or(false),
verge.enable_builtin_enhanced.clone().unwrap_or(true), verge.enable_builtin_enhanced.unwrap_or(true),
verge.enable_clash_fields.clone().unwrap_or(true), verge.enable_clash_fields.unwrap_or(true),
) )
}; };
@@ -39,18 +38,18 @@ pub fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
let profiles = Config::profiles(); let profiles = Config::profiles();
let profiles = profiles.latest(); let profiles = profiles.latest();
let current = profiles.current_mapping().unwrap_or(Mapping::new()); let current = profiles.current_mapping().unwrap_or_default();
let chain = match profiles.chain.as_ref() { let chain = match profiles.chain.as_ref() {
Some(chain) => chain Some(chain) => chain
.iter() .iter()
.filter_map(|uid| profiles.get_item(uid).ok()) .filter_map(|uid| profiles.get_item(uid).ok())
.filter_map(|item| <Option<ChainItem>>::from(item)) .filter_map(<Option<ChainItem>>::from)
.collect::<Vec<ChainItem>>(), .collect::<Vec<ChainItem>>(),
None => vec![], None => vec![],
}; };
let valid = profiles.valid.clone().unwrap_or(vec![]); let valid = profiles.valid.clone().unwrap_or_default();
(current, chain, valid) (current, chain, valid)
}; };
+2 -2
View File
@@ -3,7 +3,7 @@ use anyhow::Result;
use serde_yaml::Mapping; use serde_yaml::Mapping;
pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(String, String)>)> { pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(String, String)>)> {
use rquickjs::{Context, Func, Runtime}; use rquickjs::{function::Func, Context, Runtime};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
let runtime = Runtime::new().unwrap(); let runtime = Runtime::new().unwrap();
@@ -47,7 +47,7 @@ pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(Stri
if result == "\"\"" { if result == "\"\"" {
anyhow::bail!("main function should return object"); anyhow::bail!("main function should return object");
} }
return Ok(serde_json::from_str::<Mapping>(result.as_str())?); Ok(serde_json::from_str::<Mapping>(result.as_str())?)
}); });
let mut out = outputs.lock().unwrap(); let mut out = outputs.lock().unwrap();
+35 -17
View File
@@ -10,7 +10,7 @@ use crate::log_err;
use crate::utils::resolve; use crate::utils::resolve;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
use wry::application::clipboard::Clipboard; use tauri::{AppHandle, ClipboardManager};
// 打开面板 // 打开面板
pub fn open_dashboard() { pub fn open_dashboard() {
@@ -62,7 +62,7 @@ pub fn change_clash_mode(mode: String) {
// 切换系统代理 // 切换系统代理
pub fn toggle_system_proxy() { pub fn toggle_system_proxy() {
let enable = Config::verge().draft().enable_system_proxy.clone(); let enable = Config::verge().draft().enable_system_proxy;
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
@@ -110,7 +110,7 @@ pub fn disable_system_proxy() {
// 切换tun模式 // 切换tun模式
pub fn toggle_tun_mode() { pub fn toggle_tun_mode() {
let enable = Config::verge().data().enable_tun_mode.clone(); let enable = Config::verge().data().enable_tun_mode;
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
@@ -162,11 +162,16 @@ pub async fn patch_clash(patch: Mapping) -> Result<()> {
match { match {
let mixed_port = patch.get("mixed-port"); let mixed_port = patch.get("mixed-port");
if mixed_port.is_some() { let enable_random_port = Config::verge().latest().enable_random_port.unwrap_or(false);
let changed = mixed_port != Config::clash().data().0.get("mixed-port"); if mixed_port.is_some() && !enable_random_port {
let changed = mixed_port.unwrap()
!= Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
// 检查端口占用 // 检查端口占用
if changed { if changed {
if let Some(port) = mixed_port.clone().unwrap().as_u64() { if let Some(port) = mixed_port.unwrap().as_u64() {
if !port_scanner::local_port_available(port as u16) { if !port_scanner::local_port_available(port as u16) {
Config::clash().discard(); Config::clash().discard();
bail!("port already in use"); bail!("port already in use");
@@ -332,21 +337,34 @@ async fn update_core_config() -> Result<()> {
} }
/// copy env variable /// copy env variable
pub fn copy_clash_env(option: &str) { pub fn copy_clash_env(app_handle: &AppHandle) {
let port = { Config::clash().data().get_client_info().port }; let port = { Config::verge().latest().verge_mixed_port.unwrap_or(7897) };
let http_proxy = format!("http://127.0.0.1:{}", port); let http_proxy = format!("http://127.0.0.1:{}", port);
let socks5_proxy = format!("socks5://127.0.0.1:{}", port); let socks5_proxy = format!("socks5://127.0.0.1:{}", port);
let sh = format!("export https_proxy={http_proxy} http_proxy={http_proxy} all_proxy={socks5_proxy}"); let sh =
format!("export https_proxy={http_proxy} http_proxy={http_proxy} all_proxy={socks5_proxy}");
let cmd: String = format!("set http_proxy={http_proxy} \n set https_proxy={http_proxy}"); let cmd: String = format!("set http_proxy={http_proxy} \n set https_proxy={http_proxy}");
let ps: String = format!("$env:HTTP_PROXY=\"{http_proxy}\"; $env:HTTPS_PROXY=\"{http_proxy}\""); let ps: String = format!("$env:HTTP_PROXY=\"{http_proxy}\"; $env:HTTPS_PROXY=\"{http_proxy}\"");
let mut cliboard = Clipboard::new(); let mut cliboard = app_handle.clipboard_manager();
match option { let env_type = { Config::verge().latest().env_type.clone() };
"sh" => cliboard.write_text(sh), let env_type = match env_type {
"cmd" => cliboard.write_text(cmd), Some(env_type) => env_type,
"ps" => cliboard.write_text(ps), None => {
_ => log::error!(target: "app", "copy_clash_env: Invalid option! {option}"), #[cfg(not(target_os = "windows"))]
} let default = "bash";
#[cfg(target_os = "windows")]
let default = "powershell";
default.to_string()
}
};
match env_type.as_str() {
"bash" => cliboard.write_text(sh).unwrap_or_default(),
"cmd" => cliboard.write_text(cmd).unwrap_or_default(),
"powershell" => cliboard.write_text(ps).unwrap_or_default(),
_ => log::error!(target: "app", "copy_clash_env: Invalid env type! {env_type}"),
};
} }
+15 -3
View File
@@ -25,7 +25,10 @@ fn main() -> std::io::Result<()> {
#[allow(unused_mut)] #[allow(unused_mut)]
let mut builder = tauri::Builder::default() let mut builder = tauri::Builder::default()
.system_tray(SystemTray::new()) .system_tray(SystemTray::new())
.setup(|app| Ok(resolve::resolve_setup(app))) .setup(|app| {
resolve::resolve_setup(app);
Ok(())
})
.on_system_tray_event(core::tray::Tray::on_system_tray_event) .on_system_tray_event(core::tray::Tray::on_system_tray_event)
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
// common // common
@@ -34,6 +37,7 @@ fn main() -> std::io::Result<()> {
cmds::open_logs_dir, cmds::open_logs_dir,
cmds::open_web_url, cmds::open_web_url,
cmds::open_core_dir, cmds::open_core_dir,
cmds::get_portable_flag,
// cmds::kill_sidecar, // cmds::kill_sidecar,
cmds::restart_sidecar, cmds::restart_sidecar,
cmds::grant_permission, cmds::grant_permission,
@@ -59,6 +63,7 @@ fn main() -> std::io::Result<()> {
cmds::patch_profile, cmds::patch_profile,
cmds::create_profile, cmds::create_profile,
cmds::import_profile, cmds::import_profile,
cmds::reorder_profile,
cmds::update_profile, cmds::update_profile,
cmds::delete_profile, cmds::delete_profile,
cmds::read_profile_file, cmds::read_profile_file,
@@ -104,6 +109,10 @@ fn main() -> std::io::Result<()> {
api::process::kill_children(); api::process::kill_children();
app_handle.exit(0); app_handle.exit(0);
} }
tauri::RunEvent::Updater(tauri::UpdaterEvent::Downloaded) => {
resolve::resolve_reset();
api::process::kill_children();
}
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
tauri::RunEvent::WindowEvent { label, event, .. } => { tauri::RunEvent::WindowEvent { label, event, .. } => {
use tauri::Manager; use tauri::Manager;
@@ -126,11 +135,14 @@ fn main() -> std::io::Result<()> {
tauri::RunEvent::WindowEvent { label, event, .. } => { tauri::RunEvent::WindowEvent { label, event, .. } => {
if label == "main" { if label == "main" {
match event { match event {
tauri::WindowEvent::Destroyed => {
let _ = resolve::save_window_size_position(app_handle, true);
}
tauri::WindowEvent::CloseRequested { .. } => { tauri::WindowEvent::CloseRequested { .. } => {
let _ = resolve::save_window_size_position(&app_handle, true); let _ = resolve::save_window_size_position(app_handle, true);
} }
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => { tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => {
let _ = resolve::save_window_size_position(&app_handle, false); let _ = resolve::save_window_size_position(app_handle, false);
} }
_ => {} _ => {}
} }
+42 -75
View File
@@ -1,88 +1,69 @@
use crate::core::handle;
use anyhow::Result; use anyhow::Result;
use once_cell::sync::OnceCell;
use std::path::PathBuf; use std::path::PathBuf;
use tauri::{ use tauri::{
api::path::{home_dir, resource_dir}, api::path::{data_dir, resource_dir},
Env, PackageInfo, Env,
}; };
#[cfg(not(feature = "verge-dev"))] #[cfg(not(feature = "verge-dev"))]
static APP_DIR: &str = "clash-verge"; pub static APP_ID: &str = "io.github.clash-verge-rev.clash-verge-rev";
#[cfg(feature = "verge-dev")] #[cfg(feature = "verge-dev")]
static APP_DIR: &str = "clash-verge-dev"; pub static APP_ID: &str = "io.github.clash-verge-rev.clash-verge-rev.dev";
pub static PORTABLE_FLAG: OnceCell<bool> = OnceCell::new();
static CLASH_CONFIG: &str = "config.yaml"; static CLASH_CONFIG: &str = "config.yaml";
static VERGE_CONFIG: &str = "verge.yaml"; static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml"; static PROFILE_YAML: &str = "profiles.yaml";
static mut RESOURCE_DIR: Option<PathBuf> = None; /// init portable flag
pub fn init_portable_flag() -> Result<()> {
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
pub static mut APP_VERSION: &str = "v1.2.0";
/// initialize portable flag
#[cfg(target_os = "windows")]
pub unsafe fn init_portable_flag() -> Result<()> {
use tauri::utils::platform::current_exe; use tauri::utils::platform::current_exe;
let exe = current_exe()?; let app_exe = current_exe()?;
if let Some(dir) = app_exe.parent() {
if let Some(dir) = exe.parent() {
let dir = PathBuf::from(dir).join(".config/PORTABLE"); let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() { if dir.exists() {
PORTABLE_FLAG = true; PORTABLE_FLAG.get_or_init(|| true);
} }
} }
PORTABLE_FLAG.get_or_init(|| false);
Ok(()) Ok(())
} }
/// get the verge app home dir /// get the verge app home dir
pub fn app_home_dir() -> Result<PathBuf> { pub fn app_home_dir() -> Result<PathBuf> {
#[cfg(target_os = "windows")] use tauri::utils::platform::current_exe;
unsafe {
use tauri::utils::platform::current_exe;
if !PORTABLE_FLAG { let flag = PORTABLE_FLAG.get().unwrap_or(&false);
Ok(home_dir() if *flag {
.ok_or(anyhow::anyhow!("failed to get app home dir"))? let app_exe = current_exe()?;
.join(".config") let app_exe = dunce::canonicalize(app_exe)?;
.join(APP_DIR)) let app_dir = app_exe
} else { .parent()
let app_exe = current_exe()?; .ok_or(anyhow::anyhow!("failed to get the portable app dir"))?;
let app_exe = dunce::canonicalize(app_exe)?; return Ok(PathBuf::from(app_dir).join(".config").join(APP_ID));
let app_dir = app_exe
.parent()
.ok_or(anyhow::anyhow!("failed to get the portable app dir"))?;
Ok(PathBuf::from(app_dir).join(".config").join(APP_DIR))
}
} }
#[cfg(not(target_os = "windows"))] Ok(data_dir()
Ok(home_dir() .ok_or(anyhow::anyhow!("failed to get app home dir"))?
.ok_or(anyhow::anyhow!("failed to get the app home dir"))? .join(APP_ID))
.join(".config")
.join(APP_DIR))
} }
/// get the resources dir /// get the resources dir
pub fn app_resources_dir(package_info: &PackageInfo) -> Result<PathBuf> { pub fn app_resources_dir() -> Result<PathBuf> {
let res_dir = resource_dir(package_info, &Env::default()) let handle = handle::Handle::global();
.ok_or(anyhow::anyhow!("failed to get the resource dir"))? let app_handle = handle.app_handle.lock();
.join("resources"); if let Some(app_handle) = app_handle.as_ref() {
let res_dir = resource_dir(app_handle.package_info(), &Env::default())
unsafe { .ok_or(anyhow::anyhow!("failed to get the resource dir"))?
RESOURCE_DIR = Some(res_dir.clone()); .join("resources");
return Ok(res_dir);
let ver = package_info.version.to_string(); };
let ver_str = format!("v{ver}"); Err(anyhow::anyhow!("failed to get the resource dir"))
APP_VERSION = Box::leak(Box::new(ver_str));
}
Ok(res_dir)
} }
/// profiles dir /// profiles dir
@@ -107,32 +88,18 @@ pub fn profiles_path() -> Result<PathBuf> {
Ok(app_home_dir()?.join(PROFILE_YAML)) Ok(app_home_dir()?.join(PROFILE_YAML))
} }
#[allow(unused)] pub fn clash_pid_path() -> Result<PathBuf> {
pub fn app_res_dir() -> Result<PathBuf> { Ok(app_home_dir()?.join("clash.pid"))
unsafe {
Ok(RESOURCE_DIR
.clone()
.ok_or(anyhow::anyhow!("failed to get the resource dir"))?)
}
} }
pub fn clash_pid_path() -> Result<PathBuf> { #[cfg(windows)]
unsafe { pub fn service_dir() -> Result<PathBuf> {
Ok(RESOURCE_DIR Ok(app_home_dir()?.join("service"))
.clone()
.ok_or(anyhow::anyhow!("failed to get the resource dir"))?
.join("clash.pid"))
}
} }
#[cfg(windows)] #[cfg(windows)]
pub fn service_path() -> Result<PathBuf> { pub fn service_path() -> Result<PathBuf> {
unsafe { Ok(service_dir()?.join("clash-verge-service.exe"))
let res_dir = RESOURCE_DIR
.clone()
.ok_or(anyhow::anyhow!("failed to get the resource dir"))?;
Ok(res_dir.join("clash-verge-service.exe"))
}
} }
#[cfg(windows)] #[cfg(windows)]
+28 -25
View File
@@ -3,6 +3,10 @@ use nanoid::nanoid;
use serde::{de::DeserializeOwned, Serialize}; use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
use std::{fs, path::PathBuf, str::FromStr}; use std::{fs, path::PathBuf, str::FromStr};
use tauri::{
api::shell::{open, Program},
Manager,
};
/// read data from yaml as struct T /// read data from yaml as struct T
pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> { pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
@@ -10,7 +14,7 @@ pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
bail!("file not found \"{}\"", path.display()); bail!("file not found \"{}\"", path.display());
} }
let yaml_str = fs::read_to_string(&path) let yaml_str = fs::read_to_string(path)
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?; .with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
serde_yaml::from_str::<T>(&yaml_str).with_context(|| { serde_yaml::from_str::<T>(&yaml_str).with_context(|| {
@@ -67,32 +71,31 @@ pub fn get_uid(prefix: &str) -> String {
/// parse the string /// parse the string
/// xxx=123123; => 123123 /// xxx=123123; => 123123
pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> { pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
target.find(key).and_then(|idx| { target.split(';').map(str::trim).find_map(|s| {
let idx = idx + key.len(); let mut parts = s.splitn(2, '=');
let value = &target[idx..]; match (parts.next(), parts.next()) {
(Some(k), Some(v)) if k == key => v.parse::<T>().ok(),
match value.split(';').nth(0) { _ => None,
Some(value) => value.trim().parse(),
None => value.trim().parse(),
} }
.ok()
}) })
} }
/// open file /// open file
/// use vscode by default /// use vscode by default
pub fn open_file(path: PathBuf) -> Result<()> { pub fn open_file(app: tauri::AppHandle, path: PathBuf) -> Result<()> {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
let code = "Visual Studio Code"; let code = "Visual Studio Code";
#[cfg(not(target_os = "macos"))] #[cfg(not(target_os = "macos"))]
let code = "code"; let code = "code";
// use vscode first let _ = match Program::from_str(code) {
if let Err(err) = open::with(&path, code) { Ok(code) => open(&app.shell_scope(), path.to_string_lossy(), Some(code)),
log::error!(target: "app", "failed to open file with VScode `{err}`"); Err(err) => {
// default open log::error!(target: "app", "Can't find VScode `{err}`");
open::that(path)?; // default open
} open(&app.shell_scope(), path.to_string_lossy(), None)
}
};
Ok(()) Ok(())
} }
@@ -156,17 +159,17 @@ fn test_parse_value() {
let test_1 = "upload=111; download=2222; total=3333; expire=444"; let test_1 = "upload=111; download=2222; total=3333; expire=444";
let test_2 = "attachment; filename=Clash.yaml"; let test_2 = "attachment; filename=Clash.yaml";
assert_eq!(parse_str::<usize>(test_1, "upload=").unwrap(), 111); assert_eq!(parse_str::<usize>(test_1, "upload").unwrap(), 111);
assert_eq!(parse_str::<usize>(test_1, "download=").unwrap(), 2222); assert_eq!(parse_str::<usize>(test_1, "download").unwrap(), 2222);
assert_eq!(parse_str::<usize>(test_1, "total=").unwrap(), 3333); assert_eq!(parse_str::<usize>(test_1, "total").unwrap(), 3333);
assert_eq!(parse_str::<usize>(test_1, "expire=").unwrap(), 444); assert_eq!(parse_str::<usize>(test_1, "expire").unwrap(), 444);
assert_eq!( assert_eq!(
parse_str::<String>(test_2, "filename=").unwrap(), parse_str::<String>(test_2, "filename").unwrap(),
format!("Clash.yaml") format!("Clash.yaml")
); );
assert_eq!(parse_str::<usize>(test_1, "aaa="), None); assert_eq!(parse_str::<usize>(test_1, "aaa"), None);
assert_eq!(parse_str::<usize>(test_1, "upload1="), None); assert_eq!(parse_str::<usize>(test_1, "upload1"), None);
assert_eq!(parse_str::<usize>(test_1, "expire1="), None); assert_eq!(parse_str::<usize>(test_1, "expire1"), None);
assert_eq!(parse_str::<usize>(test_2, "attachment="), None); assert_eq!(parse_str::<usize>(test_2, "attachment"), None);
} }
+113 -14
View File
@@ -9,7 +9,6 @@ use log4rs::config::{Appender, Logger, Root};
use log4rs::encode::pattern::PatternEncoder; use log4rs::encode::pattern::PatternEncoder;
use std::fs::{self, DirEntry}; use std::fs::{self, DirEntry};
use std::str::FromStr; use std::str::FromStr;
use tauri::PackageInfo;
/// initialize this instance's log file /// initialize this instance's log file
fn init_log() -> Result<()> { fn init_log() -> Result<()> {
@@ -80,7 +79,7 @@ pub fn delete_log() -> Result<()> {
let auto_log_clean = { let auto_log_clean = {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.data(); let verge = verge.data();
verge.auto_log_clean.clone().unwrap_or(0) verge.auto_log_clean.unwrap_or(0)
}; };
let day = match auto_log_clean { let day = match auto_log_clean {
@@ -116,7 +115,10 @@ pub fn delete_log() -> Result<()> {
if file_name.ends_with(".log") { if file_name.ends_with(".log") {
let now = Local::now(); let now = Local::now();
let created_time = parse_time_str(&file_name[0..file_name.len() - 4])?; let created_time = parse_time_str(&file_name[0..file_name.len() - 4])?;
let file_time = Local.from_local_datetime(&created_time).single().ok_or(anyhow::anyhow!("invalid local datetime"))?; let file_time = Local
.from_local_datetime(&created_time)
.single()
.ok_or(anyhow::anyhow!("invalid local datetime"))?;
let duration = now.signed_duration_since(file_time); let duration = now.signed_duration_since(file_time);
if duration.num_days() > day { if duration.num_days() > day {
@@ -128,10 +130,8 @@ pub fn delete_log() -> Result<()> {
Ok(()) Ok(())
}; };
for file in fs::read_dir(&log_dir)? { for file in fs::read_dir(&log_dir)?.flatten() {
if let Ok(file) = file { let _ = process_file(file);
let _ = process_file(file);
}
} }
Ok(()) Ok(())
} }
@@ -139,11 +139,7 @@ pub fn delete_log() -> Result<()> {
/// Initialize all the config files /// Initialize all the config files
/// before tauri setup /// before tauri setup
pub fn init_config() -> Result<()> { pub fn init_config() -> Result<()> {
#[cfg(target_os = "windows")] let _ = dirs::init_portable_flag();
unsafe {
let _ = dirs::init_portable_flag();
}
let _ = init_log(); let _ = init_log();
let _ = delete_log(); let _ = delete_log();
@@ -185,9 +181,9 @@ pub fn init_config() -> Result<()> {
/// initialize app resources /// initialize app resources
/// after tauri setup /// after tauri setup
pub fn init_resources(package_info: &PackageInfo) -> Result<()> { pub fn init_resources() -> Result<()> {
let app_dir = dirs::app_home_dir()?; let app_dir = dirs::app_home_dir()?;
let res_dir = dirs::app_resources_dir(package_info)?; let res_dir = dirs::app_resources_dir()?;
if !app_dir.exists() { if !app_dir.exists() {
let _ = fs::create_dir_all(&app_dir); let _ = fs::create_dir_all(&app_dir);
@@ -241,3 +237,106 @@ pub fn init_resources(package_info: &PackageInfo) -> Result<()> {
Ok(()) Ok(())
} }
/// initialize service resources
/// after tauri setup
#[cfg(target_os = "windows")]
pub fn init_service() -> Result<()> {
let service_dir = dirs::service_dir()?;
let res_dir = dirs::app_resources_dir()?;
if !service_dir.exists() {
let _ = fs::create_dir_all(&service_dir);
}
if !res_dir.exists() {
let _ = fs::create_dir_all(&res_dir);
}
let file_list = [
"clash-verge-service.exe",
"install-service.exe",
"uninstall-service.exe",
];
// copy the resource file
// if the source file is newer than the destination file, copy it over
for file in file_list.iter() {
let src_path = res_dir.join(file);
let dest_path = service_dir.join(file);
let handle_copy = || {
match fs::copy(&src_path, &dest_path) {
Ok(_) => log::debug!(target: "app", "resources copied '{file}'"),
Err(err) => {
log::error!(target: "app", "failed to copy resources '{file}', {err}")
}
};
};
if src_path.exists() && !dest_path.exists() {
handle_copy();
continue;
}
let src_modified = fs::metadata(&src_path).and_then(|m| m.modified());
let dest_modified = fs::metadata(&dest_path).and_then(|m| m.modified());
match (src_modified, dest_modified) {
(Ok(src_modified), Ok(dest_modified)) => {
if src_modified > dest_modified {
handle_copy();
} else {
log::debug!(target: "app", "skipping resource copy '{file}'");
}
}
_ => {
log::debug!(target: "app", "failed to get modified '{file}'");
handle_copy();
}
};
}
Ok(())
}
/// initialize url scheme
#[cfg(target_os = "windows")]
pub fn init_scheme() -> Result<()> {
use tauri::utils::platform::current_exe;
use winreg::enums::*;
use winreg::RegKey;
let app_exe = current_exe()?;
let app_exe = dunce::canonicalize(app_exe)?;
let app_exe = app_exe.to_string_lossy().into_owned();
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let (clash, _) = hkcu.create_subkey("Software\\Classes\\Clash")?;
clash.set_value("", &"Clash Verge")?;
clash.set_value("URL Protocol", &"Clash Verge URL Scheme Protocol")?;
let (default_icon, _) = hkcu.create_subkey("Software\\Classes\\Clash\\DefaultIcon")?;
default_icon.set_value("", &app_exe)?;
let (command, _) = hkcu.create_subkey("Software\\Classes\\Clash\\Shell\\Open\\Command")?;
command.set_value("", &format!("{app_exe} \"%1\""))?;
Ok(())
}
#[cfg(target_os = "linux")]
pub fn init_scheme() -> Result<()> {
let output = std::process::Command::new("xdg-mime")
.arg("default")
.arg("clash-verge.desktop")
.arg("x-scheme-handler/clash")
.output()?;
if !output.status.success() {
return Err(anyhow::anyhow!(
"failed to set clash scheme, {}",
String::from_utf8_lossy(&output.stderr)
));
}
Ok(())
}
#[cfg(target_os = "macos")]
pub fn init_scheme() -> Result<()> {
Ok(())
}
-1
View File
@@ -4,4 +4,3 @@ pub mod init;
pub mod resolve; pub mod resolve;
pub mod server; pub mod server;
pub mod tmpl; pub mod tmpl;
// mod winhelp;
+114 -25
View File
@@ -1,16 +1,76 @@
use crate::{config::Config, core::*, utils::init, utils::server}; use crate::config::{IVerge, PrfOption};
use crate::{
config::{Config, PrfItem},
core::*,
utils::init,
utils::server,
};
use crate::{log_err, trace_err}; use crate::{log_err, trace_err};
use anyhow::Result; use anyhow::Result;
use once_cell::sync::OnceCell;
use serde_yaml::Mapping;
use std::net::TcpListener;
use tauri::api::notification;
use tauri::{App, AppHandle, Manager}; use tauri::{App, AppHandle, Manager};
pub static VERSION: OnceCell<String> = OnceCell::new();
pub fn find_unused_port() -> Result<u16> {
match TcpListener::bind("127.0.0.1:0") {
Ok(listener) => {
let port = listener.local_addr()?.port();
Ok(port)
}
Err(_) => {
let port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
log::warn!(target: "app", "use default port: {}", port);
Ok(port)
}
}
}
/// handle something when start app /// handle something when start app
pub fn resolve_setup(app: &mut App) { pub fn resolve_setup(app: &mut App) {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory); app.set_activation_policy(tauri::ActivationPolicy::Accessory);
let version = app.package_info().version.to_string();
handle::Handle::global().init(app.app_handle()); handle::Handle::global().init(app.app_handle());
VERSION.get_or_init(|| version.clone());
log_err!(init::init_resources(app.package_info())); log_err!(init::init_resources());
#[cfg(target_os = "windows")]
log_err!(init::init_service());
log_err!(init::init_scheme());
// 处理随机端口
let enable_random_port = Config::verge().latest().enable_random_port.unwrap_or(false);
let mut port = Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port());
if enable_random_port {
port = find_unused_port().unwrap_or(
Config::verge()
.latest()
.verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port()),
);
}
Config::verge().data().patch_config(IVerge {
verge_mixed_port: Some(port),
..IVerge::default()
});
let _ = Config::verge().data().save_file();
let mut mapping = Mapping::new();
mapping.insert("mixed-port".into(), port.into());
Config::clash().data().patch_config(mapping);
let _ = Config::clash().data().save_config();
// 启动核心 // 启动核心
log::trace!("init config"); log::trace!("init config");
@@ -26,7 +86,7 @@ pub fn resolve_setup(app: &mut App) {
log::trace!("init system tray"); log::trace!("init system tray");
log_err!(tray::Tray::update_systray(&app.app_handle())); log_err!(tray::Tray::update_systray(&app.app_handle()));
let silent_start = { Config::verge().data().enable_silent_start.clone() }; let silent_start = { Config::verge().data().enable_silent_start };
if !silent_start.unwrap_or(false) { if !silent_start.unwrap_or(false) {
create_window(&app.app_handle()); create_window(&app.app_handle());
} }
@@ -37,6 +97,13 @@ pub fn resolve_setup(app: &mut App) {
log_err!(handle::Handle::update_systray_part()); log_err!(handle::Handle::update_systray_part());
log_err!(hotkey::Hotkey::global().init(app.app_handle())); log_err!(hotkey::Hotkey::global().init(app.app_handle()));
log_err!(timer::Timer::global().init()); log_err!(timer::Timer::global().init());
let argvs: Vec<String> = std::env::args().collect();
if argvs.len() > 1 {
tauri::async_runtime::block_on(async {
resolve_scheme(argvs[1].to_owned()).await;
});
}
} }
/// reset system proxy /// reset system proxy
@@ -60,6 +127,7 @@ pub fn create_window(app_handle: &AppHandle) {
tauri::WindowUrl::App("index.html".into()), tauri::WindowUrl::App("index.html".into()),
) )
.title("Clash Verge") .title("Clash Verge")
.visible(false)
.fullscreen(false) .fullscreen(false)
.min_inner_size(600.0, 520.0); .min_inner_size(600.0, 520.0);
@@ -91,8 +159,6 @@ pub fn create_window(app_handle: &AppHandle) {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
{ {
use std::time::Duration;
use tokio::time::sleep;
use window_shadows::set_shadow; use window_shadows::set_shadow;
match builder match builder
@@ -126,19 +192,11 @@ pub fn create_window(app_handle: &AppHandle) {
log::trace!("try to create window"); log::trace!("try to create window");
let app_handle = app_handle.clone(); let app_handle = app_handle.clone();
// 加点延迟避免界面闪一下 if let Some(window) = app_handle.get_window("main") {
tauri::async_runtime::spawn(async move { trace_err!(set_shadow(&window, true), "set win shadow");
sleep(Duration::from_millis(888)).await; } else {
log::error!(target: "app", "failed to create window, get_window is None")
if let Some(window) = app_handle.get_window("main") { }
trace_err!(set_shadow(&window, true), "set win shadow");
trace_err!(window.show(), "set win visible");
trace_err!(window.unminimize(), "set win unminimize");
trace_err!(window.set_focus(), "set win focus");
} else {
log::error!(target: "app", "failed to create window, get_window is None")
}
});
} }
Err(err) => log::error!(target: "app", "failed to create window, {err}"), Err(err) => log::error!(target: "app", "failed to create window, {err}"),
} }
@@ -157,6 +215,13 @@ pub fn create_window(app_handle: &AppHandle) {
/// save window size and position /// save window size and position
pub fn save_window_size_position(app_handle: &AppHandle, save_to_file: bool) -> Result<()> { pub fn save_window_size_position(app_handle: &AppHandle, save_to_file: bool) -> Result<()> {
let verge = Config::verge();
let mut verge = verge.latest();
if save_to_file {
verge.save_file()?;
}
let win = app_handle let win = app_handle
.get_window("main") .get_window("main")
.ok_or(anyhow::anyhow!("failed to get window"))?; .ok_or(anyhow::anyhow!("failed to get window"))?;
@@ -167,13 +232,37 @@ pub fn save_window_size_position(app_handle: &AppHandle, save_to_file: bool) ->
let pos = win.outer_position()?; let pos = win.outer_position()?;
let pos = pos.to_logical::<f64>(scale); let pos = pos.to_logical::<f64>(scale);
let verge = Config::verge(); if size.width >= 600.0 && size.height >= 520.0 {
let mut verge = verge.latest(); verge.window_size_position = Some(vec![size.width, size.height, pos.x, pos.y]);
verge.window_size_position = Some(vec![size.width, size.height, pos.x, pos.y]);
if save_to_file {
verge.save_file()?;
} }
Ok(()) Ok(())
} }
pub async fn resolve_scheme(param: String) {
let url = param
.trim_start_matches("clash://install-config/?url=")
.trim_start_matches("clash://install-config?url=");
let option = PrfOption {
user_agent: None,
with_proxy: Some(true),
self_proxy: None,
update_interval: None,
};
if let Ok(item) = PrfItem::from_url(url, None, None, Some(option)).await {
if Config::profiles().data().append_item(item).is_ok() {
notification::Notification::new(crate::utils::dirs::APP_ID)
.title("Clash Verge")
.body("Import profile success")
.show()
.unwrap();
};
} else {
notification::Notification::new(crate::utils::dirs::APP_ID)
.title("Clash Verge")
.body("Import profile failed")
.show()
.unwrap();
log::error!("failed to parse url: {}", url);
}
}
+39 -5
View File
@@ -4,19 +4,42 @@ use super::resolve;
use crate::config::IVerge; use crate::config::IVerge;
use anyhow::{bail, Result}; use anyhow::{bail, Result};
use port_scanner::local_port_available; use port_scanner::local_port_available;
use std::convert::Infallible;
use tauri::AppHandle; use tauri::AppHandle;
use warp::Filter; use warp::Filter;
#[derive(serde::Deserialize, Debug)]
struct QueryParam {
param: String,
}
/// check whether there is already exists /// check whether there is already exists
pub fn check_singleton() -> Result<()> { pub fn check_singleton() -> Result<()> {
let port = IVerge::get_singleton_port(); let port = IVerge::get_singleton_port();
if !local_port_available(port) { if !local_port_available(port) {
tauri::async_runtime::block_on(async { tauri::async_runtime::block_on(async {
let url = format!("http://127.0.0.1:{port}/commands/visible"); let resp = reqwest::get(format!("http://127.0.0.1:{port}/commands/ping"))
let resp = reqwest::get(url).await?.text().await?; .await?
.text()
.await?;
if &resp == "ok" { if &resp == "ok" {
let argvs: Vec<String> = std::env::args().collect();
if argvs.len() > 1 {
let param = argvs[1].as_str();
reqwest::get(format!(
"http://127.0.0.1:{port}/commands/scheme?param={param}"
))
.await?
.text()
.await?;
} else {
reqwest::get(format!("http://127.0.0.1:{port}/commands/visible"))
.await?
.text()
.await?;
}
bail!("app exists"); bail!("app exists");
} }
@@ -34,11 +57,22 @@ pub fn embed_server(app_handle: AppHandle) {
let port = IVerge::get_singleton_port(); let port = IVerge::get_singleton_port();
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
let commands = warp::path!("commands" / "visible").map(move || { let ping = warp::path!("commands" / "ping").map(move || "ok");
let visible = warp::path!("commands" / "visible").map(move || {
resolve::create_window(&app_handle); resolve::create_window(&app_handle);
format!("ok") "ok"
}); });
warp::serve(commands).bind(([127, 0, 0, 1], port)).await; let scheme = warp::path!("commands" / "scheme")
.and(warp::query::<QueryParam>())
.and_then(scheme_handler);
async fn scheme_handler(query: QueryParam) -> Result<impl warp::Reply, Infallible> {
resolve::resolve_scheme(query.param).await;
Ok("ok")
}
let commands = ping.or(visible).or(scheme);
warp::serve(commands).run(([127, 0, 0, 1], port)).await;
}); });
} }
+1 -1
View File
@@ -1,4 +1,4 @@
///! Some config file template //! Some config file template
/// template for new a profile item /// template for new a profile item
pub const ITEM_LOCAL: &str = "# Profile Template for clash verge pub const ITEM_LOCAL: &str = "# Profile Template for clash verge
-69
View File
@@ -1,69 +0,0 @@
#![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());
}
+13 -30
View File
@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "Clash Verge", "productName": "Clash Verge",
"version": "1.4.1" "version": "1.4.7"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",
@@ -10,14 +10,9 @@
"beforeBuildCommand": "pnpm run web:build" "beforeBuildCommand": "pnpm run web:build"
}, },
"tauri": { "tauri": {
"systemTray": {
"iconPath": "icons/tray-icon.ico",
"iconAsTemplate": true
},
"bundle": { "bundle": {
"active": true, "active": true,
"targets": "all", "identifier": "io.github.clash-verge-rev.clash-verge-rev",
"identifier": "moe.elaina.clash.verge",
"icon": [ "icon": [
"icons/32x32.png", "icons/32x32.png",
"icons/128x128.png", "icons/128x128.png",
@@ -26,35 +21,17 @@
"icons/icon.ico" "icons/icon.ico"
], ],
"resources": ["resources"], "resources": ["resources"],
"externalBin": ["sidecar/clash-meta"], "externalBin": ["sidecar/clash-meta", "sidecar/clash-meta-alpha"],
"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 Meta GUI based on tauri.",
"longDescription": "A Clash GUI based on tauri.", "longDescription": "A Clash Meta GUI based on tauri."
"deb": {
"depends": ["openssl"]
},
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": null
},
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": "",
"wix": {
"language": ["zh-CN", "en-US", "ru-RU"]
}
}
}, },
"updater": { "updater": {
"active": true, "active": true,
"endpoints": [ "endpoints": [
"https://mirror.ghproxy.com/https://github.com/wonfen/clash-verge-rev/releases/download/updater/update-proxy.json", "https://mirror.ghproxy.com/https://github.com/clash-verge-rev/clash-verge-rev/releases/download/updater/update-proxy.json",
"https://github.com/wonfen/clash-verge-rev/releases/download/updater/update.json" "https://github.com/clash-verge-rev/clash-verge-rev/releases/download/updater/update.json"
], ],
"dialog": false, "dialog": false,
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEQyOEMyRjBCQkVGOUJEREYKUldUZnZmbStDeStNMHU5Mmo1N24xQXZwSVRYbXA2NUpzZE5oVzlqeS9Bc0t6RVV4MmtwVjBZaHgK" "pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IEQyOEMyRjBCQkVGOUJEREYKUldUZnZmbStDeStNMHU5Mmo1N24xQXZwSVRYbXA2NUpzZE5oVzlqeS9Bc0t6RVV4MmtwVjBZaHgK"
@@ -71,6 +48,12 @@
}, },
"globalShortcut": { "globalShortcut": {
"all": true "all": true
},
"clipboard": {
"all": true
},
"notification": {
"all": true
} }
}, },
"windows": [], "windows": [],
+14
View File
@@ -0,0 +1,14 @@
{
"tauri": {
"systemTray": {
"iconPath": "icons/tray-icon.png"
},
"bundle": {
"targets": ["deb", "appimage", "updater"],
"deb": {
"depends": ["openssl"],
"desktopTemplate": "./clash-verge.desktop"
}
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"tauri": {
"systemTray": {
"iconPath": "icons/mac-tray-icon.png",
"iconAsTemplate": true
},
"bundle": {
"targets": ["app", "dmg", "updater"],
"macOS": {
"frameworks": [],
"minimumSystemVersion": "",
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": null
}
}
}
}
+25
View File
@@ -0,0 +1,25 @@
{
"tauri": {
"systemTray": {
"iconPath": "icons/tray-icon.png"
},
"bundle": {
"targets": ["nsis", "updater"],
"windows": {
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": "",
"webviewInstallMode": {
"type": "embedBootstrapper",
"silent": true
},
"nsis": {
"displayLanguageSelector": true,
"installerIcon": "icons/icon.ico",
"languages": ["SimpChinese", "English"],
"license": "../LICENSE"
}
}
}
}
}
Binary file not shown.
-21
View File
@@ -1,21 +0,0 @@
.page-enter {
opacity: 0;
transform: scale(0.9);
}
.page-enter-active {
opacity: 1;
transform: scale(1);
transition: opacity 300ms, transform 300ms;
}
.page-exit {
opacity: 1;
transform: scale(0);
}
.page-exit-active {
opacity: 0;
transform: scale(0.9);
transition: opacity 300ms, transform 300ms;
}
+4
View File
@@ -0,0 +1,4 @@
@font-face {
font-family: "twemoji mozilla";
src: url("../fonts/Twemoji.Mozilla.ttf");
}
+2 -2
View File
@@ -18,7 +18,7 @@ body {
--scroller-color: #90939980; --scroller-color: #90939980;
--background-color: #ffffff; --background-color: #ffffff;
--background-color-alpha: rgba(24, 103, 192, 0.1); --background-color-alpha: rgba(24, 103, 192, 0.1);
--border-radius: 12px; --border-radius: 8px;
} }
::selection { ::selection {
@@ -42,7 +42,7 @@ body {
@import "./layout.scss"; @import "./layout.scss";
@import "./page.scss"; @import "./page.scss";
@import "./anime.scss"; @import "./font.scss";
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:root { :root {
+3 -3
View File
@@ -57,7 +57,7 @@
.the-menu { .the-menu {
flex: 1 1 80%; flex: 1 1 80%;
overflow-y: auto; overflow-y: auto;
margin-bottom: 8px; margin-bottom: 0px;
} }
.the-traffic { .the-traffic {
@@ -77,8 +77,8 @@
.the-bar { .the-bar {
position: absolute; position: absolute;
top: 2px; top: 0px;
right: 8px; right: 0px;
height: 36px; height: 36px;
display: flex; display: flex;
align-items: center; align-items: center;
+13 -4
View File
@@ -27,16 +27,25 @@
width: 100%; width: 100%;
height: 100%; height: 100%;
overflow: auto; overflow: auto;
padding: 5px 5px; padding: 10px 0;
box-sizing: border-box; box-sizing: border-box;
scrollbar-gutter: stable; scrollbar-gutter: stable;
background-color: var(--background-color);
.base-content { .base-content {
width: 100%; width: calc(100% - 10px * 2);
// max-width: 850px;
margin: 0 auto; margin: 0 auto;
} }
} }
&.no-padding {
> section {
padding: 0;
overflow: visible;
.base-content {
width: 100%;
}
}
}
} }
} }
+20 -6
View File
@@ -1,20 +1,25 @@
import React, { ReactNode } from "react"; import React, { ReactNode } from "react";
import { Typography } from "@mui/material"; import { Typography, alpha } from "@mui/material";
import { BaseErrorBoundary } from "./base-error-boundary"; import { BaseErrorBoundary } from "./base-error-boundary";
import { useCustomTheme } from "@/components/layout/use-custom-theme";
interface Props { interface Props {
title?: React.ReactNode; // the page title title?: React.ReactNode; // the page title
header?: React.ReactNode; // something behind title header?: React.ReactNode; // something behind title
contentStyle?: React.CSSProperties; contentStyle?: React.CSSProperties;
children?: ReactNode; children?: ReactNode;
full?: boolean;
} }
export const BasePage: React.FC<Props> = (props) => { export const BasePage: React.FC<Props> = (props) => {
const { title, header, contentStyle, children } = props; const { title, header, contentStyle, full, children } = props;
const { theme } = useCustomTheme();
const isDark = theme.palette.mode === "dark";
return ( return (
<BaseErrorBoundary> <BaseErrorBoundary>
<div className="base-page" data-windrag> <div className="base-page">
<header data-windrag style={{ userSelect: "none" }}> <header data-windrag style={{ userSelect: "none" }}>
<Typography variant="h4" component="h1" data-windrag> <Typography variant="h4" component="h1" data-windrag>
{title} {title}
@@ -23,9 +28,18 @@ export const BasePage: React.FC<Props> = (props) => {
{header} {header}
</header> </header>
<div className="base-container"> <div
<section> className={full ? "base-container no-padding" : "base-container"}
<div className="base-content" style={contentStyle} data-windrag> style={{ backgroundColor: isDark ? "#090909" : "#ffffff" }}
>
<section
style={{
backgroundColor: isDark
? alpha(theme.palette.primary.main, 0.1)
: "",
}}
>
<div className="base-content" style={contentStyle}>
{children} {children}
</div> </div>
</section> </section>
+56 -6
View File
@@ -1,16 +1,50 @@
import { Button } from "@mui/material"; import { Button, ButtonGroup } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window"; import { appWindow } from "@tauri-apps/api/window";
import { import {
CloseRounded, CloseRounded,
CropSquareRounded, CropSquareRounded,
FilterNoneRounded,
HorizontalRuleRounded, HorizontalRuleRounded,
PushPinOutlined,
PushPinRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import { useState } from "react";
export const LayoutControl = () => { export const LayoutControl = () => {
const minWidth = 40; const minWidth = 40;
const [isMaximized, setIsMaximized] = useState(false);
const [isPined, setIsPined] = useState(false);
appWindow.isMaximized().then((isMaximized) => {
setIsMaximized(() => isMaximized);
});
return ( return (
<> <ButtonGroup
variant="text"
sx={{
height: "100%",
".MuiButtonGroup-grouped": {
borderRadius: "0px",
borderRight: "0px",
},
}}
>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
onClick={() => {
appWindow.setAlwaysOnTop(!isPined);
setIsPined((isPined) => !isPined);
}}
>
{isPined ? (
<PushPinRounded fontSize="small" />
) : (
<PushPinOutlined fontSize="small" />
)}
</Button>
<Button <Button
size="small" size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }} sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
@@ -22,18 +56,34 @@ export const LayoutControl = () => {
<Button <Button
size="small" size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }} sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
onClick={() => appWindow.toggleMaximize()} onClick={() => {
setIsMaximized((isMaximized) => !isMaximized);
appWindow.toggleMaximize();
}}
> >
<CropSquareRounded fontSize="small" /> {isMaximized ? (
<FilterNoneRounded
fontSize="small"
style={{
transform: "rotate(180deg) scale(0.7)",
}}
/>
) : (
<CropSquareRounded fontSize="small" />
)}
</Button> </Button>
<Button <Button
size="small" size="small"
sx={{ minWidth, svg: { transform: "scale(1.05)" } }} sx={{
minWidth,
svg: { transform: "scale(1.05)" },
":hover": { bgcolor: "#ff000090" },
}}
onClick={() => appWindow.close()} onClick={() => appWindow.close()}
> >
<CloseRounded fontSize="small" /> <CloseRounded fontSize="small" />
</Button> </Button>
</> </ButtonGroup>
); );
}; };
+6 -8
View File
@@ -10,24 +10,22 @@ export const LayoutItem = (props: LinkProps) => {
const navigate = useNavigate(); const navigate = useNavigate();
return ( return (
<ListItem <ListItem sx={{ py: 0.5, maxWidth: 250, mx: "auto", padding: "1px 0px" }}>
sx={{ py: 0.5, maxWidth: 250, mx: "auto", padding: "4px 0px 4px 2px" }}
>
<ListItemButton <ListItemButton
selected={!!match} selected={!!match}
sx={[ sx={[
{ {
borderTopLeftRadius: 18, borderRadius: 3,
borderBottomLeftRadius: 18, marginLeft: 1,
marginRight: 1,
textAlign: "center", textAlign: "center",
"& .MuiListItemText-primary": { color: "text.secondary" }, "& .MuiListItemText-primary": { color: "text.secondary" },
}, },
({ palette: { mode, primary } }) => { ({ palette: { mode, primary } }) => {
/* const bgcolor = const bgcolor =
mode === "light" mode === "light"
? alpha(primary.main, 0.15) ? alpha(primary.main, 0.15)
: alpha(primary.main, 0.35); */ : alpha(primary.main, 0.35);
const bgcolor = mode === "light" ? "#ffffff" : "#0E1621";
const color = mode === "light" ? primary.main : primary.light; const color = mode === "light" ? primary.main : primary.light;
return { return {
+1 -1
View File
@@ -47,7 +47,7 @@ export const LayoutTraffic = () => {
}, [clashInfo, pageVisible]); }, [clashInfo, pageVisible]);
/* --------- meta memory information --------- */ /* --------- meta memory information --------- */
const isMetaCore = verge?.clash_core === "clash-meta"; const isMetaCore = verge?.clash_core?.includes("clash-meta");
const displayMemory = isMetaCore && (verge?.enable_memory_usage ?? true); const displayMemory = isMetaCore && (verge?.enable_memory_usage ?? true);
const memoryWs = useWebsocket( const memoryWs = useWebsocket(
+4 -1
View File
@@ -55,6 +55,9 @@ export const useCustomTheme = () => {
primary: setting.primary_text || dt.primary_text, primary: setting.primary_text || dt.primary_text,
secondary: setting.secondary_text || dt.secondary_text, secondary: setting.secondary_text || dt.secondary_text,
}, },
background: {
paper: dt.background_color,
},
}, },
typography: { typography: {
// todo // todo
@@ -84,7 +87,7 @@ export const useCustomTheme = () => {
} }
// css // css
const backgroundColor = mode === "light" ? "#ffffff" : "#0E1621"; const backgroundColor = mode === "light" ? "#ffffff" : "#0B121C";
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5"; const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const scrollColor = mode === "light" ? "#90939980" : "#54545480"; const scrollColor = mode === "light" ? "#90939980" : "#54545480";
+33 -16
View File
@@ -4,6 +4,8 @@ import { useEffect, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { import {
Box, Box,
Typography, Typography,
@@ -14,7 +16,7 @@ import {
Menu, Menu,
CircularProgress, CircularProgress,
} from "@mui/material"; } from "@mui/material";
import { RefreshRounded } from "@mui/icons-material"; import { RefreshRounded, DragIndicator } from "@mui/icons-material";
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 { Notice } from "@/components/base"; import { Notice } from "@/components/base";
@@ -28,6 +30,7 @@ const round = keyframes`
`; `;
interface Props { interface Props {
id: string;
selected: boolean; selected: boolean;
activating: boolean; activating: boolean;
itemData: IProfileItem; itemData: IProfileItem;
@@ -37,6 +40,8 @@ interface Props {
export const ProfileItem = (props: Props) => { export const ProfileItem = (props: Props) => {
const { selected, activating, itemData, onSelect, onEdit } = props; const { selected, activating, itemData, onSelect, onEdit } = props;
const { attributes, listeners, setNodeRef, transform, transition } =
useSortable({ id: props.id });
const { t } = useTranslation(); const { t } = useTranslation();
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
@@ -183,7 +188,12 @@ export const ProfileItem = (props: Props) => {
}; };
return ( return (
<> <Box
sx={{
transform: CSS.Transform.toString(transform),
transition,
}}
>
<ProfileBox <ProfileBox
aria-selected={selected} aria-selected={selected}
onClick={() => onSelect(false)} onClick={() => onSelect(false)}
@@ -212,17 +222,27 @@ export const ProfileItem = (props: Props) => {
<CircularProgress size={20} /> <CircularProgress size={20} />
</Box> </Box>
)} )}
<Box position="relative"> <Box position="relative">
<Typography <Box sx={{ display: "flex", justifyContent: "start" }}>
width="calc(100% - 36px)" <Box
variant="h6" ref={setNodeRef}
component="h2" sx={{ display: "flex", margin: "auto 0" }}
noWrap {...attributes}
title={name} {...listeners}
> >
{name} <DragIndicator sx={{ cursor: "move", marginLeft: "-6px" }} />
</Typography> </Box>
<Typography
width="calc(100% - 36px)"
variant="h6"
component="h2"
noWrap
title={name}
>
{name}
</Typography>
</Box>
{/* only if has url can it be updated */} {/* only if has url can it be updated */}
{hasUrl && ( {hasUrl && (
@@ -246,7 +266,6 @@ export const ProfileItem = (props: Props) => {
</IconButton> </IconButton>
)} )}
</Box> </Box>
{/* the second line show url's info or description */} {/* the second line show url's info or description */}
<Box sx={boxStyle}> <Box sx={boxStyle}>
{hasUrl ? ( {hasUrl ? (
@@ -271,7 +290,6 @@ export const ProfileItem = (props: Props) => {
</Typography> </Typography>
)} )}
</Box> </Box>
{/* the third line show extra info or last updated time */} {/* the third line show extra info or last updated time */}
{hasExtra ? ( {hasExtra ? (
<Box sx={{ ...boxStyle, fontSize: 14 }}> <Box sx={{ ...boxStyle, fontSize: 14 }}>
@@ -285,7 +303,6 @@ export const ProfileItem = (props: Props) => {
<span title="Updated Time">{parseExpire(updated)}</span> <span title="Updated Time">{parseExpire(updated)}</span>
</Box> </Box>
)} )}
<LinearProgress <LinearProgress
variant="determinate" variant="determinate"
value={progress} value={progress}
@@ -324,7 +341,7 @@ export const ProfileItem = (props: Props) => {
mode="yaml" mode="yaml"
onClose={() => setFileOpen(false)} onClose={() => setFileOpen(false)}
/> />
</> </Box>
); );
}; };
+2
View File
@@ -98,6 +98,8 @@ export const ProxyItemMini = (props: Props) => {
)} )}
<TypeBox component="span">{proxy.type}</TypeBox> <TypeBox component="span">{proxy.type}</TypeBox>
{proxy.udp && <TypeBox component="span">UDP</TypeBox>} {proxy.udp && <TypeBox component="span">UDP</TypeBox>}
{proxy.xudp && <TypeBox component="span">XUDP</TypeBox>}
{proxy.tfo && <TypeBox component="span">TFO</TypeBox>}
</Box> </Box>
)} )}
</Box> </Box>
+4
View File
@@ -104,6 +104,10 @@ export const ProxyItem = (props: Props) => {
)} )}
{showType && <TypeBox component="span">{proxy.type}</TypeBox>} {showType && <TypeBox component="span">{proxy.type}</TypeBox>}
{showType && proxy.udp && <TypeBox component="span">UDP</TypeBox>} {showType && proxy.udp && <TypeBox component="span">UDP</TypeBox>}
{showType && proxy.xudp && (
<TypeBox component="span">XUDP</TypeBox>
)}
{showType && proxy.tfo && <TypeBox component="span">TFO</TypeBox>}
</> </>
} }
/> />
+5 -5
View File
@@ -31,7 +31,7 @@ export const ProxyRender = (props: RenderProps) => {
props; props;
const { type, group, headState, proxy, proxyCol } = item; const { type, group, headState, proxy, proxyCol } = item;
if (type === 0) { if (type === 0 && !group.hidden) {
return ( return (
<ListItemButton <ListItemButton
dense dense
@@ -61,7 +61,7 @@ export const ProxyRender = (props: RenderProps) => {
); );
} }
if (type === 1) { if (type === 1 && !group.hidden) {
return ( return (
<ProxyHead <ProxyHead
sx={{ pl: indent ? 4.5 : 2.5, pr: 3, mt: indent ? 1 : 0.5, mb: 1 }} sx={{ pl: indent ? 4.5 : 2.5, pr: 3, mt: indent ? 1 : 0.5, mb: 1 }}
@@ -74,7 +74,7 @@ export const ProxyRender = (props: RenderProps) => {
); );
} }
if (type === 2) { if (type === 2 && !group.hidden) {
return ( return (
<ProxyItem <ProxyItem
groupName={group.name} groupName={group.name}
@@ -87,7 +87,7 @@ export const ProxyRender = (props: RenderProps) => {
); );
} }
if (type === 3) { if (type === 3 && !group.hidden) {
return ( return (
<Box <Box
sx={{ sx={{
@@ -105,7 +105,7 @@ export const ProxyRender = (props: RenderProps) => {
); );
} }
if (type === 4) { if (type === 4 && !group.hidden) {
return ( return (
<Box <Box
sx={{ sx={{
@@ -4,25 +4,25 @@ import { BaseDialog, DialogRef, Notice } from "@/components/base";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Lock } from "@mui/icons-material"; import { LoadingButton } from "@mui/lab";
import { SwitchAccessShortcut, RestartAlt } from "@mui/icons-material";
import { import {
Box, Box,
Button, Button,
IconButton, Tooltip,
List, List,
ListItemButton, ListItemButton,
ListItemText, ListItemText,
} from "@mui/material"; } from "@mui/material";
import { changeClashCore, restartSidecar } from "@/services/cmds"; import { changeClashCore, restartSidecar } from "@/services/cmds";
import { closeAllConnections } from "@/services/api"; import { closeAllConnections, upgradeCore } from "@/services/api";
import { grantPermission } from "@/services/cmds"; import { grantPermission } from "@/services/cmds";
import getSystem from "@/utils/get-system"; import getSystem from "@/utils/get-system";
/* const VALID_CORE = [ const VALID_CORE = [
{ name: "Clash", core: "clash" },
{ name: "Clash Meta", core: "clash-meta" }, { name: "Clash Meta", core: "clash-meta" },
]; */ { name: "Clash Meta Alpha", core: "clash-meta-alpha" },
const VALID_CORE = [{ name: "Clash Meta", core: "clash-meta" }]; ];
const OS = getSystem(); const OS = getSystem();
@@ -32,13 +32,14 @@ export const ClashCoreViewer = forwardRef<DialogRef>((props, ref) => {
const { verge, mutateVerge } = useVerge(); const { verge, mutateVerge } = useVerge();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [upgrading, setUpgrading] = useState(false);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: () => setOpen(true), open: () => setOpen(true),
close: () => setOpen(false), close: () => setOpen(false),
})); }));
const { clash_core = "clash" } = verge ?? {}; const { clash_core = "clash-meta" } = verge ?? {};
const onCoreChange = useLockFn(async (core: string) => { const onCoreChange = useLockFn(async (core: string) => {
if (core === clash_core) return; if (core === clash_core) return;
@@ -77,22 +78,53 @@ export const ClashCoreViewer = forwardRef<DialogRef>((props, ref) => {
} }
}); });
const onUpgrade = useLockFn(async () => {
try {
setUpgrading(true);
await upgradeCore();
setUpgrading(false);
Notice.success(`Successfully upgrade core`, 1000);
} catch (err: any) {
setUpgrading(false);
Notice.error(err?.response.data.message || err.toString());
}
});
return ( return (
<BaseDialog <BaseDialog
open={open} open={open}
title={ title={
<Box display="flex" justifyContent="space-between"> <Box display="flex" justifyContent="space-between">
{t("Clash Core")} {t("Clash Core")}
<Box>
<Button variant="contained" size="small" onClick={onRestart}> {clash_core !== "clash-meta" && (
{t("Restart")} <LoadingButton
</Button> variant="contained"
size="small"
startIcon={<SwitchAccessShortcut />}
loadingPosition="start"
loading={upgrading}
sx={{ marginRight: "8px" }}
onClick={onUpgrade}
>
{t("Upgrade")}
</LoadingButton>
)}
<Button
variant="contained"
size="small"
onClick={onRestart}
startIcon={<RestartAlt />}
>
{t("Restart")}
</Button>
</Box>
</Box> </Box>
} }
contentSx={{ contentSx={{
pb: 0, pb: 0,
width: 320, width: 400,
height: 90, height: 180,
overflowY: "auto", overflowY: "auto",
userSelect: "text", userSelect: "text",
marginTop: "-8px", marginTop: "-8px",
@@ -112,30 +144,19 @@ export const ClashCoreViewer = forwardRef<DialogRef>((props, ref) => {
<ListItemText primary={each.name} secondary={`/${each.core}`} /> <ListItemText primary={each.name} secondary={`/${each.core}`} />
{(OS === "macos" || OS === "linux") && ( {(OS === "macos" || OS === "linux") && (
/* <IconButton <Tooltip title={t("Tun mode requires")}>
color="inherit" <Button
size="small" variant="outlined"
edge="end" size="small"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
onGrant(each.core); onGrant(each.core);
}} }}
> >
<Lock fontSize="inherit" /> {t("Grant")}
</IconButton> */ </Button>
<Button </Tooltip>
variant="outlined"
size="small"
title={t("Tun mode requires")}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onGrant(each.core);
}}
>
{t("Grant")}
</Button>
)} )}
</ListItemButton> </ListItemButton>
))} ))}
@@ -4,30 +4,35 @@ import { useLockFn } from "ahooks";
import { List, ListItem, ListItemText, TextField } from "@mui/material"; import { List, ListItem, ListItemText, TextField } from "@mui/material";
import { useClashInfo } from "@/hooks/use-clash"; import { useClashInfo } from "@/hooks/use-clash";
import { BaseDialog, DialogRef, Notice } from "@/components/base"; import { BaseDialog, DialogRef, Notice } from "@/components/base";
import { useVerge } from "@/hooks/use-verge";
export const ClashPortViewer = forwardRef<DialogRef>((props, ref) => { export const ClashPortViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { clashInfo, patchInfo } = useClashInfo(); const { clashInfo, patchInfo } = useClashInfo();
const { verge, patchVerge } = useVerge();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [port, setPort] = useState(clashInfo?.port ?? 7890); const [port, setPort] = useState(
verge?.verge_mixed_port ?? clashInfo?.port ?? 7897
);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: () => { open: () => {
if (clashInfo?.port) setPort(clashInfo?.port); if (verge?.verge_mixed_port) setPort(verge?.verge_mixed_port);
setOpen(true); setOpen(true);
}, },
close: () => setOpen(false), close: () => setOpen(false),
})); }));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
if (port === clashInfo?.port) { if (port === verge?.verge_mixed_port) {
setOpen(false); setOpen(false);
return; return;
} }
try { try {
await patchInfo({ "mixed-port": port }); await patchInfo({ "mixed-port": port });
await patchVerge({ verge_mixed_port: port });
setOpen(false); setOpen(false);
Notice.success("Change Clash port successfully!", 1000); Notice.success("Change Clash port successfully!", 1000);
} catch (err: any) { } catch (err: any) {
+3 -3
View File
@@ -20,8 +20,8 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [values, setValues] = useState({ const [values, setValues] = useState({
appLogLevel: "info", appLogLevel: "info",
autoCloseConnection: false, autoCloseConnection: true,
enableClashFields: false, enableClashFields: true,
enableBuiltinEnhanced: true, enableBuiltinEnhanced: true,
proxyLayoutColumn: 6, proxyLayoutColumn: 6,
defaultLatencyTest: "", defaultLatencyTest: "",
@@ -34,7 +34,7 @@ export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
setValues({ setValues({
appLogLevel: verge?.app_log_level ?? "info", appLogLevel: verge?.app_log_level ?? "info",
autoCloseConnection: verge?.auto_close_connection ?? true, autoCloseConnection: verge?.auto_close_connection ?? true,
enableClashFields: verge?.enable_clash_fields ?? false, enableClashFields: verge?.enable_clash_fields ?? true,
enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true, enableBuiltinEnhanced: verge?.enable_builtin_enhanced ?? true,
proxyLayoutColumn: verge?.proxy_layout_column || 6, proxyLayoutColumn: verge?.proxy_layout_column || 6,
defaultLatencyTest: verge?.default_latency_test || "", defaultLatencyTest: verge?.default_latency_test || "",
@@ -168,6 +168,6 @@ const FlexBox = styled("div")`
.label { .label {
flex: none; flex: none;
width: 80px; width: 85px;
} }
`; `;
+38 -4
View File
@@ -2,17 +2,20 @@ import useSWR from "swr";
import snarkdown from "snarkdown"; import snarkdown from "snarkdown";
import { forwardRef, useImperativeHandle, useState, useMemo } from "react"; import { forwardRef, useImperativeHandle, useState, useMemo } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Box, styled } from "@mui/material"; import { Box, LinearProgress, styled } from "@mui/material";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { relaunch } from "@tauri-apps/api/process"; import { relaunch } from "@tauri-apps/api/process";
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater"; import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
import { BaseDialog, DialogRef, Notice } from "@/components/base"; import { BaseDialog, DialogRef, Notice } from "@/components/base";
import { atomUpdateState } from "@/services/states"; import { atomUpdateState } from "@/services/states";
import { listen, Event, UnlistenFn } from "@tauri-apps/api/event";
import { portableFlag } from "@/pages/_layout";
const UpdateLog = styled(Box)(() => ({ const UpdateLog = styled(Box)(() => ({
"h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" }, "h1,h2,h3,ul,ol,p": { margin: "0.5em 0", color: "inherit" },
})); }));
let eventListener: UnlistenFn | null = null;
export const UpdateViewer = forwardRef<DialogRef>((props, ref) => { export const UpdateViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -26,6 +29,10 @@ export const UpdateViewer = forwardRef<DialogRef>((props, ref) => {
focusThrottleInterval: 36e5, // 1 hour focusThrottleInterval: 36e5, // 1 hour
}); });
const [downloaded, setDownloaded] = useState(0);
const [buffer, setBuffer] = useState(0);
const [total, setTotal] = useState(0);
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: () => setOpen(true), open: () => setOpen(true),
close: () => setOpen(false), close: () => setOpen(false),
@@ -40,9 +47,25 @@ export const UpdateViewer = forwardRef<DialogRef>((props, ref) => {
}, [updateInfo]); }, [updateInfo]);
const onUpdate = useLockFn(async () => { const onUpdate = useLockFn(async () => {
if (portableFlag) {
Notice.error(t("Portable Updater Error"));
return;
}
if (updateState) return; if (updateState) return;
setUpdateState(true); setUpdateState(true);
if (eventListener !== null) {
eventListener();
}
eventListener = await listen(
"tauri://update-download-progress",
(e: Event<any>) => {
setTotal(e.payload.contentLength);
setBuffer(e.payload.chunkLength);
setDownloaded((a) => {
return a + e.payload.chunkLength;
});
}
);
try { try {
await installUpdate(); await installUpdate();
await relaunch(); await relaunch();
@@ -57,14 +80,25 @@ export const UpdateViewer = forwardRef<DialogRef>((props, ref) => {
<BaseDialog <BaseDialog
open={open} open={open}
title={`New Version v${updateInfo?.manifest?.version}`} title={`New Version v${updateInfo?.manifest?.version}`}
contentSx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }} contentSx={{ minWidth: 360, maxWidth: 400, height: "50vh" }}
okBtn={t("Update")} okBtn={t("Update")}
cancelBtn={t("Cancel")} cancelBtn={t("Cancel")}
onClose={() => setOpen(false)} onClose={() => setOpen(false)}
onCancel={() => setOpen(false)} onCancel={() => setOpen(false)}
onOk={onUpdate} onOk={onUpdate}
> >
<UpdateLog dangerouslySetInnerHTML={{ __html: parseContent }} /> <UpdateLog
dangerouslySetInnerHTML={{ __html: parseContent }}
sx={{ height: "calc(100% - 10px)", overflow: "auto" }}
/>
{updateState && (
<LinearProgress
variant="buffer"
value={(downloaded / total) * 100}
valueBuffer={buffer}
sx={{ marginTop: "5px" }}
/>
)}
</BaseDialog> </BaseDialog>
); );
}); });
@@ -59,7 +59,7 @@ export const WebUIViewer = forwardRef<DialogRef>((props, ref) => {
.slice(clashInfo.server.indexOf(":") + 1) .slice(clashInfo.server.indexOf(":") + 1)
.trim(); .trim();
url = url.replaceAll("%port", port || "9090"); url = url.replaceAll("%port", port || "9097");
url = url.replaceAll( url = url.replaceAll(
"%secret", "%secret",
encodeURIComponent(clashInfo.secret || "") encodeURIComponent(clashInfo.secret || "")
+70 -19
View File
@@ -1,5 +1,6 @@
import { useRef } from "react"; import { useRef } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks";
import { import {
TextField, TextField,
Switch, Switch,
@@ -7,9 +8,10 @@ import {
MenuItem, MenuItem,
Typography, Typography,
IconButton, IconButton,
Tooltip,
} from "@mui/material"; } from "@mui/material";
import { ArrowForward, Settings } from "@mui/icons-material"; import { ArrowForward, Settings, Shuffle } from "@mui/icons-material";
import { DialogRef } from "@/components/base"; import { DialogRef, Notice } from "@/components/base";
import { useClash } from "@/hooks/use-clash"; import { useClash } from "@/hooks/use-clash";
import { GuardState } from "./mods/guard-state"; import { GuardState } from "./mods/guard-state";
import { WebUIViewer } from "./mods/web-ui-viewer"; import { WebUIViewer } from "./mods/web-ui-viewer";
@@ -20,6 +22,8 @@ import { SettingList, SettingItem } from "./mods/setting-comp";
import { ClashCoreViewer } from "./mods/clash-core-viewer"; import { ClashCoreViewer } from "./mods/clash-core-viewer";
import { invoke_uwp_tool } from "@/services/cmds"; import { invoke_uwp_tool } from "@/services/cmds";
import getSystem from "@/utils/get-system"; import getSystem from "@/utils/get-system";
import { useVerge } from "@/hooks/use-verge";
import { updateGeoData } from "@/services/api";
const isWIN = getSystem() === "windows"; const isWIN = getSystem() === "windows";
@@ -31,13 +35,15 @@ const SettingClash = ({ onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { clash, version, mutateClash, patchClash } = useClash(); const { clash, version, mutateClash, patchClash } = useClash();
const { verge, mutateVerge, patchVerge } = useVerge();
const { ipv6, "allow-lan": allowLan, "log-level": logLevel } = clash ?? {};
const { const {
ipv6, enable_random_port = false,
"allow-lan": allowLan, verge_mixed_port,
"log-level": logLevel, enable_clash_fields = true,
"mixed-port": mixedPort, } = verge ?? {};
} = clash ?? {};
const webRef = useRef<DialogRef>(null); const webRef = useRef<DialogRef>(null);
const fieldRef = useRef<DialogRef>(null); const fieldRef = useRef<DialogRef>(null);
@@ -49,6 +55,17 @@ const SettingClash = ({ onError }: Props) => {
const onChangeData = (patch: Partial<IConfigData>) => { const onChangeData = (patch: Partial<IConfigData>) => {
mutateClash((old) => ({ ...(old! || {}), ...patch }), false); mutateClash((old) => ({ ...(old! || {}), ...patch }), false);
}; };
const onChangeVerge = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch }, false);
};
const onUpdateGeo = useLockFn(async () => {
try {
await updateGeoData();
Notice.success("Start update geodata");
} catch (err: any) {
Notice.error(err?.response.data.message || err.toString());
}
});
return ( return (
<SettingList title={t("Clash Setting")}> <SettingList title={t("Clash Setting")}>
@@ -103,11 +120,32 @@ const SettingClash = ({ onError }: Props) => {
</GuardState> </GuardState>
</SettingItem> </SettingItem>
<SettingItem label={t("Mixed Port")}> <SettingItem
label={t("Mixed Port")}
extra={
<Tooltip title={t("Random Port")}>
<IconButton
color={enable_random_port ? "success" : "inherit"}
size="small"
onClick={() => {
Notice.success(t("After restart to take effect"), 1000);
onChangeVerge({ enable_random_port: !enable_random_port });
patchVerge({ enable_random_port: !enable_random_port });
}}
>
<Shuffle
fontSize="inherit"
style={{ cursor: "pointer", opacity: 0.75 }}
/>
</IconButton>
</Tooltip>
}
>
<TextField <TextField
disabled={enable_random_port}
autoComplete="off" autoComplete="off"
size="small" size="small"
value={mixedPort ?? 0} value={verge_mixed_port ?? 7897}
sx={{ width: 100, input: { py: "7.5px", cursor: "pointer" } }} sx={{ width: 100, input: { py: "7.5px", cursor: "pointer" } }}
onClick={(e) => { onClick={(e) => {
portRef.current?.open(); portRef.current?.open();
@@ -138,16 +176,18 @@ const SettingClash = ({ onError }: Props) => {
</IconButton> </IconButton>
</SettingItem> </SettingItem>
<SettingItem label={t("Clash Field")}> {enable_clash_fields && (
<IconButton <SettingItem label={t("Clash Field")}>
color="inherit" <IconButton
size="small" color="inherit"
sx={{ my: "2px" }} size="small"
onClick={() => fieldRef.current?.open()} sx={{ my: "2px" }}
> onClick={() => fieldRef.current?.open()}
<ArrowForward /> >
</IconButton> <ArrowForward />
</SettingItem> </IconButton>
</SettingItem>
)}
<SettingItem <SettingItem
label={t("Clash Core")} label={t("Clash Core")}
@@ -179,6 +219,17 @@ const SettingClash = ({ onError }: Props) => {
</IconButton> </IconButton>
</SettingItem> </SettingItem>
)} )}
<SettingItem label={t("Update GeoData")}>
<IconButton
color="inherit"
size="small"
sx={{ my: "2px" }}
onClick={onUpdateGeo}
>
<ArrowForward />
</IconButton>
</SettingItem>
</SettingList> </SettingList>
); );
}; };
+20 -2
View File
@@ -18,6 +18,7 @@ import { GuardState } from "./mods/guard-state";
import { LayoutViewer } from "./mods/layout-viewer"; import { LayoutViewer } from "./mods/layout-viewer";
import { UpdateViewer } from "./mods/update-viewer"; import { UpdateViewer } from "./mods/update-viewer";
import getSystem from "@/utils/get-system"; import getSystem from "@/utils/get-system";
import { portableFlag } from "@/pages/_layout";
interface Props { interface Props {
onError?: (err: Error) => void; onError?: (err: Error) => void;
@@ -29,7 +30,7 @@ const SettingVerge = ({ onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { verge, patchVerge, mutateVerge } = useVerge(); const { verge, patchVerge, mutateVerge } = useVerge();
const { theme_mode, language, tray_event } = verge ?? {}; const { theme_mode, language, tray_event, env_type } = verge ?? {};
const configRef = useRef<DialogRef>(null); const configRef = useRef<DialogRef>(null);
const hotkeyRef = useRef<DialogRef>(null); const hotkeyRef = useRef<DialogRef>(null);
const miscRef = useRef<DialogRef>(null); const miscRef = useRef<DialogRef>(null);
@@ -103,11 +104,28 @@ const SettingVerge = ({ onError }: Props) => {
<MenuItem value="main_window">{t("Show Main Window")}</MenuItem> <MenuItem value="main_window">{t("Show Main Window")}</MenuItem>
<MenuItem value="system_proxy">{t("System Proxy")}</MenuItem> <MenuItem value="system_proxy">{t("System Proxy")}</MenuItem>
<MenuItem value="tun_mode">{t("Tun Mode")}</MenuItem> <MenuItem value="tun_mode">{t("Tun Mode")}</MenuItem>
<MenuItem value="disable">{t("Disable")}</MenuItem>
</Select> </Select>
</GuardState> </GuardState>
</SettingItem> </SettingItem>
)} )}
<SettingItem label={t("Copy Env Type")}>
<GuardState
value={env_type ?? (OS === "windows" ? "powershell" : "bash")}
onCatch={onError}
onFormat={(e: any) => e.target.value}
onChange={(e) => onChangeData({ env_type: e })}
onGuard={(e) => patchVerge({ env_type: e })}
>
<Select size="small" sx={{ width: 140, "> div": { py: "7.5px" } }}>
<MenuItem value="bash">Bash</MenuItem>
<MenuItem value="cmd">CMD</MenuItem>
<MenuItem value="powershell">PowerShell</MenuItem>
</Select>
</GuardState>
</SettingItem>
<SettingItem label={t("Theme Setting")}> <SettingItem label={t("Theme Setting")}>
<IconButton <IconButton
color="inherit" color="inherit"
@@ -196,7 +214,7 @@ const SettingVerge = ({ onError }: Props) => {
</IconButton> </IconButton>
</SettingItem> </SettingItem>
{!(OS === "windows" && WIN_PORTABLE) && ( {!portableFlag && (
<SettingItem label={t("Check for Updates")}> <SettingItem label={t("Check for Updates")}>
<IconButton <IconButton
color="inherit" color="inherit"
+8 -1
View File
@@ -67,6 +67,8 @@
"IPv6": "IPv6", "IPv6": "IPv6",
"Log Level": "Log Level", "Log Level": "Log Level",
"Mixed Port": "Mixed Port", "Mixed Port": "Mixed Port",
"Random Port": "Random Port",
"After restart to take effect": "After restart to take effect",
"External": "External", "External": "External",
"Clash Core": "Clash Core", "Clash Core": "Clash Core",
"Grant": "Grant", "Grant": "Grant",
@@ -78,6 +80,7 @@
"System Proxy": "System Proxy", "System Proxy": "System Proxy",
"System Proxy Setting": "System Proxy Setting", "System Proxy Setting": "System Proxy Setting",
"Open UWP tool": "Open UWP tool", "Open UWP tool": "Open UWP tool",
"Update GeoData": "Update GeoData",
"Proxy Guard": "Proxy Guard", "Proxy Guard": "Proxy Guard",
"Guard Duration": "Guard Duration", "Guard Duration": "Guard Duration",
"Proxy Bypass": "Proxy Bypass", "Proxy Bypass": "Proxy Bypass",
@@ -88,6 +91,7 @@
"Theme Mode": "Theme Mode", "Theme Mode": "Theme Mode",
"Theme Blur": "Theme Blur", "Theme Blur": "Theme Blur",
"Tray Click Event": "Tray Click Event", "Tray Click Event": "Tray Click Event",
"Copy Env Type": "Copy Env Type",
"Show Main Window": "Show Main Window", "Show Main Window": "Show Main Window",
"Theme Setting": "Theme Setting", "Theme Setting": "Theme Setting",
"Layout Setting": "Layout Setting", "Layout Setting": "Layout Setting",
@@ -108,6 +112,7 @@
"Runtime Config": "Runtime Config", "Runtime Config": "Runtime Config",
"ReadOnly": "ReadOnly", "ReadOnly": "ReadOnly",
"Restart": "Restart", "Restart": "Restart",
"Upgrade": "Upgrade",
"Back": "Back", "Back": "Back",
"Save": "Save", "Save": "Save",
@@ -140,5 +145,7 @@
"Never Clean": "Never Clean", "Never Clean": "Never Clean",
"Retain 7 Days": "Retain 7 Days", "Retain 7 Days": "Retain 7 Days",
"Retain 30 Days": "Retain 30 Days", "Retain 30 Days": "Retain 30 Days",
"Retain 90 Days": "Retain 90 Days" "Retain 90 Days": "Retain 90 Days",
"Portable Updater Error": "The portable version does not support in-app updates. Please manually download and replace it"
} }
+8 -1
View File
@@ -64,6 +64,8 @@
"IPv6": "IPv6", "IPv6": "IPv6",
"Log Level": "Уровень логов", "Log Level": "Уровень логов",
"Mixed Port": "Смешанный порт", "Mixed Port": "Смешанный порт",
"Random Port": "Случайный порт",
"After restart to take effect": "Чтобы изменения вступили в силу, необходимо перезапустить приложение",
"Clash Core": "Ядро Clash", "Clash Core": "Ядро Clash",
"Tun Mode": "Режим туннеля", "Tun Mode": "Режим туннеля",
"Service Mode": "Режим сервиса", "Service Mode": "Режим сервиса",
@@ -72,6 +74,7 @@
"System Proxy": "Системный прокси", "System Proxy": "Системный прокси",
"System Proxy Setting": "Настройка системного прокси", "System Proxy Setting": "Настройка системного прокси",
"Open UWP tool": "Открыть UWP инструмент", "Open UWP tool": "Открыть UWP инструмент",
"Update GeoData": "Обновление GeoData",
"Proxy Guard": "Защита прокси", "Proxy Guard": "Защита прокси",
"Guard Duration": "Период защиты", "Guard Duration": "Период защиты",
"Proxy Bypass": "Игнорирование прокси", "Proxy Bypass": "Игнорирование прокси",
@@ -79,6 +82,7 @@
"Theme Mode": "Режим темы", "Theme Mode": "Режим темы",
"Theme Blur": "Размытие темы", "Theme Blur": "Размытие темы",
"Tray Click Event": "Событие щелчка в лотке", "Tray Click Event": "Событие щелчка в лотке",
"Copy Env Type": "Скопировать тип Env",
"Show Main Window": "Показать главное окно", "Show Main Window": "Показать главное окно",
"Theme Setting": "Настройка темы", "Theme Setting": "Настройка темы",
"Hotkey Setting": "Настройка клавиатурных сокращений", "Hotkey Setting": "Настройка клавиатурных сокращений",
@@ -95,6 +99,7 @@
"Runtime Config": "Используемый конфиг", "Runtime Config": "Используемый конфиг",
"ReadOnly": "Только для чтения", "ReadOnly": "Только для чтения",
"Restart": "Перезапуск", "Restart": "Перезапуск",
"Upgrade": "Обновлять",
"Back": "Назад", "Back": "Назад",
"Save": "Сохранить", "Save": "Сохранить",
@@ -110,5 +115,7 @@
"disable_system_proxy": "Отключить системный прокси", "disable_system_proxy": "Отключить системный прокси",
"toggle_tun_mode": "Переключить режим туннеля", "toggle_tun_mode": "Переключить режим туннеля",
"enable_tun_mode": "Включить режим туннеля", "enable_tun_mode": "Включить режим туннеля",
"disable_tun_mode": "Отключить режим туннеля" "disable_tun_mode": "Отключить режим туннеля",
"Portable Updater Error": "Портативная версия не поддерживает обновление внутри приложения, пожалуйста, скачайте и замените вручную"
} }
+8 -1
View File
@@ -67,6 +67,8 @@
"IPv6": "IPv6", "IPv6": "IPv6",
"Log Level": "日志等级", "Log Level": "日志等级",
"Mixed Port": "端口设置", "Mixed Port": "端口设置",
"Random Port": "随机端口",
"After restart to take effect": "重启后生效",
"External": "外部控制", "External": "外部控制",
"Clash Core": "Clash 内核", "Clash Core": "Clash 内核",
"Grant": "授权", "Grant": "授权",
@@ -78,6 +80,7 @@
"System Proxy": "系统代理", "System Proxy": "系统代理",
"System Proxy Setting": "系统代理设置", "System Proxy Setting": "系统代理设置",
"Open UWP tool": "UWP工具", "Open UWP tool": "UWP工具",
"Update GeoData": "更新 GeoData",
"Proxy Guard": "系统代理守卫", "Proxy Guard": "系统代理守卫",
"Guard Duration": "代理守卫间隔", "Guard Duration": "代理守卫间隔",
"Proxy Bypass": "代理绕过", "Proxy Bypass": "代理绕过",
@@ -88,6 +91,7 @@
"Theme Mode": "主题模式", "Theme Mode": "主题模式",
"Theme Blur": "背景模糊", "Theme Blur": "背景模糊",
"Tray Click Event": "托盘点击事件", "Tray Click Event": "托盘点击事件",
"Copy Env Type": "复制环境变量类型",
"Show Main Window": "显示主窗口", "Show Main Window": "显示主窗口",
"Theme Setting": "主题设置", "Theme Setting": "主题设置",
"Layout Setting": "界面设置", "Layout Setting": "界面设置",
@@ -108,6 +112,7 @@
"Runtime Config": "当前配置", "Runtime Config": "当前配置",
"ReadOnly": "只读", "ReadOnly": "只读",
"Restart": "重启内核", "Restart": "重启内核",
"Upgrade": "升级内核",
"Back": "返回", "Back": "返回",
"Save": "保存", "Save": "保存",
@@ -140,5 +145,7 @@
"Never Clean": "不清理", "Never Clean": "不清理",
"Retain 7 Days": "保留7天", "Retain 7 Days": "保留7天",
"Retain 30 Days": "保留30天", "Retain 30 Days": "保留30天",
"Retain 90 Days": "保留90天" "Retain 90 Days": "保留90天",
"Portable Updater Error": "便携版不支持应用内更新,请手动下载替换"
} }
+11 -3
View File
@@ -22,6 +22,9 @@ import { useCustomTheme } from "@/components/layout/use-custom-theme";
import getSystem from "@/utils/get-system"; import getSystem from "@/utils/get-system";
import "dayjs/locale/ru"; import "dayjs/locale/ru";
import "dayjs/locale/zh-cn"; import "dayjs/locale/zh-cn";
import { getPortableFlag } from "@/services/cmds";
export let portableFlag = false;
dayjs.extend(relativeTime); dayjs.extend(relativeTime);
@@ -71,6 +74,13 @@ const Layout = () => {
break; break;
} }
}); });
setTimeout(async () => {
portableFlag = await getPortableFlag();
await appWindow.unminimize();
await appWindow.show();
await appWindow.setFocus();
}, 50);
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -114,9 +124,7 @@ const Layout = () => {
<div className="the-logo" data-windrag> <div className="the-logo" data-windrag>
<LogoSvg /> <LogoSvg />
{!(OS === "windows" && WIN_PORTABLE) && ( {!portableFlag && <UpdateButton className="the-newbtn" />}
<UpdateButton className="the-newbtn" />
)}
</div> </div>
<List className="the-menu"> <List className="the-menu">
+8 -1
View File
@@ -1,3 +1,6 @@
import getSystem from "@/utils/get-system";
const OS = getSystem();
// default theme setting // default theme setting
export const defaultTheme = { export const defaultTheme = {
primary_color: "#1867c0", primary_color: "#1867c0",
@@ -8,12 +11,16 @@ export const defaultTheme = {
error_color: "#d32f2f", error_color: "#d32f2f",
warning_color: "#ed6c02", warning_color: "#ed6c02",
success_color: "#2e7d32", success_color: "#2e7d32",
font_family: `"twemoji mozilla", "Roboto", "Helvetica", "Arial", sans-serif`, background_color: "#ffffff",
font_family: `"Roboto", "Helvetica", "Arial", sans-serif, ${
OS === "windows" ? "twemoji mozilla" : ""
}`,
}; };
// dark mode // dark mode
export const defaultDarkTheme = { export const defaultDarkTheme = {
...defaultTheme, ...defaultTheme,
primary_text: "#E8E8ED", primary_text: "#E8E8ED",
background_color: "#181818",
secondary_text: "#bbbbbb", secondary_text: "#bbbbbb",
}; };
+63 -65
View File
@@ -114,6 +114,7 @@ const ConnectionsPage = () => {
return ( return (
<BasePage <BasePage
full
title={t("Connections")} title={t("Connections")}
contentStyle={{ height: "100%" }} contentStyle={{ height: "100%" }}
header={ header={
@@ -142,75 +143,72 @@ const ConnectionsPage = () => {
</Box> </Box>
} }
> >
<Box sx={{ boxShadow: 0, height: "100%" }}> <Box
<Box sx={{
sx={{ pt: 1,
pt: 1, mb: 0.5,
mb: 0.5, mx: "10px",
mx: "12px", height: "36px",
height: "36px", display: "flex",
display: "flex", alignItems: "center",
alignItems: "center", userSelect: "text",
userSelect: "text", }}
}} >
> {!isTableLayout && (
{!isTableLayout && ( <Select
<Select
size="small"
autoComplete="off"
value={curOrderOpt}
onChange={(e) => setOrderOpt(e.target.value)}
sx={{
mr: 1,
width: i18n.language === "en" ? 190 : 120,
'[role="button"]': { py: 0.65 },
}}
>
{Object.keys(orderOpts).map((opt) => (
<MenuItem key={opt} value={opt}>
<span style={{ fontSize: 14 }}>{t(opt)}</span>
</MenuItem>
))}
</Select>
)}
<TextField
hiddenLabel
fullWidth
size="small" size="small"
autoComplete="off" autoComplete="off"
spellCheck="false" value={curOrderOpt}
variant="outlined" onChange={(e) => setOrderOpt(e.target.value)}
placeholder={t("Filter conditions")} sx={{
value={filterText} mr: 1,
onChange={(e) => setFilterText(e.target.value)} width: i18n.language === "en" ? 190 : 120,
sx={{ input: { py: 0.65, px: 1.25 } }} '[role="button"]': { py: 0.65 },
/> }}
</Box> >
{Object.keys(orderOpts).map((opt) => (
<MenuItem key={opt} value={opt}>
<span style={{ fontSize: 14 }}>{t(opt)}</span>
</MenuItem>
))}
</Select>
)}
<Box height="calc(100% - 50px)" sx={{ userSelect: "text" }}> <TextField
{filterConn.length === 0 ? ( hiddenLabel
<BaseEmpty text="No Connections" /> fullWidth
) : isTableLayout ? ( size="small"
<ConnectionTable autoComplete="off"
connections={filterConn} spellCheck="false"
onShowDetail={(detail) => detailRef.current?.open(detail)} variant="outlined"
/> placeholder={t("Filter conditions")}
) : ( value={filterText}
<Virtuoso onChange={(e) => setFilterText(e.target.value)}
data={filterConn} sx={{ input: { py: 0.65, px: 1.25 } }}
itemContent={(index, item) => ( />
<ConnectionItem
value={item}
onShowDetail={() => detailRef.current?.open(item)}
/>
)}
/>
)}
</Box>
<ConnectionDetail ref={detailRef} />
</Box> </Box>
<Box height="calc(100% - 50px)" sx={{ userSelect: "text" }}>
{filterConn.length === 0 ? (
<BaseEmpty text="No Connections" />
) : isTableLayout ? (
<ConnectionTable
connections={filterConn}
onShowDetail={(detail) => detailRef.current?.open(detail)}
/>
) : (
<Virtuoso
data={filterConn}
itemContent={(index, item) => (
<ConnectionItem
value={item}
onShowDetail={() => detailRef.current?.open(item)}
/>
)}
/>
)}
</Box>
<ConnectionDetail ref={detailRef} />
</BasePage> </BasePage>
); );
}; };
+42 -50
View File
@@ -38,6 +38,7 @@ const LogPage = () => {
return ( return (
<BasePage <BasePage
full
title={t("Logs")} title={t("Logs")}
contentStyle={{ height: "100%" }} contentStyle={{ height: "100%" }}
header={ header={
@@ -66,61 +67,52 @@ const LogPage = () => {
> >
<Box <Box
sx={{ sx={{
boxSizing: "border-box", pt: 1,
boxShadow: 0, mb: 0.5,
height: "100%", mx: "10px",
userSelect: "text", height: "36px",
display: "flex",
alignItems: "center",
}} }}
> >
<Box <Select
sx={{ size="small"
pt: 1, autoComplete="off"
mb: 0.5, value={logState}
mx: "12px", onChange={(e) => setLogState(e.target.value)}
height: "36px", sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
display: "flex",
alignItems: "center",
}}
> >
<Select <MenuItem value="all">ALL</MenuItem>
size="small" <MenuItem value="inf">INFO</MenuItem>
autoComplete="off" <MenuItem value="warn">WARN</MenuItem>
value={logState} <MenuItem value="err">ERROR</MenuItem>
onChange={(e) => setLogState(e.target.value)} </Select>
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="inf">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
<MenuItem value="err">ERROR</MenuItem>
</Select>
<TextField <TextField
hiddenLabel hiddenLabel
fullWidth fullWidth
size="small" size="small"
autoComplete="off" autoComplete="off"
spellCheck="false" spellCheck="false"
variant="outlined" variant="outlined"
placeholder={t("Filter conditions")} placeholder={t("Filter conditions")}
value={filterText} value={filterText}
onChange={(e) => setFilterText(e.target.value)} onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }} sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
{filterLogs.length > 0 ? (
<Virtuoso
initialTopMostItemIndex={999}
data={filterLogs}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/> />
</Box> ) : (
<BaseEmpty text="No Logs" />
<Box height="calc(100% - 50px)"> )}
{filterLogs.length > 0 ? (
<Virtuoso
initialTopMostItemIndex={999}
data={filterLogs}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
) : (
<BaseEmpty text="No Logs" />
)}
</Box>
</Box> </Box>
</BasePage> </BasePage>
); );
+58 -18
View File
@@ -3,6 +3,19 @@ import { useMemo, useRef, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { Box, Button, Grid, IconButton, Stack, TextField } from "@mui/material"; import { Box, Button, Grid, IconButton, Stack, TextField } from "@mui/material";
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
DragEndEvent,
} from "@dnd-kit/core";
import {
SortableContext,
sortableKeyboardCoordinates,
} from "@dnd-kit/sortable";
import { LoadingButton } from "@mui/lab"; import { LoadingButton } from "@mui/lab";
import { import {
ClearRounded, ClearRounded,
@@ -19,6 +32,7 @@ import {
getRuntimeLogs, getRuntimeLogs,
deleteProfile, deleteProfile,
updateProfile, updateProfile,
reorderProfile,
} from "@/services/cmds"; } from "@/services/cmds";
import { atomLoadingCache } from "@/services/states"; import { atomLoadingCache } from "@/services/states";
import { closeAllConnections } from "@/services/api"; import { closeAllConnections } from "@/services/api";
@@ -40,7 +54,12 @@ const ProfilePage = () => {
const [disabled, setDisabled] = useState(false); const [disabled, setDisabled] = useState(false);
const [activating, setActivating] = useState(""); const [activating, setActivating] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
const { const {
profiles = {}, profiles = {},
activateSelected, activateSelected,
@@ -106,6 +125,16 @@ const ProfilePage = () => {
} }
}; };
const onDragEnd = async (event: DragEndEvent) => {
const { active, over } = event;
if (over) {
if (active.id !== over.id) {
await reorderProfile(active.id.toString(), over.id.toString());
mutateProfiles();
}
}
};
const onSelect = useLockFn(async (current: string, force: boolean) => { const onSelect = useLockFn(async (current: string, force: boolean) => {
if (!force && current === profiles.current) return; if (!force && current === profiles.current) return;
// 避免大多数情况下loading态闪烁 // 避免大多数情况下loading态闪烁
@@ -293,22 +322,34 @@ const ProfilePage = () => {
{t("New")} {t("New")}
</Button> </Button>
</Stack> </Stack>
<DndContext
<Box sx={{ mb: 4.5 }}> sensors={sensors}
<Grid container spacing={{ xs: 1, lg: 1 }}> collisionDetection={closestCenter}
{regularItems.map((item) => ( onDragEnd={onDragEnd}
<Grid item xs={12} sm={6} md={4} lg={3} key={item.file}> >
<ProfileItem <Box sx={{ mb: 4.5 }}>
selected={profiles.current === item.uid} <Grid container spacing={{ xs: 1, lg: 1 }}>
activating={activating === item.uid} <SortableContext
itemData={item} items={regularItems.map((x) => {
onSelect={(f) => onSelect(item.uid, f)} return x.uid;
onEdit={() => viewerRef.current?.edit(item)} })}
/> >
</Grid> {regularItems.map((item) => (
))} <Grid item xs={12} sm={6} md={4} lg={3} key={item.file}>
</Grid> <ProfileItem
</Box> id={item.uid}
selected={profiles.current === item.uid}
activating={activating === item.uid}
itemData={item}
onSelect={(f) => onSelect(item.uid, f)}
onEdit={() => viewerRef.current?.edit(item)}
/>
</Grid>
))}
</SortableContext>
</Grid>
</Box>
</DndContext>
{enhanceItems.length > 0 && ( {enhanceItems.length > 0 && (
<Grid container spacing={{ xs: 2, lg: 2 }}> <Grid container spacing={{ xs: 2, lg: 2 }}>
@@ -330,7 +371,6 @@ const ProfilePage = () => {
))} ))}
</Grid> </Grid>
)} )}
<ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} /> <ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} />
<ConfigViewer ref={configRef} /> <ConfigViewer ref={configRef} />
</BasePage> </BasePage>
+3 -11
View File
@@ -25,7 +25,7 @@ const ProxyPage = () => {
const { verge } = useVerge(); const { verge } = useVerge();
const modeList = useMemo(() => { const modeList = useMemo(() => {
if (verge?.clash_core === "clash-meta") { if (verge?.clash_core?.includes("clash-meta")) {
return ["rule", "global", "direct"]; return ["rule", "global", "direct"];
} }
return ["rule", "global", "direct", "script"]; return ["rule", "global", "direct", "script"];
@@ -51,6 +51,7 @@ const ProxyPage = () => {
return ( return (
<BasePage <BasePage
full
contentStyle={{ height: "100%" }} contentStyle={{ height: "100%" }}
title={t("Proxy Groups")} title={t("Proxy Groups")}
header={ header={
@@ -72,16 +73,7 @@ const ProxyPage = () => {
</Box> </Box>
} }
> >
<Box <ProxyGroups mode={curMode!} />
sx={{
borderRadius: 1,
boxShadow: 0,
height: "100%",
boxSizing: "border-box",
}}
>
<ProxyGroups mode={curMode!} />
</Box>
</BasePage> </BasePage>
); );
}; };

Some files were not shown because too many files have changed in this diff Show More