mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-10-15 13:50:47 +08:00
Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d77d655897 | ||
|
|
ec6f259794 | ||
|
|
7a564b4ea9 | ||
|
|
cd4ff68b5b | ||
|
|
1927b5f957 | ||
|
|
58047cbbd1 | ||
|
|
ddf455508f | ||
|
|
afde2f34f4 | ||
|
|
9f6eb46e90 | ||
|
|
cf9f235270 | ||
|
|
44851466cf | ||
|
|
847a0a6afd | ||
|
|
81c56d46c1 | ||
|
|
31c0910919 | ||
|
|
87f55cfce7 | ||
|
|
bba71aaa4c | ||
|
|
a019b26ceb | ||
|
|
a4617d1fed | ||
|
|
4d72d2d0df | ||
|
|
277ded4c44 | ||
|
|
5f9096dd6e | ||
|
|
410b5bd317 | ||
|
|
a7041657c9 | ||
|
|
88764d763c | ||
|
|
8edfbbb1c6 | ||
|
|
7730cd1c5b | ||
|
|
cad1c983e1 | ||
|
|
5480e57e67 | ||
|
|
5bcb057bf9 | ||
|
|
c30eaa3678 | ||
|
|
6c6e0812b8 | ||
|
|
afa591c279 | ||
|
|
e9d63aee5e | ||
|
|
781313e8f0 | ||
|
|
c3f7ff7aa2 | ||
|
|
5397808f16 | ||
|
|
279836151c | ||
|
|
6f424ebd2b | ||
|
|
c7f5bc4e0d | ||
|
|
90e193099f | ||
|
|
b3a1fb8d23 | ||
|
|
a8e51cc6bb | ||
|
|
53867bc3a9 | ||
|
|
ae5d3c478a | ||
|
|
654152391b | ||
|
|
63a77b1c7d | ||
|
|
9a0703676b | ||
|
|
95281632a1 | ||
|
|
b17dd39f31 | ||
|
|
1af326cefc | ||
|
|
5103868119 | ||
|
|
c57a962109 | ||
|
|
36926df26c | ||
|
|
9d81a13c58 | ||
|
|
511fab9a9d | ||
|
|
88529af8c8 | ||
|
|
425096e8af | ||
|
|
8a4e2327c1 | ||
|
|
74b1687be9 | ||
|
|
6477dd61c3 | ||
|
|
6ded9bdcde | ||
|
|
13dc3feb9f | ||
|
|
c7462716e5 | ||
|
|
bf189bb144 | ||
|
|
0c6631ebb0 | ||
|
|
93e7ac1bce | ||
|
|
b921098182 | ||
|
|
440f95f617 | ||
|
|
b9667ad349 | ||
|
|
4e7cdbfcc0 | ||
|
|
966fd68087 | ||
|
|
334cec3bde | ||
|
|
6e16133393 | ||
|
|
5e976c2fe1 | ||
|
|
d81aa5f233 | ||
|
|
e5fc0de39a | ||
|
|
6c62350cc3 | ||
|
|
d1649e3017 | ||
|
|
2869a35f1e | ||
|
|
98f12a9c72 | ||
|
|
6dc8a2f232 | ||
|
|
6511f3868e | ||
|
|
7da5a804f9 | ||
|
|
20ed7a3abe | ||
|
|
fd98caccd2 | ||
|
|
a5f494bda2 | ||
|
|
d4d8ef3849 | ||
|
|
b16cbd5379 | ||
|
|
9e6689ef08 | ||
|
|
e0c35c5ee3 | ||
|
|
670055aba1 | ||
|
|
a780e44e69 |
@@ -307,7 +307,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
@@ -377,7 +377,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
@@ -505,7 +505,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
|
||||
@@ -46,7 +46,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
@@ -196,7 +196,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Pnpm Cache
|
||||
@@ -253,10 +253,12 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-24.04
|
||||
# It should be ubuntu-22.04 to match the cross-compilation environment
|
||||
# ortherwise it is hard to resolve the dependencies
|
||||
- os: ubuntu-22.04
|
||||
target: aarch64-unknown-linux-gnu
|
||||
arch: arm64
|
||||
- os: ubuntu-24.04
|
||||
- os: ubuntu-22.04
|
||||
target: armv7-unknown-linux-gnueabihf
|
||||
arch: armhf
|
||||
runs-on: ${{ matrix.os }}
|
||||
@@ -292,7 +294,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Pnpm Cache
|
||||
@@ -311,39 +313,35 @@ jobs:
|
||||
- name: Release ${{ env.TAG_CHANNEL }} Version
|
||||
run: pnpm release-version autobuild-latest
|
||||
|
||||
- name: Setup for linux
|
||||
run: |
|
||||
sudo dpkg --add-architecture ${{ matrix.arch }}
|
||||
- name: "Setup for linux"
|
||||
run: |-
|
||||
sudo ls -lR /etc/apt/
|
||||
|
||||
sudo rm -f /etc/apt/sources.list.d/ubuntu.sources
|
||||
sudo tee /etc/apt/sources.list << EOF
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu noble main restricted universe multiverse
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu noble-security main restricted universe multiverse
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu noble-updates main restricted universe multiverse
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu noble-backports main restricted universe multiverse
|
||||
cat > /tmp/sources.list << EOF
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy main multiverse universe restricted
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy-security main multiverse universe restricted
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy-updates main multiverse universe restricted
|
||||
deb [arch=amd64,i386] http://archive.ubuntu.com/ubuntu jammy-backports main multiverse universe restricted
|
||||
|
||||
deb [arch=${{ matrix.arch }}] http://ports.ubuntu.com/ubuntu-ports noble main restricted universe multiverse
|
||||
deb [arch=${{ matrix.arch }}] http://ports.ubuntu.com/ubuntu-ports noble-security main restricted universe multiverse
|
||||
deb [arch=${{ matrix.arch }}] http://ports.ubuntu.com/ubuntu-ports noble-updates main restricted universe multiverse
|
||||
deb [arch=${{ matrix.arch }}] http://ports.ubuntu.com/ubuntu-ports noble-backports main restricted universe multiverse
|
||||
deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy main multiverse universe restricted
|
||||
deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-security main multiverse universe restricted
|
||||
deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-updates main multiverse universe restricted
|
||||
deb [arch=armhf,arm64] http://ports.ubuntu.com/ubuntu-ports jammy-backports main multiverse universe restricted
|
||||
EOF
|
||||
|
||||
sudo apt-get update -y
|
||||
sudo mv /etc/apt/sources.list /etc/apt/sources.list.default
|
||||
sudo mv /tmp/sources.list /etc/apt/sources.list
|
||||
|
||||
sudo apt-get install -y libglib2.0-dev-bin
|
||||
sudo dpkg --add-architecture ${{ matrix.arch }}
|
||||
sudo apt update
|
||||
|
||||
sudo apt-get install -y \
|
||||
linux-libc-dev:${{ matrix.arch }} \
|
||||
libc6-dev:${{ matrix.arch }} \
|
||||
libicu-dev:${{ matrix.arch }}
|
||||
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libxslt1-dev:${{ matrix.arch }} \
|
||||
sudo apt install -y \
|
||||
libxslt1.1:${{ matrix.arch }} \
|
||||
libwebkit2gtk-4.1-dev:${{ matrix.arch }} \
|
||||
libayatana-appindicator3-dev:${{ matrix.arch }} \
|
||||
libssl-dev:${{ matrix.arch }} \
|
||||
librsvg2-dev:${{ matrix.arch }} \
|
||||
patchelf
|
||||
patchelf:${{ matrix.arch }} \
|
||||
librsvg2-dev:${{ matrix.arch }}
|
||||
|
||||
- name: Install aarch64 tools
|
||||
if: matrix.target == 'aarch64-unknown-linux-gnu'
|
||||
@@ -441,7 +439,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Pnpm Cache
|
||||
@@ -543,7 +541,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4.2.0
|
||||
name: Install pnpm
|
||||
|
||||
@@ -43,7 +43,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
|
||||
@@ -103,7 +103,7 @@ jobs:
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Pnpm Cache
|
||||
|
||||
@@ -47,7 +47,7 @@ jobs:
|
||||
- uses: actions/setup-node@v6
|
||||
if: steps.check_frontend.outputs.frontend == 'true'
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
cache: "pnpm"
|
||||
|
||||
- name: Restore pnpm cache
|
||||
|
||||
@@ -197,7 +197,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
@@ -281,7 +281,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- name: Install pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
@@ -420,7 +420,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
@@ -505,7 +505,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
@@ -531,7 +531,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
@@ -593,7 +593,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
|
||||
@@ -15,7 +15,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
- name: Install Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: "24.13.0"
|
||||
node-version: "24.13.1"
|
||||
|
||||
- uses: pnpm/action-setup@v4
|
||||
name: Install pnpm
|
||||
|
||||
@@ -13,3 +13,4 @@ scripts/_env.sh
|
||||
.eslintcache
|
||||
.changelog_backups
|
||||
target
|
||||
CLAUDE.md
|
||||
|
||||
+5
-42
@@ -1,51 +1,14 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "$ROOT_DIR"
|
||||
if ! command -v "cargo-make" >/dev/null 2>&1; then
|
||||
echo "❌ cargo-make is required for pre-commit checks."
|
||||
cargo install --force cargo-make
|
||||
fi
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
echo "❌ pnpm is required for pre-commit checks."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
LOCALE_DIFF="$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^src/locales/' || true)"
|
||||
if [ -n "$LOCALE_DIFF" ]; then
|
||||
echo "[pre-commit] Locale changes detected. Regenerating i18n types..."
|
||||
pnpm i18n:types
|
||||
if [ -d src/types/generated ]; then
|
||||
echo "[pre-commit] Staging regenerated i18n type artifacts..."
|
||||
git add src/types/generated
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "[pre-commit] Running pnpm format before lint..."
|
||||
pnpm format
|
||||
|
||||
echo "[pre-commit] Running lint-staged for JS/TS files..."
|
||||
pnpm exec lint-staged
|
||||
|
||||
RUST_FILES="$(git diff --cached --name-only --diff-filter=ACMR | grep -E '^src-tauri/.*\.rs$' || true)"
|
||||
if [ -n "$RUST_FILES" ]; then
|
||||
echo "[pre-commit] Formatting Rust changes with cargo fmt..."
|
||||
cargo fmt
|
||||
while IFS= read -r file; do
|
||||
[ -n "$file" ] && git add "$file"
|
||||
done <<< "$RUST_FILES"
|
||||
|
||||
echo "[pre-commit] Linting Rust changes with cargo clippy..."
|
||||
cargo clippy-all
|
||||
if ! command -v clash-verge-logging-check >/dev/null 2>&1; then
|
||||
echo "[pre-commit] Installing clash-verge-logging-check..."
|
||||
cargo install --git https://github.com/clash-verge-rev/clash-verge-logging-check.git
|
||||
fi
|
||||
clash-verge-logging-check
|
||||
fi
|
||||
|
||||
TS_FILES="$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(ts|tsx)$' || true)"
|
||||
if [ -n "$TS_FILES" ]; then
|
||||
echo "[pre-commit] Running TypeScript type check..."
|
||||
pnpm typecheck
|
||||
fi
|
||||
|
||||
echo "[pre-commit] All checks completed successfully."
|
||||
cargo make pre-commit
|
||||
|
||||
+4
-31
@@ -1,36 +1,9 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
|
||||
remote_name="${1:-origin}"
|
||||
remote_url="${2:-unknown}"
|
||||
|
||||
ROOT_DIR="$(git rev-parse --show-toplevel)"
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1; then
|
||||
echo "❌ pnpm is required for pre-push checks."
|
||||
exit 1
|
||||
if ! command -v "cargo-make" >/dev/null 2>&1; then
|
||||
echo "❌ cargo-make is required for pre-push checks."
|
||||
cargo install --force cargo-make
|
||||
fi
|
||||
|
||||
echo "[pre-push] Preparing to push to '$remote_name' ($remote_url). Running full validation..."
|
||||
|
||||
echo "[pre-push] Checking Prettier formatting..."
|
||||
pnpm format:check
|
||||
|
||||
echo "[pre-push] Running ESLint..."
|
||||
pnpm lint
|
||||
|
||||
echo "[pre-push] Running TypeScript type checking..."
|
||||
pnpm typecheck
|
||||
|
||||
if command -v cargo >/dev/null 2>&1; then
|
||||
echo "[pre-push] Verifying Rust formatting..."
|
||||
cargo fmt --check
|
||||
|
||||
echo "[pre-push] Running cargo clippy..."
|
||||
cargo clippy-all
|
||||
else
|
||||
echo "[pre-push] ⚠️ cargo not found; skipping Rust checks."
|
||||
fi
|
||||
|
||||
echo "[pre-push] All checks passed."
|
||||
cargo make pre-push
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
queue_rules:
|
||||
- name: LetMeMergeForYou
|
||||
batch_size: 3
|
||||
allow_queue_branch_edit: true
|
||||
queue_conditions: []
|
||||
Generated
+525
-551
File diff suppressed because it is too large
Load Diff
+11
-6
@@ -5,8 +5,8 @@ members = [
|
||||
"crates/clash-verge-logging",
|
||||
"crates/clash-verge-signal",
|
||||
"crates/tauri-plugin-clash-verge-sysinfo",
|
||||
"crates/clash-verge-types",
|
||||
"crates/clash-verge-i18n",
|
||||
"crates/clash-verge-limiter",
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
@@ -40,26 +40,31 @@ opt-level = 0
|
||||
debug = true
|
||||
strip = false
|
||||
|
||||
[profile.debug-release]
|
||||
inherits = "fast-release"
|
||||
codegen-units = 1
|
||||
split-debuginfo = "unpacked"
|
||||
|
||||
[workspace.dependencies]
|
||||
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
||||
clash-verge-logging = { path = "crates/clash-verge-logging" }
|
||||
clash-verge-signal = { path = "crates/clash-verge-signal" }
|
||||
clash-verge-types = { path = "crates/clash-verge-types" }
|
||||
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
|
||||
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||
|
||||
tauri = { version = "2.9.5" }
|
||||
tauri = { version = "2.10.2" }
|
||||
tauri-plugin-clipboard-manager = "2.3.2"
|
||||
parking_lot = { version = "0.12.5", features = ["hardware-lock-elision"] }
|
||||
anyhow = "1.0.100"
|
||||
criterion = { version = "0.8.1", features = ["async_tokio"] }
|
||||
anyhow = "1.0.101"
|
||||
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
||||
tokio = { version = "1.49.0", features = [
|
||||
"rt-multi-thread",
|
||||
"macros",
|
||||
"time",
|
||||
"sync",
|
||||
] }
|
||||
flexi_logger = "0.31.7"
|
||||
flexi_logger = "0.31.8"
|
||||
log = "0.4.29"
|
||||
|
||||
smartstring = { version = "1.0.1" }
|
||||
|
||||
+27
-33
@@ -1,49 +1,43 @@
|
||||
## v2.4.5
|
||||
## v(2.4.6)
|
||||
|
||||
- **Mihomo(Meta) 内核升级至 v1.19.18**
|
||||
> [!IMPORTANT]
|
||||
> 历经多轮磨合与修正,这是自 2.0 以来我们最满意的里程碑版本。建议所有用户立即升级。
|
||||
|
||||
### 🐞 修复问题
|
||||
|
||||
- 修复 macOS 有线网络 DNS 劫持失败
|
||||
- 修复 Monaco 编辑器内右键菜单显示异常
|
||||
- 修复设置代理端口时检查端口占用
|
||||
- 修复 Monaco 编辑器初始化卡 Loading
|
||||
- 修复恢复备份时 `config.yaml` / `profiles.yaml` 文件内字段未正确恢复
|
||||
- 修复 Windows 下系统主题同步问题
|
||||
- 修复 URL Schemes 无法正常导入
|
||||
- 修复 Linux 下无法安装 TUN 服务
|
||||
- 修复首次启动时代理信息刷新缓慢
|
||||
- 修复无网络时无限请求 IP 归属查询
|
||||
- 修复 WebDAV 页面重试逻辑
|
||||
- 修复 Linux 通过 GUI 安装服务模式权限不符合预期
|
||||
- 修复 macOS 因网口顺序导致无法正确设置代理
|
||||
- 修复恢复休眠后无法操作托盘
|
||||
- 修复首页当前节点图标语义显示不一致
|
||||
- 修复使用 URL scheme 导入订阅时没有及时重载配置
|
||||
- 修复规则界面里的行号展示逻辑
|
||||
- 修复 Windows 托盘打开日志失败
|
||||
- 修复 KDE 首次启动报错
|
||||
|
||||
<details>
|
||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||
|
||||
- 允许代理页面允许高级过滤搜索
|
||||
- 备份设置页面新增导入备份按钮
|
||||
- 允许修改通知弹窗位置
|
||||
- 支持收起导航栏(导航栏右键菜单 / 界面设置)
|
||||
- 允许将出站模式显示在托盘一级菜单
|
||||
- 允许禁用在托盘中显示代理组
|
||||
- 支持在「编辑节点」中直接导入 AnyTLS URI 配置
|
||||
- 支持关闭「验证代理绕过格式」
|
||||
- 新增系统代理绕过和 TUN 排除自定义网段的可视化编辑器
|
||||
- 升级 Mihomo 内核到最新
|
||||
- 支持订阅设置自动延时监测间隔
|
||||
- 新增流量隧道管理界面,支持可视化添加/删除隧道配置
|
||||
- Masque 协议的 GUI 支持
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||
|
||||
- 应用内更新日志支持解析并渲染 HTML 标签
|
||||
- 性能优化前后端在渲染流量图时的资源
|
||||
- 在 Linux NVIDIA 显卡环境下尝试禁用 WebKit DMABUF 渲染以规避潜在问题
|
||||
- Windows 下自启动改为计划任务实现
|
||||
- 改进托盘和窗口操作频率限制实现
|
||||
- 使用「编辑节点」添加节点时,自动将节点添加到第一个 `select` 类型的代理组的第一位
|
||||
- 隐藏侧边导航栏和悬浮跳转导航的滚动条
|
||||
- 完善对 AnyTLS / Mieru / Sudoku 的 GUI 支持
|
||||
- macOS 和 Linux 对服务 IPC 权限进一步限制
|
||||
- 移除 Windows 自启动计划任务中冗余的 3 秒延时
|
||||
- 右键错误通知可复制错误详情
|
||||
- 保存 TUN 设置时优化执行流程,避免界面卡顿
|
||||
- 补充 `deb` / `rpm` 依赖 `libayatana-appindicator`
|
||||
- 「连接」表格标题的排序点击区域扩展到整列宽度
|
||||
- 安装服务失败时报告更详细的错误
|
||||
- 避免脏订阅地址无法 Scheme 导入订阅
|
||||
- macOS TUN 覆盖 DNS 时使用 114.114.114.114
|
||||
- 连通性测试替换为更快的 http://1.0.0.1
|
||||
- 连接、规则、日志等页面的过滤搜索组件新增了清空输入框按钮
|
||||
- 链式代理增加明显的入口出口与数据流向标识
|
||||
- 优化 IP 信息卡
|
||||
- 美化代理组图标样式
|
||||
- 移除 Linux resources 文件夹下多余的服务二进制文件
|
||||
|
||||
</details>
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
[config]
|
||||
skip_core_tasks = true
|
||||
skip_git_env_info = true
|
||||
skip_rust_env_info = true
|
||||
skip_crate_env_info = true
|
||||
|
||||
# --- Backend ---
|
||||
|
||||
[tasks.rust-format]
|
||||
install_crate = "rustfmt"
|
||||
command = "cargo"
|
||||
args = ["fmt", "--", "--emit=files"]
|
||||
|
||||
[tasks.rust-clippy]
|
||||
description = "Run cargo clippy to lint the code"
|
||||
command = "cargo"
|
||||
args = ["clippy", "--all-targets", "--all-features", "--", "-D", "warnings"]
|
||||
|
||||
# --- Frontend ---
|
||||
|
||||
[tasks.eslint]
|
||||
description = "Run ESLint to lint the code"
|
||||
command = "pnpm"
|
||||
args = ["lint"]
|
||||
[tasks.eslint.windows]
|
||||
command = "pnpm.cmd"
|
||||
|
||||
[tasks.typecheck]
|
||||
description = "Run type checks"
|
||||
command = "pnpm"
|
||||
args = ["typecheck"]
|
||||
[tasks.typecheck.windows]
|
||||
command = "pnpm.cmd"
|
||||
|
||||
[tasks.lint-staged]
|
||||
description = "Run lint-staged for staged files"
|
||||
command = "pnpm"
|
||||
args = ["exec", "lint-staged"]
|
||||
[tasks.lint-staged.windows]
|
||||
command = "pnpm.cmd"
|
||||
|
||||
# --- Jobs ---
|
||||
|
||||
# Rust format (for pre-commit)
|
||||
[tasks.rust-format-check]
|
||||
description = "Check Rust code formatting"
|
||||
dependencies = ["rust-format"]
|
||||
[tasks.rust-format-check.condition]
|
||||
files_modified.input = [
|
||||
"./src-tauri/**/*.rs",
|
||||
"./crates/**/*.rs",
|
||||
"**/Cargo.toml",
|
||||
]
|
||||
files_modified.output = ["./target/debug/*", "./target/release/*"]
|
||||
|
||||
# Rust lint (for pre-push)
|
||||
[tasks.rust-lint]
|
||||
description = "Run Rust linting"
|
||||
dependencies = ["rust-clippy"]
|
||||
[tasks.rust-lint.condition]
|
||||
files_modified.input = [
|
||||
"./src-tauri/**/*.rs",
|
||||
"./crates/**/*.rs",
|
||||
"**/Cargo.toml",
|
||||
]
|
||||
files_modified.output = ["./target/debug/*", "./target/release/*"]
|
||||
|
||||
# Frontend format (for pre-commit)
|
||||
[tasks.frontend-format]
|
||||
description = "Frontend format checks"
|
||||
dependencies = ["lint-staged"]
|
||||
|
||||
# Frontend lint (for pre-push)
|
||||
[tasks.frontend-lint]
|
||||
description = "Frontend linting and type checking"
|
||||
dependencies = ["eslint", "typecheck"]
|
||||
|
||||
# --- Git Hooks ---
|
||||
|
||||
[tasks.pre-commit]
|
||||
description = "Pre-commit checks: format only"
|
||||
dependencies = ["rust-format-check", "frontend-format"]
|
||||
|
||||
[tasks.pre-push]
|
||||
description = "Pre-push checks: lint and typecheck"
|
||||
dependencies = ["rust-lint", "frontend-lint"]
|
||||
@@ -66,19 +66,6 @@ Supports Windows (x64/x86), Linux (x64/arm64) and macOS 10.15+ (intel/apple).
|
||||
|
||||
🌐 官网:👉 [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### 本项目的构建与发布环境由 [YXVM](https://yxvm.com/aff.php?aff=827) 独立服务器全力支持,
|
||||
|
||||
感谢提供 独享资源、高性能、高速网络 的强大后端环境。如果你觉得下载够快、使用够爽,那是因为我们用了好服务器!
|
||||
|
||||
🧩 YXVM 独立服务器优势:
|
||||
|
||||
- 🌎 优质网络,回程优化,下载快到飞起
|
||||
- 🔧 物理机独享资源,非VPS可比,性能拉满
|
||||
- 🧠 适合跑代理、搭建 WEB 站 CDN 站 、搞 CI/CD 或任何高负载应用
|
||||
- 💡 支持即开即用,多机房选择,CN2 / IEPL 可选
|
||||
- 📦 本项目使用配置已在售,欢迎同款入手!
|
||||
- 🎯 想要同款构建体验?[立即下单 YXVM 独立服务器!](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## Features
|
||||
|
||||
- 基于性能强劲的 Rust 和 Tauri 2 框架
|
||||
|
||||
@@ -6,8 +6,8 @@ type DraftInner<T> = (SharedDraft<T>, Option<SharedDraft<T>>);
|
||||
|
||||
/// Draft 管理:committed 与 optional draft 都以 Arc<Box<T>> 存储,
|
||||
// (committed_snapshot, optional_draft_snapshot)
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Draft<T: Clone> {
|
||||
#[derive(Debug)]
|
||||
pub struct Draft<T> {
|
||||
inner: Arc<RwLock<DraftInner<T>>>,
|
||||
}
|
||||
|
||||
@@ -90,3 +90,11 @@ impl<T: Clone> Draft<T> {
|
||||
Ok(res)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clone> Clone for Draft<T> {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: Arc::clone(&self.inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: لوحة التحكم
|
||||
body: تم تحديث حالة عرض لوحة التحكم.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: تبديل الوضع
|
||||
body: تم التبديل إلى {mode}.
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: وكيل النظام
|
||||
body: تم تحديث حالة وكيل النظام.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: وضع TUN
|
||||
body: تم تحديث حالة وضع TUN.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: الوضع الخفيف
|
||||
body: تم الدخول إلى الوضع الخفيف.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: الملفات التعريفية
|
||||
body: تمت إعادة تفعيل الملف التعريفي.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: على وشك الخروج
|
||||
body: Clash Verge على وشك الخروج.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: تم إخفاء التطبيق
|
||||
body: Clash Verge يعمل في الخلفية.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: يتطلب تثبيت خدمة Clash Verge صلاحيات المسؤول.
|
||||
adminUninstallPrompt: يتطلب إلغاء تثبيت خدمة Clash Verge صلاحيات المسؤول.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
rule: Rule
|
||||
direct: Direct
|
||||
global: Global
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
dashboard: لوحة التحكم
|
||||
ruleMode: وضع القواعد
|
||||
globalMode: الوضع العام
|
||||
directMode: الوضع المباشر
|
||||
outboundModes: أوضاع الخروج
|
||||
rule: قاعدة
|
||||
direct: مباشر
|
||||
global: عام
|
||||
profiles: الملفات التعريفية
|
||||
proxies: وكلاء
|
||||
systemProxy: وكيل النظام
|
||||
tunMode: وضع TUN
|
||||
closeAllConnections: إغلاق كل الاتصالات
|
||||
lightweightMode: الوضع الخفيف
|
||||
copyEnv: نسخ متغيرات البيئة
|
||||
confDir: دليل الإعدادات
|
||||
coreDir: دليل النواة
|
||||
logsDir: دليل السجلات
|
||||
openDir: فتح الدليل
|
||||
appLog: سجل التطبيق
|
||||
coreLog: سجل النواة
|
||||
restartClash: إعادة تشغيل نواة Clash
|
||||
restartApp: إعادة تشغيل التطبيق
|
||||
vergeVersion: إصدار Verge
|
||||
more: المزيد
|
||||
exit: خروج
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: وكيل النظام
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: ملف تعريفي
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: Übersicht
|
||||
body: Die Sichtbarkeit der Übersicht wurde aktualisiert.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: Moduswechsel
|
||||
body: Auf {mode} umgeschaltet.
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: Systemproxy
|
||||
body: Der Status des Systemproxys wurde aktualisiert.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: TUN-Modus
|
||||
body: Der Status des TUN-Modus wurde aktualisiert.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: Leichtmodus
|
||||
body: Leichtmodus aktiviert.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: Profile
|
||||
body: Profil reaktiviert.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: Beenden steht bevor
|
||||
body: Clash Verge wird gleich beendet.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: Anwendung ausgeblendet
|
||||
body: Clash Verge läuft im Hintergrund.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Für die Installation des Clash-Verge-Dienstes sind Administratorrechte erforderlich.
|
||||
adminUninstallPrompt: Für die Deinstallation des Clash-Verge-Dienstes sind Administratorrechte erforderlich.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
dashboard: Übersicht
|
||||
ruleMode: Regelmodus
|
||||
globalMode: Globaler Modus
|
||||
directMode: Direktmodus
|
||||
outboundModes: Ausgangsmodi
|
||||
rule: Regel
|
||||
direct: Direkt
|
||||
global: Global
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
profiles: Profile
|
||||
proxies: Proxy
|
||||
systemProxy: Systemproxy
|
||||
tunMode: TUN-Modus
|
||||
closeAllConnections: Alle Verbindungen schließen
|
||||
lightweightMode: Leichtmodus
|
||||
copyEnv: Umgebungsvariablen kopieren
|
||||
confDir: Konfigurationsverzeichnis
|
||||
coreDir: Core-Verzeichnis
|
||||
logsDir: Log-Verzeichnis
|
||||
openDir: Verzeichnis öffnen
|
||||
appLog: Anwendungslog
|
||||
coreLog: Core-Log
|
||||
restartClash: Clash-Core neu starten
|
||||
restartApp: Anwendung neu starten
|
||||
vergeVersion: Verge-Version
|
||||
more: Mehr
|
||||
exit: Beenden
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: Systemproxy
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: Profil
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: Panel
|
||||
body: La visibilidad del panel se ha actualizado.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: Cambio de modo
|
||||
body: Cambiado a {mode}.
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: Proxy del sistema
|
||||
body: El estado del proxy del sistema se ha actualizado.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: Modo TUN
|
||||
body: El estado del modo TUN se ha actualizado.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: Modo ligero
|
||||
body: Se ha entrado en el modo ligero.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: Perfiles
|
||||
body: Perfil reactivado.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: A punto de salir
|
||||
body: Clash Verge está a punto de salir.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: Aplicación oculta
|
||||
body: Clash Verge se está ejecutando en segundo plano.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Instalar el servicio de Clash Verge requiere privilegios de administrador.
|
||||
adminUninstallPrompt: Desinstalar el servicio de Clash Verge requiere privilegios de administrador.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
dashboard: Panel
|
||||
ruleMode: Modo de reglas
|
||||
globalMode: Modo global
|
||||
directMode: Modo directo
|
||||
outboundModes: Modos de salida
|
||||
rule: Regla
|
||||
direct: Directo
|
||||
global: Global
|
||||
profiles: Profiles
|
||||
profiles: Perfiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
systemProxy: Proxy del sistema
|
||||
tunMode: Modo TUN
|
||||
closeAllConnections: Cerrar todas las conexiones
|
||||
lightweightMode: Modo ligero
|
||||
copyEnv: Copiar variables de entorno
|
||||
confDir: Directorio de configuración
|
||||
coreDir: Directorio del núcleo
|
||||
logsDir: Directorio de registros
|
||||
openDir: Abrir directorio
|
||||
appLog: Registro de la aplicación
|
||||
coreLog: Registro del núcleo
|
||||
restartClash: Reiniciar el núcleo de Clash
|
||||
restartApp: Reiniciar aplicación
|
||||
vergeVersion: Versión de Verge
|
||||
more: Más
|
||||
exit: Salir
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: Proxy del sistema
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: Perfil
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: داشبورد
|
||||
body: وضعیت نمایش داشبورد بهروزرسانی شد.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: تغییر حالت
|
||||
body: به {mode} تغییر کرد.
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: پروکسی سیستم
|
||||
body: وضعیت پروکسی سیستم بهروزرسانی شد.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: حالت TUN
|
||||
body: وضعیت حالت TUN بهروزرسانی شد.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: حالت سبک
|
||||
body: به حالت سبک وارد شد.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: پروفایلها
|
||||
body: پروفایل دوباره فعال شد.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: در آستانه خروج
|
||||
body: Clash Verge در آستانه خروج است.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: برنامه پنهان شد
|
||||
body: Clash Verge در پسزمینه در حال اجراست.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: نصب سرویس Clash Verge به دسترسی مدیر نیاز دارد.
|
||||
adminUninstallPrompt: حذف سرویس Clash Verge به دسترسی مدیر نیاز دارد.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
rule: Rule
|
||||
direct: Direct
|
||||
global: Global
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
dashboard: داشبورد
|
||||
ruleMode: حالت قوانین
|
||||
globalMode: حالت سراسری
|
||||
directMode: حالت مستقیم
|
||||
outboundModes: حالتهای خروجی
|
||||
rule: قانون
|
||||
direct: مستقیم
|
||||
global: سراسری
|
||||
profiles: پروفایلها
|
||||
proxies: پروکسیها
|
||||
systemProxy: پروکسی سیستم
|
||||
tunMode: حالت TUN
|
||||
closeAllConnections: بستن همه اتصالها
|
||||
lightweightMode: حالت سبک
|
||||
copyEnv: کپی متغیرهای محیطی
|
||||
confDir: پوشه پیکربندی
|
||||
coreDir: پوشه هسته
|
||||
logsDir: پوشه گزارشها
|
||||
openDir: باز کردن پوشه
|
||||
appLog: گزارش برنامه
|
||||
coreLog: گزارش هسته
|
||||
restartClash: راهاندازی مجدد هسته Clash
|
||||
restartApp: راهاندازی مجدد برنامه
|
||||
vergeVersion: نسخه Verge
|
||||
more: بیشتر
|
||||
exit: خروج
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: پروکسی سیستم
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: پروفایل
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: Dasbor
|
||||
body: Visibilitas dasbor telah diperbarui.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: Peralihan Mode
|
||||
body: Beralih ke {mode}.
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: Proksi Sistem
|
||||
body: Status proksi sistem telah diperbarui.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: Mode TUN
|
||||
body: Status mode TUN telah diperbarui.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: Mode Ringan
|
||||
body: Masuk ke mode ringan.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: Profil
|
||||
body: Profil diaktifkan kembali.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: Akan Keluar
|
||||
body: Clash Verge akan keluar.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: Aplikasi Disembunyikan
|
||||
body: Clash Verge berjalan di latar belakang.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Menginstal layanan Clash Verge memerlukan hak administrator.
|
||||
adminUninstallPrompt: Menghapus instalasi layanan Clash Verge memerlukan hak administrator.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
dashboard: Dasbor
|
||||
ruleMode: Mode Aturan
|
||||
globalMode: Mode Global
|
||||
directMode: Mode Langsung
|
||||
outboundModes: Mode Keluar
|
||||
rule: Aturan
|
||||
direct: Langsung
|
||||
global: Global
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
profiles: Profil
|
||||
proxies: Proksi
|
||||
systemProxy: Proksi Sistem
|
||||
tunMode: Mode TUN
|
||||
closeAllConnections: Tutup Semua Koneksi
|
||||
lightweightMode: Mode Ringan
|
||||
copyEnv: Salin Variabel Lingkungan
|
||||
confDir: Direktori Konfigurasi
|
||||
coreDir: Direktori Core
|
||||
logsDir: Direktori Log
|
||||
openDir: Buka Direktori
|
||||
appLog: Log Aplikasi
|
||||
coreLog: Log Core
|
||||
restartClash: Mulai Ulang Core Clash
|
||||
restartApp: Mulai Ulang Aplikasi
|
||||
vergeVersion: Versi Verge
|
||||
more: Lainnya
|
||||
exit: Keluar
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: Proksi Sistem
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: Profil
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: ダッシュボード
|
||||
body: ダッシュボードの表示状態が更新されました。
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: モード切り替え
|
||||
body: "{mode} に切り替えました。"
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: システムプロキシ
|
||||
body: システムプロキシの状態が更新されました。
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: TUN モード
|
||||
body: TUN モードの状態が更新されました。
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: 軽量モード
|
||||
body: 軽量モードに入りました。
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: プロファイル
|
||||
body: プロファイルが再有効化されました。
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: 終了間近
|
||||
body: Clash Verge はまもなく終了します。
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: アプリが非表示
|
||||
body: Clash Verge はバックグラウンドで実行中です。
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Clash Verge サービスのインストールには管理者権限が必要です。
|
||||
adminUninstallPrompt: Clash Verge サービスのアンインストールには管理者権限が必要です。
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
dashboard: ダッシュボード
|
||||
ruleMode: ルールモード
|
||||
globalMode: グローバルモード
|
||||
directMode: ダイレクトモード
|
||||
outboundModes: アウトバウンドモード
|
||||
rule: ルール
|
||||
direct: ダイレクト
|
||||
global: グローバル
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
profiles: プロファイル
|
||||
proxies: プロキシ
|
||||
systemProxy: システムプロキシ
|
||||
tunMode: TUN モード
|
||||
closeAllConnections: すべての接続を閉じる
|
||||
lightweightMode: 軽量モード
|
||||
copyEnv: 環境変数をコピー
|
||||
confDir: 設定ディレクトリ
|
||||
coreDir: コアディレクトリ
|
||||
logsDir: ログディレクトリ
|
||||
openDir: ディレクトリを開く
|
||||
appLog: アプリケーションログ
|
||||
coreLog: コアログ
|
||||
restartClash: Clash コアを再起動
|
||||
restartApp: アプリケーションを再起動
|
||||
vergeVersion: Verge バージョン
|
||||
more: その他
|
||||
exit: 終了
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: システムプロキシ
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: プロファイル
|
||||
|
||||
@@ -16,8 +16,8 @@ notifications:
|
||||
title: 경량 모드
|
||||
body: 경량 모드에 진입했습니다.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: 프로필
|
||||
body: 프로필이 다시 활성화되었습니다.
|
||||
appQuit:
|
||||
title: 곧 종료
|
||||
body: Clash Verge가 곧 종료됩니다.
|
||||
@@ -25,14 +25,14 @@ notifications:
|
||||
title: 앱이 숨겨짐
|
||||
body: Clash Verge가 백그라운드에서 실행 중입니다.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Clash Verge 서비스 설치에는 관리자 권한이 필요합니다.
|
||||
adminUninstallPrompt: Clash Verge 서비스 제거에는 관리자 권한이 필요합니다.
|
||||
tray:
|
||||
dashboard: 대시보드
|
||||
ruleMode: 규칙 모드
|
||||
globalMode: 전역 모드
|
||||
directMode: 직접 모드
|
||||
outboundModes: Outbound Modes
|
||||
outboundModes: 아웃바운드 모드
|
||||
rule: 규칙
|
||||
direct: 직접
|
||||
global: 글로벌
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: Панель
|
||||
body: Видимость панели обновлена.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: Смена режима
|
||||
body: Переключено на {mode}.
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: Системный прокси
|
||||
body: Статус системного прокси обновлен.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: Режим TUN
|
||||
body: Статус режима TUN обновлен.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: Легкий режим
|
||||
body: Включен легкий режим.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: Профили
|
||||
body: Профиль повторно активирован.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: Скорый выход
|
||||
body: Clash Verge скоро завершит работу.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: Приложение скрыто
|
||||
body: Clash Verge работает в фоновом режиме.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Для установки службы Clash Verge требуются права администратора.
|
||||
adminUninstallPrompt: Для удаления службы Clash Verge требуются права администратора.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
dashboard: Панель
|
||||
ruleMode: Режим правил
|
||||
globalMode: Глобальный режим
|
||||
directMode: Прямой режим
|
||||
outboundModes: Исходящие режимы
|
||||
rule: Правило
|
||||
direct: Прямой
|
||||
global: Глобальный
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
profiles: Профили
|
||||
proxies: Прокси
|
||||
systemProxy: Системный прокси
|
||||
tunMode: Режим TUN
|
||||
closeAllConnections: Закрыть все соединения
|
||||
lightweightMode: Легкий режим
|
||||
copyEnv: Копировать переменные среды
|
||||
confDir: Каталог конфигурации
|
||||
coreDir: Каталог ядра
|
||||
logsDir: Каталог журналов
|
||||
openDir: Открыть каталог
|
||||
appLog: Журнал приложения
|
||||
coreLog: Журнал ядра
|
||||
restartClash: Перезапустить ядро Clash
|
||||
restartApp: Перезапустить приложение
|
||||
vergeVersion: Версия Verge
|
||||
more: Еще
|
||||
exit: Выход
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: Системный прокси
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: Профиль
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: Gösterge Paneli
|
||||
body: Gösterge panelinin görünürlüğü güncellendi.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: Mod Değişimi
|
||||
body: "{mode} moduna geçildi."
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: Sistem Vekil'i
|
||||
body: Sistem vekil'i durumu güncellendi.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: TUN Modu
|
||||
body: TUN modu durumu güncellendi.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: Hafif Mod
|
||||
body: Hafif moda geçildi.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: Profiller
|
||||
body: Profil yeniden etkinleştirildi.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: Çıkış Yapılmak Üzere
|
||||
body: Clash Verge kapanmak üzere.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: Uygulama Gizlendi
|
||||
body: Clash Verge arka planda çalışıyor.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Clash Verge hizmetini kurmak için yönetici ayrıcalıkları gerekir.
|
||||
adminUninstallPrompt: Clash Verge hizmetini kaldırmak için yönetici ayrıcalıkları gerekir.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
dashboard: Gösterge Paneli
|
||||
ruleMode: Kural Modu
|
||||
globalMode: Küresel Mod
|
||||
directMode: Doğrudan Mod
|
||||
outboundModes: Giden Modlar
|
||||
rule: Kural
|
||||
direct: Doğrudan
|
||||
global: Küresel
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
profiles: Profiller
|
||||
proxies: Vekil'ler
|
||||
systemProxy: Sistem Vekil'i
|
||||
tunMode: TUN Modu
|
||||
closeAllConnections: Tüm Bağlantıları Kapat
|
||||
lightweightMode: Hafif Mod
|
||||
copyEnv: Ortam Değişkenlerini Kopyala
|
||||
confDir: Yapılandırma Dizini
|
||||
coreDir: Çekirdek Dizini
|
||||
logsDir: Günlük Dizini
|
||||
openDir: Dizini Aç
|
||||
appLog: Uygulama Günlüğü
|
||||
coreLog: Çekirdek Günlüğü
|
||||
restartClash: Clash Çekirdeğini Yeniden Başlat
|
||||
restartApp: Uygulamayı Yeniden Başlat
|
||||
vergeVersion: Verge Sürümü
|
||||
more: Daha Fazla
|
||||
exit: Çıkış
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: Sistem Vekil'i
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: Profil
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
_version: 1
|
||||
notifications:
|
||||
dashboardToggled:
|
||||
title: Dashboard
|
||||
body: Dashboard visibility has been updated.
|
||||
title: Идарә панеле
|
||||
body: Идарә панеленең күренеше яңартылды.
|
||||
clashModeChanged:
|
||||
title: Mode Switch
|
||||
body: Switched to {mode}.
|
||||
title: Режим алыштыру
|
||||
body: "{mode} режимына күчтел."
|
||||
systemProxyToggled:
|
||||
title: System Proxy
|
||||
body: System proxy status has been updated.
|
||||
title: Системалы прокси
|
||||
body: Системалы прокси хәле яңартылды.
|
||||
tunModeToggled:
|
||||
title: TUN Mode
|
||||
body: TUN mode status has been updated.
|
||||
title: TUN режимы
|
||||
body: TUN режимы хәле яңартылды.
|
||||
lightweightModeEntered:
|
||||
title: Lightweight Mode
|
||||
body: Entered lightweight mode.
|
||||
title: Җиңел режим
|
||||
body: Җиңел режимга күчелде.
|
||||
profilesReactivated:
|
||||
title: Profiles
|
||||
body: Profile Reactivated.
|
||||
title: Профильләр
|
||||
body: Профиль яңадан активлаштырылды.
|
||||
appQuit:
|
||||
title: About to Exit
|
||||
body: Clash Verge is about to exit.
|
||||
title: Чыгар алдыннан
|
||||
body: Clash Verge чыгарга җыена.
|
||||
appHidden:
|
||||
title: Application Hidden
|
||||
body: Clash Verge is running in the background.
|
||||
title: Кушымта яшерелде
|
||||
body: Clash Verge фон режимында эшли.
|
||||
service:
|
||||
adminInstallPrompt: Installing the Clash Verge service requires administrator privileges.
|
||||
adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges.
|
||||
adminInstallPrompt: Clash Verge хезмәтен урнаштыру өчен администратор хокуклары кирәк.
|
||||
adminUninstallPrompt: Clash Verge хезмәтен бетерү өчен администратор хокуклары кирәк.
|
||||
tray:
|
||||
dashboard: Dashboard
|
||||
ruleMode: Rule Mode
|
||||
globalMode: Global Mode
|
||||
directMode: Direct Mode
|
||||
outboundModes: Outbound Modes
|
||||
rule: Rule
|
||||
direct: Direct
|
||||
global: Global
|
||||
profiles: Profiles
|
||||
proxies: Proxies
|
||||
systemProxy: System Proxy
|
||||
tunMode: TUN Mode
|
||||
closeAllConnections: Close All Connections
|
||||
lightweightMode: Lightweight Mode
|
||||
copyEnv: Copy Environment Variables
|
||||
confDir: Configuration Directory
|
||||
coreDir: Core Directory
|
||||
logsDir: Log Directory
|
||||
openDir: Open Directory
|
||||
appLog: Application Log
|
||||
coreLog: Core Log
|
||||
restartClash: Restart Clash Core
|
||||
restartApp: Restart Application
|
||||
vergeVersion: Verge Version
|
||||
more: More
|
||||
exit: Exit
|
||||
dashboard: Идарә панеле
|
||||
ruleMode: Кагыйдә режимы
|
||||
globalMode: Глобаль режим
|
||||
directMode: Турыдан-туры режим
|
||||
outboundModes: Чыгыш режимнары
|
||||
rule: Кагыйдә
|
||||
direct: Турыдан-туры
|
||||
global: Глобаль
|
||||
profiles: Профильләр
|
||||
proxies: Проксилар
|
||||
systemProxy: Системалы прокси
|
||||
tunMode: TUN режимы
|
||||
closeAllConnections: Барлык тоташуларны ябу
|
||||
lightweightMode: Җиңел режим
|
||||
copyEnv: Мохит үзгәрүчәннәрен күчерү
|
||||
confDir: Конфигурация каталогы
|
||||
coreDir: Ядро каталогы
|
||||
logsDir: Журнал каталогы
|
||||
openDir: Каталогны ачу
|
||||
appLog: Кушымта журналы
|
||||
coreLog: Ядро журналы
|
||||
restartClash: Clash ядрәсен кабат җибәрү
|
||||
restartApp: Кушымтаны кабат җибәрү
|
||||
vergeVersion: Verge версиясе
|
||||
more: Күбрәк
|
||||
exit: Чыгу
|
||||
tooltip:
|
||||
systemProxy: System Proxy
|
||||
systemProxy: Системалы прокси
|
||||
tun: TUN
|
||||
profile: Profile
|
||||
profile: Профиль
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "clash-verge-limiter"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,165 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub type SystemLimiter = Limiter<SystemClock>;
|
||||
|
||||
pub trait Clock: Send + Sync {
|
||||
fn now_ms(&self) -> u64;
|
||||
}
|
||||
|
||||
impl<T: Clock + ?Sized> Clock for &T {
|
||||
fn now_ms(&self) -> u64 {
|
||||
(**self).now_ms()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Clock + ?Sized> Clock for Arc<T> {
|
||||
fn now_ms(&self) -> u64 {
|
||||
(**self).now_ms()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SystemClock;
|
||||
|
||||
impl Clock for SystemClock {
|
||||
fn now_ms(&self) -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as u64
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Limiter<C: Clock = SystemClock> {
|
||||
last_run_ms: AtomicU64,
|
||||
period_ms: u64,
|
||||
clock: C,
|
||||
}
|
||||
|
||||
impl<C: Clock> Limiter<C> {
|
||||
pub const fn new(period: Duration, clock: C) -> Self {
|
||||
Self {
|
||||
last_run_ms: AtomicU64::new(0),
|
||||
period_ms: period.as_millis() as u64,
|
||||
clock,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check(&self) -> bool {
|
||||
let now = self.clock.now_ms();
|
||||
let last = self.last_run_ms.load(Ordering::Relaxed);
|
||||
|
||||
if now < last + self.period_ms && now >= last {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.last_run_ms
|
||||
.compare_exchange(last, now, Ordering::SeqCst, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod extra_tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
struct MockClock(AtomicU64);
|
||||
impl Clock for MockClock {
|
||||
fn now_ms(&self) -> u64 {
|
||||
self.0.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_zero_period_always_passes() {
|
||||
let mock = MockClock(AtomicU64::new(100));
|
||||
let limiter = Limiter::new(Duration::from_millis(0), &mock);
|
||||
|
||||
assert!(limiter.check());
|
||||
assert!(limiter.check());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_boundary_condition() {
|
||||
let period_ms = 100;
|
||||
let mock = MockClock(AtomicU64::new(1000));
|
||||
let limiter = Limiter::new(Duration::from_millis(period_ms), &mock);
|
||||
|
||||
assert!(limiter.check());
|
||||
|
||||
mock.0.store(1099, Ordering::SeqCst);
|
||||
assert!(!limiter.check());
|
||||
|
||||
mock.0.store(1100, Ordering::SeqCst);
|
||||
assert!(limiter.check(), "Should pass exactly at period boundary");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_high_concurrency_consistency() {
|
||||
let period = Duration::from_millis(1000);
|
||||
let mock = Arc::new(MockClock(AtomicU64::new(1000)));
|
||||
let limiter = Arc::new(Limiter::new(period, Arc::clone(&mock)));
|
||||
|
||||
assert!(limiter.check());
|
||||
|
||||
mock.0.store(2500, Ordering::SeqCst);
|
||||
|
||||
let mut handles = vec![];
|
||||
for _ in 0..20 {
|
||||
let l = Arc::clone(&limiter);
|
||||
handles.push(thread::spawn(move || l.check()));
|
||||
}
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let results: Vec<bool> = handles.into_iter().map(|h| h.join().unwrap()).collect();
|
||||
|
||||
let success_count = results.iter().filter(|&&x| x).count();
|
||||
assert_eq!(success_count, 1);
|
||||
|
||||
assert_eq!(limiter.last_run_ms.load(Ordering::SeqCst), 2500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extreme_time_jump() {
|
||||
let mock = MockClock(AtomicU64::new(100));
|
||||
let limiter = Limiter::new(Duration::from_millis(100), &mock);
|
||||
|
||||
assert!(limiter.check());
|
||||
|
||||
mock.0.store(u64::MAX - 10, Ordering::SeqCst);
|
||||
assert!(limiter.check());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_system_clock_real_path() {
|
||||
let clock = SystemClock;
|
||||
let start = clock.now_ms();
|
||||
assert!(start > 0);
|
||||
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
assert!(clock.now_ms() >= start);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_limiter_with_system_clock_default() {
|
||||
let limiter = Limiter::new(Duration::from_millis(100), SystemClock);
|
||||
assert!(limiter.check());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_coverage_time_backward() {
|
||||
let mock = MockClock(AtomicU64::new(5000));
|
||||
let limiter = Limiter::new(Duration::from_millis(100), &mock);
|
||||
|
||||
assert!(limiter.check());
|
||||
|
||||
mock.0.store(4000, Ordering::SeqCst);
|
||||
|
||||
assert!(limiter.check(), "Should pass and reset when time moves backward");
|
||||
|
||||
assert_eq!(limiter.last_run_ms.load(Ordering::SeqCst), 4000);
|
||||
}
|
||||
}
|
||||
@@ -14,18 +14,20 @@ where
|
||||
F: Fn() -> Fut + Send + Sync + 'static,
|
||||
Fut: Future + Send + 'static,
|
||||
{
|
||||
RUNTIME.get_or_init(|| match tokio::runtime::Runtime::new() {
|
||||
Ok(rt) => Some(rt),
|
||||
Err(e) => {
|
||||
logging!(
|
||||
info,
|
||||
Type::SystemSignal,
|
||||
"register shutdown signal failed, create tokio runtime error: {}",
|
||||
e
|
||||
);
|
||||
None
|
||||
}
|
||||
});
|
||||
RUNTIME.get_or_init(
|
||||
|| match tokio::runtime::Builder::new_current_thread().enable_all().build() {
|
||||
Ok(rt) => Some(rt),
|
||||
Err(e) => {
|
||||
logging!(
|
||||
info,
|
||||
Type::SystemSignal,
|
||||
"register shutdown signal failed, create tokio runtime error: {}",
|
||||
e
|
||||
);
|
||||
None
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
#[cfg(unix)]
|
||||
unix::register(f);
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-types"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
smartstring = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1 +0,0 @@
|
||||
pub mod runtime;
|
||||
@@ -8,7 +8,7 @@ rust-version = "1.91"
|
||||
tauri = { workspace = true }
|
||||
tauri-plugin-clipboard-manager = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
sysinfo = { version = "0.37.2", features = ["network", "system"] }
|
||||
sysinfo = { version = "0.38.0", features = ["network", "system"] }
|
||||
|
||||
[target.'cfg(not(windows))'.dependencies]
|
||||
libc = "0.2.180"
|
||||
|
||||
@@ -120,6 +120,12 @@ fn is_binary_admin() -> bool {
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(unix)]
|
||||
pub fn current_gid() -> u32 {
|
||||
unsafe { libc::getgid() }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn list_network_interfaces() -> Vec<String> {
|
||||
let mut networks = Networks::new();
|
||||
|
||||
@@ -1,3 +1,57 @@
|
||||
## v2.4.5
|
||||
|
||||
- **Mihomo(Meta) 内核升级至 v1.19.19**
|
||||
|
||||
### 🐞 修复问题
|
||||
|
||||
- 修复 macOS 有线网络 DNS 劫持失败
|
||||
- 修复 Monaco 编辑器内右键菜单显示异常
|
||||
- 修复设置代理端口时检查端口占用
|
||||
- 修复 Monaco 编辑器初始化卡 Loading
|
||||
- 修复恢复备份时 `config.yaml` / `profiles.yaml` 文件内字段未正确恢复
|
||||
- 修复 Windows 下系统主题同步问题
|
||||
- 修复 URL Schemes 无法正常导入
|
||||
- 修复 Linux 下无法安装 TUN 服务
|
||||
- 修复可能的端口被占用误报
|
||||
- 修复设置允许外部控制来源不能立即生效
|
||||
- 修复前端性能回归问题
|
||||
|
||||
<details>
|
||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||
|
||||
- 允许代理页面允许高级过滤搜索
|
||||
- 备份设置页面新增导入备份按钮
|
||||
- 允许修改通知弹窗位置
|
||||
- 支持收起导航栏(导航栏右键菜单 / 界面设置)
|
||||
- 允许将出站模式显示在托盘一级菜单
|
||||
- 允许禁用在托盘中显示代理组
|
||||
- 支持在「编辑节点」中直接导入 AnyTLS URI 配置
|
||||
- 支持关闭「验证代理绕过格式」
|
||||
- 新增系统代理绕过和 TUN 排除自定义网段的可视化编辑器
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||
|
||||
- 应用内更新日志支持解析并渲染 HTML 标签
|
||||
- 性能优化前后端在渲染流量图时的资源
|
||||
- 在 Linux NVIDIA 显卡环境下尝试禁用 WebKit DMABUF 渲染以规避潜在问题
|
||||
- Windows 下自启动改为计划任务实现
|
||||
- 改进托盘和窗口操作频率限制实现
|
||||
- 使用「编辑节点」添加节点时,自动将节点添加到第一个 `select` 类型的代理组的第一位
|
||||
- 隐藏侧边导航栏和悬浮跳转导航的滚动条
|
||||
- 完善对 AnyTLS / Mieru / Sudoku 的 GUI 支持
|
||||
- macOS 和 Linux 对服务 IPC 权限进一步限制
|
||||
- 移除 Windows 自启动计划任务中冗余的 3 秒延时
|
||||
- 右键错误通知可复制错误详情
|
||||
- 保存 TUN 设置时优化执行流程,避免界面卡顿
|
||||
- 补充 `deb` / `rpm` 依赖 `libayatana-appindicator`
|
||||
- 「连接」表格标题的排序点击区域扩展到整列宽度
|
||||
- 备份恢复时显示加载覆盖层,恢复过程无需再手动关闭对话框
|
||||
|
||||
</details>
|
||||
|
||||
## v2.4.4
|
||||
|
||||
- **Mihomo(Meta) 内核升级至 v1.19.17**
|
||||
|
||||
@@ -69,19 +69,6 @@ Join [@clash_verge_rev](https://t.me/clash_verge_re) for update announcements.
|
||||
|
||||
🌐 Official Website: 👉 [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### Build Infrastructure Sponsor — [YXVM Dedicated Servers](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
Our builds and releases run on YXVM dedicated servers that deliver premium resources, strong performance, and high-speed networking. If downloads feel fast and usage feels snappy, it is thanks to robust hardware.
|
||||
|
||||
🧩 Highlights of YXVM Dedicated Servers:
|
||||
|
||||
- 🌎 Optimized global routes for dramatically faster downloads
|
||||
- 🔧 Bare-metal resources instead of shared VPS capacity for maximum performance
|
||||
- 🧠 Great for proxy workloads, hosting web/CDN services, CI/CD pipelines, or any high-load tasks
|
||||
- 💡 Ready to use instantly with multiple datacenter options, including CN2 and IEPL
|
||||
- 📦 The configuration used by this project is on sale—feel free to get the same setup
|
||||
- 🎯 Want the same build environment? [Order a YXVM server today](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## Features
|
||||
|
||||
- Built on high-performance Rust with the Tauri 2 framework
|
||||
|
||||
@@ -63,19 +63,6 @@ Consulta la [documentación del proyecto](https://clash-verge-rev.github.io/) pa
|
||||
- Desbloquea servicios de streaming y acceso a ChatGPT
|
||||
- Sitio oficial: [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### Patrocinador de la infraestructura de compilación — [Servidores dedicados YXVM](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
Las compilaciones y lanzamientos del proyecto se ejecutan en servidores dedicados de YXVM, que proporcionan recursos premium, alto rendimiento y redes de alta velocidad. Si las descargas son rápidas y el uso es fluido, es gracias a este hardware robusto.
|
||||
|
||||
🧩 Ventajas de los servidores dedicados YXVM:
|
||||
|
||||
- 🌎 Rutas globales optimizadas para descargas significativamente más rápidas
|
||||
- 🔧 Recursos bare-metal, en lugar de VPS compartidos, para obtener el máximo rendimiento
|
||||
- 🧠 Ideales para proxys, alojamiento de sitios web/CDN, pipelines de CI/CD o cualquier carga elevada
|
||||
- 💡 Listos para usar al instante, con múltiples centros de datos disponibles (incluidos CN2 e IEPL)
|
||||
- 📦 La misma configuración utilizada por este proyecto está disponible para su compra
|
||||
- 🎯 ¿Quieres el mismo entorno de compilación? [Solicita un servidor YXVM hoy](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## Funciones
|
||||
|
||||
- Basado en Rust de alto rendimiento y en el framework Tauri 2
|
||||
|
||||
@@ -62,18 +62,6 @@
|
||||
- پشتیبانی از سرویسهای استریم و دسترسی به ChatGPT
|
||||
- وبسایت رسمی: [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### حامی زیرساخت ساخت — [سرورهای اختصاصی YXVM](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
بیلدها و نسخههای ما روی سرورهای اختصاصی YXVM اجرا میشوند که منابع ممتاز، عملکرد قوی و شبکه پرسرعت را ارائه میدهند. اگر دانلودها سریع و استفاده از آن سریع به نظر میرسد، به لطف سختافزار قوی است.
|
||||
🧩 نکات برجسته سرورهای اختصاصی YXVM:
|
||||
|
||||
- 🌎 مسیرهای جهانی بهینه شده برای دانلودهای بسیار سریعتر
|
||||
- 🔧 منابع فیزیکی به جای ظرفیت VPS مشترک برای حداکثر کارایی
|
||||
- 🧠 عالی برای بارهای کاری پروکسی، میزبانی سرویسهای وب/CDN، خطوط لوله CI/CD یا هرگونه کار با بار بالا
|
||||
- 💡 آماده استفاده فوری با گزینههای متعدد مرکز داده، از جمله CN2 و IEPL
|
||||
- 📦 پیکربندی مورد استفاده در این پروژه در حال فروش است - میتوانید همان تنظیمات را تهیه کنید.
|
||||
- 🎯 آیا محیط ساخت مشابهی میخواهید؟ [همین امروز یک سرور YXVM سفارش دهید](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## ویژگیها
|
||||
|
||||
- ساخته شده بر اساس Rust با کارایی بالا و فریمورک Tauri 2
|
||||
|
||||
@@ -63,19 +63,6 @@ Windows (x64/x86)、Linux (x64/arm64)、macOS 10.15+ (Intel/Apple) をサポー
|
||||
- ストリーミングおよび ChatGPT の利用にも対応
|
||||
- 公式サイト: [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### ビルド環境スポンサー — [YXVM 専用サーバー](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
本プロジェクトのビルドとリリースは、YXVM の専用サーバーによって支えられています。高速ダウンロードや快適な操作性は、強力なハードウェアがあってこそです。
|
||||
|
||||
🧩 YXVM 専用サーバーの特長:
|
||||
|
||||
- 🌎 最適化されたグローバル回線で圧倒的なダウンロード速度
|
||||
- 🔧 VPS とは異なるベアメタル資源で最高性能を発揮
|
||||
- 🧠 プロキシ運用、Web/CDN ホスティング、CI/CD など高負荷ワークロードに最適
|
||||
- 💡 複数データセンターから即時利用可能。CN2 や IEPL も選択可
|
||||
- 📦 本プロジェクトが使用している構成も販売中。同じ環境を入手できます
|
||||
- 🎯 同じビルド体験をしたい方は [今すぐ YXVM サーバーを注文](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## 機能
|
||||
|
||||
- 高性能な Rust と Tauri 2 フレームワークに基づくデスクトップアプリ
|
||||
|
||||
@@ -63,19 +63,6 @@ Windows (x64/x86), Linux (x64/arm64), macOS 10.15+ (Intel/Apple)을 지원합니
|
||||
- 스트리밍 및 ChatGPT 접근 지원
|
||||
- 공식 사이트: [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### 빌드 인프라 스폰서 — [YXVM 전용 서버](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
본 프로젝트의 빌드 및 릴리스는 YXVM 전용 서버에서 구동됩니다. 빠른 다운로드와 경쾌한 사용감은 탄탄한 하드웨어 덕분입니다.
|
||||
|
||||
🧩 YXVM 전용 서버 하이라이트:
|
||||
|
||||
- 🌎 최적화된 글로벌 라우팅으로 대폭 빨라진 다운로드
|
||||
- 🔧 공유 VPS가 아닌 베어메탈 자원으로 최대 성능 제공
|
||||
- 🧠 프록시 워크로드, Web/CDN 호스팅, CI/CD, 고부하 작업에 적합
|
||||
- 💡 CN2 / IEPL 등 다양한 데이터센터 옵션, 즉시 사용 가능
|
||||
- 📦 본 프로젝트가 사용하는 구성도 판매 중 — 동일한 환경을 사용할 수 있습니다
|
||||
- 🎯 동일한 빌드 환경이 필요하다면 [지금 YXVM 서버 주문](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## 기능
|
||||
|
||||
- 고성능 Rust와 Tauri 2 프레임워크 기반 데스크톱 앱
|
||||
|
||||
@@ -59,19 +59,6 @@ Clash Meta GUI базируется на <a href="https://github.com/tauri-apps/
|
||||
- Разблокировка потоковые сервисы и ChatGPT
|
||||
- Официальный сайт: [https://狗狗加速.com](https://verge.dginv.click/#/register?code=oaxsAGo6)
|
||||
|
||||
#### Среда сборки и публикации этого проекта полностью поддерживается выделенным сервером [YXVM](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
Благодарим вас за предоставление надежной бэкэнд-среды с эксклюзивными ресурсами, высокой производительностью и высокоскоростной сетью. Если вы считаете, что загрузка файлов происходит достаточно быстро, а использование — достаточно плавно, то это потому, что мы используем серверы высшего уровня!
|
||||
|
||||
🧩 Преимущества выделенного сервера YXVM:
|
||||
|
||||
- 🌎 Премиум-сеть с оптимизацией обратного пути для молниеносной скорости загрузки
|
||||
- 🔧 Выделенные физические серверные ресурсы, не имеющие аналогов среди VPS, обеспечивающие максимальную производительность
|
||||
- 🧠 Идеально подходит для прокси, хостинга веб-сайтов/CDN-сайтов, рабочих процессов CI/CD или любых приложений с высокой нагрузкой
|
||||
- 💡 Поддержка использования сразу после включения, выбор нескольких дата-центров, CN2 / IEPL на выбор
|
||||
- 📦 Эта конфигурация в настоящее время доступна для покупки — не стесняйтесь заказывать ту же модель!
|
||||
- 🎯 Хотите попробовать такую же сборку? [Закажите выделенный сервер YXVM прямо сейчас!](https://yxvm.com/aff.php?aff=827)
|
||||
|
||||
## Фичи
|
||||
|
||||
- Основан на произвоительном Rust и фреймворке Tauri 2
|
||||
|
||||
@@ -37,6 +37,11 @@ export default defineConfig([
|
||||
|
||||
languageOptions: {
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
projectService: {
|
||||
allowDefaultProject: ["src/polyfills/*.js"],
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
settings: {
|
||||
|
||||
+37
-35
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "clash-verge",
|
||||
"version": "2.4.5-rc.1",
|
||||
"version": "2.4.6",
|
||||
"license": "GPL-3.0-only",
|
||||
"scripts": {
|
||||
"prepare": "husky || true",
|
||||
@@ -46,75 +46,77 @@
|
||||
"@mui/material": "^7.3.7",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/react-virtual": "^3.13.18",
|
||||
"@tauri-apps/api": "2.9.1",
|
||||
"@tauri-apps/api": "2.10.1",
|
||||
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
|
||||
"@tauri-apps/plugin-dialog": "^2.5.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.6.0",
|
||||
"@tauri-apps/plugin-fs": "^2.4.5",
|
||||
"@tauri-apps/plugin-http": "~2.5.5",
|
||||
"@tauri-apps/plugin-http": "~2.5.7",
|
||||
"@tauri-apps/plugin-process": "^2.3.1",
|
||||
"@tauri-apps/plugin-shell": "2.3.4",
|
||||
"@tauri-apps/plugin-updater": "2.9.0",
|
||||
"@tauri-apps/plugin-shell": "2.3.5",
|
||||
"@tauri-apps/plugin-updater": "2.10.0",
|
||||
"ahooks": "^3.9.6",
|
||||
"axios": "^1.13.2",
|
||||
"axios": "^1.13.5",
|
||||
"dayjs": "1.11.19",
|
||||
"foxact": "^0.2.52",
|
||||
"i18next": "^25.7.4",
|
||||
"foxts": "^5.2.1",
|
||||
"i18next": "^25.8.4",
|
||||
"ipaddr.js": "^2.3.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"lodash-es": "^4.17.22",
|
||||
"lodash-es": "^4.17.23",
|
||||
"monaco-editor": "^0.55.1",
|
||||
"monaco-yaml": "^5.4.0",
|
||||
"nanoid": "^5.1.6",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"react-error-boundary": "6.0.3",
|
||||
"react-hook-form": "^7.71.0",
|
||||
"react-i18next": "16.5.2",
|
||||
"react": "19.2.4",
|
||||
"react-dom": "19.2.4",
|
||||
"react-error-boundary": "6.1.1",
|
||||
"react-hook-form": "^7.71.1",
|
||||
"react-i18next": "16.5.4",
|
||||
"react-markdown": "10.1.0",
|
||||
"react-router": "^7.12.0",
|
||||
"react-router": "^7.13.0",
|
||||
"react-virtuoso": "^4.18.1",
|
||||
"rehype-raw": "^7.0.0",
|
||||
"swr": "^2.3.8",
|
||||
"swr": "^2.4.0",
|
||||
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
||||
"types-pac": "^1.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@actions/github": "^7.0.0",
|
||||
"@eslint-react/eslint-plugin": "^2.5.5",
|
||||
"@eslint/js": "^9.39.2",
|
||||
"@tauri-apps/cli": "2.9.6",
|
||||
"@actions/github": "^9.0.0",
|
||||
"@eslint-react/eslint-plugin": "^2.12.2",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tauri-apps/cli": "2.10.0",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^24.10.7",
|
||||
"@types/react": "19.2.8",
|
||||
"@types/node": "^24.10.12",
|
||||
"@types/react": "19.2.14",
|
||||
"@types/react-dom": "19.2.3",
|
||||
"@vitejs/plugin-legacy": "^7.2.1",
|
||||
"@vitejs/plugin-react-swc": "^4.2.2",
|
||||
"@vitejs/plugin-react-swc": "^4.2.3",
|
||||
"adm-zip": "^0.5.16",
|
||||
"cli-color": "^2.0.4",
|
||||
"commander": "^14.0.2",
|
||||
"commander": "^14.0.3",
|
||||
"cross-env": "^10.1.0",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint": "^10.0.0",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-import-resolver-typescript": "^4.4.4",
|
||||
"eslint-plugin-import-x": "^4.16.1",
|
||||
"eslint-plugin-prettier": "^5.5.4",
|
||||
"eslint-plugin-prettier": "^5.5.5",
|
||||
"eslint-plugin-react-compiler": "19.1.0-rc.2",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"eslint-plugin-react-refresh": "^0.4.26",
|
||||
"eslint-plugin-react-refresh": "^0.5.0",
|
||||
"eslint-plugin-unused-imports": "^4.3.0",
|
||||
"glob": "^13.0.0",
|
||||
"globals": "^17.0.0",
|
||||
"glob": "^13.0.1",
|
||||
"globals": "^17.3.0",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"husky": "^9.1.7",
|
||||
"jiti": "^2.6.1",
|
||||
"lint-staged": "^16.2.7",
|
||||
"node-fetch": "^3.3.2",
|
||||
"prettier": "^3.7.4",
|
||||
"sass": "^1.97.2",
|
||||
"tar": "^7.5.2",
|
||||
"terser": "^5.44.1",
|
||||
"prettier": "^3.8.1",
|
||||
"sass": "^1.97.3",
|
||||
"tar": "^7.5.7",
|
||||
"terser": "^5.46.0",
|
||||
"typescript": "^5.9.3",
|
||||
"typescript-eslint": "^8.52.0",
|
||||
"typescript-eslint": "^8.54.0",
|
||||
"vite": "^7.3.1",
|
||||
"vite-plugin-svgr": "^4.5.0"
|
||||
},
|
||||
@@ -128,7 +130,7 @@
|
||||
]
|
||||
},
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@10.28.0",
|
||||
"packageManager": "pnpm@10.29.2",
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
"@parcel/watcher",
|
||||
|
||||
Generated
+1784
-1816
File diff suppressed because it is too large
Load Diff
+16
-10
@@ -68,6 +68,11 @@ const SIDECAR_HOST = target
|
||||
.toString()
|
||||
.match(/(?<=host: ).+(?=\s*)/g)[0];
|
||||
|
||||
const RESOURCES_DIR = path.join(cwd, "src-tauri", "resources");
|
||||
const SIDECAR_DIR = path.join(cwd, "src-tauri", "sidecar");
|
||||
// Linux service binaries are bundled as externalBin sidecars (see tauri.linux.conf.json)
|
||||
const SERVICE_DIR = platform === "linux" ? SIDECAR_DIR : RESOURCES_DIR;
|
||||
|
||||
// =======================
|
||||
// Version Cache
|
||||
// =======================
|
||||
@@ -369,9 +374,8 @@ async function downloadFile(url, outPath) {
|
||||
// =======================
|
||||
async function resolveSidecar(binInfo) {
|
||||
const { name, targetFile, zipFile, exeFile, downloadURL } = binInfo;
|
||||
const sidecarDir = path.join(cwd, "src-tauri", "sidecar");
|
||||
const sidecarPath = path.join(sidecarDir, targetFile);
|
||||
await fsp.mkdir(sidecarDir, { recursive: true });
|
||||
const sidecarPath = path.join(SIDECAR_DIR, targetFile);
|
||||
await fsp.mkdir(SIDECAR_DIR, { recursive: true });
|
||||
|
||||
if (!FORCE && fs.existsSync(sidecarPath)) {
|
||||
log_success(`"${name}" already exists, skipping download`);
|
||||
@@ -460,9 +464,9 @@ async function resolveSidecar(binInfo) {
|
||||
}
|
||||
|
||||
async function resolveResource(binInfo) {
|
||||
const { file, downloadURL, localPath } = binInfo;
|
||||
const resDir = path.join(cwd, "src-tauri/resources");
|
||||
const targetPath = path.join(resDir, file);
|
||||
const { file, downloadURL, localPath, dir } = binInfo;
|
||||
const baseDir = dir ?? RESOURCES_DIR;
|
||||
const targetPath = path.join(baseDir, file);
|
||||
|
||||
if (!FORCE && fs.existsSync(targetPath) && !downloadURL && !localPath) {
|
||||
log_success(`"${file}" already exists, skipping`);
|
||||
@@ -474,7 +478,7 @@ async function resolveResource(binInfo) {
|
||||
log_success(`"${file}" already exists, skipping download`);
|
||||
return;
|
||||
}
|
||||
await fsp.mkdir(resDir, { recursive: true });
|
||||
await fsp.mkdir(baseDir, { recursive: true });
|
||||
await downloadFile(downloadURL, targetPath);
|
||||
await updateHashCache(targetPath);
|
||||
}
|
||||
@@ -483,7 +487,7 @@ async function resolveResource(binInfo) {
|
||||
if (!(await hasFileChanged(localPath, targetPath))) {
|
||||
return;
|
||||
}
|
||||
await fsp.mkdir(resDir, { recursive: true });
|
||||
await fsp.mkdir(baseDir, { recursive: true });
|
||||
await fsp.copyFile(localPath, targetPath);
|
||||
await updateHashCache(targetPath);
|
||||
log_success(`Copied file: ${file}`);
|
||||
@@ -545,12 +549,11 @@ const resolveServicePermission = async () => {
|
||||
"clash-verge-service-install*",
|
||||
"clash-verge-service-uninstall*",
|
||||
];
|
||||
const resDir = path.join(cwd, "src-tauri/resources");
|
||||
const hashCache = await loadHashCache();
|
||||
let hasChanges = false;
|
||||
|
||||
for (const f of serviceExecutables) {
|
||||
const files = glob.sync(path.join(resDir, f));
|
||||
const files = glob.sync(path.join(SERVICE_DIR, f));
|
||||
for (const filePath of files) {
|
||||
if (fs.existsSync(filePath)) {
|
||||
const currentHash = await calculateFileHash(filePath);
|
||||
@@ -584,6 +587,7 @@ const resolveService = () => {
|
||||
const suffix = platform === "linux" ? "-" + SIDECAR_HOST : "";
|
||||
return resolveResource({
|
||||
file: "clash-verge-service" + suffix + ext,
|
||||
dir: SERVICE_DIR,
|
||||
downloadURL: `${SERVICE_URL}/clash-verge-service${ext}`,
|
||||
});
|
||||
};
|
||||
@@ -592,6 +596,7 @@ const resolveInstall = () => {
|
||||
const suffix = platform === "linux" ? "-" + SIDECAR_HOST : "";
|
||||
return resolveResource({
|
||||
file: "clash-verge-service-install" + suffix + ext,
|
||||
dir: SERVICE_DIR,
|
||||
downloadURL: `${SERVICE_URL}/clash-verge-service-install${ext}`,
|
||||
});
|
||||
};
|
||||
@@ -600,6 +605,7 @@ const resolveUninstall = () => {
|
||||
const suffix = platform === "linux" ? "-" + SIDECAR_HOST : "";
|
||||
return resolveResource({
|
||||
file: "clash-verge-service-uninstall" + suffix + ext,
|
||||
dir: SERVICE_DIR,
|
||||
downloadURL: `${SERVICE_URL}/clash-verge-service-uninstall${ext}`,
|
||||
});
|
||||
};
|
||||
|
||||
+18
-34
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "clash-verge"
|
||||
version = "2.4.5-rc.1"
|
||||
version = "2.4.6"
|
||||
description = "clash verge"
|
||||
authors = ["zzzgydi", "Tunglies", "wonfen", "MystiPanda"]
|
||||
license = "GPL-3.0-only"
|
||||
@@ -22,20 +22,19 @@ tauri-dev = []
|
||||
tokio-trace = ["console-subscriber"]
|
||||
clippy = ["tauri/test"]
|
||||
tracing = []
|
||||
tracing-full = []
|
||||
|
||||
[package.metadata.bundle]
|
||||
identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.5.3", features = [] }
|
||||
tauri-build = { version = "2.5.5", features = [] }
|
||||
|
||||
[dependencies]
|
||||
clash-verge-draft = { workspace = true }
|
||||
clash-verge-logging = { workspace = true }
|
||||
clash-verge-signal = { workspace = true }
|
||||
clash-verge-types = { workspace = true }
|
||||
clash-verge-i18n = { workspace = true }
|
||||
clash-verge-limiter = { workspace = true }
|
||||
tauri-plugin-clash-verge-sysinfo = { workspace = true }
|
||||
tauri-plugin-clipboard-manager = { workspace = true }
|
||||
tauri = { workspace = true, features = [
|
||||
@@ -60,78 +59,63 @@ warp = { version = "0.4.2", features = ["server"] }
|
||||
open = "5.3.3"
|
||||
dunce = "1.0.5"
|
||||
nanoid = "0.4"
|
||||
chrono = "0.4.42"
|
||||
chrono = "0.4.43"
|
||||
boa_engine = "0.21.0"
|
||||
once_cell = { version = "1.21.3", features = ["parking_lot"] }
|
||||
delay_timer = "0.11.6"
|
||||
percent-encoding = "2.3.2"
|
||||
reqwest = { version = "0.13.1", features = [
|
||||
reqwest = { version = "0.13.2", features = [
|
||||
"json",
|
||||
"cookies",
|
||||
"rustls",
|
||||
"form",
|
||||
] }
|
||||
regex = "1.12.2"
|
||||
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs", features = [
|
||||
regex = "1.12.3"
|
||||
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs", branch = "0.4.5", features = [
|
||||
"guard",
|
||||
] }
|
||||
network-interface = { version = "2.0.5", features = ["serde"] }
|
||||
tauri-plugin-shell = "2.3.4"
|
||||
tauri-plugin-dialog = "2.5.0"
|
||||
tauri-plugin-shell = "2.3.5"
|
||||
tauri-plugin-dialog = "2.6.0"
|
||||
tauri-plugin-fs = "2.4.5"
|
||||
tauri-plugin-process = "2.3.1"
|
||||
tauri-plugin-deep-link = "2.4.6"
|
||||
tauri-plugin-deep-link = "2.4.7"
|
||||
tauri-plugin-window-state = "2.4.1"
|
||||
zip = "7.0.0"
|
||||
reqwest_dav = "0.2.2"
|
||||
zip = "8.0.0"
|
||||
reqwest_dav = "0.3.2"
|
||||
aes-gcm = { version = "0.10.3", features = ["std"] }
|
||||
base64 = "0.22.1"
|
||||
getrandom = "0.3.4"
|
||||
getrandom = "0.4.1"
|
||||
futures = "0.3.31"
|
||||
gethostname = "1.1.0"
|
||||
scopeguard = "1.2.0"
|
||||
tauri-plugin-notification = "2.3.3"
|
||||
tokio-stream = "0.1.18"
|
||||
backoff = { version = "0.4.0", features = ["tokio"] }
|
||||
tauri-plugin-http = "2.5.5"
|
||||
tauri-plugin-http = "2.5.7"
|
||||
console-subscriber = { version = "0.5.0", optional = true }
|
||||
tauri-plugin-devtools = { version = "2.0.1" }
|
||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo" }
|
||||
clash_verge_logger = { git = "https://github.com/clash-verge-rev/clash-verge-logger" }
|
||||
async-trait = "0.1.89"
|
||||
clash_verge_service_ipc = { version = "2.0.29", features = [
|
||||
clash_verge_service_ipc = { version = "2.1.3", features = [
|
||||
"client",
|
||||
], git = "https://github.com/clash-verge-rev/clash-verge-service-ipc" }
|
||||
arc-swap = "1.8.0"
|
||||
arc-swap = "1.8.1"
|
||||
rust_iso3166 = "0.1.14"
|
||||
# Use the git repo until the next release after v2.0.0.
|
||||
dark-light = { git = "https://github.com/rust-dark-light/dark-light" }
|
||||
governor = "0.10.4"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
deelevate = { workspace = true }
|
||||
runas = "=1.2.0"
|
||||
winreg = "0.55.0"
|
||||
winapi = { version = "0.3.9", features = [
|
||||
"winbase",
|
||||
"fileapi",
|
||||
"winnt",
|
||||
"handleapi",
|
||||
"errhandlingapi",
|
||||
"minwindef",
|
||||
"winerror",
|
||||
"stringapiset",
|
||||
"tlhelp32",
|
||||
"processthreadsapi",
|
||||
"winhttp",
|
||||
"winreg",
|
||||
"winnls",
|
||||
] }
|
||||
windows = { version = "0.62.2", features = ["Win32_Globalization"] }
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-autostart = "2.5.1"
|
||||
tauri-plugin-global-shortcut = "2.3.1"
|
||||
tauri-plugin-updater = "2.9.0"
|
||||
tauri-plugin-updater = "2.10.0"
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = { workspace = true }
|
||||
|
||||
@@ -45,14 +45,20 @@ pub fn open_web_url(url: String) -> CmdResult<()> {
|
||||
/// 打开 Verge 最新日志
|
||||
#[tauri::command]
|
||||
pub async fn open_app_log() -> CmdResult<()> {
|
||||
open::that(dirs::app_latest_log().stringify_err()?).stringify_err()
|
||||
let log_path = dirs::app_latest_log().stringify_err()?;
|
||||
#[cfg(target_os = "windows")]
|
||||
let log_path = crate::utils::help::snapshot_path(&log_path).stringify_err()?;
|
||||
open::that(log_path).stringify_err()
|
||||
}
|
||||
|
||||
// TODO 后续可以为前端提供接口,当前作为托盘菜单使用
|
||||
/// 打开 Clash 最新日志
|
||||
#[tauri::command]
|
||||
pub async fn open_core_log() -> CmdResult<()> {
|
||||
open::that(dirs::clash_latest_log().stringify_err()?).stringify_err()
|
||||
let log_path = dirs::clash_latest_log().stringify_err()?;
|
||||
#[cfg(target_os = "windows")]
|
||||
let log_path = crate::utils::help::snapshot_path(&log_path).stringify_err()?;
|
||||
open::that(log_path).stringify_err()
|
||||
}
|
||||
|
||||
/// 打开/关闭开发者工具
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use super::CmdResult;
|
||||
use super::StringifyErr as _;
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{
|
||||
config::{
|
||||
Config, IProfiles, PrfItem, PrfOption,
|
||||
@@ -117,7 +118,7 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
|
||||
pub async fn reorder_profile(active_id: String, over_id: String) -> CmdResult {
|
||||
match profiles_reorder_safe(&active_id, &over_id).await {
|
||||
Ok(_) => {
|
||||
logging!(debug, Type::Cmd, "重新排序配置文件");
|
||||
logging!(info, Type::Cmd, "重新排序配置文件");
|
||||
Config::profiles().await.apply();
|
||||
Ok(())
|
||||
}
|
||||
@@ -310,7 +311,9 @@ async fn handle_success(current_value: Option<&String>) -> CmdResult<bool> {
|
||||
logging!(warn, Type::Cmd, "Warning: 异步保存配置文件失败: {e}");
|
||||
}
|
||||
|
||||
if let Some(current) = current_value {
|
||||
if let Some(current) = current_value
|
||||
&& WindowManager::get_main_window().is_some()
|
||||
{
|
||||
logging!(info, Type::Cmd, "向前端发送配置变更事件: {}", current);
|
||||
handle::Handle::notify_profile_changed(current.to_owned());
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{IClashTemp, IProfiles, IVerge};
|
||||
use crate::{
|
||||
config::{PrfItem, profiles_append_item_safe},
|
||||
config::{PrfItem, profiles_append_item_safe, runtime::IRuntime},
|
||||
constants::{files, timing},
|
||||
core::{
|
||||
CoreManager,
|
||||
@@ -16,9 +16,9 @@ use anyhow::{Result, anyhow};
|
||||
use backoff::{Error as BackoffError, ExponentialBackoff};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_types::runtime::IRuntime;
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use smartstring::alias::String;
|
||||
use std::path::PathBuf;
|
||||
use std::{collections::HashSet, path::PathBuf};
|
||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio::time::sleep;
|
||||
@@ -188,7 +188,9 @@ impl Config {
|
||||
}
|
||||
|
||||
pub async fn generate() -> Result<()> {
|
||||
let (config, exists_keys, logs) = enhance::enhance().await;
|
||||
let (mut config, exists_keys, logs) = enhance::enhance().await;
|
||||
|
||||
sanitize_tunnels_proxy(&mut config);
|
||||
|
||||
Self::runtime().await.edit_draft(|d| {
|
||||
*d = IRuntime {
|
||||
@@ -250,6 +252,73 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize_tunnels_proxy(config: &mut Mapping) {
|
||||
// 检查是否存在 tunnels
|
||||
if !config
|
||||
.get("tunnels")
|
||||
.and_then(|v| v.as_sequence())
|
||||
.is_some_and(|t| tunnels_need_validation(t))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 在需要时,收集可用目标(proxies + proxy-groups + 内建)
|
||||
let mut valid: HashSet<String> = HashSet::with_capacity(64);
|
||||
collect_names(config, "proxies", &mut valid);
|
||||
collect_names(config, "proxy-groups", &mut valid);
|
||||
|
||||
valid.insert("DIRECT".into());
|
||||
valid.insert("REJECT".into());
|
||||
|
||||
let Some(tunnels) = config.get_mut("tunnels").and_then(|v| v.as_sequence_mut()) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// 修改 tunnels:删除无效 proxy
|
||||
for item in tunnels {
|
||||
let Some(tunnel) = item.as_mapping_mut() else { continue };
|
||||
|
||||
let Some(proxy_name) = tunnel.get("proxy").and_then(|v| v.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if proxy_name == "DIRECT" || proxy_name == "REJECT" {
|
||||
continue;
|
||||
}
|
||||
|
||||
if !valid.contains(proxy_name) {
|
||||
tunnel.remove("proxy");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// tunnels 存在且至少有一条 tunnel 的 proxy 需要校验时才返回 true
|
||||
fn tunnels_need_validation(tunnels: &[Value]) -> bool {
|
||||
tunnels.iter().any(|item| {
|
||||
item.as_mapping()
|
||||
.and_then(|t| t.get("proxy"))
|
||||
.and_then(|p| p.as_str())
|
||||
.is_some_and(|name| name != "DIRECT" && name != "REJECT")
|
||||
})
|
||||
}
|
||||
|
||||
fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
|
||||
let Some(Value::Sequence(seq)) = config.get(list_key) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for item in seq {
|
||||
let Value::Mapping(map) = item else {
|
||||
continue;
|
||||
};
|
||||
if let Some(Value::String(n)) = map.get("name")
|
||||
&& !n.is_empty()
|
||||
{
|
||||
out.insert(n.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ConfigType {
|
||||
Run,
|
||||
|
||||
@@ -4,6 +4,7 @@ mod config;
|
||||
mod encrypt;
|
||||
mod prfitem;
|
||||
pub mod profiles;
|
||||
pub mod runtime;
|
||||
mod verge;
|
||||
|
||||
pub use self::{clash::*, config::*, encrypt::*, prfitem::*, profiles::*, verge::*};
|
||||
|
||||
@@ -12,6 +12,9 @@ use serde_yaml_ng::Mapping;
|
||||
use smartstring::alias::String;
|
||||
use std::time::Duration;
|
||||
use tokio::fs;
|
||||
// TODO, use other re-export
|
||||
use reqwest_dav::re_exports::url::form_urlencoded;
|
||||
use tauri::Url;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
|
||||
pub struct PrfItem {
|
||||
@@ -60,13 +63,13 @@ pub struct PrfItem {
|
||||
pub file_data: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, PartialEq, Deserialize, Serialize)]
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct PrfSelected {
|
||||
pub name: Option<String>,
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Deserialize, Serialize)]
|
||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize)]
|
||||
pub struct PrfExtra {
|
||||
pub upload: u64,
|
||||
pub download: u64,
|
||||
@@ -124,22 +127,25 @@ pub struct PrfOption {
|
||||
impl PrfOption {
|
||||
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
|
||||
match (one, other) {
|
||||
(Some(a), Some(b)) => Some(Self {
|
||||
user_agent: b.user_agent.as_ref().or(a.user_agent.as_ref()).cloned(),
|
||||
with_proxy: b.with_proxy.or(a.with_proxy),
|
||||
self_proxy: b.self_proxy.or(a.self_proxy),
|
||||
danger_accept_invalid_certs: b.danger_accept_invalid_certs.or(a.danger_accept_invalid_certs),
|
||||
allow_auto_update: b.allow_auto_update.or(a.allow_auto_update),
|
||||
update_interval: b.update_interval.or(a.update_interval),
|
||||
merge: b.merge.as_ref().or(a.merge.as_ref()).cloned(),
|
||||
script: b.script.as_ref().or(a.script.as_ref()).cloned(),
|
||||
rules: b.rules.as_ref().or(a.rules.as_ref()).cloned(),
|
||||
proxies: b.proxies.as_ref().or(a.proxies.as_ref()).cloned(),
|
||||
groups: b.groups.as_ref().or(a.groups.as_ref()).cloned(),
|
||||
timeout_seconds: b.timeout_seconds.or(a.timeout_seconds),
|
||||
}),
|
||||
(Some(a), None) => Some(a.clone()),
|
||||
(None, Some(b)) => Some(b.clone()),
|
||||
(Some(a_ref), Some(b_ref)) => {
|
||||
let mut result = a_ref.clone();
|
||||
result.user_agent = b_ref.user_agent.clone().or(result.user_agent);
|
||||
result.with_proxy = b_ref.with_proxy.or(result.with_proxy);
|
||||
result.self_proxy = b_ref.self_proxy.or(result.self_proxy);
|
||||
result.danger_accept_invalid_certs =
|
||||
b_ref.danger_accept_invalid_certs.or(result.danger_accept_invalid_certs);
|
||||
result.allow_auto_update = b_ref.allow_auto_update.or(result.allow_auto_update);
|
||||
result.update_interval = b_ref.update_interval.or(result.update_interval);
|
||||
result.merge = b_ref.merge.clone().or(result.merge);
|
||||
result.script = b_ref.script.clone().or(result.script);
|
||||
result.rules = b_ref.rules.clone().or(result.rules);
|
||||
result.proxies = b_ref.proxies.clone().or(result.proxies);
|
||||
result.groups = b_ref.groups.clone().or(result.groups);
|
||||
result.timeout_seconds = b_ref.timeout_seconds.or(result.timeout_seconds);
|
||||
Some(result)
|
||||
}
|
||||
(Some(a_ref), None) => Some(a_ref.clone()),
|
||||
(None, Some(b_ref)) => Some(b_ref.clone()),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
@@ -275,9 +281,17 @@ impl PrfItem {
|
||||
ProxyType::None
|
||||
};
|
||||
|
||||
let url = fix_dirty_url(url)?;
|
||||
|
||||
// 使用网络管理器发送请求
|
||||
let resp = match NetworkManager::new()
|
||||
.get_with_interrupt(url, proxy_type, Some(timeout), user_agent.clone(), accept_invalid_certs)
|
||||
.get_with_interrupt(
|
||||
url.as_str(),
|
||||
proxy_type,
|
||||
Some(timeout),
|
||||
user_agent.clone(),
|
||||
accept_invalid_certs,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
@@ -337,7 +351,9 @@ impl PrfItem {
|
||||
},
|
||||
}
|
||||
}
|
||||
None => Some(crate::utils::help::get_last_part_and_decode(url).unwrap_or_else(|| "Remote File".into())),
|
||||
None => {
|
||||
Some(crate::utils::help::get_last_part_and_decode(url.as_str()).unwrap_or_else(|| "Remote File".into()))
|
||||
}
|
||||
};
|
||||
let update_interval = match update_interval {
|
||||
Some(val) => Some(val),
|
||||
@@ -407,7 +423,7 @@ impl PrfItem {
|
||||
name: Some(name),
|
||||
desc: desc.cloned(),
|
||||
file: Some(file),
|
||||
url: Some(url.into()),
|
||||
url: Some(url.as_str().into()),
|
||||
selected: None,
|
||||
extra,
|
||||
option: Some(PrfOption {
|
||||
@@ -566,3 +582,32 @@ impl PrfItem {
|
||||
const fn default_allow_auto_update() -> Option<bool> {
|
||||
Some(true)
|
||||
}
|
||||
|
||||
/// Fix URLs where query parameters are incorrectly appended to the path segment
|
||||
///
|
||||
/// Incorrect Example: https://example.com/path¶m1=value1
|
||||
fn fix_dirty_url(input: &str) -> Result<Url> {
|
||||
let mut url = match Url::parse(input) {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"failed to parse deep link url: {:?}, input: {:?}",
|
||||
e,
|
||||
input
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
if url.query().is_none() && url.path().contains('&') {
|
||||
let path = url.path().to_string();
|
||||
|
||||
if let Some((clean_path, dirty_params)) = path.split_once('&') {
|
||||
url.set_path(clean_path);
|
||||
|
||||
url.query_pairs_mut()
|
||||
.extend_pairs(form_urlencoded::parse(dirty_params.as_bytes()));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
+261
-242
@@ -5,16 +5,12 @@ use crate::utils::{
|
||||
};
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use once_cell::sync::OnceCell;
|
||||
use regex::Regex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use smartstring::alias::String;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use tokio::fs;
|
||||
|
||||
static PROFILE_FILE_RE: OnceCell<Regex> = OnceCell::new();
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct IProfiles {
|
||||
@@ -35,21 +31,25 @@ pub struct IProfilePreview<'a> {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CleanupResult {
|
||||
pub total_files: usize,
|
||||
pub deleted_files: Vec<String>,
|
||||
pub failed_deletions: Vec<String>,
|
||||
pub deleted_files: usize,
|
||||
pub failed_deletions: usize,
|
||||
}
|
||||
|
||||
macro_rules! patch {
|
||||
($lv: expr, $rv: expr, $key: tt) => {
|
||||
if let Some(ref val) = $rv.$key {
|
||||
if Some(val) != $lv.$key.as_ref() {
|
||||
$lv.$key = Some(val.to_owned());
|
||||
}
|
||||
if ($rv.$key).is_some() {
|
||||
$lv.$key = $rv.$key.to_owned();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl IProfiles {
|
||||
// Helper to find and remove an item by uid from the items vec, returning its file name (if any).
|
||||
fn take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
|
||||
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
|
||||
items.remove(index).file
|
||||
}
|
||||
|
||||
pub async fn new() -> Self {
|
||||
let path = match dirs::profiles_path() {
|
||||
Ok(p) => p,
|
||||
@@ -59,22 +59,21 @@ impl IProfiles {
|
||||
}
|
||||
};
|
||||
|
||||
let mut profiles = match help::read_yaml::<Self>(&path).await {
|
||||
Ok(profiles) => profiles,
|
||||
match help::read_yaml::<Self>(&path).await {
|
||||
Ok(mut profiles) => {
|
||||
let items = profiles.items.get_or_insert_with(Vec::new);
|
||||
for item in items.iter_mut() {
|
||||
if item.uid.is_none() {
|
||||
item.uid = Some(help::get_uid("d").into());
|
||||
}
|
||||
}
|
||||
profiles
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Config, "{err}");
|
||||
return Self::default();
|
||||
}
|
||||
};
|
||||
|
||||
let items = profiles.items.get_or_insert_with(Vec::new);
|
||||
for item in items.iter_mut() {
|
||||
if item.uid.is_none() {
|
||||
item.uid = Some(help::get_uid("d").into());
|
||||
Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
profiles
|
||||
}
|
||||
|
||||
pub async fn save_file(&self) -> Result<()> {
|
||||
@@ -110,28 +109,38 @@ impl IProfiles {
|
||||
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem> {
|
||||
let uid_str = uid.as_ref();
|
||||
|
||||
self.items
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("no profile items found"))?
|
||||
.iter()
|
||||
.find(|each| each.uid.as_ref().is_some_and(|uid_val| uid_val.as_str() == uid_str))
|
||||
.ok_or_else(|| anyhow::anyhow!("failed to get the profile item \"uid:{}\"", uid_str))
|
||||
if let Some(items) = self.items.as_ref() {
|
||||
for each in items.iter() {
|
||||
if let Some(uid_val) = &each.uid
|
||||
&& uid_val.as_str() == uid_str
|
||||
{
|
||||
return Ok(each);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bail!("failed to get the profile item \"uid:{}\"", uid_str);
|
||||
}
|
||||
|
||||
/// append new item
|
||||
/// if the file_data is some
|
||||
/// then should save the data to file
|
||||
pub async fn append_item(&mut self, item: &mut PrfItem) -> Result<()> {
|
||||
anyhow::ensure!(item.uid.is_some(), "the uid should not be null");
|
||||
let uid = &item.uid;
|
||||
if uid.is_none() {
|
||||
bail!("the uid should not be null");
|
||||
}
|
||||
|
||||
// save the file data
|
||||
// move the field value after save
|
||||
if let Some(file_data) = item.file_data.take() {
|
||||
anyhow::ensure!(item.file.is_some(), "the file should not be null");
|
||||
if item.file.is_none() {
|
||||
bail!("the file should not be null");
|
||||
}
|
||||
|
||||
let file = item
|
||||
.file
|
||||
.as_ref()
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?;
|
||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
|
||||
@@ -140,116 +149,111 @@ impl IProfiles {
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
}
|
||||
|
||||
if self.current.is_none()
|
||||
&& let Some(t) = item.itype.as_deref()
|
||||
&& (t == "remote" || t == "local")
|
||||
{
|
||||
self.current = item.uid.to_owned();
|
||||
if self.current.is_none() && (item.itype == Some("remote".into()) || item.itype == Some("local".into())) {
|
||||
self.current = uid.to_owned();
|
||||
}
|
||||
|
||||
self.items.get_or_insert_default().push(std::mem::take(item));
|
||||
if self.items.is_none() {
|
||||
self.items = Some(vec![]);
|
||||
}
|
||||
|
||||
if let Some(items) = self.items.as_mut() {
|
||||
items.push(item.to_owned());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// reorder items
|
||||
pub async fn reorder(&mut self, active_id: &str, over_id: &str) -> Result<()> {
|
||||
if active_id == over_id {
|
||||
return Ok(());
|
||||
pub async 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.as_ref() == Some(active_id) {
|
||||
old_index = Some(i);
|
||||
}
|
||||
if items[i].uid.as_ref() == Some(over_id) {
|
||||
new_index = Some(i);
|
||||
}
|
||||
}
|
||||
|
||||
let Some(items) = self.items.as_mut() else {
|
||||
return Ok(());
|
||||
let (old_idx, new_idx) = match (old_index, new_index) {
|
||||
(Some(old), Some(new)) => (old, new),
|
||||
_ => return Ok(()),
|
||||
};
|
||||
|
||||
let mut old_idx = None;
|
||||
let mut new_idx = None;
|
||||
|
||||
for (i, item) in items.iter().enumerate() {
|
||||
if let Some(uid) = item.uid.as_ref() {
|
||||
if uid == active_id {
|
||||
old_idx = Some(i);
|
||||
}
|
||||
if uid == over_id {
|
||||
new_idx = Some(i);
|
||||
}
|
||||
}
|
||||
if old_idx.is_some() && new_idx.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if let (Some(old), Some(new)) = (old_idx, new_idx) {
|
||||
if old < new {
|
||||
items[old..=new].rotate_left(1);
|
||||
} else {
|
||||
items[new..=old].rotate_right(1);
|
||||
}
|
||||
|
||||
return self.save_file().await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
let item = items.remove(old_idx);
|
||||
items.insert(new_idx, item);
|
||||
self.items = Some(items);
|
||||
self.save_file().await
|
||||
}
|
||||
|
||||
/// update the item value
|
||||
pub async fn patch_item(&mut self, uid: &String, item: &PrfItem) -> Result<()> {
|
||||
let items = self
|
||||
.items
|
||||
.as_mut()
|
||||
.ok_or_else(|| anyhow::anyhow!("no profile items found"))?;
|
||||
let mut items = self.items.take().unwrap_or_default();
|
||||
|
||||
let target = items.iter_mut().find(|each| each.uid.as_ref() == Some(uid));
|
||||
for each in items.iter_mut() {
|
||||
if each.uid.as_ref() == Some(uid) {
|
||||
patch!(each, item, itype);
|
||||
patch!(each, item, name);
|
||||
patch!(each, item, desc);
|
||||
patch!(each, item, file);
|
||||
patch!(each, item, url);
|
||||
patch!(each, item, selected);
|
||||
patch!(each, item, extra);
|
||||
patch!(each, item, updated);
|
||||
patch!(each, item, option);
|
||||
|
||||
if let Some(each) = target {
|
||||
patch!(each, item, itype);
|
||||
patch!(each, item, name);
|
||||
patch!(each, item, desc);
|
||||
patch!(each, item, file);
|
||||
patch!(each, item, url);
|
||||
patch!(each, item, selected);
|
||||
patch!(each, item, extra);
|
||||
patch!(each, item, updated);
|
||||
patch!(each, item, option);
|
||||
|
||||
return self.save_file().await;
|
||||
self.items = Some(items);
|
||||
return self.save_file().await;
|
||||
}
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
bail!("failed to find the profile item \"uid:{uid}\"")
|
||||
}
|
||||
|
||||
/// be used to update the remote item
|
||||
/// only patch `updated` `extra` `file_data`
|
||||
pub async fn update_item(&mut self, uid: &String, item: &mut PrfItem) -> Result<()> {
|
||||
let target = self
|
||||
.items
|
||||
.get_or_insert_default()
|
||||
.iter_mut()
|
||||
.find(|each| each.uid.as_ref() == Some(uid))
|
||||
.ok_or_else(|| anyhow::anyhow!("Item not found"))?;
|
||||
if self.items.is_none() {
|
||||
self.items = Some(vec![]);
|
||||
}
|
||||
|
||||
target.extra = item.extra;
|
||||
target.updated = item.updated;
|
||||
target.home = std::mem::take(&mut item.home);
|
||||
target.option = PrfOption::merge(target.option.as_ref(), item.option.as_ref());
|
||||
// find the item
|
||||
let _ = self.get_item(uid)?;
|
||||
|
||||
let Some(file_data) = item.file_data.take() else {
|
||||
return self.save_file().await;
|
||||
};
|
||||
if let Some(items) = self.items.as_mut() {
|
||||
let some_uid = Some(uid.clone());
|
||||
|
||||
let file = target
|
||||
.file
|
||||
.take()
|
||||
.or_else(|| item.file.take())
|
||||
.unwrap_or_else(|| format!("{}.yaml", uid).into());
|
||||
for each in items.iter_mut() {
|
||||
if each.uid == some_uid {
|
||||
each.extra = item.extra;
|
||||
each.updated = item.updated;
|
||||
each.home = item.home.to_owned();
|
||||
each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref());
|
||||
// save the file data
|
||||
// move the field value after save
|
||||
if let Some(file_data) = item.file_data.take() {
|
||||
let file = each.file.take();
|
||||
let file =
|
||||
file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", &uid).into()));
|
||||
|
||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
// the file must exists
|
||||
each.file = Some(file.clone());
|
||||
|
||||
fs::write(&path, file_data.as_bytes())
|
||||
.await
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
|
||||
target.file = Some(file);
|
||||
fs::write(&path, file_data.as_bytes())
|
||||
.await
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.save_file().await
|
||||
}
|
||||
@@ -257,82 +261,73 @@ impl IProfiles {
|
||||
/// delete item
|
||||
/// if delete the current then return true
|
||||
pub async fn delete_item(&mut self, uid: &String) -> Result<bool> {
|
||||
let uids_to_remove: HashSet<String> = {
|
||||
let current = self.current.as_ref().unwrap_or(uid);
|
||||
let current = current.clone();
|
||||
let (merge_uid, script_uid, rules_uid, proxies_uid, groups_uid) = {
|
||||
let item = self.get_item(uid)?;
|
||||
let mut set = HashSet::new();
|
||||
set.insert(uid.clone());
|
||||
|
||||
if let Some(opt) = &item.option {
|
||||
if let Some(u) = &opt.merge {
|
||||
set.insert(u.clone());
|
||||
}
|
||||
if let Some(u) = &opt.script {
|
||||
set.insert(u.clone());
|
||||
}
|
||||
if let Some(u) = &opt.rules {
|
||||
set.insert(u.clone());
|
||||
}
|
||||
if let Some(u) = &opt.proxies {
|
||||
set.insert(u.clone());
|
||||
}
|
||||
if let Some(u) = &opt.groups {
|
||||
set.insert(u.clone());
|
||||
}
|
||||
}
|
||||
set
|
||||
let option = item.option.as_ref();
|
||||
(
|
||||
option.and_then(|e| e.merge.clone()),
|
||||
option.and_then(|e| e.script.clone()),
|
||||
option.and_then(|e| e.rules.clone()),
|
||||
option.and_then(|e| e.proxies.clone()),
|
||||
option.and_then(|e| e.groups.clone()),
|
||||
)
|
||||
};
|
||||
|
||||
let mut items = self.items.take().unwrap_or_default();
|
||||
let mut deleted_files = Vec::new();
|
||||
|
||||
items.retain_mut(|item| {
|
||||
if let Some(item_uid) = item.uid.as_ref()
|
||||
&& uids_to_remove.contains(item_uid)
|
||||
{
|
||||
if let Some(file) = item.file.take() {
|
||||
deleted_files.push(file);
|
||||
// remove the main item (if exists) and delete its file
|
||||
if let Some(file) = Self::take_item_file_by_uid(&mut items, Some(uid.as_str())) {
|
||||
let _ = dirs::app_profiles_dir()?.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
|
||||
// remove related extension items (merge, script, rules, proxies, groups)
|
||||
if let Some(file) = Self::take_item_file_by_uid(&mut items, merge_uid.as_deref()) {
|
||||
let _ = dirs::app_profiles_dir()?.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
if let Some(file) = Self::take_item_file_by_uid(&mut items, script_uid.as_deref()) {
|
||||
let _ = dirs::app_profiles_dir()?.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
if let Some(file) = Self::take_item_file_by_uid(&mut items, rules_uid.as_deref()) {
|
||||
let _ = dirs::app_profiles_dir()?.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
if let Some(file) = Self::take_item_file_by_uid(&mut items, proxies_uid.as_deref()) {
|
||||
let _ = dirs::app_profiles_dir()?.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
if let Some(file) = Self::take_item_file_by_uid(&mut items, groups_uid.as_deref()) {
|
||||
let _ = dirs::app_profiles_dir()?.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
// delete the original uid
|
||||
if current == *uid {
|
||||
self.current = None;
|
||||
for item in items.iter() {
|
||||
if item.itype == Some("remote".into()) || item.itype == Some("local".into()) {
|
||||
self.current = item.uid.clone();
|
||||
break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
|
||||
let is_deleting_current = self.current.as_ref() == Some(uid);
|
||||
if is_deleting_current {
|
||||
self.current = items
|
||||
.iter()
|
||||
.find(|i| i.itype.as_deref() == Some("remote") || i.itype.as_deref() == Some("local"))
|
||||
.and_then(|i| i.uid.clone());
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
|
||||
if let Ok(profile_dir) = dirs::app_profiles_dir() {
|
||||
for file in deleted_files {
|
||||
let _ = profile_dir.join(file.as_str()).remove_if_exists().await;
|
||||
}
|
||||
}
|
||||
|
||||
self.save_file().await?;
|
||||
Ok(is_deleting_current)
|
||||
Ok(current == *uid)
|
||||
}
|
||||
|
||||
/// 获取current指向的订阅内容
|
||||
pub async fn current_mapping(&self) -> Result<Mapping> {
|
||||
let (Some(current), Some(items)) = (self.current.as_ref(), self.items.as_ref()) else {
|
||||
return Ok(Mapping::new());
|
||||
};
|
||||
|
||||
let Some(target) = items.iter().find(|e| e.uid.as_ref() == Some(current)) else {
|
||||
bail!("failed to find the current profile \"uid:{current}\"");
|
||||
};
|
||||
|
||||
let file = target
|
||||
.file
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("failed to get the file field"))?;
|
||||
let file_path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
help::read_mapping(&file_path).await
|
||||
match (self.current.as_ref(), self.items.as_ref()) {
|
||||
(Some(current), Some(items)) => {
|
||||
if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) {
|
||||
let file_path = match item.file.as_ref() {
|
||||
Some(file) => dirs::app_profiles_dir()?.join(file.as_str()),
|
||||
None => bail!("failed to get the file field"),
|
||||
};
|
||||
return help::read_mapping(&file_path).await;
|
||||
}
|
||||
bail!("failed to find the current profile \"uid:{current}\"");
|
||||
}
|
||||
_ => Ok(Mapping::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断profile是否是current指向的
|
||||
@@ -342,44 +337,40 @@ impl IProfiles {
|
||||
|
||||
/// 获取所有的profiles(uid,名称, 是否为 current)
|
||||
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
|
||||
let items = self.items.as_ref()?;
|
||||
let current_uid = self.current.as_ref();
|
||||
|
||||
let previews = items
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
let uid = e.uid.as_ref()?;
|
||||
let name = e.name.as_ref()?;
|
||||
Some(IProfilePreview {
|
||||
uid,
|
||||
name,
|
||||
is_current: current_uid == Some(uid),
|
||||
self.items.as_ref().map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
|
||||
let is_current = self.is_current_profile_index(uid);
|
||||
let preview = IProfilePreview { uid, name, is_current };
|
||||
Some(preview)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(previews)
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
/// 通过 uid 获取名称
|
||||
pub fn get_name_by_uid(&self, uid: &str) -> Option<&String> {
|
||||
self.items
|
||||
.as_ref()?
|
||||
.iter()
|
||||
.find(|item| item.uid.as_deref() == Some(uid))
|
||||
.and_then(|item| item.name.as_ref())
|
||||
pub fn get_name_by_uid(&self, uid: &String) -> Option<&String> {
|
||||
if let Some(items) = &self.items {
|
||||
for item in items {
|
||||
if item.uid.as_ref() == Some(uid) {
|
||||
return item.name.as_ref();
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 以 app 中的 profile 列表为准,删除不再需要的文件
|
||||
pub async fn cleanup_orphaned_files(&self) -> Result<CleanupResult> {
|
||||
pub async fn cleanup_orphaned_files(&self) -> Result<()> {
|
||||
let profiles_dir = dirs::app_profiles_dir()?;
|
||||
|
||||
if !profiles_dir.exists() {
|
||||
return Ok(CleanupResult {
|
||||
total_files: 0,
|
||||
deleted_files: vec![],
|
||||
failed_deletions: vec![],
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 获取所有 active profile 的文件名集合
|
||||
@@ -390,11 +381,11 @@ impl IProfiles {
|
||||
|
||||
// 扫描 profiles 目录下的所有文件
|
||||
let mut total_files = 0;
|
||||
let mut deleted_files = vec![];
|
||||
let mut failed_deletions = vec![];
|
||||
let mut deleted_files = 0;
|
||||
let mut failed_deletions = 0;
|
||||
|
||||
for entry in std::fs::read_dir(&profiles_dir)? {
|
||||
let entry = entry?;
|
||||
let mut dir_entries = tokio::fs::read_dir(&profiles_dir).await?;
|
||||
while let Some(entry) = dir_entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
|
||||
if !path.is_file() {
|
||||
@@ -416,11 +407,11 @@ impl IProfiles {
|
||||
if !active_files.contains(file_name) {
|
||||
match path.to_path_buf().remove_if_exists().await {
|
||||
Ok(_) => {
|
||||
deleted_files.push(file_name.into());
|
||||
deleted_files += 1;
|
||||
logging!(debug, Type::Config, "已清理冗余文件: {file_name}");
|
||||
}
|
||||
Err(e) => {
|
||||
failed_deletions.push(format!("{file_name}: {e}").into());
|
||||
failed_deletions += 1;
|
||||
logging!(warn, Type::Config, "Warning: 清理文件失败: {file_name} - {e}");
|
||||
}
|
||||
}
|
||||
@@ -439,11 +430,11 @@ impl IProfiles {
|
||||
Type::Config,
|
||||
"Profile 文件清理完成: 总文件数={}, 删除文件数={}, 失败数={}",
|
||||
result.total_files,
|
||||
result.deleted_files.len(),
|
||||
result.failed_deletions.len()
|
||||
result.deleted_files,
|
||||
result.failed_deletions
|
||||
);
|
||||
|
||||
Ok(result)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 不删除全局扩展配置
|
||||
@@ -458,39 +449,59 @@ impl IProfiles {
|
||||
|
||||
/// 获取所有 active profile 关联的文件名
|
||||
fn get_all_active_files(&self) -> HashSet<&str> {
|
||||
let mut active_files = HashSet::new();
|
||||
let items = match &self.items {
|
||||
Some(i) => i,
|
||||
None => return active_files,
|
||||
};
|
||||
let mut active_files: HashSet<&str> = HashSet::new();
|
||||
|
||||
let item_map: HashMap<Option<&str>, &PrfItem> = items.iter().map(|i| (i.uid.as_deref(), i)).collect();
|
||||
if let Some(items) = &self.items {
|
||||
for item in items {
|
||||
// 收集所有类型 profile 的文件
|
||||
if let Some(file) = &item.file {
|
||||
active_files.insert(file);
|
||||
}
|
||||
|
||||
for item in items {
|
||||
if let Some(f) = &item.file {
|
||||
active_files.insert(f.as_str());
|
||||
}
|
||||
|
||||
let Some(opt) = &item.option else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let related = [
|
||||
opt.merge.as_deref(),
|
||||
opt.script.as_deref(),
|
||||
opt.rules.as_deref(),
|
||||
opt.proxies.as_deref(),
|
||||
opt.groups.as_deref(),
|
||||
];
|
||||
|
||||
for r_uid in related.into_iter().flatten() {
|
||||
if let Some(r_item) = item_map.get(&Some(r_uid))
|
||||
&& let Some(f) = &r_item.file
|
||||
// 对于主 profile 类型(remote/local),还需要收集其关联的扩展文件
|
||||
if let Some(itype) = &item.itype
|
||||
&& (itype == "remote" || itype == "local")
|
||||
&& let Some(option) = &item.option
|
||||
{
|
||||
active_files.insert(f.as_str());
|
||||
// 收集关联的扩展文件
|
||||
if let Some(merge_uid) = &option.merge
|
||||
&& let Ok(merge_item) = self.get_item(merge_uid)
|
||||
&& let Some(file) = &merge_item.file
|
||||
{
|
||||
active_files.insert(file);
|
||||
}
|
||||
|
||||
if let Some(script_uid) = &option.script
|
||||
&& let Ok(script_item) = self.get_item(script_uid)
|
||||
&& let Some(file) = &script_item.file
|
||||
{
|
||||
active_files.insert(file);
|
||||
}
|
||||
|
||||
if let Some(rules_uid) = &option.rules
|
||||
&& let Ok(rules_item) = self.get_item(rules_uid)
|
||||
&& let Some(file) = &rules_item.file
|
||||
{
|
||||
active_files.insert(file);
|
||||
}
|
||||
|
||||
if let Some(proxies_uid) = &option.proxies
|
||||
&& let Ok(proxies_item) = self.get_item(proxies_uid)
|
||||
&& let Some(file) = &proxies_item.file
|
||||
{
|
||||
active_files.insert(file);
|
||||
}
|
||||
|
||||
if let Some(groups_uid) = &option.groups
|
||||
&& let Ok(groups_item) = self.get_item(groups_uid)
|
||||
&& let Some(file) = &groups_item.file
|
||||
{
|
||||
active_files.insert(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
active_files
|
||||
}
|
||||
|
||||
@@ -505,10 +516,18 @@ impl IProfiles {
|
||||
// p12345678.yaml (proxies)
|
||||
// g12345678.yaml (groups)
|
||||
|
||||
#[allow(clippy::unwrap_used)]
|
||||
let re = PROFILE_FILE_RE
|
||||
.get_or_init(|| Regex::new(r"^(?:[RLmprg][a-zA-Z0-9_-]+\.yaml|s[a-zA-Z0-9_-]+\.js)$").unwrap());
|
||||
re.is_match(filename)
|
||||
let patterns = [
|
||||
r"^[RL][a-zA-Z0-9]+\.yaml$", // Remote/Local profiles
|
||||
r"^m[a-zA-Z0-9]+\.yaml$", // Merge files
|
||||
r"^s[a-zA-Z0-9]+\.js$", // Script files
|
||||
r"^[rpg][a-zA-Z0-9]+\.yaml$", // Rules/Proxies/Groups files
|
||||
];
|
||||
|
||||
patterns.iter().any(|pattern| {
|
||||
regex::Regex::new(pattern)
|
||||
.map(|re| re.is_match(filename))
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ use serde_yaml_ng::{Mapping, Value};
|
||||
use smartstring::alias::String;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const PATCH_CONFIG_INNER: [&str; 4] = ["allow-lan", "ipv6", "log-level", "unified-delay"];
|
||||
use crate::enhance::field::use_keys;
|
||||
|
||||
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct IRuntime {
|
||||
@@ -20,7 +22,7 @@ impl IRuntime {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
// 这里只更改 allow-lan | ipv6 | log-level | tun
|
||||
// 这里只更改 allow-lan | ipv6 | log-level | tun | tunnels
|
||||
#[inline]
|
||||
pub fn patch_config(&mut self, patch: &Mapping) {
|
||||
let config = if let Some(config) = self.config.as_mut() {
|
||||
@@ -136,13 +138,3 @@ impl IRuntime {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO 完整迁移 enhance 行为后移除
|
||||
#[inline]
|
||||
fn use_keys<'a>(config: &'a Mapping) -> impl Iterator<Item = String> + 'a {
|
||||
config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| {
|
||||
let mut s: String = s.into();
|
||||
s.make_ascii_lowercase();
|
||||
s
|
||||
})
|
||||
}
|
||||
@@ -155,6 +155,9 @@ pub struct IVerge {
|
||||
/// 是否自动检测当前节点延迟
|
||||
pub enable_auto_delay_detection: Option<bool>,
|
||||
|
||||
/// 自动检测当前节点延迟的间隔(分钟)
|
||||
pub auto_delay_detection_interval_minutes: Option<u64>,
|
||||
|
||||
/// 是否使用内部的脚本支持,默认为真
|
||||
pub enable_builtin_enhanced: Option<bool>,
|
||||
|
||||
@@ -523,6 +526,7 @@ impl IVerge {
|
||||
patch!(default_latency_test);
|
||||
patch!(default_latency_timeout);
|
||||
patch!(enable_auto_delay_detection);
|
||||
patch!(auto_delay_detection_interval_minutes);
|
||||
patch!(enable_builtin_enhanced);
|
||||
patch!(proxy_layout_column);
|
||||
patch!(test_list);
|
||||
|
||||
@@ -14,7 +14,6 @@ use std::{
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
use tauri_plugin_http::reqwest as tauri_reqwest;
|
||||
use tokio::{fs, time::timeout};
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
@@ -111,12 +110,12 @@ impl WebDavClient {
|
||||
// 创建新的客户端
|
||||
let client = reqwest_dav::ClientBuilder::new()
|
||||
.set_agent(
|
||||
tauri_reqwest::Client::builder()
|
||||
reqwest::Client::builder()
|
||||
.use_rustls_tls()
|
||||
.danger_accept_invalid_certs(true)
|
||||
.timeout(Duration::from_secs(op.timeout()))
|
||||
.user_agent(format!("clash-verge/{APP_VERSION} ({OS} WebDAV-Client)"))
|
||||
.redirect(tauri_reqwest::redirect::Policy::custom(|attempt| {
|
||||
.redirect(reqwest::redirect::Policy::custom(|attempt| {
|
||||
// 允许所有请求类型的重定向,包括PUT
|
||||
if attempt.previous().len() >= 5 {
|
||||
attempt.error("重定向次数过多")
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use tauri::{AppHandle, Manager as _, WebviewWindow};
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
|
||||
use tokio::sync::RwLockReadGuard;
|
||||
|
||||
@@ -55,10 +55,6 @@ impl Handle {
|
||||
Self::app_handle().mihomo().read().await
|
||||
}
|
||||
|
||||
pub fn get_window() -> Option<WebviewWindow> {
|
||||
Self::app_handle().get_webview_window("main")
|
||||
}
|
||||
|
||||
pub fn refresh_clash() {
|
||||
let handle = Self::global();
|
||||
if handle.is_exiting() {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::process::AsyncHandler;
|
||||
use crate::singleton;
|
||||
use crate::utils::notification::{NotificationEvent, notify_event};
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{config::Config, core::handle, feat, module::lightweight::entry_lightweight_mode};
|
||||
use anyhow::{Result, bail};
|
||||
use arc_swap::ArcSwap;
|
||||
@@ -243,7 +244,7 @@ impl Hotkey {
|
||||
logging!(debug, Type::Hotkey, "Hotkey pressed: {:?}", hotkey_event);
|
||||
let hotkey = hotkey_event.key;
|
||||
if hotkey == Code::KeyQ && is_quit {
|
||||
if let Some(window) = handle::Handle::get_window()
|
||||
if let Some(window) = WindowManager::get_main_window()
|
||||
&& window.is_focused().unwrap_or(false)
|
||||
{
|
||||
logging!(debug, Type::Hotkey, "Executing quit function");
|
||||
@@ -260,8 +261,9 @@ impl Hotkey {
|
||||
Self::execute_function(function);
|
||||
} else {
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
let is_visible = WindowManager::is_main_window_visible();
|
||||
let is_focused = WindowManager::is_main_window_focused();
|
||||
let window = WindowManager::get_main_window();
|
||||
let is_visible = WindowManager::is_main_window_visible(window.as_ref());
|
||||
let is_focused = WindowManager::is_main_window_focused(window.as_ref());
|
||||
|
||||
if is_focused && is_visible {
|
||||
Self::execute_function(function);
|
||||
|
||||
@@ -68,6 +68,7 @@ impl Logger {
|
||||
self.log_max_size.store(log_max_size, Ordering::SeqCst);
|
||||
self.log_max_count.store(log_max_count, Ordering::SeqCst);
|
||||
|
||||
#[cfg(not(feature = "tokio-trace"))]
|
||||
#[cfg(not(feature = "tauri-dev"))]
|
||||
{
|
||||
let log_spec = Self::generate_log_spec(log_level);
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
use super::CoreManager;
|
||||
use crate::{
|
||||
config::{Config, ConfigType},
|
||||
config::{Config, ConfigType, runtime::IRuntime},
|
||||
constants::timing,
|
||||
core::{handle, validate::CoreConfigValidator},
|
||||
utils::{dirs, help},
|
||||
};
|
||||
use anyhow::{Result, anyhow};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_types::runtime::IRuntime;
|
||||
use smartstring::alias::String;
|
||||
use std::{collections::HashSet, path::PathBuf, time::Instant};
|
||||
use tauri_plugin_mihomo::Error as MihomoError;
|
||||
|
||||
@@ -64,7 +64,7 @@ impl CoreManager {
|
||||
match event {
|
||||
tauri_plugin_shell::process::CommandEvent::Stdout(line)
|
||||
| tauri_plugin_shell::process::CommandEvent::Stderr(line) => {
|
||||
let message = CompactString::from(String::from_utf8_lossy(&line).as_ref());
|
||||
let message = CompactString::from(&*String::from_utf8_lossy(&line));
|
||||
Logger::global().writer_sidecar_log(Level::Error, &message);
|
||||
CLASH_LOGGER.append_log(message).await;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::handle::Handle;
|
||||
use crate::constants::timing;
|
||||
use crate::{constants::timing, utils::window_manager::WindowManager};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use smartstring::alias::String;
|
||||
use std::{sync::mpsc, thread};
|
||||
@@ -84,7 +84,7 @@ impl NotificationSystem {
|
||||
None => return,
|
||||
};
|
||||
|
||||
if let Some(window) = super::handle::Handle::get_window() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
system.emit_to_window(&window, event);
|
||||
drop(binding);
|
||||
thread::sleep(timing::EVENT_EMIT_DELAY);
|
||||
|
||||
+112
-41
@@ -3,18 +3,19 @@ use crate::{
|
||||
core::{logger::Logger, tray::Tray},
|
||||
utils::dirs,
|
||||
};
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use anyhow::{Context as _, Result, anyhow, bail};
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_service_ipc::CoreConfig;
|
||||
use compact_str::CompactString;
|
||||
use once_cell::sync::Lazy;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
env::current_exe,
|
||||
path::{Path, PathBuf},
|
||||
process::Command as StdCommand,
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::{sync::Mutex, time::sleep};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ServiceStatus {
|
||||
@@ -64,6 +65,7 @@ fn uninstall_service() -> Result<()> {
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn install_service() -> Result<()> {
|
||||
use std::process::Output;
|
||||
logging!(info, Type::Service, "install service");
|
||||
|
||||
use deelevate::{PrivilegeLevel, Token};
|
||||
@@ -79,13 +81,30 @@ fn install_service() -> Result<()> {
|
||||
|
||||
let token = Token::with_current_process()?;
|
||||
let level = token.privilege_level()?;
|
||||
let status = match level {
|
||||
PrivilegeLevel::NotPrivileged => RunasCommand::new(install_path).show(false).status()?,
|
||||
_ => StdCommand::new(install_path).creation_flags(0x08000000).status()?,
|
||||
let output = match level {
|
||||
PrivilegeLevel::NotPrivileged => {
|
||||
let status = RunasCommand::new(&install_path).show(false).status()?;
|
||||
Output {
|
||||
status,
|
||||
stdout: Vec::new(),
|
||||
stderr: Vec::new(),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// StdCommand returns Output directly
|
||||
StdCommand::new(&install_path).creation_flags(0x08000000).output()?
|
||||
}
|
||||
};
|
||||
|
||||
if !status.success() {
|
||||
bail!("failed to install service with status {}", status.code().unwrap_or(-1));
|
||||
if let Some((code, err)) = check_output_error(&output) {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"failed to install service code: {}, details: {}",
|
||||
code,
|
||||
err
|
||||
);
|
||||
bail!("failed to install service code: {}, details: {}", code, err);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -160,41 +179,42 @@ fn install_service() -> Result<()> {
|
||||
let install_shell: String = install_path.to_string_lossy().replace(" ", "\\ ");
|
||||
|
||||
let elevator = crate::utils::help::linux_elevator();
|
||||
let status = if linux_running_as_root() {
|
||||
StdCommand::new(&install_path).status()?
|
||||
let output = if linux_running_as_root() {
|
||||
StdCommand::new(&install_path).output()?
|
||||
} else {
|
||||
let result = StdCommand::new(&elevator)
|
||||
.arg("sh")
|
||||
.arg("-c")
|
||||
.arg(&install_shell)
|
||||
.status()?;
|
||||
.output()?;
|
||||
|
||||
// 如果 pkexec 执行失败,回退到 sudo
|
||||
if !result.success() && elevator.contains("pkexec") {
|
||||
if !result.status.success() && elevator.contains("pkexec") {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"pkexec failed with code {}, falling back to sudo",
|
||||
result.code().unwrap_or(-1)
|
||||
result.status.code().unwrap_or(-1)
|
||||
);
|
||||
StdCommand::new("sudo")
|
||||
.arg("sh")
|
||||
.arg("-c")
|
||||
.arg(&install_shell)
|
||||
.status()?
|
||||
.output()?
|
||||
} else {
|
||||
result
|
||||
}
|
||||
};
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"install status code:{}",
|
||||
status.code().unwrap_or(-1)
|
||||
);
|
||||
|
||||
if !status.success() {
|
||||
bail!("failed to install service with status {}", status.code().unwrap_or(-1));
|
||||
if let Some((code, err)) = check_output_error(&output) {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"failed to install service code: {}, details: {}",
|
||||
code,
|
||||
err
|
||||
);
|
||||
bail!("failed to install service code: {}, details: {}", code, err);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -256,19 +276,43 @@ fn install_service() -> Result<()> {
|
||||
|
||||
// clash_verge_i18n::sync_locale(Config::verge().await.latest_arc().language.as_deref());
|
||||
|
||||
let gid = tauri_plugin_clash_verge_sysinfo::current_gid();
|
||||
let prompt = clash_verge_i18n::t!("service.adminInstallPrompt");
|
||||
let command =
|
||||
format!(r#"do shell script "sudo '{install_shell}'" with administrator privileges with prompt "{prompt}""#);
|
||||
let command = format!(
|
||||
r#"do shell script "sudo CLASH_VERGE_SERVICE_GID={gid} '{install_shell}'" with administrator privileges with prompt "{prompt}""#
|
||||
);
|
||||
|
||||
let status = StdCommand::new("osascript").args(vec!["-e", &command]).status()?;
|
||||
|
||||
if !status.success() {
|
||||
bail!("failed to install service with status {}", status.code().unwrap_or(-1));
|
||||
let output = StdCommand::new("osascript").args(vec!["-e", &command]).output()?;
|
||||
if let Some((code, err)) = check_output_error(&output) {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"failed to install service code: {}, details: {}",
|
||||
code,
|
||||
err
|
||||
);
|
||||
bail!("failed to install service code: {}, details: {}", code, err);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn check_output_error(output: &std::process::Output) -> Option<(i32, Cow<'_, str>)> {
|
||||
if output.status.success() {
|
||||
return None;
|
||||
}
|
||||
let code = output.status.code().unwrap_or(-1);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.is_empty() {
|
||||
return Some((code, stderr));
|
||||
}
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if !stdout.is_empty() {
|
||||
return Some((code, stdout));
|
||||
}
|
||||
Some((code, Cow::Borrowed("Unknown error")))
|
||||
}
|
||||
|
||||
fn reinstall_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "reinstall service");
|
||||
|
||||
@@ -334,10 +378,7 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result
|
||||
pub(super) async fn run_core_by_service(config_file: &PathBuf) -> Result<()> {
|
||||
logging!(info, Type::Service, "正在尝试通过服务启动核心");
|
||||
|
||||
let mut manager = SERVICE_MANAGER.lock().await;
|
||||
let status = manager.check_service_comprehensive().await;
|
||||
manager.handle_service_status(&status).await?;
|
||||
drop(manager);
|
||||
SERVICE_MANAGER.lock().await.refresh().await?;
|
||||
|
||||
logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
|
||||
start_with_existing_service(config_file).await
|
||||
@@ -381,20 +422,50 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
/// 检查服务是否正在运行
|
||||
pub async fn is_service_available() -> Result<()> {
|
||||
if let Err(e) = Path::metadata(clash_verge_service_ipc::IPC_PATH.as_ref()) {
|
||||
logging!(warn, Type::Service, "Some issue with service IPC Path: {}", e);
|
||||
let verge = Config::verge().await;
|
||||
let verge_last = verge.latest_arc();
|
||||
let is_enable = verge_last.enable_tun_mode.unwrap_or(false);
|
||||
if is_enable {
|
||||
logging!(warn, Type::Service, "Some issue with service IPC Path: {}", e);
|
||||
}
|
||||
return Err(e.into());
|
||||
}
|
||||
clash_verge_service_ipc::connect().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 等待一会,再检查服务是否正在运行
|
||||
/// TODO 使用 tokio select 之类机制并结合 timeout 实现更优雅的等待机制,期望等待文件出现,再尝试连接
|
||||
pub async fn wait_and_check_service_available(status: &mut ServiceManager) -> Result<()> {
|
||||
status.0 = ServiceStatus::Unavailable("Waiting for service to be available".into());
|
||||
clash_verge_service_ipc::connect().await?;
|
||||
status.0 = ServiceStatus::Ready;
|
||||
Ok(())
|
||||
wait_for_service_ipc(status, "Waiting for service to be available").await
|
||||
}
|
||||
|
||||
async fn wait_for_service_ipc(status: &mut ServiceManager, reason: &str) -> Result<()> {
|
||||
status.0 = ServiceStatus::Unavailable(reason.into());
|
||||
let config = ServiceManager::config();
|
||||
let mut attempts = 0u32;
|
||||
#[allow(unused_assignments)]
|
||||
let mut last_err = anyhow!("service not ready");
|
||||
|
||||
loop {
|
||||
if Path::new(clash_verge_service_ipc::IPC_PATH).exists() {
|
||||
match clash_verge_service_ipc::connect().await {
|
||||
Ok(_) => {
|
||||
status.0 = ServiceStatus::Ready;
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last_err = e,
|
||||
}
|
||||
} else {
|
||||
last_err = anyhow!("IPC path not ready");
|
||||
}
|
||||
|
||||
if attempts >= config.max_retries as u32 {
|
||||
break;
|
||||
}
|
||||
attempts += 1;
|
||||
sleep(config.retry_delay).await;
|
||||
}
|
||||
|
||||
Err(last_err)
|
||||
}
|
||||
|
||||
pub fn is_service_ipc_path_exists() -> bool {
|
||||
@@ -408,9 +479,9 @@ impl ServiceManager {
|
||||
|
||||
pub const fn config() -> clash_verge_service_ipc::IpcConfig {
|
||||
clash_verge_service_ipc::IpcConfig {
|
||||
default_timeout: Duration::from_millis(100),
|
||||
retry_delay: Duration::from_millis(200),
|
||||
max_retries: 6,
|
||||
default_timeout: Duration::from_millis(150),
|
||||
retry_delay: Duration::from_millis(250),
|
||||
max_retries: 20,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ pub struct TimerTask {
|
||||
pub last_run: i64, // Timestamp of last execution
|
||||
}
|
||||
|
||||
// TODO 一个 Timer 负责轻量, 一个 Timer 负责订阅更新。当前会生产 N(订阅数量) + 1 个定时任务
|
||||
pub struct Timer {
|
||||
/// cron manager
|
||||
pub delay_timer: Arc<RwLock<DelayTimer>>,
|
||||
|
||||
@@ -55,7 +55,7 @@ pub(crate) enum TrayAction {
|
||||
SystemProxy,
|
||||
TunMode,
|
||||
MainWindow,
|
||||
TrayMenue,
|
||||
TrayMenu,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ impl From<&str> for TrayAction {
|
||||
"system_proxy" => Self::SystemProxy,
|
||||
"tun_mode" => Self::TunMode,
|
||||
"main_window" => Self::MainWindow,
|
||||
"tray_menue" => Self::TrayMenue,
|
||||
"tray_menu" => Self::TrayMenu,
|
||||
_ => Self::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
+121
-109
@@ -9,8 +9,9 @@ use crate::{
|
||||
Type, cmd, config::Config, feat, logging, module::lightweight::is_in_lightweight_mode,
|
||||
utils::dirs::find_target_icons,
|
||||
};
|
||||
use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
|
||||
use tauri::tray::TrayIconBuilder;
|
||||
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};
|
||||
use clash_verge_logging::logging_error;
|
||||
use tauri::tray::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
|
||||
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
|
||||
use tauri_plugin_mihomo::models::Proxies;
|
||||
use tokio::fs;
|
||||
@@ -19,12 +20,10 @@ use super::handle;
|
||||
use anyhow::Result;
|
||||
use smartstring::alias::String;
|
||||
use std::collections::HashMap;
|
||||
use std::num::NonZeroU32;
|
||||
use std::time::Duration;
|
||||
use tauri::{
|
||||
AppHandle, Wry,
|
||||
menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu},
|
||||
tray::{MouseButton, MouseButtonState, TrayIconEvent},
|
||||
};
|
||||
mod menu_def;
|
||||
use menu_def::{MenuIds, MenuTexts};
|
||||
@@ -33,13 +32,13 @@ use menu_def::{MenuIds, MenuTexts};
|
||||
|
||||
type ProxyMenuItem = (Option<Submenu<Wry>>, Vec<Box<dyn IsMenuItem<Wry>>>);
|
||||
|
||||
const TRAY_CLICK_DEBOUNCE_MS: u64 = 1_275;
|
||||
const TRAY_CLICK_DEBOUNCE_MS: u64 = 300;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TrayState {}
|
||||
|
||||
pub struct Tray {
|
||||
limiter: DefaultDirectRateLimiter,
|
||||
limiter: SystemLimiter,
|
||||
}
|
||||
|
||||
impl TrayState {
|
||||
@@ -136,11 +135,7 @@ impl Default for Tray {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
limiter: RateLimiter::direct(
|
||||
Quota::with_period(Duration::from_millis(TRAY_CLICK_DEBOUNCE_MS))
|
||||
.unwrap()
|
||||
.allow_burst(NonZeroU32::new(1).unwrap()),
|
||||
),
|
||||
limiter: Limiter::new(Duration::from_millis(TRAY_CLICK_DEBOUNCE_MS), SystemClock),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -190,7 +185,7 @@ impl Tray {
|
||||
.tray_by_id("main")
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to get main tray"))?;
|
||||
match tray_event {
|
||||
TrayAction::TrayMenue => tray.set_show_menu_on_left_click(true)?,
|
||||
TrayAction::TrayMenu => tray.set_show_menu_on_left_click(true)?,
|
||||
_ => tray.set_show_menu_on_left_click(false)?,
|
||||
}
|
||||
Ok(())
|
||||
@@ -207,6 +202,11 @@ impl Tray {
|
||||
}
|
||||
|
||||
async fn update_menu_internal(&self, app_handle: &AppHandle) -> Result<()> {
|
||||
let Some(tray) = app_handle.tray_by_id("main") else {
|
||||
logging!(warn, Type::Tray, "Failed to update tray menu: tray not found");
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
let system_proxy = verge.enable_system_proxy.as_ref().unwrap_or(&false);
|
||||
let tun_mode = verge.enable_tun_mode.as_ref().unwrap_or(&false);
|
||||
@@ -227,28 +227,24 @@ impl Tray {
|
||||
let profiles_preview = profiles_arc.profiles_preview().unwrap_or_default();
|
||||
let is_lightweight_mode = is_in_lightweight_mode();
|
||||
|
||||
match app_handle.tray_by_id("main") {
|
||||
Some(tray) => {
|
||||
let _ = tray.set_menu(Some(
|
||||
create_tray_menu(
|
||||
app_handle,
|
||||
Some(mode.as_str()),
|
||||
*system_proxy,
|
||||
*tun_mode,
|
||||
tun_mode_available,
|
||||
profiles_preview,
|
||||
is_lightweight_mode,
|
||||
)
|
||||
.await?,
|
||||
));
|
||||
logging!(debug, Type::Tray, "托盘菜单更新成功");
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
logging!(warn, Type::Tray, "Failed to update tray menu: tray not found");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
logging_error!(
|
||||
Type::Tray,
|
||||
tray.set_menu(Some(
|
||||
create_tray_menu(
|
||||
app_handle,
|
||||
Some(mode.as_str()),
|
||||
*system_proxy,
|
||||
*tun_mode,
|
||||
tun_mode_available,
|
||||
profiles_preview,
|
||||
is_lightweight_mode,
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
);
|
||||
|
||||
logging!(debug, Type::Tray, "托盘菜单更新成功");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 更新托盘图标
|
||||
@@ -261,12 +257,9 @@ impl Tray {
|
||||
|
||||
let app_handle = handle::Handle::app_handle();
|
||||
|
||||
let tray = match app_handle.tray_by_id("main") {
|
||||
Some(tray) => tray,
|
||||
None => {
|
||||
logging!(warn, Type::Tray, "Failed to update tray icon: tray not found");
|
||||
return Ok(());
|
||||
}
|
||||
let Some(tray) = app_handle.tray_by_id("main") else {
|
||||
logging!(warn, Type::Tray, "Failed to update tray icon: tray not found");
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let (_is_custom_icon, icon_bytes) = TrayState::get_tray_icon(verge).await;
|
||||
@@ -274,8 +267,11 @@ impl Tray {
|
||||
let colorful = verge.tray_icon.clone().unwrap_or_else(|| "monochrome".into());
|
||||
let is_colorful = colorful == "colorful";
|
||||
|
||||
let _ = tray.set_icon(Some(tauri::image::Image::from_bytes(&icon_bytes)?));
|
||||
let _ = tray.set_icon_as_template(!is_colorful);
|
||||
logging_error!(
|
||||
Type::Tray,
|
||||
tray.set_icon(Some(tauri::image::Image::from_bytes(&icon_bytes)?))
|
||||
);
|
||||
logging_error!(Type::Tray, tray.set_icon_as_template(!is_colorful));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -288,17 +284,17 @@ impl Tray {
|
||||
|
||||
let app_handle = handle::Handle::app_handle();
|
||||
|
||||
let tray = match app_handle.tray_by_id("main") {
|
||||
Some(tray) => tray,
|
||||
None => {
|
||||
logging!(warn, Type::Tray, "Failed to update tray icon: tray not found");
|
||||
return Ok(());
|
||||
}
|
||||
let Some(tray) = app_handle.tray_by_id("main") else {
|
||||
logging!(warn, Type::Tray, "Failed to update tray icon: tray not found");
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let (_is_custom_icon, icon_bytes) = TrayState::get_tray_icon(verge).await;
|
||||
|
||||
let _ = tray.set_icon(Some(tauri::image::Image::from_bytes(&icon_bytes)?));
|
||||
logging_error!(
|
||||
Type::Tray,
|
||||
tray.set_icon(Some(tauri::image::Image::from_bytes(&icon_bytes)?))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -312,14 +308,11 @@ impl Tray {
|
||||
let app_handle = handle::Handle::app_handle();
|
||||
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
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 system_proxy = verge.enable_system_proxy.unwrap_or(false);
|
||||
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
|
||||
|
||||
let switch_map = {
|
||||
let mut map = std::collections::HashMap::new();
|
||||
map.insert(true, "on");
|
||||
map.insert(false, "off");
|
||||
map
|
||||
let switch_str = |flag: bool| {
|
||||
if flag { "on" } else { "off" }
|
||||
};
|
||||
|
||||
let mut current_profile_name = "None".into();
|
||||
@@ -351,18 +344,19 @@ impl Tray {
|
||||
"Clash Verge {}\n{}: {}\n{}: {}\n{}: {}",
|
||||
reassembled_version,
|
||||
sys_proxy_text,
|
||||
switch_map[system_proxy],
|
||||
switch_str(system_proxy),
|
||||
tun_text,
|
||||
switch_map[tun_mode],
|
||||
switch_str(tun_mode),
|
||||
profile_text,
|
||||
current_profile_name
|
||||
);
|
||||
|
||||
if let Some(tray) = app_handle.tray_by_id("main") {
|
||||
let _ = tray.set_tooltip(Some(&tooltip));
|
||||
} else {
|
||||
let Some(tray) = app_handle.tray_by_id("main") else {
|
||||
logging!(warn, Type::Tray, "Failed to update tray tooltip: tray not found");
|
||||
}
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
logging_error!(Type::Tray, tray.set_tooltip(Some(&tooltip)));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -414,56 +408,17 @@ impl Tray {
|
||||
}
|
||||
|
||||
let tray = builder.build(app_handle)?;
|
||||
let tray_event = verge.tray_event.clone().unwrap_or_else(|| "main_window".into());
|
||||
let tray_action = TrayAction::from(tray_event.as_str());
|
||||
|
||||
tray.on_tray_icon_event(move |_app_handle, event| {
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Down,
|
||||
..
|
||||
} = event
|
||||
{
|
||||
// 添加防抖检查,防止快速连击
|
||||
#[allow(clippy::use_self)]
|
||||
if !Tray::global().should_handle_tray_click() {
|
||||
return;
|
||||
}
|
||||
logging!(debug, Type::Tray, "tray event: {tray_action:?}");
|
||||
match tray_action {
|
||||
TrayAction::SystemProxy => {
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let _ = feat::toggle_system_proxy().await;
|
||||
});
|
||||
}
|
||||
TrayAction::TunMode => {
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let _ = feat::toggle_tun_mode(None).await;
|
||||
});
|
||||
}
|
||||
TrayAction::MainWindow => {
|
||||
AsyncHandler::spawn(|| async move {
|
||||
if !lightweight::exit_lightweight_mode().await {
|
||||
WindowManager::show_main_window().await;
|
||||
};
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
logging!(warn, Type::Tray, "invalid tray event: {}", tray_event);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
tray.on_tray_icon_event(on_tray_icon_event);
|
||||
tray.on_menu_event(on_menu_event);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn should_handle_tray_click(&self) -> bool {
|
||||
let res = self.limiter.check().is_ok();
|
||||
if !res {
|
||||
let allow = self.limiter.check();
|
||||
if !allow {
|
||||
logging!(debug, Type::Tray, "tray click rate limited");
|
||||
}
|
||||
res
|
||||
allow
|
||||
}
|
||||
}
|
||||
|
||||
@@ -925,14 +880,68 @@ async fn create_tray_menu(
|
||||
Ok(menu)
|
||||
}
|
||||
|
||||
fn on_tray_icon_event(_tray_icon: &TrayIcon, tray_event: TrayIconEvent) {
|
||||
if matches!(
|
||||
tray_event,
|
||||
TrayIconEvent::Move { .. } | TrayIconEvent::Leave { .. } | TrayIconEvent::Enter { .. }
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let TrayIconEvent::Click {
|
||||
button: MouseButton::Left,
|
||||
button_state: MouseButtonState::Down,
|
||||
..
|
||||
} = tray_event
|
||||
{
|
||||
// 添加防抖检查,防止快速连击
|
||||
#[allow(clippy::use_self)]
|
||||
if !Tray::global().should_handle_tray_click() {
|
||||
return;
|
||||
}
|
||||
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let verge = Config::verge().await.data_arc();
|
||||
let verge_tray_event = verge.tray_event.clone().unwrap_or_else(|| "main_window".into());
|
||||
let verge_tray_action = TrayAction::from(verge_tray_event.as_str());
|
||||
logging!(debug, Type::Tray, "tray event: {verge_tray_action:?}");
|
||||
match verge_tray_action {
|
||||
TrayAction::SystemProxy => {
|
||||
let _ = feat::toggle_system_proxy().await;
|
||||
}
|
||||
TrayAction::TunMode => {
|
||||
let _ = feat::toggle_tun_mode(None).await;
|
||||
}
|
||||
TrayAction::MainWindow => {
|
||||
if !lightweight::exit_lightweight_mode().await {
|
||||
WindowManager::show_main_window().await;
|
||||
};
|
||||
}
|
||||
_ => {
|
||||
logging!(warn, Type::Tray, "invalid tray event: {}", verge_tray_event);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn on_menu_event(_: &AppHandle, event: MenuEvent) {
|
||||
if !Tray::global().should_handle_tray_click() {
|
||||
return;
|
||||
}
|
||||
if event.id.as_ref().is_empty() {
|
||||
return;
|
||||
}
|
||||
AsyncHandler::spawn(|| async move {
|
||||
match event.id.as_ref() {
|
||||
mode @ (MenuIds::RULE_MODE | MenuIds::GLOBAL_MODE | MenuIds::DIRECT_MODE) => {
|
||||
// Removing the the "tray_" prefix and "_mode" suffix
|
||||
let mode = &mode[5..mode.len() - 5];
|
||||
logging!(info, Type::ProxyMode, "Switch Proxy Mode To: {}", mode);
|
||||
feat::change_clash_mode(mode.into()).await;
|
||||
if let Some(stripped) = mode.strip_prefix("tray_")
|
||||
&& let Some(final_mode) = stripped.strip_suffix("_mode")
|
||||
{
|
||||
logging!(info, Type::ProxyMode, "Switch Proxy Mode To: {}", final_mode);
|
||||
feat::change_clash_mode(final_mode.into()).await;
|
||||
}
|
||||
}
|
||||
MenuIds::DASHBOARD => {
|
||||
logging!(info, Type::Tray, "托盘菜单点击: 打开窗口");
|
||||
@@ -980,7 +989,10 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
|
||||
feat::quit().await;
|
||||
}
|
||||
id if id.starts_with("profiles_") => {
|
||||
let profile_index = &id["profiles_".len()..];
|
||||
let profile_index = match id.strip_prefix("profiles_") {
|
||||
Some(index_str) => index_str,
|
||||
None => return,
|
||||
};
|
||||
feat::toggle_proxy_profile(profile_index.into()).await;
|
||||
}
|
||||
id if id.starts_with("proxy_") => {
|
||||
|
||||
@@ -61,14 +61,11 @@ pub fn use_sort(config: Mapping) -> Mapping {
|
||||
ret
|
||||
}
|
||||
|
||||
pub fn use_keys(config: &Mapping) -> Vec<String> {
|
||||
config
|
||||
.iter()
|
||||
.filter_map(|(key, _)| key.as_str())
|
||||
.map(|s: &str| {
|
||||
let mut s: String = s.into();
|
||||
s.make_ascii_lowercase();
|
||||
s
|
||||
})
|
||||
.collect()
|
||||
#[inline]
|
||||
pub fn use_keys<'a>(config: &'a Mapping) -> impl Iterator<Item = String> + 'a {
|
||||
config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| {
|
||||
let mut s: String = s.into();
|
||||
s.make_ascii_lowercase();
|
||||
s
|
||||
})
|
||||
}
|
||||
|
||||
@@ -310,7 +310,7 @@ fn process_global_items(
|
||||
profile_name: &String,
|
||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||
let mut result_map = HashMap::new();
|
||||
let mut exists_keys = use_keys(&config);
|
||||
let mut exists_keys = use_keys(&config).collect::<Vec<_>>();
|
||||
|
||||
if let ChainType::Merge(merge) = global_merge.data {
|
||||
exists_keys.extend(use_keys(&merge));
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
|
||||
{
|
||||
AsyncHandler::spawn(move || async move {
|
||||
crate::utils::resolve::dns::restore_public_dns().await;
|
||||
crate::utils::resolve::dns::set_public_dns("223.6.6.6".to_string()).await;
|
||||
crate::utils::resolve::dns::set_public_dns("114.114.114.114".to_string()).await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,7 +178,7 @@ pub async fn hide() {
|
||||
add_light_weight_timer().await;
|
||||
}
|
||||
|
||||
if let Some(window) = handle::Handle::get_window()
|
||||
if let Some(window) = WindowManager::get_main_window()
|
||||
&& window.is_visible().unwrap_or(false)
|
||||
{
|
||||
let _ = window.hide();
|
||||
|
||||
@@ -19,7 +19,6 @@ use crate::{
|
||||
use anyhow::Result;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Manager as _};
|
||||
#[cfg(target_os = "macos")]
|
||||
use tauri_plugin_autostart::MacosLauncher;
|
||||
@@ -61,11 +60,11 @@ mod app_init {
|
||||
.socket_path(crate::config::IClashTemp::guard_external_controller_ipc())
|
||||
.pool_config(
|
||||
tauri_plugin_mihomo::IpcPoolConfigBuilder::new()
|
||||
.min_connections(1)
|
||||
.min_connections(3)
|
||||
.max_connections(32)
|
||||
.idle_timeout(std::time::Duration::from_secs(60))
|
||||
.health_check_interval(std::time::Duration::from_secs(60))
|
||||
.reject_policy(RejectPolicy::Timeout(Duration::from_secs(3)))
|
||||
.reject_policy(RejectPolicy::Wait)
|
||||
.build(),
|
||||
)
|
||||
.build(),
|
||||
@@ -265,7 +264,6 @@ pub fn run() {
|
||||
mod event_handlers {
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::module::lightweight;
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{
|
||||
config::Config,
|
||||
@@ -317,7 +315,7 @@ pub fn run() {
|
||||
|
||||
if let tauri::WindowEvent::CloseRequested { api, .. } = api {
|
||||
api.prevent_close();
|
||||
if let Some(window) = core::handle::Handle::get_window() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let _ = window.hide();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{
|
||||
config::Config,
|
||||
core::{handle, timer::Timer, tray::Tray},
|
||||
core::{timer::Timer, tray::Tray},
|
||||
process::AsyncHandler,
|
||||
};
|
||||
|
||||
@@ -143,7 +143,7 @@ pub async fn add_light_weight_timer() {
|
||||
}
|
||||
|
||||
fn setup_window_close_listener() {
|
||||
if let Some(window) = handle::Handle::get_window() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let handler_id = window.listen("tauri://close-requested", move |_event| {
|
||||
std::mem::drop(AsyncHandler::spawn(|| async {
|
||||
if let Err(e) = setup_light_weight_timer().await {
|
||||
@@ -161,7 +161,7 @@ fn setup_window_close_listener() {
|
||||
}
|
||||
|
||||
fn cancel_window_close_listener() {
|
||||
if let Some(window) = handle::Handle::get_window() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let id = WINDOW_CLOSE_HANDLER_ID.swap(0, Ordering::AcqRel);
|
||||
if id != 0 {
|
||||
window.unlisten(id);
|
||||
@@ -171,7 +171,7 @@ fn cancel_window_close_listener() {
|
||||
}
|
||||
|
||||
fn setup_webview_focus_listener() {
|
||||
if let Some(window) = handle::Handle::get_window() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let handler_id = window.listen("tauri://focus", move |_event| {
|
||||
logging_error!(Type::Lightweight, cancel_light_weight_timer());
|
||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
||||
@@ -181,7 +181,7 @@ fn setup_webview_focus_listener() {
|
||||
}
|
||||
|
||||
fn cancel_webview_focus_listener() {
|
||||
if let Some(window) = handle::Handle::get_window() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let id = WEBVIEW_FOCUS_HANDLER_ID.swap(0, Ordering::AcqRel);
|
||||
if id != 0 {
|
||||
window.unlisten(id);
|
||||
|
||||
@@ -4,6 +4,8 @@ use clash_verge_logging::{Type, logging};
|
||||
use nanoid::nanoid;
|
||||
use serde::{Serialize, de::DeserializeOwned};
|
||||
use serde_yaml_ng::Mapping;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::path::Path;
|
||||
use std::{path::PathBuf, str::FromStr};
|
||||
|
||||
/// read data from yaml as struct T
|
||||
@@ -134,3 +136,24 @@ pub fn linux_elevator() -> String {
|
||||
Err(_) => "sudo".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
/// copy the file to the dist path and return the dist path
|
||||
pub fn snapshot_path(original_path: &Path) -> Result<PathBuf> {
|
||||
let temp_dir = original_path
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow!("Invalid log path"))?
|
||||
.join("temp");
|
||||
|
||||
std::fs::create_dir_all(&temp_dir)?;
|
||||
|
||||
let temp_path = temp_dir.join(format!(
|
||||
"{}_{}.log",
|
||||
original_path.file_stem().unwrap_or_default().to_string_lossy(),
|
||||
chrono::Local::now().format("%Y-%m-%d_%H-%M-%S")
|
||||
));
|
||||
|
||||
std::fs::copy(original_path, &temp_path)?;
|
||||
|
||||
Ok(temp_path)
|
||||
}
|
||||
|
||||
@@ -13,11 +13,35 @@ use crate::{
|
||||
use anyhow::Result;
|
||||
use chrono::{Local, TimeZone as _};
|
||||
use clash_verge_logging::Type;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::path::Path;
|
||||
use std::{path::PathBuf, str::FromStr as _};
|
||||
use tauri_plugin_shell::ShellExt as _;
|
||||
use tokio::fs;
|
||||
use tokio::fs::DirEntry;
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn delete_snapshot_logs(log_dir: &Path) -> Result<()> {
|
||||
let temp_dirs = [
|
||||
log_dir.join("temp"),
|
||||
log_dir.join("service").join("temp"),
|
||||
log_dir.join("sidecar").join("temp"),
|
||||
];
|
||||
|
||||
for temp_dir in temp_dirs.iter().filter(|d| d.exists()) {
|
||||
let mut entries = fs::read_dir(temp_dir).await?;
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|s| s.to_str()) == Some("log") {
|
||||
let _ = path.remove_if_exists().await;
|
||||
logging!(info, Type::Setup, "delete snapshot log file: {}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// TODO flexi_logger 提供了最大保留天数,或许我们应该用内置删除log文件
|
||||
/// 删除log文件
|
||||
pub async fn delete_log() -> Result<()> {
|
||||
@@ -26,6 +50,9 @@ pub async fn delete_log() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
delete_snapshot_logs(&log_dir).await?;
|
||||
|
||||
let auto_log_clean = {
|
||||
let verge = Config::verge().await;
|
||||
let verge = verge.data_arc();
|
||||
|
||||
@@ -33,6 +33,7 @@ pub fn init_work_dir_and_logger() -> anyhow::Result<()> {
|
||||
init_work_config().await;
|
||||
init_resources().await;
|
||||
logging!(info, Type::Setup, "Initializing logger");
|
||||
// #[cfg(not(feature = "tokio-trace"))]
|
||||
Logger::global().init().await?;
|
||||
Ok(())
|
||||
})
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::Result;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use smartstring::alias::String;
|
||||
use tauri::Url;
|
||||
|
||||
use crate::{
|
||||
config::{Config, PrfItem, profiles},
|
||||
core::handle,
|
||||
core::{CoreManager, handle},
|
||||
};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
|
||||
@@ -22,90 +22,136 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
|
||||
param
|
||||
};
|
||||
|
||||
// 解析 URL
|
||||
let link_parsed = match Url::parse(param_str) {
|
||||
Ok(url) => url,
|
||||
Err(e) => {
|
||||
bail!("failed to parse deep link: {:?}, param: {:?}", e, param);
|
||||
}
|
||||
};
|
||||
let link_parsed =
|
||||
Url::parse(param_str).map_err(|e| anyhow::anyhow!("failed to parse deep link: {:?}, param: {:?}", e, param))?;
|
||||
|
||||
let (url_param, name) = if link_parsed.scheme() == "clash" || link_parsed.scheme() == "clash-verge" {
|
||||
let name_owned: Option<String> = link_parsed
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "name")
|
||||
.map(|(_, value)| value.into_owned().into());
|
||||
|
||||
let url_param = if let Some(query) = link_parsed.query() {
|
||||
let prefix = "url=";
|
||||
if let Some(pos) = query.find(prefix) {
|
||||
let raw_url = query[pos + prefix.len()..].trim();
|
||||
// Avoid double-decoding nested subscription URLs; decode only when needed.
|
||||
let decoded = if Url::parse(raw_url).is_ok() {
|
||||
raw_url.to_string()
|
||||
} else {
|
||||
let mut candidate = raw_url.to_string();
|
||||
for _ in 0..2 {
|
||||
let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string();
|
||||
if next == candidate {
|
||||
break;
|
||||
}
|
||||
candidate = next;
|
||||
if Url::parse(&candidate).is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
candidate
|
||||
};
|
||||
Some(decoded)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
(url_param, name_owned)
|
||||
} else {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
let url = if let Some(ref url) = url_param {
|
||||
url
|
||||
} else {
|
||||
let Some((url, name)) = extract_subscription_info(&link_parsed) else {
|
||||
logging!(error, Type::Config, "missing url parameter in deep link: {}", param_str);
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut item = match PrfItem::from_url(url, name.as_ref(), None, None).await {
|
||||
Ok(item) => item,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
|
||||
handle::Handle::notice_message("import_sub_url::error", e.to_string());
|
||||
return Ok(());
|
||||
import_subscription(&url, name.as_ref()).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option<String>)> {
|
||||
if !matches!(link_parsed.scheme(), "clash" | "clash-verge") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let name = link_parsed
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "name")
|
||||
.map(|(_, value)| value.into_owned().into());
|
||||
let url = extract_subscription_url(link_parsed)?;
|
||||
Some((url, name))
|
||||
}
|
||||
|
||||
fn extract_subscription_url(link_parsed: &Url) -> Option<std::string::String> {
|
||||
let query = link_parsed.query()?;
|
||||
let prefix = "url=";
|
||||
let pos = query.find(prefix)?;
|
||||
let raw_url = query[pos + prefix.len()..].trim();
|
||||
Some(decode_subscription_url(raw_url))
|
||||
}
|
||||
|
||||
fn decode_subscription_url(raw_url: &str) -> std::string::String {
|
||||
// Avoid double-decoding nested subscription URLs; decode only when needed.
|
||||
if Url::parse(raw_url).is_ok() {
|
||||
return raw_url.to_string();
|
||||
}
|
||||
|
||||
let mut candidate = raw_url.to_string();
|
||||
for _ in 0..2 {
|
||||
let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string();
|
||||
if next == candidate {
|
||||
break;
|
||||
}
|
||||
candidate = next;
|
||||
if Url::parse(&candidate).is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
async fn import_subscription(url: &str, name: Option<&String>) {
|
||||
let had_current_profile = {
|
||||
let profiles = Config::profiles().await;
|
||||
profiles.latest_arc().current.is_some()
|
||||
};
|
||||
|
||||
let Some(mut item) = fetch_profile_item(url, name).await else {
|
||||
return;
|
||||
};
|
||||
|
||||
let uid = item.uid.clone().unwrap_or_default();
|
||||
match profiles::profiles_append_item_safe(&mut item).await {
|
||||
Ok(_) => {
|
||||
Config::profiles().await.apply();
|
||||
let _ = Config::profiles().await.data_arc().save_file().await;
|
||||
handle::Handle::notice_message(
|
||||
"import_sub_url::ok",
|
||||
"", // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
|
||||
);
|
||||
handle::Handle::refresh_verge();
|
||||
handle::Handle::notify_profile_changed(uid.clone());
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
handle::Handle::notify_profile_changed(uid);
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Config, "failed to import subscription url: {:?}", e);
|
||||
Config::profiles().await.discard();
|
||||
handle::Handle::notice_message("import_sub_url::error", e.to_string());
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(e) = profiles::profiles_append_item_safe(&mut item).await {
|
||||
logging!(error, Type::Config, "failed to import subscription url: {:?}", e);
|
||||
Config::profiles().await.discard();
|
||||
handle::Handle::notice_message("import_sub_url::error", e.to_string());
|
||||
return;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Config::profiles().await.apply();
|
||||
let _ = Config::profiles().await.data_arc().save_file().await;
|
||||
handle::Handle::notice_message(
|
||||
"import_sub_url::ok",
|
||||
"", // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
|
||||
);
|
||||
|
||||
post_import_updates(&uid, had_current_profile).await;
|
||||
}
|
||||
|
||||
async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem> {
|
||||
match PrfItem::from_url(url, name, None, None).await {
|
||||
Ok(item) => Some(item),
|
||||
Err(e) => {
|
||||
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
|
||||
handle::Handle::notice_message("import_sub_url::error", e.to_string());
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn post_import_updates(uid: &String, had_current_profile: bool) {
|
||||
handle::Handle::refresh_verge();
|
||||
handle::Handle::notify_profile_changed(uid.clone());
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
|
||||
let should_update_core = if uid.is_empty() || had_current_profile {
|
||||
false
|
||||
} else {
|
||||
let profiles = Config::profiles().await;
|
||||
profiles.latest_arc().is_current_profile_index(uid)
|
||||
};
|
||||
handle::Handle::notify_profile_changed(uid.clone());
|
||||
|
||||
if should_update_core {
|
||||
refresh_core_config().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn refresh_core_config() {
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
"Deep link import set current profile; refreshing core config"
|
||||
);
|
||||
match CoreManager::global().update_config().await {
|
||||
Ok((true, _)) => handle::Handle::refresh_clash(),
|
||||
Ok((false, msg)) => {
|
||||
let message = if msg.is_empty() {
|
||||
String::from("Failed to apply subscription configuration")
|
||||
} else {
|
||||
msg
|
||||
};
|
||||
logging!(warn, Type::Config, "Apply config failed: {}", message);
|
||||
handle::Handle::notice_message("config_validate::error", message);
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Config, "Apply config error: {}", err);
|
||||
handle::Handle::notice_message("update_failed", format!("{err}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,8 +5,7 @@ use std::fs;
|
||||
use std::os::windows::process::CommandExt as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
use winapi::um::stringapiset::MultiByteToWideChar;
|
||||
use winapi::um::winnls::{GetACP, GetOEMCP};
|
||||
use windows::Win32::Globalization::{GetACP, GetOEMCP, MULTI_BYTE_TO_WIDE_CHAR_FLAGS, MultiByteToWideChar};
|
||||
|
||||
const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||
const TASK_NAME_USER: &str = "Clash Verge";
|
||||
@@ -207,34 +206,16 @@ fn decode_with_code_page(bytes: &[u8], code_page: u32) -> Option<String> {
|
||||
return None;
|
||||
}
|
||||
|
||||
let required = unsafe {
|
||||
MultiByteToWideChar(
|
||||
code_page,
|
||||
0,
|
||||
bytes.as_ptr() as *const i8,
|
||||
len as i32,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
let required = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, None) };
|
||||
|
||||
if required == 0 {
|
||||
if required <= 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut wide = vec![0u16; required as usize];
|
||||
let written = unsafe {
|
||||
MultiByteToWideChar(
|
||||
code_page,
|
||||
0,
|
||||
bytes.as_ptr() as *const i8,
|
||||
len as i32,
|
||||
wide.as_mut_ptr(),
|
||||
required,
|
||||
)
|
||||
};
|
||||
let written = unsafe { MultiByteToWideChar(code_page, MULTI_BYTE_TO_WIDE_CHAR_FLAGS(0), bytes, Some(&mut wide)) };
|
||||
|
||||
if written == 0 {
|
||||
if written <= 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
use crate::{core::handle, utils::resolve::window::build_new_window};
|
||||
use clash_verge_limiter::Limiter;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
|
||||
use once_cell::sync::Lazy;
|
||||
use std::num::NonZeroU32;
|
||||
use std::pin::Pin;
|
||||
use std::time::Duration;
|
||||
use tauri::{Manager as _, WebviewWindow, Wry};
|
||||
@@ -40,28 +39,48 @@ pub enum WindowState {
|
||||
}
|
||||
|
||||
// 窗口操作防抖机制
|
||||
const WINDOW_OPERATION_DEBOUNCE_MS: u64 = 1_275;
|
||||
static WINDOW_OPERATION_LIMITER: Lazy<DefaultDirectRateLimiter> = Lazy::new(|| {
|
||||
#[allow(clippy::unwrap_used)]
|
||||
RateLimiter::direct(
|
||||
Quota::with_period(Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS))
|
||||
.unwrap()
|
||||
.allow_burst(NonZeroU32::new(1).unwrap()),
|
||||
const WINDOW_OPERATION_DEBOUNCE_MS: u64 = 625;
|
||||
static WINDOW_OPERATION_LIMITER: Lazy<Limiter> = Lazy::new(|| {
|
||||
Limiter::new(
|
||||
Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS),
|
||||
clash_verge_limiter::SystemClock,
|
||||
)
|
||||
});
|
||||
|
||||
fn should_handle_window_operation() -> bool {
|
||||
let res = WINDOW_OPERATION_LIMITER.check().is_ok();
|
||||
if !res {
|
||||
let allow = WINDOW_OPERATION_LIMITER.check();
|
||||
if !allow {
|
||||
logging!(debug, Type::Window, "window operation rate limited");
|
||||
}
|
||||
res
|
||||
allow
|
||||
}
|
||||
|
||||
/// 统一的窗口管理器
|
||||
pub struct WindowManager;
|
||||
|
||||
impl WindowManager {
|
||||
pub fn get_main_window_with_state() -> (Option<WebviewWindow<Wry>>, WindowState) {
|
||||
let Some(window) = Self::get_main_window() else {
|
||||
return (None, WindowState::NotExist);
|
||||
};
|
||||
|
||||
let is_minimized = window.is_minimized().unwrap_or(false);
|
||||
let is_visible = window.is_visible().unwrap_or(false);
|
||||
let is_focused = window.is_focused().unwrap_or(false);
|
||||
|
||||
let state = if is_minimized {
|
||||
WindowState::Minimized
|
||||
} else if !is_visible {
|
||||
WindowState::Hidden
|
||||
} else if is_focused {
|
||||
WindowState::VisibleFocused
|
||||
} else {
|
||||
WindowState::VisibleUnfocused
|
||||
};
|
||||
|
||||
(Some(window), state)
|
||||
}
|
||||
|
||||
pub fn get_main_window_state() -> WindowState {
|
||||
match Self::get_main_window() {
|
||||
Some(window) => {
|
||||
@@ -122,12 +141,12 @@ impl WindowManager {
|
||||
WindowOperationResult::NoAction
|
||||
}
|
||||
WindowState::VisibleUnfocused | WindowState::Minimized | WindowState::Hidden => {
|
||||
if let Some(window) = Self::get_main_window() {
|
||||
let state_after_check = Self::get_main_window_state();
|
||||
if state_after_check == WindowState::VisibleFocused {
|
||||
logging!(info, Type::Window, "窗口在检查期间已变为可见和有焦点状态");
|
||||
return WindowOperationResult::NoAction;
|
||||
}
|
||||
let (window, state_after_check) = Self::get_main_window_with_state();
|
||||
if state_after_check == WindowState::VisibleFocused {
|
||||
logging!(info, Type::Window, "窗口在检查期间已变为可见和有焦点状态");
|
||||
return WindowOperationResult::NoAction;
|
||||
}
|
||||
if let Some(window) = window {
|
||||
Self::activate_window(&window)
|
||||
} else {
|
||||
WindowOperationResult::Failed
|
||||
@@ -138,25 +157,18 @@ impl WindowManager {
|
||||
|
||||
/// 切换主窗口显示状态(显示/隐藏)
|
||||
pub async fn toggle_main_window() -> WindowOperationResult {
|
||||
// 防抖检查
|
||||
if !should_handle_window_operation() {
|
||||
return WindowOperationResult::NoAction;
|
||||
};
|
||||
logging!(info, Type::Window, "开始切换主窗口显示状态");
|
||||
}
|
||||
|
||||
let current_state = Self::get_main_window_state();
|
||||
logging!(
|
||||
info,
|
||||
Type::Window,
|
||||
"当前窗口状态: {:?} | 详细状态: {}",
|
||||
current_state,
|
||||
Self::get_window_status_info()
|
||||
);
|
||||
let (window, state) = Self::get_main_window_with_state();
|
||||
|
||||
match current_state {
|
||||
logging!(debug, Type::Window, "当前状态: {:?}", state);
|
||||
|
||||
match state {
|
||||
WindowState::NotExist => Self::handle_not_exist_toggle().await,
|
||||
WindowState::VisibleFocused | WindowState::VisibleUnfocused => Self::hide_main_window(),
|
||||
WindowState::Minimized | WindowState::Hidden => Self::activate_existing_main_window(),
|
||||
WindowState::VisibleFocused | WindowState::VisibleUnfocused => Self::hide_main_window(window.as_ref()),
|
||||
WindowState::Minimized | WindowState::Hidden => Self::activate_existing_main_window(window.as_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,9 +184,9 @@ impl WindowManager {
|
||||
}
|
||||
|
||||
// 隐藏主窗口
|
||||
fn hide_main_window() -> WindowOperationResult {
|
||||
fn hide_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
|
||||
logging!(info, Type::Window, "窗口可见,将隐藏窗口");
|
||||
if let Some(window) = Self::get_main_window() {
|
||||
if let Some(window) = window {
|
||||
match window.hide() {
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Window, "窗口已成功隐藏");
|
||||
@@ -192,10 +204,10 @@ impl WindowManager {
|
||||
}
|
||||
|
||||
// 激活已存在的主窗口
|
||||
fn activate_existing_main_window() -> WindowOperationResult {
|
||||
fn activate_existing_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
|
||||
logging!(info, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口");
|
||||
if let Some(window) = Self::get_main_window() {
|
||||
Self::activate_window(&window)
|
||||
if let Some(window) = window {
|
||||
Self::activate_window(window)
|
||||
} else {
|
||||
logging!(warn, Type::Window, "无法获取窗口实例");
|
||||
WindowOperationResult::Failed
|
||||
@@ -258,24 +270,18 @@ impl WindowManager {
|
||||
}
|
||||
|
||||
/// 检查窗口是否可见
|
||||
pub fn is_main_window_visible() -> bool {
|
||||
Self::get_main_window()
|
||||
.map(|window| window.is_visible().unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
pub fn is_main_window_visible(window: Option<&WebviewWindow<Wry>>) -> bool {
|
||||
window.map(|w| w.is_visible().unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 检查窗口是否有焦点
|
||||
pub fn is_main_window_focused() -> bool {
|
||||
Self::get_main_window()
|
||||
.map(|window| window.is_focused().unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
|
||||
window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 检查窗口是否最小化
|
||||
pub fn is_main_window_minimized() -> bool {
|
||||
Self::get_main_window()
|
||||
.map(|window| window.is_minimized().unwrap_or(false))
|
||||
.unwrap_or(false)
|
||||
pub fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
|
||||
window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// 创建新窗口,防抖避免重复调用
|
||||
@@ -323,11 +329,11 @@ impl WindowManager {
|
||||
}
|
||||
|
||||
/// 获取详细的窗口状态信息
|
||||
pub fn get_window_status_info() -> String {
|
||||
let state = Self::get_main_window_state();
|
||||
let is_visible = Self::is_main_window_visible();
|
||||
let is_focused = Self::is_main_window_focused();
|
||||
let is_minimized = Self::is_main_window_minimized();
|
||||
fn get_window_status_info() -> String {
|
||||
let (window, state) = Self::get_main_window_with_state();
|
||||
let is_visible = Self::is_main_window_visible(window.as_ref());
|
||||
let is_focused = Self::is_main_window_focused(window.as_ref());
|
||||
let is_minimized = Self::is_main_window_minimized(window.as_ref());
|
||||
|
||||
format!("窗口状态: {state:?} | 可见: {is_visible} | 有焦点: {is_focused} | 最小化: {is_minimized}")
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "2.4.5-rc.1",
|
||||
"version": "2.4.6",
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"bundle": {
|
||||
"active": true,
|
||||
|
||||
@@ -24,9 +24,9 @@
|
||||
}
|
||||
},
|
||||
"externalBin": [
|
||||
"./resources/clash-verge-service",
|
||||
"./resources/clash-verge-service-install",
|
||||
"./resources/clash-verge-service-uninstall",
|
||||
"./sidecar/clash-verge-service",
|
||||
"./sidecar/clash-verge-service-install",
|
||||
"./sidecar/clash-verge-service-uninstall",
|
||||
"./sidecar/verge-mihomo",
|
||||
"./sidecar/verge-mihomo-alpha"
|
||||
]
|
||||
|
||||
@@ -2,15 +2,18 @@ import { ReactNode } from "react";
|
||||
import { ErrorBoundary, FallbackProps } from "react-error-boundary";
|
||||
|
||||
function ErrorFallback({ error }: FallbackProps) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
const errorStack = error instanceof Error ? error.stack : undefined;
|
||||
|
||||
return (
|
||||
<div role="alert" style={{ padding: 16 }}>
|
||||
<h4>Something went wrong:(</h4>
|
||||
|
||||
<pre>{error.message}</pre>
|
||||
<pre>{errorMessage}</pre>
|
||||
|
||||
<details title="Error Stack">
|
||||
<summary>Error Stack</summary>
|
||||
<pre>{error.stack}</pre>
|
||||
<pre>{errorStack}</pre>
|
||||
</details>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Box, SvgIcon, TextField, styled } from "@mui/material";
|
||||
import { ClearRounded } from "@mui/icons-material";
|
||||
import { Box, SvgIcon, TextField, styled, IconButton } from "@mui/material";
|
||||
import Tooltip from "@mui/material/Tooltip";
|
||||
import {
|
||||
ChangeEvent,
|
||||
@@ -168,6 +169,11 @@ export const BaseSearchBox = ({
|
||||
});
|
||||
};
|
||||
|
||||
const handleClearInput = () => {
|
||||
setText("");
|
||||
emitSearch({ text: "", matchCase, matchWholeWord, useRegularExpression });
|
||||
};
|
||||
|
||||
const handleToggleMatchCase = () => {
|
||||
const next = !matchCase;
|
||||
setMatchCase(next);
|
||||
@@ -200,35 +206,40 @@ export const BaseSearchBox = ({
|
||||
sx: { pr: 1 },
|
||||
endAdornment: (
|
||||
<Box display="flex">
|
||||
<Tooltip title={t("shared.placeholders.matchCase")}>
|
||||
<div>
|
||||
<SvgIcon
|
||||
component={matchCaseIcon}
|
||||
{!!text && (
|
||||
<Tooltip title={t("shared.placeholders.resetInput")}>
|
||||
<IconButton
|
||||
size="small"
|
||||
{...iconStyle}
|
||||
aria-label={matchCase ? "active" : "inactive"}
|
||||
onClick={handleToggleMatchCase}
|
||||
/>
|
||||
</div>
|
||||
onClick={handleClearInput}
|
||||
>
|
||||
<ClearRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip title={t("shared.placeholders.matchCase")}>
|
||||
<SvgIcon
|
||||
component={matchCaseIcon}
|
||||
{...iconStyle}
|
||||
aria-label={matchCase ? "active" : "inactive"}
|
||||
onClick={handleToggleMatchCase}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={t("shared.placeholders.matchWholeWord")}>
|
||||
<div>
|
||||
<SvgIcon
|
||||
component={matchWholeWordIcon}
|
||||
{...iconStyle}
|
||||
aria-label={matchWholeWord ? "active" : "inactive"}
|
||||
onClick={handleToggleMatchWholeWord}
|
||||
/>
|
||||
</div>
|
||||
<SvgIcon
|
||||
component={matchWholeWordIcon}
|
||||
{...iconStyle}
|
||||
aria-label={matchWholeWord ? "active" : "inactive"}
|
||||
onClick={handleToggleMatchWholeWord}
|
||||
/>
|
||||
</Tooltip>
|
||||
<Tooltip title={t("shared.placeholders.useRegex")}>
|
||||
<div>
|
||||
<SvgIcon
|
||||
component={UseRegularExpressionIcon}
|
||||
aria-label={useRegularExpression ? "active" : "inactive"}
|
||||
{...iconStyle}
|
||||
onClick={handleToggleUseRegularExpression}
|
||||
/>
|
||||
</div>
|
||||
<SvgIcon
|
||||
component={UseRegularExpressionIcon}
|
||||
aria-label={useRegularExpression ? "active" : "inactive"}
|
||||
{...iconStyle}
|
||||
onClick={handleToggleUseRegularExpression}
|
||||
/>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
),
|
||||
|
||||
@@ -21,20 +21,14 @@ import {
|
||||
ListItem,
|
||||
ListItemText,
|
||||
} from "@mui/material";
|
||||
import type { Column } from "@tanstack/react-table";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface ColumnOption {
|
||||
field: string;
|
||||
label: string;
|
||||
visible: boolean;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
columns: ColumnOption[];
|
||||
columns: Column<IConnectionsItem, unknown>[];
|
||||
onClose: () => void;
|
||||
onToggle: (field: string, visible: boolean) => void;
|
||||
onOrderChange: (order: string[]) => void;
|
||||
onReset: () => void;
|
||||
}
|
||||
@@ -43,7 +37,6 @@ export const ConnectionColumnManager = ({
|
||||
open,
|
||||
columns,
|
||||
onClose,
|
||||
onToggle,
|
||||
onOrderChange,
|
||||
onReset,
|
||||
}: Props) => {
|
||||
@@ -54,9 +47,9 @@ export const ConnectionColumnManager = ({
|
||||
);
|
||||
const { t } = useTranslation();
|
||||
|
||||
const items = useMemo(() => columns.map((column) => column.field), [columns]);
|
||||
const items = useMemo(() => columns.map((column) => column.id), [columns]);
|
||||
const visibleCount = useMemo(
|
||||
() => columns.filter((column) => column.visible).length,
|
||||
() => columns.filter((column) => column.getIsVisible()).length,
|
||||
[columns],
|
||||
);
|
||||
|
||||
@@ -65,7 +58,7 @@ export const ConnectionColumnManager = ({
|
||||
const { active, over } = event;
|
||||
if (!over || active.id === over.id) return;
|
||||
|
||||
const order = columns.map((column) => column.field);
|
||||
const order = columns.map((column) => column.id);
|
||||
const oldIndex = order.indexOf(active.id as string);
|
||||
const newIndex = order.indexOf(over.id as string);
|
||||
if (oldIndex === -1 || newIndex === -1) return;
|
||||
@@ -94,13 +87,16 @@ export const ConnectionColumnManager = ({
|
||||
>
|
||||
{columns.map((column) => (
|
||||
<SortableColumnItem
|
||||
key={column.field}
|
||||
key={column.id}
|
||||
column={column}
|
||||
onToggle={onToggle}
|
||||
label={getColumnLabel(column)}
|
||||
dragHandleLabel={t(
|
||||
"connections.components.columnManager.dragHandle",
|
||||
)}
|
||||
disableToggle={column.visible && visibleCount <= 1}
|
||||
disableToggle={
|
||||
!column.getCanHide() ||
|
||||
(column.getIsVisible() && visibleCount <= 1)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</List>
|
||||
@@ -120,15 +116,15 @@ export const ConnectionColumnManager = ({
|
||||
};
|
||||
|
||||
interface SortableColumnItemProps {
|
||||
column: ColumnOption;
|
||||
onToggle: (field: string, visible: boolean) => void;
|
||||
column: Column<IConnectionsItem, unknown>;
|
||||
label: string;
|
||||
dragHandleLabel: string;
|
||||
disableToggle?: boolean;
|
||||
}
|
||||
|
||||
const SortableColumnItem = ({
|
||||
column,
|
||||
onToggle,
|
||||
label,
|
||||
dragHandleLabel,
|
||||
disableToggle = false,
|
||||
}: SortableColumnItemProps) => {
|
||||
@@ -139,7 +135,7 @@ const SortableColumnItem = ({
|
||||
transform,
|
||||
transition,
|
||||
isDragging,
|
||||
} = useSortable({ id: column.field });
|
||||
} = useSortable({ id: column.id });
|
||||
|
||||
const style = useMemo(
|
||||
() => ({
|
||||
@@ -167,12 +163,12 @@ const SortableColumnItem = ({
|
||||
>
|
||||
<Checkbox
|
||||
edge="start"
|
||||
checked={column.visible}
|
||||
checked={column.getIsVisible()}
|
||||
disabled={disableToggle}
|
||||
onChange={(event) => onToggle(column.field, event.target.checked)}
|
||||
onChange={(event) => column.toggleVisibility(event.target.checked)}
|
||||
/>
|
||||
<ListItemText
|
||||
primary={column.label}
|
||||
primary={label}
|
||||
slotProps={{ primary: { variant: "body2" } }}
|
||||
sx={{ mr: 1 }}
|
||||
/>
|
||||
@@ -189,3 +185,11 @@ const SortableColumnItem = ({
|
||||
</ListItem>
|
||||
);
|
||||
};
|
||||
|
||||
const getColumnLabel = (column: Column<IConnectionsItem, unknown>) => {
|
||||
const meta = column.columnDef.meta as { label?: string } | undefined;
|
||||
if (meta?.label) return meta.label;
|
||||
|
||||
const header = column.columnDef.header;
|
||||
return typeof header === "string" ? header : column.id;
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ViewColumnRounded } from "@mui/icons-material";
|
||||
import { Box, IconButton, Tooltip } from "@mui/material";
|
||||
import {
|
||||
ColumnDef,
|
||||
ColumnOrderState,
|
||||
ColumnSizingState,
|
||||
flexRender,
|
||||
getCoreRowModel,
|
||||
@@ -43,50 +44,57 @@ const reconcileColumnOrder = (
|
||||
return [...filtered, ...missing];
|
||||
};
|
||||
|
||||
const createConnectionRow = (each: IConnectionsItem) => {
|
||||
type ColumnField =
|
||||
| "host"
|
||||
| "download"
|
||||
| "upload"
|
||||
| "dlSpeed"
|
||||
| "ulSpeed"
|
||||
| "chains"
|
||||
| "rule"
|
||||
| "process"
|
||||
| "time"
|
||||
| "source"
|
||||
| "remoteDestination"
|
||||
| "type";
|
||||
|
||||
const getConnectionCellValue = (field: ColumnField, each: IConnectionsItem) => {
|
||||
const { metadata, rulePayload } = each;
|
||||
const chains = [...each.chains].reverse().join(" / ");
|
||||
const rule = rulePayload ? `${each.rule}(${rulePayload})` : each.rule;
|
||||
const destination = metadata.destinationIP
|
||||
? `${metadata.destinationIP}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`;
|
||||
|
||||
return {
|
||||
id: each.id,
|
||||
host: metadata.host
|
||||
? `${metadata.host}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`,
|
||||
download: each.download,
|
||||
upload: each.upload,
|
||||
dlSpeed: each.curDownload,
|
||||
ulSpeed: each.curUpload,
|
||||
chains,
|
||||
rule,
|
||||
process: truncateStr(metadata.process || metadata.processPath),
|
||||
time: each.start,
|
||||
source: `${metadata.sourceIP}:${metadata.sourcePort}`,
|
||||
remoteDestination: destination,
|
||||
type: `${metadata.type}(${metadata.network})`,
|
||||
connectionData: each,
|
||||
};
|
||||
switch (field) {
|
||||
case "host":
|
||||
return metadata.host
|
||||
? `${metadata.host}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`;
|
||||
case "download":
|
||||
return each.download;
|
||||
case "upload":
|
||||
return each.upload;
|
||||
case "dlSpeed":
|
||||
return each.curDownload;
|
||||
case "ulSpeed":
|
||||
return each.curUpload;
|
||||
case "chains":
|
||||
return [...each.chains].reverse().join(" / ");
|
||||
case "rule":
|
||||
return rulePayload ? `${each.rule}(${rulePayload})` : each.rule;
|
||||
case "process":
|
||||
return truncateStr(metadata.process || metadata.processPath);
|
||||
case "time":
|
||||
return each.start;
|
||||
case "source":
|
||||
return `${metadata.sourceIP}:${metadata.sourcePort}`;
|
||||
case "remoteDestination":
|
||||
return metadata.destinationIP
|
||||
? `${metadata.destinationIP}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`;
|
||||
case "type":
|
||||
return `${metadata.type}(${metadata.network})`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
type ConnectionRow = ReturnType<typeof createConnectionRow>;
|
||||
|
||||
const areRowsEqual = (a: ConnectionRow, b: ConnectionRow) =>
|
||||
a.host === b.host &&
|
||||
a.download === b.download &&
|
||||
a.upload === b.upload &&
|
||||
a.dlSpeed === b.dlSpeed &&
|
||||
a.ulSpeed === b.ulSpeed &&
|
||||
a.chains === b.chains &&
|
||||
a.rule === b.rule &&
|
||||
a.process === b.process &&
|
||||
a.time === b.time &&
|
||||
a.source === b.source &&
|
||||
a.remoteDestination === b.remoteDestination &&
|
||||
a.type === b.type;
|
||||
|
||||
interface Props {
|
||||
connections: IConnectionsItem[];
|
||||
onShowDetail: (data: IConnectionsItem) => void;
|
||||
@@ -104,33 +112,30 @@ export const ConnectionTable = (props: Props) => {
|
||||
onCloseColumnManager,
|
||||
} = props;
|
||||
const { t } = useTranslation();
|
||||
const [columnWidths, setColumnWidths] = useLocalStorage<
|
||||
Record<string, number>
|
||||
>(
|
||||
const [columnWidths, setColumnWidths] = useLocalStorage<ColumnSizingState>(
|
||||
"connection-table-widths",
|
||||
// server-side value, this is the default value used by server-side rendering (if any)
|
||||
// Do not omit (otherwise a Suspense boundary will be triggered)
|
||||
{},
|
||||
);
|
||||
|
||||
const [columnVisibilityModel, setColumnVisibilityModel] = useLocalStorage<
|
||||
Partial<Record<string, boolean>>
|
||||
>(
|
||||
"connection-table-visibility",
|
||||
{},
|
||||
{
|
||||
serializer: JSON.stringify,
|
||||
deserializer: (value) => {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
if (parsed && typeof parsed === "object") return parsed;
|
||||
} catch (err) {
|
||||
console.warn("Failed to parse connection-table-visibility", err);
|
||||
}
|
||||
return {};
|
||||
const [columnVisibilityModel, setColumnVisibilityModel] =
|
||||
useLocalStorage<VisibilityState>(
|
||||
"connection-table-visibility",
|
||||
{},
|
||||
{
|
||||
serializer: JSON.stringify,
|
||||
deserializer: (value) => {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
if (parsed && typeof parsed === "object") return parsed;
|
||||
} catch (err) {
|
||||
console.warn("Failed to parse connection-table-visibility", err);
|
||||
}
|
||||
return {};
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
);
|
||||
|
||||
const [columnOrder, setColumnOrder] = useLocalStorage<string[]>(
|
||||
"connection-table-order",
|
||||
@@ -149,15 +154,13 @@ export const ConnectionTable = (props: Props) => {
|
||||
},
|
||||
);
|
||||
|
||||
type ColumnField = Exclude<keyof ConnectionRow, "connectionData">;
|
||||
|
||||
interface BaseColumn {
|
||||
field: ColumnField;
|
||||
headerName: string;
|
||||
width?: number;
|
||||
minWidth?: number;
|
||||
align?: "left" | "right";
|
||||
cell?: (row: ConnectionRow) => ReactNode;
|
||||
cell?: (row: IConnectionsItem) => ReactNode;
|
||||
}
|
||||
|
||||
const baseColumns = useMemo<BaseColumn[]>(() => {
|
||||
@@ -190,7 +193,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
width: 76,
|
||||
minWidth: 60,
|
||||
align: "right",
|
||||
cell: (row) => `${parseTraffic(row.dlSpeed).join(" ")}/s`,
|
||||
cell: (row) => `${parseTraffic(row.curDownload).join(" ")}/s`,
|
||||
},
|
||||
{
|
||||
field: "ulSpeed",
|
||||
@@ -198,7 +201,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
width: 76,
|
||||
minWidth: 60,
|
||||
align: "right",
|
||||
cell: (row) => `${parseTraffic(row.ulSpeed).join(" ")}/s`,
|
||||
cell: (row) => `${parseTraffic(row.curUpload).join(" ")}/s`,
|
||||
},
|
||||
{
|
||||
field: "chains",
|
||||
@@ -262,177 +265,76 @@ export const ConnectionTable = (props: Props) => {
|
||||
});
|
||||
}, [baseColumns, setColumnOrder]);
|
||||
|
||||
const columns = useMemo<BaseColumn[]>(() => {
|
||||
const order = Array.isArray(columnOrder) ? columnOrder : [];
|
||||
const orderMap = new Map(order.map((field, index) => [field, index]));
|
||||
|
||||
return [...baseColumns].sort((a, b) => {
|
||||
const aIndex = orderMap.has(a.field)
|
||||
? (orderMap.get(a.field) as number)
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
const bIndex = orderMap.has(b.field)
|
||||
? (orderMap.get(b.field) as number)
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
|
||||
if (aIndex === bIndex) {
|
||||
return order.indexOf(a.field) - order.indexOf(b.field);
|
||||
}
|
||||
|
||||
return aIndex - bIndex;
|
||||
});
|
||||
}, [baseColumns, columnOrder]);
|
||||
|
||||
const visibleColumnsCount = useMemo(() => {
|
||||
return columns.reduce((count, column) => {
|
||||
return (columnVisibilityModel?.[column.field] ?? true) !== false
|
||||
? count + 1
|
||||
: count;
|
||||
}, 0);
|
||||
}, [columns, columnVisibilityModel]);
|
||||
|
||||
const handleToggleColumn = useCallback(
|
||||
(field: string, visible: boolean) => {
|
||||
if (!visible && visibleColumnsCount <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handleColumnVisibilityChange = useCallback(
|
||||
(update: Updater<VisibilityState>) => {
|
||||
setColumnVisibilityModel((prev) => {
|
||||
const next = { ...(prev ?? {}) };
|
||||
if (visible) {
|
||||
delete next[field];
|
||||
} else {
|
||||
next[field] = false;
|
||||
const current = prev ?? {};
|
||||
const nextState =
|
||||
typeof update === "function" ? update(current) : update;
|
||||
|
||||
const visibleCount = baseColumns.reduce((count, column) => {
|
||||
const isVisible = (nextState[column.field] ?? true) !== false;
|
||||
return count + (isVisible ? 1 : 0);
|
||||
}, 0);
|
||||
|
||||
if (visibleCount === 0) {
|
||||
return current;
|
||||
}
|
||||
return next;
|
||||
|
||||
const sanitized: VisibilityState = {};
|
||||
baseColumns.forEach((column) => {
|
||||
if (nextState[column.field] === false) {
|
||||
sanitized[column.field] = false;
|
||||
}
|
||||
});
|
||||
return sanitized;
|
||||
});
|
||||
},
|
||||
[setColumnVisibilityModel, visibleColumnsCount],
|
||||
[baseColumns, setColumnVisibilityModel],
|
||||
);
|
||||
|
||||
const handleManagerOrderChange = useCallback(
|
||||
(order: string[]) => {
|
||||
setColumnOrder(() => {
|
||||
const handleColumnOrderChange = useCallback(
|
||||
(update: Updater<ColumnOrderState>) => {
|
||||
setColumnOrder((prev) => {
|
||||
const current = Array.isArray(prev) ? prev : [];
|
||||
const nextState =
|
||||
typeof update === "function" ? update(current) : update;
|
||||
const baseFields = baseColumns.map((col) => col.field);
|
||||
return reconcileColumnOrder(order, baseFields);
|
||||
return reconcileColumnOrder(nextState, baseFields);
|
||||
});
|
||||
},
|
||||
[baseColumns, setColumnOrder],
|
||||
);
|
||||
|
||||
const handleResetColumns = useCallback(() => {
|
||||
setColumnVisibilityModel({});
|
||||
setColumnOrder(baseColumns.map((col) => col.field));
|
||||
}, [baseColumns, setColumnOrder, setColumnVisibilityModel]);
|
||||
|
||||
const handleColumnVisibilityChange = useCallback(
|
||||
(update: Updater<VisibilityState>) => {
|
||||
setColumnVisibilityModel((prev) => {
|
||||
const current = prev ?? {};
|
||||
const baseState: VisibilityState = {};
|
||||
columns.forEach((column) => {
|
||||
baseState[column.field] = (current[column.field] ?? true) !== false;
|
||||
});
|
||||
|
||||
const mergedState =
|
||||
typeof update === "function"
|
||||
? update(baseState)
|
||||
: { ...baseState, ...update };
|
||||
|
||||
const hiddenFields = columns
|
||||
.filter((column) => mergedState[column.field] === false)
|
||||
.map((column) => column.field);
|
||||
|
||||
if (columns.length - hiddenFields.length === 0) {
|
||||
return current;
|
||||
}
|
||||
|
||||
const sanitized: Partial<Record<string, boolean>> = {};
|
||||
hiddenFields.forEach((field) => {
|
||||
sanitized[field] = false;
|
||||
});
|
||||
return sanitized;
|
||||
});
|
||||
},
|
||||
[columns, setColumnVisibilityModel],
|
||||
);
|
||||
|
||||
const columnVisibilityState = useMemo<VisibilityState>(() => {
|
||||
const result: VisibilityState = {};
|
||||
if (!columnVisibilityModel) {
|
||||
columns.forEach((column) => {
|
||||
result[column.field] = true;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
columns.forEach((column) => {
|
||||
result[column.field] =
|
||||
(columnVisibilityModel?.[column.field] ?? true) !== false;
|
||||
});
|
||||
|
||||
return result;
|
||||
}, [columnVisibilityModel, columns]);
|
||||
|
||||
const columnOptions = useMemo(() => {
|
||||
return columns.map((column) => ({
|
||||
field: column.field,
|
||||
label: column.headerName ?? column.field,
|
||||
visible: (columnVisibilityModel?.[column.field] ?? true) !== false,
|
||||
}));
|
||||
}, [columns, columnVisibilityModel]);
|
||||
|
||||
const prevRowsRef = useRef<Map<string, ConnectionRow>>(new Map());
|
||||
|
||||
const connRows = useMemo<ConnectionRow[]>(() => {
|
||||
const prevMap = prevRowsRef.current;
|
||||
const nextMap = new Map<string, ConnectionRow>();
|
||||
|
||||
const nextRows = connections.map((each) => {
|
||||
const nextRow = createConnectionRow(each);
|
||||
const prevRow = prevMap.get(each.id);
|
||||
|
||||
if (prevRow && areRowsEqual(prevRow, nextRow)) {
|
||||
nextMap.set(each.id, prevRow);
|
||||
return prevRow;
|
||||
}
|
||||
|
||||
nextMap.set(each.id, nextRow);
|
||||
return nextRow;
|
||||
});
|
||||
|
||||
prevRowsRef.current = nextMap;
|
||||
return nextRows;
|
||||
}, [connections]);
|
||||
|
||||
const [sorting, setSorting] = useState<SortingState>([]);
|
||||
const [relativeNow, setRelativeNow] = useState(() => Date.now());
|
||||
|
||||
const columnDefs = useMemo<ColumnDef<ConnectionRow>[]>(() => {
|
||||
return columns.map((column) => {
|
||||
const baseCell: ColumnDef<ConnectionRow>["cell"] = column.cell
|
||||
const columnDefs = useMemo<ColumnDef<IConnectionsItem>[]>(() => {
|
||||
return baseColumns.map((column) => {
|
||||
const baseCell: ColumnDef<IConnectionsItem>["cell"] = column.cell
|
||||
? (ctx) => column.cell?.(ctx.row.original)
|
||||
: (ctx) => ctx.getValue() as ReactNode;
|
||||
|
||||
const cell: ColumnDef<ConnectionRow>["cell"] =
|
||||
const cell: ColumnDef<IConnectionsItem>["cell"] =
|
||||
column.field === "time"
|
||||
? (ctx) => dayjs(ctx.row.original.time).from(relativeNow)
|
||||
? (ctx) => dayjs(ctx.getValue() as string).from(relativeNow)
|
||||
: baseCell;
|
||||
|
||||
return {
|
||||
id: column.field,
|
||||
accessorKey: column.field,
|
||||
accessorFn: (row) => getConnectionCellValue(column.field, row),
|
||||
header: column.headerName,
|
||||
size: column.width,
|
||||
minSize: column.minWidth ?? 80,
|
||||
enableResizing: true,
|
||||
minSize: column.minWidth,
|
||||
meta: {
|
||||
align: column.align ?? "left",
|
||||
field: column.field,
|
||||
label: column.headerName,
|
||||
},
|
||||
cell,
|
||||
} satisfies ColumnDef<ConnectionRow>;
|
||||
} satisfies ColumnDef<IConnectionsItem>;
|
||||
});
|
||||
}, [columns, relativeNow]);
|
||||
}, [baseColumns, relativeNow]);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
@@ -450,7 +352,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
const prevState = prev ?? {};
|
||||
const nextState =
|
||||
typeof updater === "function" ? updater(prevState) : updater;
|
||||
const sanitized: Record<string, number> = {};
|
||||
const sanitized: ColumnSizingState = {};
|
||||
Object.entries(nextState).forEach(([key, size]) => {
|
||||
if (typeof size === "number" && Number.isFinite(size)) {
|
||||
sanitized[key] = size;
|
||||
@@ -463,22 +365,45 @@ export const ConnectionTable = (props: Props) => {
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
data: connRows,
|
||||
data: connections,
|
||||
state: {
|
||||
columnVisibility: columnVisibilityState,
|
||||
columnVisibility: columnVisibilityModel ?? {},
|
||||
columnSizing: columnWidths,
|
||||
columnOrder,
|
||||
sorting,
|
||||
},
|
||||
initialState: {
|
||||
columnOrder: baseColumns.map((col) => col.field),
|
||||
},
|
||||
defaultColumn: {
|
||||
minSize: 80,
|
||||
enableResizing: true,
|
||||
},
|
||||
columnResizeMode: "onChange",
|
||||
enableSortingRemoval: true,
|
||||
getRowId: (row) => row.id,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getSortedRowModel: sorting.length ? getSortedRowModel() : undefined,
|
||||
onSortingChange: setSorting,
|
||||
onColumnSizingChange: handleColumnSizingChange,
|
||||
onColumnVisibilityChange: handleColumnVisibilityChange,
|
||||
onColumnOrderChange: handleColumnOrderChange,
|
||||
columns: columnDefs,
|
||||
});
|
||||
|
||||
const handleManagerOrderChange = useCallback(
|
||||
(order: string[]) => {
|
||||
const baseFields = baseColumns.map((col) => col.field);
|
||||
table.setColumnOrder(reconcileColumnOrder(order, baseFields));
|
||||
},
|
||||
[baseColumns, table],
|
||||
);
|
||||
|
||||
const handleResetColumns = useCallback(() => {
|
||||
table.resetColumnVisibility();
|
||||
table.resetColumnOrder();
|
||||
}, [table]);
|
||||
|
||||
const rows = table.getRowModel().rows;
|
||||
const tableContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
@@ -491,6 +416,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const totalSize = rowVirtualizer.getTotalSize();
|
||||
const tableWidth = table.getTotalSize();
|
||||
const managerColumns = table.getAllLeafColumns();
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -669,7 +595,7 @@ export const ConnectionTable = (props: Props) => {
|
||||
return (
|
||||
<Box
|
||||
key={row.id}
|
||||
onClick={() => onShowDetail(row.original.connectionData)}
|
||||
onClick={() => onShowDetail(row.original)}
|
||||
sx={{
|
||||
display: "flex",
|
||||
position: "absolute",
|
||||
@@ -726,9 +652,8 @@ export const ConnectionTable = (props: Props) => {
|
||||
</Box>
|
||||
<ConnectionColumnManager
|
||||
open={columnManagerOpen}
|
||||
columns={columnOptions}
|
||||
columns={managerColumns}
|
||||
onClose={onCloseColumnManager}
|
||||
onToggle={handleToggleColumn}
|
||||
onOrderChange={handleManagerOrderChange}
|
||||
onReset={handleResetColumns}
|
||||
/>
|
||||
|
||||
@@ -4,13 +4,7 @@ import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { useClash } from "@/hooks/use-clash";
|
||||
import {
|
||||
useAppUptime,
|
||||
useClashConfig,
|
||||
useRulesData,
|
||||
useSystemProxyAddress,
|
||||
useSystemProxyData,
|
||||
} from "@/hooks/use-clash-data";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
|
||||
import { EnhancedCard } from "./enhanced-card";
|
||||
|
||||
@@ -25,14 +19,7 @@ const formatUptime = (uptimeMs: number) => {
|
||||
export const ClashInfoCard = () => {
|
||||
const { t } = useTranslation();
|
||||
const { version: clashVersion } = useClash();
|
||||
const { clashConfig } = useClashConfig();
|
||||
const { sysproxy } = useSystemProxyData();
|
||||
const { rules } = useRulesData();
|
||||
const { uptime } = useAppUptime();
|
||||
const systemProxyAddress = useSystemProxyAddress({
|
||||
clashConfig,
|
||||
sysproxy,
|
||||
});
|
||||
const { clashConfig, rules, uptime, systemProxyAddress } = useAppData();
|
||||
|
||||
// 使用useMemo缓存格式化后的uptime,避免频繁计算
|
||||
const formattedUptime = useMemo(() => formatUptime(uptime), [uptime]);
|
||||
|
||||
@@ -9,8 +9,8 @@ import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { closeAllConnections } from "tauri-plugin-mihomo-api";
|
||||
|
||||
import { useClashConfig } from "@/hooks/use-clash-data";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
import { patchClashMode } from "@/services/cmds";
|
||||
import type { TranslationKey } from "@/types/generated/i18n-keys";
|
||||
|
||||
@@ -41,7 +41,7 @@ const MODE_META: Record<
|
||||
export const ClashModeCard = () => {
|
||||
const { t } = useTranslation();
|
||||
const { verge } = useVerge();
|
||||
const { clashConfig, refreshClashConfig } = useClashConfig();
|
||||
const { clashConfig, refreshClashConfig } = useAppData();
|
||||
|
||||
// 支持的模式列表
|
||||
const modeList = CLASH_MODES;
|
||||
|
||||
@@ -27,21 +27,22 @@ import {
|
||||
useTheme,
|
||||
} from "@mui/material";
|
||||
import { useLockFn } from "ahooks";
|
||||
import React from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router";
|
||||
import { delayGroup, healthcheckProxyProvider } from "tauri-plugin-mihomo-api";
|
||||
|
||||
import { EnhancedCard } from "@/components/home/enhanced-card";
|
||||
import {
|
||||
useClashConfig,
|
||||
useProxiesData,
|
||||
useRulesData,
|
||||
} from "@/hooks/use-clash-data";
|
||||
import { useProfiles } from "@/hooks/use-profiles";
|
||||
import { useProxySelection } from "@/hooks/use-proxy-selection";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
import delayManager from "@/services/delay";
|
||||
import { debugLog } from "@/utils/debug";
|
||||
|
||||
@@ -50,8 +51,8 @@ const STORAGE_KEY_GROUP = "clash-verge-selected-proxy-group";
|
||||
const STORAGE_KEY_PROXY = "clash-verge-selected-proxy";
|
||||
const STORAGE_KEY_SORT_TYPE = "clash-verge-proxy-sort-type";
|
||||
|
||||
const AUTO_CHECK_INITIAL_DELAY_MS = 1500;
|
||||
const AUTO_CHECK_INTERVAL_MS = 5 * 60 * 1000;
|
||||
const AUTO_CHECK_DEFAULT_INTERVAL_MINUTES = 5;
|
||||
const AUTO_CHECK_INITIAL_DELAY_MS = 100;
|
||||
|
||||
// 代理节点信息接口
|
||||
interface ProxyOption {
|
||||
@@ -88,9 +89,13 @@ function getSignalIcon(delay: number): {
|
||||
text: string;
|
||||
color: string;
|
||||
} {
|
||||
if (delay < 0)
|
||||
if (delay === -2)
|
||||
return { icon: <SignalNone />, text: "测试中", color: "text.secondary" };
|
||||
if (delay === -1)
|
||||
return { icon: <SignalNone />, text: "未测试", color: "text.secondary" };
|
||||
if (delay >= 10000)
|
||||
if (delay > 1e5)
|
||||
return { icon: <SignalError />, text: "错误", color: "error.main" };
|
||||
if (delay === 0 || delay >= 10000)
|
||||
return { icon: <SignalError />, text: "超时", color: "error.main" };
|
||||
if (delay >= 500)
|
||||
return { icon: <SignalWeak />, text: "延迟较高", color: "error.main" };
|
||||
@@ -105,13 +110,19 @@ export const CurrentProxyCard = () => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const theme = useTheme();
|
||||
const { proxies, refreshProxy } = useProxiesData();
|
||||
const { clashConfig } = useClashConfig();
|
||||
const { rules } = useRulesData();
|
||||
const { proxies, clashConfig, refreshProxy, rules } = useAppData();
|
||||
const { verge } = useVerge();
|
||||
const { current: currentProfile } = useProfiles();
|
||||
const autoDelayEnabled = verge?.enable_auto_delay_detection ?? false;
|
||||
const defaultLatencyTimeout = verge?.default_latency_timeout;
|
||||
const autoDelayIntervalMs = useMemo(() => {
|
||||
const rawInterval = verge?.auto_delay_detection_interval_minutes;
|
||||
const intervalMinutes =
|
||||
typeof rawInterval === "number" && rawInterval > 0
|
||||
? rawInterval
|
||||
: AUTO_CHECK_DEFAULT_INTERVAL_MINUTES;
|
||||
return Math.max(1, Math.round(intervalMinutes)) * 60 * 1000;
|
||||
}, [verge?.auto_delay_detection_interval_minutes]);
|
||||
const currentProfileId = currentProfile?.uid || null;
|
||||
|
||||
const getProfileStorageKey = useCallback(
|
||||
@@ -598,13 +609,13 @@ export const CurrentProxyCard = () => {
|
||||
if (disposed) return;
|
||||
await checkCurrentProxyDelay();
|
||||
if (disposed) return;
|
||||
intervalTimer = setTimeout(runAndSchedule, AUTO_CHECK_INTERVAL_MS);
|
||||
intervalTimer = setTimeout(runAndSchedule, autoDelayIntervalMs);
|
||||
};
|
||||
|
||||
initialTimer = setTimeout(async () => {
|
||||
await checkCurrentProxyDelay();
|
||||
if (disposed) return;
|
||||
intervalTimer = setTimeout(runAndSchedule, AUTO_CHECK_INTERVAL_MS);
|
||||
intervalTimer = setTimeout(runAndSchedule, autoDelayIntervalMs);
|
||||
}, AUTO_CHECK_INITIAL_DELAY_MS);
|
||||
|
||||
return () => {
|
||||
@@ -614,6 +625,7 @@ export const CurrentProxyCard = () => {
|
||||
};
|
||||
}, [
|
||||
checkCurrentProxyDelay,
|
||||
autoDelayIntervalMs,
|
||||
isDirectMode,
|
||||
state.selection.group,
|
||||
state.selection.proxy,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Box, Typography, alpha, useTheme } from "@mui/material";
|
||||
import { ReactNode } from "react";
|
||||
import React, { forwardRef, ReactNode } from "react";
|
||||
|
||||
// 自定义卡片组件接口
|
||||
interface EnhancedCardProps {
|
||||
@@ -19,103 +19,109 @@ interface EnhancedCardProps {
|
||||
}
|
||||
|
||||
// 自定义卡片组件
|
||||
export const EnhancedCard = ({
|
||||
title,
|
||||
icon,
|
||||
action,
|
||||
children,
|
||||
iconColor = "primary",
|
||||
minHeight,
|
||||
noContentPadding = false,
|
||||
}: EnhancedCardProps) => {
|
||||
const theme = useTheme();
|
||||
const isDark = theme.palette.mode === "dark";
|
||||
export const EnhancedCard = forwardRef<HTMLElement, EnhancedCardProps>(
|
||||
(
|
||||
{
|
||||
title,
|
||||
icon,
|
||||
action,
|
||||
children,
|
||||
iconColor = "primary",
|
||||
minHeight,
|
||||
noContentPadding = false,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const theme = useTheme();
|
||||
const isDark = theme.palette.mode === "dark";
|
||||
|
||||
// 统一的标题截断样式
|
||||
const titleTruncateStyle = {
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
display: "block",
|
||||
};
|
||||
// 统一的标题截断样式
|
||||
const titleTruncateStyle = {
|
||||
minWidth: 0,
|
||||
maxWidth: "100%",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
display: "block",
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
borderRadius: 2,
|
||||
backgroundColor: isDark ? "#282a36" : "#ffffff",
|
||||
}}
|
||||
>
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
height: "100%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
borderBottom: 1,
|
||||
borderColor: "divider",
|
||||
flexDirection: "column",
|
||||
borderRadius: 2,
|
||||
backgroundColor: isDark ? "#282a36" : "#ffffff",
|
||||
}}
|
||||
ref={ref}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
px: 2,
|
||||
py: 1,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
minWidth: 0,
|
||||
flex: 1,
|
||||
overflow: "hidden",
|
||||
justifyContent: "space-between",
|
||||
borderBottom: 1,
|
||||
borderColor: "divider",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: 1.5,
|
||||
width: 38,
|
||||
height: 38,
|
||||
mr: 1.5,
|
||||
flexShrink: 0,
|
||||
backgroundColor: alpha(theme.palette[iconColor].main, 0.12),
|
||||
color: theme.palette[iconColor].main,
|
||||
minWidth: 0,
|
||||
flex: 1,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
<Box sx={{ minWidth: 0, flex: 1 }}>
|
||||
{typeof title === "string" ? (
|
||||
<Typography
|
||||
variant="h6"
|
||||
fontWeight="medium"
|
||||
fontSize={18}
|
||||
sx={titleTruncateStyle}
|
||||
title={title}
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
) : (
|
||||
<Box sx={titleTruncateStyle}>{title}</Box>
|
||||
)}
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: 1.5,
|
||||
width: 38,
|
||||
height: 38,
|
||||
mr: 1.5,
|
||||
flexShrink: 0,
|
||||
backgroundColor: alpha(theme.palette[iconColor].main, 0.12),
|
||||
color: theme.palette[iconColor].main,
|
||||
}}
|
||||
>
|
||||
{icon}
|
||||
</Box>
|
||||
<Box sx={{ minWidth: 0, flex: 1 }}>
|
||||
{typeof title === "string" ? (
|
||||
<Typography
|
||||
variant="h6"
|
||||
fontWeight="medium"
|
||||
fontSize={18}
|
||||
sx={titleTruncateStyle}
|
||||
title={title}
|
||||
>
|
||||
{title}
|
||||
</Typography>
|
||||
) : (
|
||||
<Box sx={titleTruncateStyle}>{title}</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
{action && <Box sx={{ ml: 2, flexShrink: 0 }}>{action}</Box>}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
p: noContentPadding ? 0 : 2,
|
||||
...(minHeight && { minHeight }),
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
{action && <Box sx={{ ml: 2, flexShrink: 0 }}>{action}</Box>}
|
||||
</Box>
|
||||
<Box
|
||||
sx={{
|
||||
flex: 1,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
p: noContentPadding ? 0 : 2,
|
||||
...(minHeight && { minHeight }),
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -24,7 +24,7 @@ import { useCallback, useMemo, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router";
|
||||
|
||||
import { useRefreshAll } from "@/hooks/use-clash-data";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
import { openWebUrl, updateProfile } from "@/services/cmds";
|
||||
import { showNotice } from "@/services/notice-service";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
@@ -281,7 +281,7 @@ export const HomeProfileCard = ({
|
||||
}: HomeProfileCardProps) => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const refreshAll = useRefreshAll();
|
||||
const { refreshAll } = useAppData();
|
||||
|
||||
// 更新当前订阅
|
||||
const [updating, setUpdating] = useState(false);
|
||||
|
||||
@@ -5,19 +5,32 @@ import {
|
||||
VisibilityOutlined,
|
||||
} from "@mui/icons-material";
|
||||
import { Box, Button, IconButton, Skeleton, Typography } from "@mui/material";
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import { useEffect } from "foxact/use-abortable-effect";
|
||||
import { useIntersection } from "foxact/use-intersection";
|
||||
import type { XOR } from "foxts/ts-xor";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useState,
|
||||
useEffectEvent,
|
||||
useMemo,
|
||||
forwardRef,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import useSWRImmutable from "swr/immutable";
|
||||
|
||||
import { getIpInfo } from "@/services/api";
|
||||
import { SWR_EXTERNAL_API } from "@/services/config";
|
||||
|
||||
import { EnhancedCard } from "./enhanced-card";
|
||||
|
||||
// 定义刷新时间(秒)
|
||||
const IP_REFRESH_SECONDS = 300;
|
||||
const COUNTDOWN_TICK_INTERVAL = 5_000;
|
||||
const IP_INFO_CACHE_KEY = "cv_ip_info_cache";
|
||||
|
||||
// 提取InfoItem子组件并使用memo优化
|
||||
const InfoItem = memo(({ label, value }: { label: string; value: string }) => (
|
||||
const InfoItem = memo(({ label, value }: { label: string; value?: string }) => (
|
||||
<Box sx={{ mb: 0.7, display: "flex", alignItems: "flex-start" }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
@@ -43,7 +56,7 @@ const InfoItem = memo(({ label, value }: { label: string; value: string }) => (
|
||||
));
|
||||
|
||||
// 获取国旗表情
|
||||
const getCountryFlag = (countryCode: string) => {
|
||||
const getCountryFlag = (countryCode: string | undefined) => {
|
||||
if (!countryCode) return "";
|
||||
const codePoints = countryCode
|
||||
.toUpperCase()
|
||||
@@ -52,162 +65,184 @@ const getCountryFlag = (countryCode: string) => {
|
||||
return String.fromCodePoint(...codePoints);
|
||||
};
|
||||
|
||||
// IP信息卡片组件
|
||||
export const IpInfoCard = () => {
|
||||
const { t } = useTranslation();
|
||||
const [ipInfo, setIpInfo] = useState<any>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState("");
|
||||
const [showIp, setShowIp] = useState(false);
|
||||
const [countdown, setCountdown] = useState(IP_REFRESH_SECONDS);
|
||||
const lastFetchRef = useRef<number | null>(null);
|
||||
type CountDownState = XOR<
|
||||
{
|
||||
type: "countdown";
|
||||
remainingSeconds: number;
|
||||
},
|
||||
{
|
||||
type: "revalidating";
|
||||
}
|
||||
>;
|
||||
|
||||
const fetchIpInfo = useCallback(
|
||||
async (force = false) => {
|
||||
setError("");
|
||||
const IPInfoCardContainer = forwardRef<HTMLElement, React.PropsWithChildren>(
|
||||
({ children }, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const { mutate } = useIPInfo();
|
||||
|
||||
try {
|
||||
if (!force && typeof window !== "undefined" && window.sessionStorage) {
|
||||
const raw = window.sessionStorage.getItem(IP_INFO_CACHE_KEY);
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
const now = Date.now();
|
||||
if (
|
||||
parsed?.ts &&
|
||||
parsed?.data &&
|
||||
now - parsed.ts < IP_REFRESH_SECONDS * 1000
|
||||
) {
|
||||
setIpInfo(parsed.data);
|
||||
lastFetchRef.current = parsed.ts;
|
||||
const elapsed = Math.floor((now - parsed.ts) / 1000);
|
||||
setCountdown(Math.max(IP_REFRESH_SECONDS - elapsed, 0));
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Failed to read IP info from sessionStorage:", e);
|
||||
}
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
const data = await getIpInfo();
|
||||
setIpInfo(data);
|
||||
const ts = Date.now();
|
||||
lastFetchRef.current = ts;
|
||||
try {
|
||||
if (typeof window !== "undefined" && window.sessionStorage) {
|
||||
window.sessionStorage.setItem(
|
||||
IP_INFO_CACHE_KEY,
|
||||
JSON.stringify({ data, ts }),
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Failed to write IP info to sessionStorage:", e);
|
||||
}
|
||||
setCountdown(IP_REFRESH_SECONDS);
|
||||
} catch (err) {
|
||||
setError(
|
||||
err instanceof Error
|
||||
? err.message
|
||||
: t("home.components.ipInfo.errors.load"),
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[t],
|
||||
);
|
||||
|
||||
// 组件加载时获取IP信息并启动基于上次请求时间的倒计时
|
||||
useEffect(() => {
|
||||
fetchIpInfo();
|
||||
|
||||
let timer: number | null = null;
|
||||
|
||||
const startCountdown = () => {
|
||||
timer = window.setInterval(() => {
|
||||
const now = Date.now();
|
||||
let ts = lastFetchRef.current;
|
||||
try {
|
||||
if (!ts && typeof window !== "undefined" && window.sessionStorage) {
|
||||
const raw = window.sessionStorage.getItem(IP_INFO_CACHE_KEY);
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw);
|
||||
ts = parsed?.ts || null;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Failed to read IP info from sessionStorage:", e);
|
||||
ts = ts || null;
|
||||
}
|
||||
|
||||
const elapsed = ts ? Math.floor((now - ts) / 1000) : 0;
|
||||
let remaining = IP_REFRESH_SECONDS - elapsed;
|
||||
|
||||
if (remaining <= 0) {
|
||||
fetchIpInfo();
|
||||
remaining = IP_REFRESH_SECONDS;
|
||||
}
|
||||
|
||||
// 每5秒或倒计时结束时才更新UI
|
||||
if (remaining % 5 === 0 || remaining <= 0) {
|
||||
setCountdown(remaining);
|
||||
}
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
startCountdown();
|
||||
return () => {
|
||||
if (timer) clearInterval(timer);
|
||||
};
|
||||
}, [fetchIpInfo]);
|
||||
|
||||
const toggleShowIp = useCallback(() => {
|
||||
setShowIp((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
// 渲染加载状态
|
||||
if (loading) {
|
||||
return (
|
||||
<EnhancedCard
|
||||
title={t("home.components.ipInfo.title")}
|
||||
icon={<LocationOnOutlined />}
|
||||
iconColor="info"
|
||||
ref={ref}
|
||||
action={
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => fetchIpInfo(true)}
|
||||
disabled={true}
|
||||
>
|
||||
<IconButton size="small" onClick={() => mutate()}>
|
||||
<RefreshOutlined />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</EnhancedCard>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// IP信息卡片组件
|
||||
export const IpInfoCard = () => {
|
||||
const { t } = useTranslation();
|
||||
const [showIp, setShowIp] = useState(false);
|
||||
const appWindow = useMemo(() => getCurrentWebviewWindow(), []);
|
||||
|
||||
// track ip info card has been in viewport or not
|
||||
// hasIntersected default to false, and will be true once the card is in viewport
|
||||
// and will never be false again afterwards (unless resetIntersected is called or
|
||||
// the component is unmounted)
|
||||
const [containerRef, hasIntersected, _resetIntersected] = useIntersection({
|
||||
rootMargin: "0px",
|
||||
});
|
||||
|
||||
const [countdown, setCountdown] = useState<CountDownState>({
|
||||
type: "countdown",
|
||||
remainingSeconds: IP_REFRESH_SECONDS,
|
||||
});
|
||||
|
||||
const { data: ipInfo, error, isLoading, mutate } = useIPInfo();
|
||||
|
||||
// function useEffectEvent
|
||||
const onCountdownTick = useEffectEvent(async () => {
|
||||
const now = Date.now();
|
||||
const ts = ipInfo?.lastFetchTs;
|
||||
if (!ts) {
|
||||
return;
|
||||
}
|
||||
|
||||
const elapsed = Math.floor((now - ts) / 1000);
|
||||
const remaining = IP_REFRESH_SECONDS - elapsed;
|
||||
|
||||
if (remaining <= 0) {
|
||||
if (
|
||||
// has intersected at least once
|
||||
// this avoids unncessary revalidation if user never scrolls down,
|
||||
// then we will only load initially once.
|
||||
hasIntersected &&
|
||||
// is online
|
||||
navigator.onLine &&
|
||||
// there is no ongoing revalidation already scheduled
|
||||
countdown.type !== "revalidating" &&
|
||||
// window is visible
|
||||
(await appWindow.isVisible())
|
||||
) {
|
||||
setCountdown({ type: "revalidating" });
|
||||
// we do not care about the result of mutate here. after mutate is done,
|
||||
// simply wait for next interval tick with `setCountdown({ type: "countdown", ... })`
|
||||
try {
|
||||
await mutate();
|
||||
} finally {
|
||||
// in case mutate throws error, we still need to reset the countdown state
|
||||
setCountdown({
|
||||
type: "countdown",
|
||||
remainingSeconds: IP_REFRESH_SECONDS,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// do nothing. we even skip "setCountdown" to reduce re-renders
|
||||
//
|
||||
// but the remaining time still <= 0, and setInterval is not stopped, this
|
||||
// callback will still be regularly triggered, as soon as the window is visible
|
||||
// or network online again, we mutate() immediately in the following tick.
|
||||
}
|
||||
} else {
|
||||
setCountdown({
|
||||
type: "countdown",
|
||||
remainingSeconds: remaining,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Countdown / refresh scheduler — updates UI every 1s and triggers immediate revalidation when expired
|
||||
useEffect(() => {
|
||||
let timer: number | null = null;
|
||||
|
||||
// Do not add document.hidden check here as it is not reliable in Tauri.
|
||||
//
|
||||
// Thank god IntersectionObserver is a DOM API that relies on DOM/webview
|
||||
// instead of Tauri, which is reliable enough.
|
||||
if (hasIntersected) {
|
||||
console.debug(
|
||||
"IP info card has entered the viewport, starting the countdown interval.",
|
||||
);
|
||||
timer = window.setInterval(onCountdownTick, COUNTDOWN_TICK_INTERVAL);
|
||||
} else {
|
||||
console.debug(
|
||||
"IP info card has not yet entered the viewport, no counting down.",
|
||||
);
|
||||
}
|
||||
|
||||
// This will fire when the window is minimized or restored
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
// Tauri's visibility change detection is actually broken on some platforms:
|
||||
// https://github.com/tauri-apps/tauri/issues/10592
|
||||
//
|
||||
// It is working on macOS though (tested).
|
||||
// So at least we should try to pause countdown on supported platforms to
|
||||
// reduce power consumption.
|
||||
function onVisibilityChange() {
|
||||
if (document.hidden) {
|
||||
console.debug("Document hidden, pause the interval");
|
||||
// Pause the timer
|
||||
if (timer != null) {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
} else if (hasIntersected) {
|
||||
console.debug("Document visible, resume the interval");
|
||||
// Resume the timer only when previous one is cleared
|
||||
if (timer == null) {
|
||||
timer = window.setInterval(onCountdownTick, COUNTDOWN_TICK_INTERVAL);
|
||||
}
|
||||
} else {
|
||||
console.debug(
|
||||
"Document visible, but IP info card has never entered the viewport, not even once, not starting the interval.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (timer != null) clearInterval(timer);
|
||||
document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
};
|
||||
}, [hasIntersected]);
|
||||
|
||||
const toggleShowIp = useCallback(() => {
|
||||
setShowIp((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
let mainElement: React.ReactElement;
|
||||
|
||||
switch (true) {
|
||||
case isLoading:
|
||||
mainElement = (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 1 }}>
|
||||
<Skeleton variant="text" width="60%" height={30} />
|
||||
<Skeleton variant="text" width="80%" height={24} />
|
||||
<Skeleton variant="text" width="70%" height={24} />
|
||||
<Skeleton variant="text" width="50%" height={24} />
|
||||
</Box>
|
||||
</EnhancedCard>
|
||||
);
|
||||
}
|
||||
|
||||
// 渲染错误状态
|
||||
if (error) {
|
||||
return (
|
||||
<EnhancedCard
|
||||
title={t("home.components.ipInfo.title")}
|
||||
icon={<LocationOnOutlined />}
|
||||
iconColor="info"
|
||||
action={
|
||||
<IconButton size="small" onClick={() => fetchIpInfo(true)}>
|
||||
<RefreshOutlined />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
);
|
||||
break;
|
||||
case !!error:
|
||||
mainElement = (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
@@ -219,170 +254,173 @@ export const IpInfoCard = () => {
|
||||
}}
|
||||
>
|
||||
<Typography variant="body1" color="error">
|
||||
{error}
|
||||
{error instanceof Error
|
||||
? error.message
|
||||
: t("home.components.ipInfo.errors.load")}
|
||||
</Typography>
|
||||
<Button onClick={() => fetchIpInfo(true)} sx={{ mt: 2 }}>
|
||||
<Button onClick={() => mutate()} sx={{ mt: 2 }}>
|
||||
{t("shared.actions.retry")}
|
||||
</Button>
|
||||
</Box>
|
||||
</EnhancedCard>
|
||||
);
|
||||
}
|
||||
|
||||
// 渲染正常数据
|
||||
return (
|
||||
<EnhancedCard
|
||||
title={t("home.components.ipInfo.title")}
|
||||
icon={<LocationOnOutlined />}
|
||||
iconColor="info"
|
||||
action={
|
||||
<IconButton size="small" onClick={() => fetchIpInfo(true)}>
|
||||
<RefreshOutlined />
|
||||
</IconButton>
|
||||
}
|
||||
>
|
||||
<Box sx={{ height: "100%", display: "flex", flexDirection: "column" }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "row",
|
||||
flex: 1,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{/* 左侧:国家和IP地址 */}
|
||||
<Box sx={{ width: "40%", overflow: "hidden" }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
mb: 1,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
fontSize: "1.5rem",
|
||||
mr: 1,
|
||||
display: "inline-block",
|
||||
width: 28,
|
||||
textAlign: "center",
|
||||
flexShrink: 0,
|
||||
fontFamily: '"twemoji mozilla", sans-serif',
|
||||
}}
|
||||
>
|
||||
{getCountryFlag(ipInfo?.country_code)}
|
||||
</Box>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
sx={{
|
||||
fontWeight: "medium",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
maxWidth: "100%",
|
||||
}}
|
||||
>
|
||||
{ipInfo?.country || t("home.components.ipInfo.labels.unknown")}
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", alignItems: "center", mb: 1 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{ flexShrink: 0 }}
|
||||
>
|
||||
{t("home.components.ipInfo.labels.ip")}:
|
||||
</Typography>
|
||||
);
|
||||
break;
|
||||
default: // Normal render
|
||||
mainElement = (
|
||||
<Box sx={{ height: "100%", display: "flex", flexDirection: "column" }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: "row",
|
||||
flex: 1,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
{/* 左侧:国家和IP地址 */}
|
||||
<Box sx={{ width: "40%", overflow: "hidden" }}>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
ml: 1,
|
||||
mb: 1,
|
||||
overflow: "hidden",
|
||||
maxWidth: "calc(100% - 30px)",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
<Box
|
||||
component="span"
|
||||
sx={{
|
||||
fontFamily: "monospace",
|
||||
fontSize: "0.75rem",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
wordBreak: "break-all",
|
||||
fontSize: "1.5rem",
|
||||
mr: 1,
|
||||
display: "inline-block",
|
||||
width: 28,
|
||||
textAlign: "center",
|
||||
flexShrink: 0,
|
||||
fontFamily: '"twemoji mozilla", sans-serif',
|
||||
}}
|
||||
>
|
||||
{showIp ? ipInfo?.ip : "••••••••••"}
|
||||
{getCountryFlag(ipInfo?.country_code)}
|
||||
</Box>
|
||||
<Typography
|
||||
variant="subtitle1"
|
||||
sx={{
|
||||
fontWeight: "medium",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
whiteSpace: "nowrap",
|
||||
maxWidth: "100%",
|
||||
}}
|
||||
>
|
||||
{ipInfo?.country ||
|
||||
t("home.components.ipInfo.labels.unknown")}
|
||||
</Typography>
|
||||
<IconButton size="small" onClick={toggleShowIp}>
|
||||
{showIp ? (
|
||||
<VisibilityOffOutlined fontSize="small" />
|
||||
) : (
|
||||
<VisibilityOutlined fontSize="small" />
|
||||
)}
|
||||
</IconButton>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", alignItems: "center", mb: 1 }}>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{ flexShrink: 0 }}
|
||||
>
|
||||
{t("home.components.ipInfo.labels.ip")}:
|
||||
</Typography>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
ml: 1,
|
||||
overflow: "hidden",
|
||||
maxWidth: "calc(100% - 30px)",
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
sx={{
|
||||
fontFamily: "monospace",
|
||||
fontSize: "0.75rem",
|
||||
overflow: "hidden",
|
||||
textOverflow: "ellipsis",
|
||||
wordBreak: "break-all",
|
||||
}}
|
||||
>
|
||||
{showIp ? ipInfo?.ip : "••••••••••"}
|
||||
</Typography>
|
||||
<IconButton size="small" onClick={toggleShowIp}>
|
||||
{showIp ? (
|
||||
<VisibilityOffOutlined fontSize="small" />
|
||||
) : (
|
||||
<VisibilityOutlined fontSize="small" />
|
||||
)}
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.asn")}
|
||||
value={ipInfo?.asn ? `AS${ipInfo.asn}` : "N/A"}
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.asn")}
|
||||
value={ipInfo?.asn ? `AS${ipInfo.asn}` : "N/A"}
|
||||
/>
|
||||
{/* 右侧:组织、ISP和位置信息 */}
|
||||
<Box sx={{ width: "60%", overflow: "auto" }}>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.isp")}
|
||||
value={ipInfo?.organization}
|
||||
/>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.org")}
|
||||
value={ipInfo?.asn_organization}
|
||||
/>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.location")}
|
||||
value={[ipInfo?.city, ipInfo?.region]
|
||||
.filter(Boolean)
|
||||
.join(", ")}
|
||||
/>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.timezone")}
|
||||
value={ipInfo?.timezone}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* 右侧:组织、ISP和位置信息 */}
|
||||
<Box sx={{ width: "60%", overflow: "auto" }}>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.isp")}
|
||||
value={ipInfo?.isp}
|
||||
/>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.org")}
|
||||
value={ipInfo?.asn_organization}
|
||||
/>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.location")}
|
||||
value={[ipInfo?.city, ipInfo?.region].filter(Boolean).join(", ")}
|
||||
/>
|
||||
<InfoItem
|
||||
label={t("home.components.ipInfo.labels.timezone")}
|
||||
value={ipInfo?.timezone}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
mt: "auto",
|
||||
pt: 0.5,
|
||||
borderTop: 1,
|
||||
borderColor: "divider",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
opacity: 0.7,
|
||||
fontSize: "0.7rem",
|
||||
}}
|
||||
>
|
||||
<Typography variant="caption">
|
||||
{t("home.components.ipInfo.labels.autoRefresh")}: {countdown}s
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
<Box
|
||||
sx={{
|
||||
textOverflow: "ellipsis",
|
||||
overflow: "hidden",
|
||||
whiteSpace: "nowrap",
|
||||
mt: "auto",
|
||||
pt: 0.5,
|
||||
borderTop: 1,
|
||||
borderColor: "divider",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
opacity: 0.7,
|
||||
fontSize: "0.7rem",
|
||||
}}
|
||||
>
|
||||
{ipInfo?.country_code}, {ipInfo?.longitude?.toFixed(2)},{" "}
|
||||
{ipInfo?.latitude?.toFixed(2)}
|
||||
</Typography>
|
||||
<Typography variant="caption">
|
||||
{t("home.components.ipInfo.labels.autoRefresh")}
|
||||
{countdown.type === "countdown"
|
||||
? `: ${countdown.remainingSeconds}s`
|
||||
: "..."}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="caption"
|
||||
sx={{
|
||||
textOverflow: "ellipsis",
|
||||
overflow: "hidden",
|
||||
whiteSpace: "nowrap",
|
||||
}}
|
||||
>
|
||||
{`${ipInfo?.country_code ?? "N/A"}, ${ipInfo?.longitude?.toFixed(2) ?? "N/A"}, ${ipInfo?.latitude?.toFixed(2) ?? "N/A"}`}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</EnhancedCard>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<IPInfoCardContainer ref={containerRef}>{mainElement}</IPInfoCardContainer>
|
||||
);
|
||||
};
|
||||
|
||||
function useIPInfo() {
|
||||
return useSWRImmutable(IP_INFO_CACHE_KEY, getIpInfo, SWR_EXTERNAL_API);
|
||||
}
|
||||
|
||||
@@ -10,14 +10,13 @@ import { useLockFn } from "ahooks";
|
||||
import { useCallback, useEffect, useMemo, useReducer } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useNavigate } from "react-router";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { useServiceInstaller } from "@/hooks/use-service-installer";
|
||||
import { useSystemState } from "@/hooks/use-system-state";
|
||||
import { useUpdate } from "@/hooks/use-update";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { getSystemInfo } from "@/services/cmds";
|
||||
import { showNotice } from "@/services/notice-service";
|
||||
import { checkUpdateSafe as checkUpdate } from "@/services/update";
|
||||
import { version as appVersion } from "@root/package.json";
|
||||
|
||||
import { EnhancedCard } from "./enhanced-card";
|
||||
@@ -52,6 +51,18 @@ export const SystemInfoCard = () => {
|
||||
const { isAdminMode, isSidecarMode } = useSystemState();
|
||||
const { installServiceAndRestartCore } = useServiceInstaller();
|
||||
|
||||
// 自动检查更新逻辑
|
||||
const { checkUpdate: triggerCheckUpdate } = useUpdate(true, {
|
||||
onSuccess: () => {
|
||||
const now = Date.now();
|
||||
localStorage.setItem("last_check_update", now.toString());
|
||||
dispatchSystemState({
|
||||
type: "set-last-check-update",
|
||||
payload: new Date(now).toLocaleString(),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
// 系统信息状态
|
||||
const [systemState, dispatchSystemState] = useReducer(systemStateReducer, {
|
||||
osInfo: "",
|
||||
@@ -109,7 +120,7 @@ export const SystemInfoCard = () => {
|
||||
|
||||
timeoutId = window.setTimeout(() => {
|
||||
if (verge?.auto_check_update) {
|
||||
checkUpdate().catch(console.error);
|
||||
triggerCheckUpdate().catch(console.error);
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
@@ -118,26 +129,7 @@ export const SystemInfoCard = () => {
|
||||
window.clearTimeout(timeoutId);
|
||||
}
|
||||
};
|
||||
}, [verge?.auto_check_update, dispatchSystemState]);
|
||||
|
||||
// 自动检查更新逻辑
|
||||
useSWR(
|
||||
verge?.auto_check_update ? "checkUpdate" : null,
|
||||
async () => {
|
||||
const now = Date.now();
|
||||
localStorage.setItem("last_check_update", now.toString());
|
||||
dispatchSystemState({
|
||||
type: "set-last-check-update",
|
||||
payload: new Date(now).toLocaleString(),
|
||||
});
|
||||
return await checkUpdate();
|
||||
},
|
||||
{
|
||||
revalidateOnFocus: false,
|
||||
refreshInterval: 24 * 60 * 60 * 1000, // 每天检查一次
|
||||
dedupingInterval: 60 * 60 * 1000, // 1小时内不重复检查
|
||||
},
|
||||
);
|
||||
}, [verge?.auto_check_update, dispatchSystemState, triggerCheckUpdate]);
|
||||
|
||||
// 导航到设置页面
|
||||
const goToSettings = useCallback(() => {
|
||||
@@ -164,7 +156,7 @@ export const SystemInfoCard = () => {
|
||||
// 检查更新
|
||||
const onCheckUpdate = useLockFn(async () => {
|
||||
try {
|
||||
const info = await checkUpdate();
|
||||
const info = await triggerCheckUpdate();
|
||||
if (!info?.available) {
|
||||
showNotice.success(
|
||||
"settings.components.verge.advanced.notifications.latestVersion",
|
||||
|
||||
@@ -107,10 +107,7 @@ export function TrafficGraph({ ref }: { ref?: Ref<TrafficRef> }) {
|
||||
countY(y),
|
||||
]);
|
||||
|
||||
let x = points[0][0];
|
||||
let y = points[0][1];
|
||||
|
||||
context.moveTo(x, y);
|
||||
context.moveTo(points[0][0], points[0][1]);
|
||||
|
||||
for (let i = 1; i < points.length; i++) {
|
||||
const p1 = points[i];
|
||||
@@ -120,8 +117,6 @@ export function TrafficGraph({ ref }: { ref?: Ref<TrafficRef> }) {
|
||||
const y1 = (p1[1] + p2[1]) / 2;
|
||||
|
||||
context.quadraticCurveTo(p1[0], p1[1], x1, y1);
|
||||
x = x1;
|
||||
y = y1;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { Button } from "@mui/material";
|
||||
import { useRef } from "react";
|
||||
import useSWR from "swr";
|
||||
|
||||
import { DialogRef } from "@/components/base";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { checkUpdateSafe } from "@/services/update";
|
||||
import { useUpdate } from "@/hooks/use-update";
|
||||
|
||||
import { UpdateViewer } from "../setting/mods/update-viewer";
|
||||
|
||||
@@ -14,20 +12,9 @@ interface Props {
|
||||
|
||||
export const UpdateButton = (props: Props) => {
|
||||
const { className } = props;
|
||||
const { verge } = useVerge();
|
||||
const { auto_check_update } = verge || {};
|
||||
|
||||
const viewerRef = useRef<DialogRef>(null);
|
||||
|
||||
const { data: updateInfo } = useSWR(
|
||||
auto_check_update || auto_check_update === null ? "checkUpdate" : null,
|
||||
checkUpdateSafe,
|
||||
{
|
||||
errorRetryCount: 2,
|
||||
revalidateIfStale: false,
|
||||
focusThrottleInterval: 36e5, // 1 hour
|
||||
},
|
||||
);
|
||||
const { updateInfo } = useUpdate();
|
||||
|
||||
if (!updateInfo?.available) return null;
|
||||
|
||||
|
||||
@@ -86,6 +86,10 @@ export const GroupItem = (props: Props) => {
|
||||
<img
|
||||
src={`data:image/svg+xml;base64,${btoa(group.icon ?? "")}`}
|
||||
width="32px"
|
||||
style={{
|
||||
marginRight: "12px",
|
||||
borderRadius: "6px",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<ListItemText
|
||||
|
||||
@@ -490,11 +490,18 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
]}
|
||||
value={field.value}
|
||||
getOptionLabel={translateStrategy}
|
||||
renderOption={(props, option) => (
|
||||
<li {...props} title={translateStrategy(option)}>
|
||||
{translateStrategy(option)}
|
||||
</li>
|
||||
)}
|
||||
renderOption={(props, option) => {
|
||||
const { key, ...optionProps } = props;
|
||||
return (
|
||||
<li
|
||||
key={key}
|
||||
{...optionProps}
|
||||
title={translateStrategy(option)}
|
||||
>
|
||||
{translateStrategy(option)}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
onChange={(_, value) => value && field.onChange(value)}
|
||||
renderInput={(params) => <TextField {...params} />}
|
||||
/>
|
||||
@@ -557,11 +564,18 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
disableCloseOnSelect
|
||||
onChange={(_, value) => value && field.onChange(value)}
|
||||
renderInput={(params) => <TextField {...params} />}
|
||||
renderOption={(props, option) => (
|
||||
<li {...props} title={translatePolicy(option)}>
|
||||
{translatePolicy(option)}
|
||||
</li>
|
||||
)}
|
||||
renderOption={(props, option) => {
|
||||
const { key, ...optionProps } = props;
|
||||
return (
|
||||
<li
|
||||
key={key}
|
||||
{...optionProps}
|
||||
title={translatePolicy(option)}
|
||||
>
|
||||
{translatePolicy(option)}
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
getOptionLabel={translatePolicy}
|
||||
/>
|
||||
</Item>
|
||||
@@ -601,7 +615,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
/>
|
||||
<TextField
|
||||
autoComplete="new-password"
|
||||
placeholder="https://cp.cloudflare.com/generate_204"
|
||||
placeholder="http://1.0.0.1"
|
||||
size="small"
|
||||
sx={{ width: "calc(100% - 150px)" }}
|
||||
{...field}
|
||||
@@ -827,6 +841,7 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
"WireGuard",
|
||||
"Tuic",
|
||||
"Mieru",
|
||||
"Masque",
|
||||
"AnyTLS",
|
||||
"Sudoku",
|
||||
"Relay",
|
||||
|
||||
@@ -141,7 +141,7 @@ export const ProxiesEditorViewer = (props: Props) => {
|
||||
const handleParseAsync = (cb: (proxies: IProxyConfig[]) => void) => {
|
||||
const proxies: IProxyConfig[] = [];
|
||||
const names: string[] = [];
|
||||
let uris = "";
|
||||
let uris: string;
|
||||
try {
|
||||
uris = atob(proxyUri);
|
||||
} catch {
|
||||
|
||||
@@ -557,11 +557,12 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
t(RULE_TYPE_LABEL_KEYS[option.name] ?? option.name)
|
||||
}
|
||||
renderOption={(props, option) => {
|
||||
const { key, ...optionProps } = props;
|
||||
const label = t(
|
||||
RULE_TYPE_LABEL_KEYS[option.name] ?? option.name,
|
||||
);
|
||||
return (
|
||||
<li {...props} title={label}>
|
||||
<li key={key} {...optionProps} title={label}>
|
||||
{label}
|
||||
</li>
|
||||
);
|
||||
@@ -624,9 +625,10 @@ export const RulesEditorViewer = (props: Props) => {
|
||||
t(PROXY_POLICY_LABEL_KEYS[option] ?? option)
|
||||
}
|
||||
renderOption={(props, option) => {
|
||||
const { key, ...optionProps } = props;
|
||||
const label = t(PROXY_POLICY_LABEL_KEYS[option] ?? option);
|
||||
return (
|
||||
<li {...props} title={label}>
|
||||
<li key={key} {...optionProps} title={label}>
|
||||
{label}
|
||||
</li>
|
||||
);
|
||||
|
||||
@@ -22,7 +22,7 @@ import { useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { updateProxyProvider } from "tauri-plugin-mihomo-api";
|
||||
|
||||
import { useProxiesData, useProxyProvidersData } from "@/hooks/use-clash-data";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
import { showNotice } from "@/services/notice-service";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
|
||||
@@ -48,8 +48,7 @@ const parseExpire = (expire?: number) => {
|
||||
export const ProviderButton = () => {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const { proxyProviders, refreshProxyProviders } = useProxyProvidersData();
|
||||
const { refreshProxy } = useProxiesData();
|
||||
const { proxyProviders, refreshProxy, refreshProxyProviders } = useAppData();
|
||||
const [updating, setUpdating] = useState<Record<string, boolean>>({});
|
||||
|
||||
// 检查是否有提供者
|
||||
@@ -176,8 +175,8 @@ export const ProviderButton = () => {
|
||||
<List sx={{ py: 0, minHeight: 250 }}>
|
||||
{Object.entries(proxyProviders || {})
|
||||
.sort()
|
||||
.map(([key, provider]) => {
|
||||
if (!provider) return null;
|
||||
.map(([key, item]) => {
|
||||
const provider = item;
|
||||
const time = dayjs(provider.updatedAt);
|
||||
const isUpdating = updating[key];
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from "@dnd-kit/sortable";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
ArrowDownward,
|
||||
Delete as DeleteIcon,
|
||||
DragIndicator,
|
||||
Link,
|
||||
@@ -38,7 +39,7 @@ import {
|
||||
selectNodeForGroup,
|
||||
} from "tauri-plugin-mihomo-api";
|
||||
|
||||
import { useProxiesData } from "@/hooks/use-clash-data";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
import { updateProxyChainConfigInRuntime } from "@/services/cmds";
|
||||
import { debugLog } from "@/utils/debug";
|
||||
|
||||
@@ -69,10 +70,18 @@ interface ProxyChainProps {
|
||||
interface SortableItemProps {
|
||||
proxy: ProxyChainItem;
|
||||
index: number;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
onRemove: (id: string) => void;
|
||||
}
|
||||
|
||||
const SortableItem = ({ proxy, index, onRemove }: SortableItemProps) => {
|
||||
const SortableItem = ({
|
||||
proxy,
|
||||
index,
|
||||
isFirst,
|
||||
isLast,
|
||||
onRemove,
|
||||
}: SortableItemProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
@@ -90,12 +99,24 @@ const SortableItem = ({ proxy, index, onRemove }: SortableItemProps) => {
|
||||
opacity: isDragging ? 0.5 : 1,
|
||||
};
|
||||
|
||||
const roleLabel = isFirst
|
||||
? t("proxies.page.chain.entryNode")
|
||||
: isLast
|
||||
? t("proxies.page.chain.exitNode")
|
||||
: undefined;
|
||||
|
||||
const roleColor = isFirst
|
||||
? theme.palette.success.main
|
||||
: isLast
|
||||
? theme.palette.warning.main
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Box
|
||||
ref={setNodeRef}
|
||||
style={style}
|
||||
sx={{
|
||||
mb: 1,
|
||||
mb: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
p: 1,
|
||||
@@ -103,7 +124,9 @@ const SortableItem = ({ proxy, index, onRemove }: SortableItemProps) => {
|
||||
? theme.palette.action.selected
|
||||
: theme.palette.background.default,
|
||||
borderRadius: 1,
|
||||
border: `1px solid ${theme.palette.divider}`,
|
||||
border: roleColor
|
||||
? `1.5px solid ${roleColor}`
|
||||
: `1px solid ${theme.palette.divider}`,
|
||||
boxShadow: isDragging ? theme.shadows[4] : theme.shadows[1],
|
||||
transition: "box-shadow 0.2s, background-color 0.2s",
|
||||
}}
|
||||
@@ -125,12 +148,25 @@ const SortableItem = ({ proxy, index, onRemove }: SortableItemProps) => {
|
||||
<DragIndicator />
|
||||
</Box>
|
||||
|
||||
<Chip
|
||||
label={`${index + 1}`}
|
||||
size="small"
|
||||
color="primary"
|
||||
sx={{ mr: 1, minWidth: 32 }}
|
||||
/>
|
||||
{roleLabel ? (
|
||||
<Chip
|
||||
label={roleLabel}
|
||||
size="small"
|
||||
sx={{
|
||||
mr: 1,
|
||||
fontWeight: 700,
|
||||
color: "#fff",
|
||||
backgroundColor: roleColor,
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<Chip
|
||||
label={`${index + 1}`}
|
||||
size="small"
|
||||
color="primary"
|
||||
sx={{ mr: 1, minWidth: 32 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Typography
|
||||
variant="body2"
|
||||
@@ -199,7 +235,7 @@ export const ProxyChain = ({
|
||||
}: ProxyChainProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const { proxies, refreshProxy } = useProxiesData();
|
||||
const { proxies, refreshProxy } = useAppData();
|
||||
const [isConnecting, setIsConnecting] = useState(false);
|
||||
const markUnsavedChanges = useCallback(() => {
|
||||
onMarkUnsavedChanges?.();
|
||||
@@ -221,7 +257,7 @@ export const ProxyChain = ({
|
||||
}
|
||||
|
||||
const proxyChainGroup = proxies.groups.find(
|
||||
(group) => group.name === selectedGroup,
|
||||
(group: { name: string }) => group.name === selectedGroup,
|
||||
);
|
||||
|
||||
return proxyChainGroup?.now === lastNode.name;
|
||||
@@ -579,12 +615,34 @@ export const ProxyChain = ({
|
||||
}}
|
||||
>
|
||||
{proxyChain.map((proxy, index) => (
|
||||
<SortableItem
|
||||
key={proxy.id}
|
||||
proxy={proxy}
|
||||
index={index}
|
||||
onRemove={handleRemoveProxy}
|
||||
/>
|
||||
<Box key={proxy.id}>
|
||||
<SortableItem
|
||||
proxy={proxy}
|
||||
index={index}
|
||||
isFirst={index === 0}
|
||||
isLast={
|
||||
index === proxyChain.length - 1 && proxyChain.length > 1
|
||||
}
|
||||
onRemove={handleRemoveProxy}
|
||||
/>
|
||||
{index < proxyChain.length - 1 && (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
justifyContent: "center",
|
||||
py: 0.25,
|
||||
}}
|
||||
>
|
||||
<ArrowDownward
|
||||
sx={{
|
||||
fontSize: 20,
|
||||
color: theme.palette.primary.main,
|
||||
opacity: 0.7,
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</SortableContext>
|
||||
|
||||
@@ -16,9 +16,9 @@ import { Virtuoso, type VirtuosoHandle } from "react-virtuoso";
|
||||
import { delayGroup, healthcheckProxyProvider } from "tauri-plugin-mihomo-api";
|
||||
|
||||
import { BaseEmpty } from "@/components/base";
|
||||
import { useProxiesData } from "@/hooks/use-clash-data";
|
||||
import { useProxySelection } from "@/hooks/use-proxy-selection";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { useAppData } from "@/providers/app-data-context";
|
||||
import { updateProxyChainConfigInRuntime } from "@/services/cmds";
|
||||
import delayManager from "@/services/delay";
|
||||
import { debugLog } from "@/utils/debug";
|
||||
@@ -80,7 +80,7 @@ export const ProxyGroups = (props: Props) => {
|
||||
}>({ open: false, message: "" });
|
||||
|
||||
const { verge } = useVerge();
|
||||
const { proxies: proxiesData } = useProxiesData();
|
||||
const { proxies: proxiesData } = useAppData();
|
||||
const groups = proxiesData?.groups;
|
||||
const availableGroups = useMemo(() => {
|
||||
if (!groups) return [];
|
||||
|
||||
@@ -66,8 +66,7 @@ export const ProxyHead = ({
|
||||
|
||||
const { verge } = useVerge();
|
||||
const defaultLatencyUrl =
|
||||
verge?.default_latency_test?.trim() ||
|
||||
"https://cp.cloudflare.com/generate_204";
|
||||
verge?.default_latency_test?.trim() || "http://1.0.0.1";
|
||||
|
||||
useEffect(() => {
|
||||
delayManager.setUrl(groupName, testUrl?.trim() || url || defaultLatencyUrl);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user