Compare commits

..
Author SHA1 Message Date
Tunglies 8ad95657bd style(widget): adopt system type styles and control conventions
Replace fixed point sizes with semantic footnote/caption styles, dim
unselected mode labels into a secondary tier, drop the mode track fill
and capsule borders in favor of one capsule language, and reshape the
toggles as borderless system-style pills. Section spacing unifies at
8pt and the error row gains a leading warning glyph. No behavior
change.
2026-09-14 18:50:16 +08:00
Tunglies a544990f9f fix(widget): raise the window via a dedicated deep-link route
Tapping a desktop-widget background activates a tray-only host through
LaunchServices, which never fires the macOS reopen event, so the app
appeared in the Dock without a window. Point the widget tap URL at the
dedicated clash-verge://show route and handle it in the scheme resolver
by raising the main window (including leaving lightweight mode). Bare
and subscription deep links keep their previous behavior.

Signed-off-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
2026-09-14 15:03:41 +08:00
Tunglies e35a239a06 refactor(widget): resolve all SwiftLint warnings
Split the extension socket client into connect/send/read helpers so
exchange() stays under the complexity and body-length limits, rename the
file-descriptor parameters, drop redundant nil initialization on the
debug preview knobs, and wrap over-length lines. No behavior change.
2026-09-14 13:59:51 +08:00
Tunglies 143ed48aa9 feat(widget): add macOS desktop widget
Ship a native WidgetKit extension (routing mode, TUN and system proxy
toggles) as part of every macOS build. The extension talks to the Rust
backend over an App Group Unix socket with mutual code-signing checks,
reuses the backend i18n catalogs, and stays inert on macOS < 14.

A beforeBundle hook builds, localizes and pre-signs the extension before
Tauri signs the host; pnpm build resolves a single local signing identity
automatically and CI keeps using its injected credentials. An Xcode
style-preview host is included for iterating on the widget layout. The
i18n cleanup scanner now also scans Swift sources so widget-only keys
are not flagged unused.

Signed-off-by: Tunglies <77394545+Tunglies@users.noreply.github.com>
2026-09-14 13:59:40 +08:00
63 changed files with 3490 additions and 1492 deletions
-8
View File
@@ -30,19 +30,11 @@ jobs:
PR_BODY: ${{ github.event.pull_request.body }}
LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
DRAFT: ${{ github.event.pull_request.draft }}
ASSOCIATION: ${{ github.event.pull_request.author_association }}
AUTHOR_TYPE: ${{ github.event.pull_request.user.type }}
run: |
if [ "$DRAFT" = "true" ] || printf '%s' "$LABELS" | grep -q 'no-issue-needed'; then
echo "Draft or no-issue-needed; linkage check skipped."
exit 0
fi
# OWNER/MEMBER/COLLABORATOR and bots mirror the slop review's
# skip-roles/skip-bots trust tier.
if [ "$AUTHOR_TYPE" = "Bot" ] || [ "$ASSOCIATION" = "OWNER" ] || [ "$ASSOCIATION" = "MEMBER" ] || [ "$ASSOCIATION" = "COLLABORATOR" ]; then
echo "Bot or trusted author ($ASSOCIATION); linkage check skipped."
exit 0
fi
if printf '%s\n%s\n' "$PR_TITLE" "$PR_BODY" | grep -Eq '#[0-9]+|issues/[0-9]+'; then
echo "Issue reference found."
else
+1 -1
View File
@@ -31,6 +31,6 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@045beb2d14bda8d0c1f2e83b41527f63770d2855 # v0.89.15
uses: github/gh-aw-actions/setup-cli@96dc6d905bdbe195f719ddc990a3f5b59b751016 # v0.89.10
with:
version: v0.89.1
+1
View File
@@ -17,3 +17,4 @@ target
.vfox
.claude
.zed
/src-tauri/generated/widget/
Generated
+1017 -685
View File
File diff suppressed because it is too large Load Diff
+9 -14
View File
@@ -8,6 +8,7 @@ members = [
"crates/tauri-plugin-clash-verge-sysinfo",
"crates/clash-verge-i18n",
"crates/clash-verge-limiter",
"crates/clash-verge-widget",
]
resolver = "2"
@@ -53,13 +54,13 @@ clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" }
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
clash-verge-widget = { path = "crates/clash-verge-widget" }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
tracing = "0.1"
tauri = { version = "3.0.0-alpha.1" }
tauri-runtime-wry = "3.0.0-alpha.1"
tauri-plugin-clipboard-manager = "3.0.0-alpha.0"
tauri = { version = "2.11.5" }
tauri-plugin-clipboard-manager = "2.3.2"
parking_lot = { version = "0.12.5", features = ["hardware-lock-elision"] }
anyhow = "1.0.104"
chrono = "0.4.45"
@@ -71,15 +72,9 @@ tokio = { version = "1.53.1", features = [
"sync",
] }
flexi_logger = "0.31.10"
log = "0.4.34"
log = "0.4.33"
regex = "1.13.1"
reqwest = { version = "0.13.5", features = [
"json",
"cookies",
"gzip",
"rustls",
"form",
] }
reqwest = { version = "0.13.4", features = ["json", "cookies", "gzip", "rustls", "form"] }
rust_iso3166 = "0.2.0"
smartstring = { version = "1.0.1" }
@@ -87,7 +82,7 @@ smartstring = { version = "1.0.1" }
serde = { version = "1.0.229" }
serde_json = { version = "1.0.151" }
serde_yaml_ng = { version = "0.10.0" }
bitflags = { version = "2.13.2" }
bitflags = { version = "2.13.1" }
socket2 = "0.6.5"
# *** For Windows platform only ***
@@ -100,7 +95,7 @@ windows-sys = { version = "0.61.2", features = [
"Win32_Security_Authorization",
"Win32_Storage_FileSystem",
"Win32_System_Threading",
"Win32_System_JobObjects",
"Win32_System_JobObjects"
] }
# *********************************
-3
View File
@@ -27,10 +27,8 @@
**🖥️ Windows**
- 修复 Windows 便携版或 Scoop 安装后服务内核无法启动的问题
- 修复 Windows 系统代理设置偶发失败的问题
- 修复 Windows 关机被应用阻止的问题
- 修复 Windows 服务模式下 TUN 使用 system/mixed 堆栈时无法接管流量的问题,防火墙放行规则改为自动添加
**🍎 macOS**
@@ -62,7 +60,6 @@
- 新增代理页排查提示,方便检查订阅和内核状态
- 新增订阅更新频率提醒,间隔不足 24 小时时提示
- 新增启动失败提示,显示原因并保存启动日志
- 新增 TUN「Mips」堆栈选项,需配合 mihomo v1.19.31 及以上内核
**🍎 macOS**
+1 -1
View File
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
rust-i18n = "4.2.2"
rust-i18n = "4.2.1"
sys-locale = "0.3.2"
[lints]
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: وكيل النظام
tun: TUN
profile: ملف تعريفي
widget:
unavailable: افتح Clash Verge
failed: فشل التحديث؛ تحقق من Clash Verge
'on': مفعّل
'off': معطّل
unknown: غير معروف
name: توجيه Clash Verge
description: التحكم في وضع التوجيه وTUN ووكيل النظام.
update: تحديث Clash Verge
setting: الإعداد
value: القيمة
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: Systemproxy
tun: TUN
profile: Profil
widget:
unavailable: Clash Verge öffnen
failed: Aktualisierung fehlgeschlagen; Clash Verge prüfen
'on': Ein
'off': Aus
unknown: Unbekannt
name: Clash Verge Routing
description: Routingmodus, TUN und Systemproxy steuern.
update: Clash Verge aktualisieren
setting: Einstellung
value: Wert
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: System Proxy
tun: TUN
profile: Profile
widget:
unavailable: Open Clash Verge
failed: Update failed; check Clash Verge
'on': 'On'
'off': 'Off'
unknown: Unknown
name: Clash Verge Routing
description: Routing mode, TUN and system proxy controls.
update: Update Clash Verge
setting: Setting
value: Value
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: Proxy del sistema
tun: TUN
profile: Perfil
widget:
unavailable: Abre Clash Verge
failed: Error al actualizar; revisa Clash Verge
'on': Activado
'off': Desactivado
unknown: Desconocido
name: Enrutamiento de Clash Verge
description: Controles del modo de enrutamiento, TUN y proxy del sistema.
update: Actualizar Clash Verge
setting: Ajuste
value: Valor
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: پروکسی سیستم
tun: TUN
profile: پروفایل
widget:
unavailable: Clash Verge را باز کنید
failed: به‌روزرسانی ناموفق بود؛ Clash Verge را بررسی کنید
'on': روشن
'off': خاموش
unknown: نامشخص
name: مسیریابی Clash Verge
description: کنترل حالت مسیریابی، TUN و پراکسی سیستم.
update: به‌روزرسانی Clash Verge
setting: تنظیم
value: مقدار
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: Proksi Sistem
tun: TUN
profile: Profil
widget:
unavailable: Buka Clash Verge
failed: Pembaruan gagal; periksa Clash Verge
'on': Aktif
'off': Nonaktif
unknown: Tidak diketahui
name: Perutean Clash Verge
description: Kontrol mode perutean, TUN, dan proksi sistem.
update: Perbarui Clash Verge
setting: Pengaturan
value: Nilai
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: システムプロキシ
tun: TUN
profile: プロファイル
widget:
unavailable: Clash Verge を開いてください
failed: 更新失敗。Clash Verge を確認してください
'on': オン
'off': オフ
unknown: 不明
name: Clash Verge ルーティング
description: ルーティングモード、TUN、システムプロキシの操作。
update: Clash Verge を更新
setting: 設定
value: 値
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: 시스템 프록시
tun: TUN
profile: 프로필
widget:
unavailable: Clash Verge를 여세요
failed: 업데이트 실패. Clash Verge를 확인하세요
'on': 켜짐
'off': 꺼짐
unknown: 알 수 없음
name: Clash Verge 라우팅
description: 라우팅 모드, TUN 및 시스템 프록시 제어.
update: Clash Verge 업데이트
setting: 설정
value: 값
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: Системный прокси
tun: TUN
profile: Профиль
widget:
unavailable: Откройте Clash Verge
failed: Ошибка обновления; проверьте Clash Verge
'on': Вкл.
'off': Выкл.
unknown: Неизвестно
name: Маршрутизация Clash Verge
description: Управление режимом маршрутизации, TUN и системным прокси.
update: Обновить Clash Verge
setting: Настройка
value: Значение
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: Sistem Vekil'i
tun: TUN
profile: Profil
widget:
unavailable: Clash Verge uygulamasını açın
failed: Güncelleme başarısız; Clash Verge uygulamasını kontrol edin
'on': Açık
'off': Kapalı
unknown: Bilinmiyor
name: Clash Verge Yönlendirme
description: Yönlendirme modu, TUN ve sistem vekili denetimleri.
update: Clash Verge güncelle
setting: Ayar
value: Değer
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: Системалы прокси
tun: TUN
profile: Профиль
widget:
unavailable: Clash Verge ачыгыз
failed: Яңарту уңышсыз; Clash Verge тикшерегез
'on': Кабызылган
'off': Сүндерелгән
unknown: Билгесез
name: Clash Verge маршрутлау
description: Маршрутлау режимы, TUN һәм система проксие белән идарә итү.
update: Clash Verge яңарту
setting: Көйләү
value: Кыйммәт
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: 系统代理
tun: TUN
profile: 订阅
widget:
unavailable: 请打开 Clash Verge
failed: 更新失败,请检查 Clash Verge
'on': 开启
'off': 关闭
unknown: 未知
name: Clash Verge 路由
description: 路由模式、TUN 和系统代理控制。
update: 更新 Clash Verge
setting: 设置
value: 值
+11
View File
@@ -91,3 +91,14 @@ tray:
systemProxy: 系統代理
tun: 虛擬網路介面卡
profile: 訂閱
widget:
unavailable: 請開啟 Clash Verge
failed: 更新失敗,請檢查 Clash Verge
'on': 開啟
'off': 關閉
unknown: 未知
name: Clash Verge 路由
description: 路由模式、TUN 和系統代理控制。
update: 更新 Clash Verge
setting: 設定
value: 值
+3
View File
@@ -0,0 +1,3 @@
# Xcode per-user state and local build output
xcuserdata/
DerivedData/
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "clash-verge-widget"
version = "0.1.0"
edition = "2024"
license = "GPL-3.0-only"
[dependencies]
serde = { workspace = true, features = ["derive"] }
[target.'cfg(target_os = "macos")'.dependencies]
anyhow = { workspace = true }
libc = "0.2.189"
log = { workspace = true }
scopeguard = "1.2.0"
serde_json = { workspace = true }
tokio = { workspace = true, features = ["net", "io-util"] }
[lints]
workspace = true
+232
View File
@@ -0,0 +1,232 @@
import { execFileSync } from 'node:child_process'
import { X509Certificate, randomBytes } from 'node:crypto'
import {
cpSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const crate = resolve(dirname(fileURLToPath(import.meta.url)), '..')
const root = resolve(crate, '../..')
const app = join(root, 'src-tauri')
const stage = join(app, 'generated/widget')
const run = (command, args) => {
try {
return execFileSync(command, args, {
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
stdio: ['ignore', 'pipe', 'pipe'],
})
} catch (error) {
throw new Error(
`${command} failed (${error.status}); ${command === 'security' ? 'check signing credentials' : error.stderr?.toString() || 'no diagnostic output'}`,
{ cause: error },
)
}
}
const config = JSON.parse(readFileSync(join(app, 'tauri.conf.json'), 'utf8'))
const mac = JSON.parse(readFileSync(join(app, 'tauri.macos.conf.json'), 'utf8'))
const temporary = mkdtempSync(join(tmpdir(), 'verge-widget-build-'))
let keychain
try {
if (process.platform !== 'darwin')
throw new Error('Widget packaging requires macOS.')
run('xcodebuild', ['-version'])
run('xcrun', ['--find', 'appintentsmetadataprocessor'])
const target = process.env.TAURI_ENV_TARGET_TRIPLE
const arch = {
'aarch64-apple-darwin': 'arm64',
'x86_64-apple-darwin': 'x86_64',
'universal-apple-darwin': 'arm64 x86_64',
}[target]
if (!arch) throw new Error(`Unsupported widget target: ${target}`)
if (process.env.APPLE_CERTIFICATE) {
keychain = join(temporary, 'widget.keychain-db')
const password = randomBytes(24).toString('hex')
const certificate = join(temporary, 'signing.p12')
writeFileSync(
certificate,
Buffer.from(process.env.APPLE_CERTIFICATE, 'base64'),
{ mode: 0o600 },
)
run('security', ['create-keychain', '-p', password, keychain])
run('security', ['unlock-keychain', '-p', password, keychain])
run('security', [
'import',
certificate,
'-k',
keychain,
'-P',
process.env.APPLE_CERTIFICATE_PASSWORD || '',
'-T',
'/usr/bin/codesign',
])
run('security', [
'set-key-partition-list',
'-S',
'apple-tool:,apple:,codesign:',
'-s',
'-k',
password,
keychain,
])
}
const keychainArgs = keychain ? [keychain] : []
const identities = [
...run('security', [
'find-identity',
'-v',
'-p',
'codesigning',
...keychainArgs,
]).matchAll(/\b([A-F0-9]{40}) "([^"]+)"/g),
].map((match) => ({ hash: match[1], name: match[2] }))
const requested =
process.env.APPLE_SIGNING_IDENTITY || mac.bundle.macOS.signingIdentity
if (requested === '-') {
console.warn(
'CLASH_VERGE_WIDGET=0: skipping widget embedding; this build has no desktop widget extension.',
)
process.exit(0)
}
if (!requested)
throw new Error(
'pnpm build on macOS needs APPLE_SIGNING_IDENTITY (or a single valid signing certificate) for widget and host signing.',
)
const matches = identities.filter(
({ hash, name }) => hash === requested.toUpperCase() || name === requested,
)
if (matches.length !== 1)
throw new Error(
'Widget packaging requires one valid Apple signing identity; run pnpm build with APPLE_SIGNING_IDENTITY set.',
)
const identity = matches[0]
const certificates =
run('security', ['find-certificate', '-a', '-p', ...keychainArgs]).match(
/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g,
) || []
const certificate = certificates
.map((pem) => new X509Certificate(pem))
.find((cert) => cert.fingerprint.replaceAll(':', '') === identity.hash)
const team = certificate?.subject.match(
/(?:^|\n)OU=([A-Z0-9]{10})(?:\n|$)/,
)?.[1]
if (!team) throw new Error('Selected certificate has no Apple Team ID.')
const group = `${team}.io.vergewidget`
const version = config.version
mkdirSync(stage, { recursive: true })
run('python3', [
'-c',
`
import json, plistlib, sys
from pathlib import Path
app, stage, team, group, version = sys.argv[1:]
stage = Path(stage)
common = {'VergeWidgetTeam': team, 'VergeWidgetGroup': group}
info = dict(common, CFBundleIdentifier='io.github.clash-verge-rev.clash-verge-rev.widget', CFBundleName='VergeWidget', CFBundleDevelopmentRegion='zh-Hans', CFBundleDisplayName='Clash Verge Routing', CFBundleExecutable='VergeWidget', CFBundlePackageType='XPC!', CFBundleShortVersionString=version, CFBundleVersion=version, LSMinimumSystemVersion='14.0', NSExtension={'NSExtensionPointIdentifier':'com.apple.widgetkit-extension'})
with open(Path(app)/'packages/macos/info_merge.plist','rb') as f: host_info = plistlib.load(f)
host_info.update(common)
with open(Path(app)/'packages/macos/entitlements.plist','rb') as f: host_entitlements = plistlib.load(f)
host_entitlements['com.apple.security.application-groups'] = [group]
host_entitlements.pop('com.apple.security.inherit', None)
ext_entitlements = {'com.apple.security.app-sandbox': True, 'com.apple.security.application-groups': [group], 'com.apple.security.network.client': True}
for name, value in [('Widget.plist',info), ('Host.plist',host_info), ('Host.entitlements',host_entitlements), ('Widget.entitlements',ext_entitlements)]:
with (stage/name).open('wb') as f: plistlib.dump(value,f)
`,
app,
stage,
team,
group,
version,
])
const products = join(temporary, 'products')
run('xcodebuild', [
'-project',
join(crate, 'native/Widget.xcodeproj'),
'-target',
'VergeWidget',
'-configuration',
'Release',
`CONFIGURATION_BUILD_DIR=${products}`,
`OBJROOT=${temporary}/objects`,
`SYMROOT=${temporary}/symbols`,
`ARCHS=${arch}`,
'ONLY_ACTIVE_ARCH=NO',
'MACOSX_DEPLOYMENT_TARGET=14.0',
'CODE_SIGNING_ALLOWED=NO',
`WIDGET_INFO_PLIST=${stage}/Widget.plist`,
`WIDGET_ENTITLEMENTS=${stage}/Widget.entitlements`,
'build',
])
readFileSync(
join(
products,
'VergeWidget.appex/Contents/Resources/Metadata.appintents/extract.actionsdata',
),
)
const extension = join(products, 'VergeWidget.appex')
if (process.env.WIDGET_PROFILE) {
cpSync(
process.env.WIDGET_PROFILE,
join(extension, 'Contents/embedded.provisionprofile'),
)
}
run('codesign', [
'--force',
'--sign',
identity.hash,
...(keychain ? ['--keychain', keychain] : []),
'--options',
'runtime',
'--entitlements',
join(stage, 'Widget.entitlements'),
extension,
])
rmSync(join(stage, 'VergeWidget.appex'), { recursive: true, force: true })
cpSync(extension, join(stage, 'VergeWidget.appex'), { recursive: true })
const slices = arch.split(' ').map((architecture) => {
const output = join(temporary, `${architecture}.dylib`)
run('xcrun', [
'swiftc',
'-emit-library',
'-parse-as-library',
'-target',
`${architecture}-apple-macos14.0`,
join(crate, 'native/Bridge.swift'),
'-o',
output,
])
return output
})
run('xcrun', [
'lipo',
'-create',
...slices,
'-output',
join(stage, 'VergeWidgetBridge.dylib'),
])
console.log(
`Prepared signed widget ${version} (${arch}); Tauri will embed it before host signing and packaging.`,
)
} catch (error) {
console.error(
'Widget packaging failed:',
error.stderr?.toString() || error.message,
)
process.exitCode = 1
} finally {
if (keychain) {
try {
run('security', ['delete-keychain', keychain])
} catch {
console.error('Could not remove temporary widget keychain.')
}
}
rmSync(temporary, { recursive: true, force: true })
}
@@ -0,0 +1,37 @@
import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { load } from 'js-yaml'
const root = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
const resources = process.argv[2]
if (!resources) throw new Error('Pass the extension resources directory.')
const catalogs = join(root, 'crates/clash-verge-i18n/locales')
for (const file of readdirSync(catalogs)
.filter((file) => file.endsWith('.yml'))
.sort()) {
const locale = file.slice(0, -4)
const catalog = load(readFileSync(join(catalogs, file), 'utf8'))
const language =
{ jp: 'ja', zh: 'zh-Hans', zhtw: 'zh-Hant' }[locale] || locale
const strings = {
'tray.rule': catalog.tray.rule,
'tray.global': catalog.tray.global,
'tray.direct': catalog.tray.direct,
'tray.systemProxy': catalog.tray.systemProxy,
'tray.tooltip.tun': catalog.tray.tooltip.tun,
}
for (const [key, value] of Object.entries(catalog.widget))
strings[`widget.${key}`] = value
const directory = join(resources, `${language}.lproj`)
mkdirSync(directory, { recursive: true })
writeFileSync(
join(directory, 'Localizable.strings'),
Object.entries(strings)
.map(
([key, value]) => `${JSON.stringify(key)} = ${JSON.stringify(value)};`,
)
.join('\n'),
)
}
@@ -0,0 +1,53 @@
import Darwin
import Foundation
import Security
import WidgetKit
let widgetKind = "VergeRoutingWidget"
let hostID = "io.github.clash-verge-rev.clash-verge-rev"
func socketPath() -> String? {
guard let group = Bundle.main.object(forInfoDictionaryKey: "VergeWidgetGroup") as? String else { return nil }
guard let container = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group) else {
return nil
}
return container.appendingPathComponent("verge-widget.sock").path
}
func authenticPeer(_ descriptor: Int32, identifier: String) -> Bool {
var token = audit_token_t()
var size = socklen_t(MemoryLayout.size(ofValue: token))
guard getsockopt(descriptor, SOL_LOCAL, LOCAL_PEERTOKEN, &token, &size) == 0,
size == MemoryLayout.size(ofValue: token) else { return false }
let data = withUnsafeBytes(of: token) { Data($0) }
var peer: SecCode?
let attributes = [kSecGuestAttributeAudit: data] as CFDictionary
guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &peer) == errSecSuccess,
let peer,
let team = Bundle.main.object(forInfoDictionaryKey: "VergeWidgetTeam") as? String,
team.range(of: "^[A-Z0-9]{10}$", options: .regularExpression) != nil else { return false }
var requirement: SecRequirement?
let expression = """
anchor apple generic and certificate leaf[subject.OU] = "\(team)" and identifier "\(identifier)"
"""
guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess,
let requirement else { return false }
return SecCodeCheckValidity(peer, [], requirement) == errSecSuccess
}
#if !WIDGET_EXTENSION
@_cdecl("verge_widget_path")
public func vergeWidgetPath() -> UnsafeMutablePointer<CChar>? {
socketPath().flatMap { strdup($0) }
}
@_cdecl("verge_widget_authenticate")
public func vergeWidgetAuthenticate(_ descriptor: Int32) -> Bool {
authenticPeer(descriptor, identifier: hostID + ".widget")
}
@_cdecl("verge_widget_reload")
public func vergeWidgetReload() {
WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)
}
#endif
@@ -0,0 +1,11 @@
import SwiftUI
@main
struct WidgetPreviewHost: App {
var body: some Scene {
WindowGroup("Widget Preview Host") {
Text("Use the StylePreviews.swift Canvas to preview routing controls.")
.padding(24)
}
}
}
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key><string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleExecutable</key><string>$(EXECUTABLE_NAME)</string>
<key>CFBundleName</key><string>VergeWidget</string>
<key>CFBundlePackageType</key><string>XPC!</string>
<key>CFBundleShortVersionString</key><string>1.0</string>
<key>CFBundleVersion</key><string>1</string>
<key>CFBundleDevelopmentRegion</key><string>zh-Hans</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSExtension</key><dict>
<key>NSExtensionPointIdentifier</key><string>com.apple.widgetkit-extension</string>
</dict>
</dict>
</plist>
@@ -0,0 +1,201 @@
import SwiftUI
import WidgetKit
import Foundation
struct RoutingView: View {
let entry: Entry
@Environment(\.widgetFamily) private var widgetFamily
#if DEBUG
var previewFamily: WidgetFamily?
private var family: WidgetFamily { previewFamily ?? widgetFamily }
#else
private var family: WidgetFamily { widgetFamily }
#endif
@Environment(\.widgetRenderingMode) private var systemRenderingMode
#if DEBUG
var previewRenderingMode: WidgetRenderingMode?
var previewMaterial = "automatic"
var previewIncreaseContrast = false
private var renderingMode: WidgetRenderingMode { previewRenderingMode ?? systemRenderingMode }
#else
private var renderingMode: WidgetRenderingMode { systemRenderingMode }
#endif
@Environment(\.colorScheme) private var colorScheme
@Environment(\.colorSchemeContrast) private var systemContrast
#if DEBUG
private var contrast: ColorSchemeContrast { previewIncreaseContrast ? .increased : systemContrast }
#else
private var contrast: ColorSchemeContrast { systemContrast }
#endif
@Environment(\.accessibilityReduceMotion) private var systemReduceMotion
@Environment(\.accessibilityReduceTransparency) private var systemReduceTransparency
#if DEBUG
var previewReduceMotion: Bool?
var previewReduceTransparency: Bool?
private var reduceMotion: Bool { previewReduceMotion ?? systemReduceMotion }
private var reduceTransparency: Bool { previewReduceTransparency ?? systemReduceTransparency }
#else
private var reduceMotion: Bool { systemReduceMotion }
private var reduceTransparency: Bool { systemReduceTransparency }
#endif
private func text(_ key: String) -> String { localized(key, language: entry.status.language) }
private let modes = ["rule", "global", "direct"]
private var ink: Color { renderingMode == .fullColor ? (colorScheme == .dark ? .white : .black) : .primary }
private var secondaryInk: Color { ink.opacity(contrast == .increased ? 0.8 : 0.6) }
@ViewBuilder private var selectionBackground: some View {
#if DEBUG
if previewMaterial == "thin" && renderingMode == .fullColor && !reduceTransparency {
Capsule().fill(.thinMaterial)
} else {
automaticSelectionBackground
}
#else
automaticSelectionBackground
#endif
}
@ViewBuilder private var automaticSelectionBackground: some View {
if renderingMode != .fullColor {
Capsule().strokeBorder(ink.opacity(0.65), lineWidth: 1)
} else if reduceTransparency {
Capsule().fill(ink)
} else if #available(macOS 26.0, *) {
Capsule().fill(.clear)
.glassEffect(.regular, in: Capsule())
} else {
Capsule().fill(.thinMaterial)
}
}
private func modeInk(selected: Bool) -> Color {
guard selected && reduceTransparency && renderingMode == .fullColor else {
return selected ? ink : secondaryInk
}
return colorScheme == .dark ? .black : .white
}
private var locale: Locale {
let aliases = ["jp": "ja", "zh": "zh-Hans", "zhtw": "zh-Hant"]
let identifier = entry.status.language.map { aliases[$0] ?? $0 } ?? Locale.current.identifier
return Locale(identifier: identifier)
}
private var rtl: Bool { locale.language.characterDirection == .rightToLeft }
func control(_ title: String, action: String, value: Bool?, icon: String) -> some View {
let compact = family == .systemSmall
return Button(intent: SetRouting(action, value == true ? "false" : "true")) {
let label = HStack(spacing: 4) {
if !compact { Image(systemName: icon).font(.caption2) }
Text(title).font(.caption)
.lineLimit(compact ? 2 : 1)
.frame(height: compact ? 30 : nil, alignment: .topLeading)
}
let toggle = ZStack(alignment: .leading) {
Capsule().fill(ink.opacity(value == true ? 0.28 : 0.08))
Circle().fill(ink)
.frame(width: 13, height: 13)
.offset(x: value.map { $0 ? 19.0 : 4.0 } ?? 11.5)
}
.frame(width: 36, height: 22)
.environment(\.layoutDirection, .leftToRight)
if compact {
VStack(alignment: .leading, spacing: 8) {
label
if value == nil { Text(text("widget.unknown")).font(.caption2) } else { toggle }
}
} else {
HStack(spacing: 8) {
label
Spacer(minLength: 0)
if value == nil { Text(text("widget.unknown")).font(.caption2) } else { toggle }
}
}
}
.foregroundStyle(secondaryInk)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(8)
.disabled(value == nil)
.transaction { $0.animation = nil; $0.disablesAnimations = true }
.invalidatableContent()
.accessibilityLabel(title)
.accessibilityValue(text(value.map { $0 ? "widget.on" : "widget.off" } ?? "widget.unknown"))
}
@ViewBuilder private var containerMaterial: some View {
if reduceTransparency {
Rectangle().fill(.background)
} else {
Rectangle().fill(.ultraThinMaterial)
}
}
@ViewBuilder var body: some View {
#if DEBUG
if previewFamily != nil {
content.padding(16)
.frame(width: family == .systemSmall ? 170 : 360, height: 170)
.background { containerMaterial }
.clipShape(RoundedRectangle(cornerRadius: 24))
} else {
content.containerBackground(for: .widget) { containerMaterial }
}
#else
content.containerBackground(for: .widget) { containerMaterial }
#endif
}
private var content: some View {
VStack(alignment: .leading, spacing: 8) {
GeometryReader { geometry in
let width = (geometry.size.width - 4) / 3
let orderedModes = rtl ? Array(modes.reversed()) : modes
let index = orderedModes.firstIndex(of: entry.status.mode ?? "")
ZStack(alignment: .leading) {
selectionBackground
.frame(width: width - 2, height: 26)
.offset(x: 3 + CGFloat(index ?? 0) * width)
.opacity(index == nil ? 0 : 1)
.allowsHitTesting(false)
HStack(spacing: 0) {
ForEach(orderedModes, id: \.self) { mode in
let selected = entry.status.mode == mode
let label = Text(text("tray." + mode))
.font(selected ? .footnote.weight(.semibold) : .footnote)
.lineLimit(1)
.frame(maxWidth: .infinity)
.frame(height: 30)
.foregroundStyle(modeInk(selected: selected))
.contentTransition(reduceMotion ? .identity : .opacity)
.contentShape(Rectangle())
Button(intent: SetRouting("mode", mode)) { label }
.disabled(index == nil)
.accessibilityAddTraits(selected ? .isSelected : [])
}
}
.padding(.horizontal, 2)
.zIndex(1)
}
.invalidatableContent()
.environment(\.layoutDirection, .leftToRight)
}
.frame(height: 30)
HStack(spacing: 8) {
control(text("tray.tooltip.tun"), action: "tun", value: entry.status.tun, icon: "network")
control(
text("tray.systemProxy"), action: "proxy",
value: entry.status.proxy, icon: "shield.lefthalf.filled"
)
}
if let error = entry.status.error {
Label {
Text(text(error)).font(.caption2).lineLimit(2)
} icon: {
Image(systemName: "exclamationmark.triangle.fill").font(.caption2)
}
.foregroundStyle(secondaryInk)
}
}
.environment(\.locale, locale)
.environment(\.layoutDirection, rtl ? .rightToLeft : .leftToRight)
.transaction { $0.animation = nil }
.buttonStyle(.plain)
.widgetURL(URL(string: "clash-verge://show"))
}
}
@@ -0,0 +1,204 @@
import SwiftUI
import WidgetKit
#if DEBUG && PREVIEW_HOST
import UniformTypeIdentifiers
import AppKit
private struct RoutingStylePreview: View {
@State var medium = false
@State var dark = false
@State var language = "en"
@State var mode = "rule"
@State var tun = "on"
@State var proxy = "off"
@State var error = "none"
@State var reduceTransparency = false
@State var reduceMotion = false
@State private var backdrop = "gradient"
@State private var material = "automatic"
@State private var rendering = "automatic"
@State private var increaseContrast = false
@State private var importingWallpaper = false
@State private var wallpaper: NSImage?
@State private var wallpaperName = ""
@State private var wallpaperError: String?
private var renderingOverride: WidgetRenderingMode? {
switch rendering {
case "fullColor": .fullColor
case "accented": .accented
case "vibrant": .vibrant
default: nil
}
}
private func importWallpaper(_ result: Result<URL, Error>) {
do {
let url = try result.get()
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
let data = try Data(contentsOf: url)
guard let image = NSImage(data: data) else {
wallpaperError = "The selected file is not a readable image."
return
}
wallpaper = image
wallpaperName = url.lastPathComponent
wallpaperError = nil
backdrop = "wallpaper"
} catch {
let failure = error as NSError
if failure.domain != NSCocoaErrorDomain || failure.code != NSUserCancelledError {
wallpaperError = error.localizedDescription
}
}
}
private func state(_ value: String) -> Bool? {
value == "unknown" ? nil : value == "on"
}
private var sample: Status {
Status(mode: mode == "unknown" ? nil : mode, tun: state(tun), proxy: state(proxy),
error: error == "none" ? nil : "widget." + error, language: language)
}
@ViewBuilder private var background: some View {
switch backdrop {
case "wallpaper":
if let wallpaper {
GeometryReader { geometry in
Image(nsImage: wallpaper).resizable().scaledToFill()
.frame(width: geometry.size.width, height: geometry.size.height).clipped()
}
}
case "light": Color(white: 0.92)
case "dark": Color(white: 0.1)
case "pattern":
Canvas { context, _ in
for row in 0..<8 {
for column in 0..<14 {
let rect = CGRect(x: CGFloat(column) * 32, y: CGFloat(row) * 32, width: 32, height: 32)
context.fill(Path(rect), with: .color((row + column).isMultiple(of: 2) ? .white : .black))
}
}
}
default:
LinearGradient(colors: [.blue, .purple, .orange], startPoint: .topLeading, endPoint: .bottomTrailing)
}
}
var body: some View {
VStack(spacing: 12) {
ZStack {
background
RoutingView(
entry: Entry(date: .now, status: sample),
previewFamily: medium ? .systemMedium : .systemSmall,
previewRenderingMode: renderingOverride,
previewMaterial: material,
previewIncreaseContrast: increaseContrast,
previewReduceMotion: reduceMotion,
previewReduceTransparency: reduceTransparency
)
.environment(\.colorScheme, dark ? .dark : .light)
.allowsHitTesting(false)
}
.frame(height: 218)
.clipShape(RoundedRectangle(cornerRadius: 12))
ScrollView {
VStack(alignment: .leading, spacing: 10) {
HStack {
Toggle("Medium", isOn: $medium)
Toggle("Dark", isOn: $dark)
}
Picker("Background", selection: $backdrop) {
Text("Light").tag("light")
Text("Dark").tag("dark")
Text("Gradient").tag("gradient")
Text("Contrast pattern").tag("pattern")
if wallpaper != nil { Text("Selected wallpaper").tag("wallpaper") }
}
HStack {
Button("Choose wallpaper…") { importingWallpaper = true }
if wallpaper != nil {
Text(wallpaperName).lineLimit(1).truncationMode(.middle)
Button("Clear") {
wallpaper = nil; wallpaperName = ""; wallpaperError = nil
if backdrop == "wallpaper" { backdrop = "gradient" }
}
}
}
if let wallpaperError { Text(wallpaperError).font(.caption).foregroundStyle(.red) }
Picker("Selected material", selection: $material) {
Text("Automatic").tag("automatic")
Text("Thin material").tag("thin")
if #available(macOS 26.0, *) { Text("Liquid Glass").tag("glass") }
}
Text("Selected material applies only in full-color rendering with Reduce transparency off.")
.font(.caption).foregroundStyle(.secondary)
Picker("Rendering input (approximate)", selection: $rendering) {
Text("Automatic").tag("automatic")
Text("Full color").tag("fullColor")
Text("Accented").tag("accented")
Text("Vibrant").tag("vibrant")
}
Toggle("Increase contrast (approximate)", isOn: $increaseContrast)
Picker("Language", selection: $language) {
Text("English").tag("en")
Text("简体中文").tag("zh")
}
Picker("Mode", selection: $mode) {
Text("Rule").tag("rule")
Text("Global").tag("global")
Text("Direct").tag("direct")
Text("Unknown").tag("unknown")
}
.pickerStyle(.segmented)
HStack {
Picker("TUN", selection: $tun) {
Text("On").tag("on"); Text("Off").tag("off"); Text("Unknown").tag("unknown")
}
Picker("Proxy", selection: $proxy) {
Text("On").tag("on"); Text("Off").tag("off"); Text("Unknown").tag("unknown")
}
}
Picker("Error", selection: $error) {
Text("None").tag("none")
Text("Offline").tag("unavailable")
Text("Failed").tag("failed")
}
Toggle("Reduce transparency", isOn: $reduceTransparency)
Toggle("Reduce motion", isOn: $reduceMotion)
Text(
"Style only. Controls change sample data; no proxy requests. "
+ "Desktop WidgetKit compositing is not simulated."
)
.font(.caption).foregroundStyle(.secondary)
}
.padding(4)
}
}
.padding(16)
.frame(width: 440, height: 570)
.fileImporter(isPresented: $importingWallpaper, allowedContentTypes: [.image], onCompletion: importWallpaper)
}
}
#Preview("Style control panel") {
RoutingStylePreview()
}
#Preview("Medium · 中文 · Dark") {
RoutingStylePreview(medium: true, dark: true, language: "zh", mode: "global")
}
#Preview("Small · English · Reduced transparency") {
RoutingStylePreview(language: "en", mode: "direct", reduceTransparency: true)
}
#Preview("中文 · Unknown · Offline") {
RoutingStylePreview(
medium: true, dark: true, language: "zh", mode: "unknown",
tun: "unknown", proxy: "unknown", error: "unavailable"
)
}
#endif
@@ -0,0 +1,65 @@
import AppIntents
import SwiftUI
import WidgetKit
import Foundation
struct SetRouting: AppIntent {
static let title: LocalizedStringResource = "widget.update"
static let openAppWhenRun = false
@Parameter(title: "widget.setting") var action: String
@Parameter(title: "widget.value") var value: String
init() {}
init(_ action: String, _ value: String) { self.action = action; self.value = value }
func perform() async throws -> some IntentResult {
let status = await Task.detached { exchange(action: action, value: value.isEmpty ? nil : value) }.value
if let error = status.error {
WidgetCenter.shared.reloadTimelines(ofKind: widgetKind)
throw WidgetFailure(message: localized(error, language: status.language))
}
return .result()
}
}
struct WidgetFailure: LocalizedError {
let message: String
var errorDescription: String? { message }
}
struct Entry: TimelineEntry {
var date: Date
var status: Status
}
struct Provider: TimelineProvider {
func placeholder(in context: Context) -> Entry {
Entry(date: .now, status: Status(error: "widget.unavailable"))
}
func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) {
if context.isPreview {
completion(Entry(date: .now, status: Status(mode: "rule", tun: true, proxy: false)))
} else {
getTimeline(in: context) { completion($0.entries[0]) }
}
}
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
DispatchQueue.global().async {
let status = exchange()
let now = Date()
let unavailable = status.mode == nil || status.tun == nil || status.proxy == nil
let refresh = now.addingTimeInterval(unavailable ? 60 : 900)
completion(Timeline(entries: [Entry(date: now, status: status)], policy: .after(refresh)))
}
}
}
#if !PREVIEW_HOST
@main
#endif
struct RoutingWidget: Widget {
var body: some WidgetConfiguration {
StaticConfiguration(kind: widgetKind, provider: Provider()) { RoutingView(entry: $0) }
.configurationDisplayName("widget.name")
.description("widget.description")
.supportedFamilies([.systemSmall, .systemMedium])
}
}
@@ -0,0 +1,83 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {};
objectVersion = 56;
objects = {
A00000000000000000000001 = {isa = PBXProject; buildConfigurationList = A00000000000000000000002; compatibilityVersion = "Xcode 14.0"; developmentRegion = en; knownRegions = (en, Base); mainGroup = A00000000000000000000003; productRefGroup = A00000000000000000000004; projectDirPath = ""; projectRoot = ""; targets = (A00000000000000000000005, A00000000000000000000020); };
A00000000000000000000002 = {isa = XCConfigurationList; buildConfigurations = (A00000000000000000000006, A00000000000000000000010); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; };
A00000000000000000000003 = {isa = PBXGroup; children = (A00000000000000000000007, A00000000000000000000008, A00000000000000000000021, A00000000000000000000030, A00000000000000000000040, A00000000000000000000041, A00000000000000000000004); sourceTree = "<group>"; };
A00000000000000000000004 = {isa = PBXGroup; children = (A00000000000000000000009, A00000000000000000000022); name = Products; sourceTree = "<group>"; };
A00000000000000000000005 = {isa = PBXNativeTarget; buildConfigurationList = A0000000000000000000000A; buildPhases = (A0000000000000000000000B, A0000000000000000000000C, A00000000000000000000012); buildRules = (); dependencies = (); name = VergeWidget; productName = VergeWidget; productReference = A00000000000000000000009; productType = "com.apple.product-type.app-extension"; };
A00000000000000000000006 = {isa = XCBuildConfiguration; name = Release; buildSettings = {MACOSX_DEPLOYMENT_TARGET = 14.0; SDKROOT = macosx; SWIFT_VERSION = 5.0; }; };
A00000000000000000000007 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Widget.swift; sourceTree = "<group>"; };
A00000000000000000000008 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Bridge.swift; sourceTree = "<group>"; };
A00000000000000000000009 = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; path = VergeWidget.appex; sourceTree = BUILT_PRODUCTS_DIR; };
A0000000000000000000000A = {isa = XCConfigurationList; buildConfigurations = (A0000000000000000000000D, A00000000000000000000011); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; };
A0000000000000000000000B = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A0000000000000000000000E, A0000000000000000000000F, A00000000000000000000042, A00000000000000000000043); runOnlyForDeploymentPostprocessing = 0; };
A0000000000000000000000C = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
A0000000000000000000000D = {isa = XCBuildConfiguration; name = Release; buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CODE_SIGN_ENTITLEMENTS = "$(WIDGET_ENTITLEMENTS)";
CODE_SIGN_STYLE = Manual;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "$(WIDGET_INFO_PLIST)";
WIDGET_INFO_PLIST = "$(SRCROOT)/Preview.plist";
WIDGET_ENTITLEMENTS = "";
ENABLE_USER_SCRIPT_SANDBOXING = NO;
LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks", "@executable_path/../../../../Frameworks");
PRODUCT_BUNDLE_IDENTIFIER = "io.github.clash-verge-rev.clash-verge-rev.widget";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = WIDGET_EXTENSION;
SWIFT_EMIT_LOC_STRINGS = YES;
}; };
A00000000000000000000011 = {isa = XCBuildConfiguration; name = Debug; buildSettings = {
APPLICATION_EXTENSION_API_ONLY = YES;
CODE_SIGN_ENTITLEMENTS = "$(WIDGET_ENTITLEMENTS)";
CODE_SIGN_STYLE = Manual;
GENERATE_INFOPLIST_FILE = NO;
INFOPLIST_FILE = "$(WIDGET_INFO_PLIST)";
WIDGET_INFO_PLIST = "$(SRCROOT)/Preview.plist";
WIDGET_ENTITLEMENTS = "";
ENABLE_USER_SCRIPT_SANDBOXING = NO;
LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks", "@executable_path/../../../../Frameworks");
PRODUCT_BUNDLE_IDENTIFIER = "io.github.clash-verge-rev.clash-verge-rev.preview.widget";
PRODUCT_NAME = "$(TARGET_NAME)";
SKIP_INSTALL = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "WIDGET_EXTENSION DEBUG";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
CODE_SIGN_IDENTITY = "-";
ENABLE_PREVIEWS = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
}; };
A0000000000000000000000E = {isa = PBXBuildFile; fileRef = A00000000000000000000007; };
A0000000000000000000000F = {isa = PBXBuildFile; fileRef = A00000000000000000000008; };
A00000000000000000000010 = {isa = XCBuildConfiguration; name = Debug; buildSettings = {MACOSX_DEPLOYMENT_TARGET = 14.0; SDKROOT = macosx; SWIFT_VERSION = 5.0; }; };
A00000000000000000000012 = {isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = (); inputPaths = (); outputPaths = (); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; alwaysOutOfDate = 1; shellScript = "export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH\nnode \"$SRCROOT/../build/localize.mjs\" \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH\"\n"; };
A00000000000000000000020 = {isa = PBXNativeTarget; buildConfigurationList = A00000000000000000000023; buildPhases = (A00000000000000000000024, A00000000000000000000025, A00000000000000000000026, A00000000000000000000034); buildRules = (); dependencies = (A00000000000000000000027); name = PreviewHost; productName = PreviewHost; productReference = A00000000000000000000022; productType = "com.apple.product-type.application"; };
A00000000000000000000021 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Host.swift; sourceTree = "<group>"; };
A00000000000000000000022 = {isa = PBXFileReference; explicitFileType = wrapper.application; path = PreviewHost.app; sourceTree = BUILT_PRODUCTS_DIR; };
A00000000000000000000023 = {isa = XCConfigurationList; buildConfigurations = (A00000000000000000000028); defaultConfigurationIsVisible = 0; defaultConfigurationName = Debug; };
A00000000000000000000024 = {isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = (A00000000000000000000029, A00000000000000000000031, A00000000000000000000032, A00000000000000000000033, A00000000000000000000044, A00000000000000000000045); runOnlyForDeploymentPostprocessing = 0; };
A00000000000000000000025 = {isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = (); runOnlyForDeploymentPostprocessing = 0; };
A00000000000000000000026 = {isa = PBXCopyFilesBuildPhase; buildActionMask = 2147483647; dstPath = ""; dstSubfolderSpec = 13; files = (A0000000000000000000002A); name = "Embed Widget"; runOnlyForDeploymentPostprocessing = 0; };
A00000000000000000000027 = {isa = PBXTargetDependency; target = A00000000000000000000005; targetProxy = A0000000000000000000002B; };
A00000000000000000000028 = {isa = XCBuildConfiguration; name = Debug; buildSettings = {CODE_SIGN_IDENTITY = "-"; CODE_SIGN_STYLE = Manual; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_KEY_CFBundleDisplayName = "Widget Preview Host"; PRODUCT_BUNDLE_IDENTIFIER = "io.github.clash-verge-rev.clash-verge-rev.preview"; PRODUCT_NAME = "$(TARGET_NAME)"; MARKETING_VERSION = 1.0; CURRENT_PROJECT_VERSION = 1; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG PREVIEW_HOST WIDGET_EXTENSION"; ENABLE_USER_SCRIPT_SANDBOXING = NO; ENABLE_PREVIEWS = YES; LD_RUNPATH_SEARCH_PATHS = ("$(inherited)", "@executable_path/../Frameworks"); }; };
A00000000000000000000029 = {isa = PBXBuildFile; fileRef = A00000000000000000000021; };
A0000000000000000000002A = {isa = PBXBuildFile; fileRef = A00000000000000000000009; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy); }; };
A0000000000000000000002B = {isa = PBXContainerItemProxy; containerPortal = A00000000000000000000001; proxyType = 1; remoteGlobalIDString = A00000000000000000000005; remoteInfo = VergeWidget; };
A00000000000000000000030 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StylePreviews.swift; sourceTree = "<group>"; };
A00000000000000000000031 = {isa = PBXBuildFile; fileRef = A00000000000000000000007; };
A00000000000000000000032 = {isa = PBXBuildFile; fileRef = A00000000000000000000008; };
A00000000000000000000033 = {isa = PBXBuildFile; fileRef = A00000000000000000000030; };
A00000000000000000000034 = {isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = (); inputPaths = (); outputPaths = (); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; alwaysOutOfDate = 1; shellScript = "export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH\nnode \"$SRCROOT/../build/localize.mjs\" \"$TARGET_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH\"\n"; };
A00000000000000000000040 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetClient.swift; sourceTree = "<group>"; };
A00000000000000000000041 = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RoutingView.swift; sourceTree = "<group>"; };
A00000000000000000000042 = {isa = PBXBuildFile; fileRef = A00000000000000000000040; };
A00000000000000000000043 = {isa = PBXBuildFile; fileRef = A00000000000000000000041; };
A00000000000000000000044 = {isa = PBXBuildFile; fileRef = A00000000000000000000040; };
A00000000000000000000045 = {isa = PBXBuildFile; fileRef = A00000000000000000000041; };
};
rootObject = A00000000000000000000001;
}
@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "NO"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A00000000000000000000020"
BuildableName = "PreviewHost.app"
BlueprintName = "PreviewHost"
ReferencedContainer = "container:Widget.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "NO">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A00000000000000000000020"
BuildableName = "PreviewHost.app"
BlueprintName = "PreviewHost"
ReferencedContainer = "container:Widget.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Debug"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "A00000000000000000000020"
BuildableName = "PreviewHost.app"
BlueprintName = "PreviewHost"
ReferencedContainer = "container:Widget.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,104 @@
import Darwin
import Foundation
struct Status: Codable {
var mode: String?
var tun: Bool?
var proxy: Bool?
var error: String?
var language: String?
}
func localized(_ key: String, language: String? = nil) -> String {
let code = language.map { ["jp": "ja", "zh": "zh-Hans", "zhtw": "zh-Hant"][$0] ?? $0 }
let path = code.flatMap { Bundle.main.path(forResource: $0, ofType: "lproj") }
let bundle = path.flatMap(Bundle.init(path:)) ?? .main
return bundle.localizedString(forKey: key, value: nil, table: nil)
}
private func connectSocket(_ path: String) -> Int32? {
let descriptor = socket(AF_UNIX, SOCK_STREAM, 0)
guard descriptor >= 0 else { return nil }
var timeout = timeval(tv_sec: 8, tv_usec: 0)
var noSignal: Int32 = 1
setsockopt(descriptor, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
setsockopt(descriptor, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout)))
setsockopt(descriptor, SOL_SOCKET, SO_NOSIGPIPE, &noSignal, socklen_t(MemoryLayout.size(ofValue: noSignal)))
var address = sockaddr_un()
address.sun_family = sa_family_t(AF_UNIX)
address.sun_len = UInt8(MemoryLayout<sockaddr_un>.size)
path.withCString { source in
withUnsafeMutableBytes(of: &address.sun_path) { bytes in
bytes.copyMemory(from: UnsafeRawBufferPointer(start: source, count: path.utf8.count + 1))
}
}
let connected = withUnsafePointer(to: &address) { pointer in
pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) {
connect(descriptor, $0, socklen_t(MemoryLayout<sockaddr_un>.size))
}
}
guard connected == 0 else {
close(descriptor)
return nil
}
return descriptor
}
private func sendRequest(_ data: Data, descriptor: Int32) -> Bool {
data.withUnsafeBytes { bytes in
var offset = 0
while offset < bytes.count {
let count = write(descriptor, bytes.baseAddress!.advanced(by: offset), bytes.count - offset)
if count < 0 && errno == EINTR { continue }
guard count > 0 else { return false }
offset += count
}
return true
}
}
private func readResponse(descriptor: Int32) -> Status? {
var response = Data(count: 4096)
var received = 0
while received < 4096 {
let count = response.withUnsafeMutableBytes { bytes in
read(descriptor, bytes.baseAddress!.advanced(by: received), bytes.count - received)
}
if count < 0 && errno == EINTR { continue }
guard count > 0 else { return nil }
let end = received + count
if let newline = response[received..<end].firstIndex(of: 10) {
response.count = newline
return try? JSONDecoder().decode(Status.self, from: response)
}
received = end
}
return nil
}
func exchange(action: String = "status", value: String? = nil) -> Status {
#if PREVIEW_HOST
return Status(mode: "rule", tun: true, proxy: false, language: "en")
#else
#if DEBUG
if ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" {
return Status(mode: "rule", tun: true, proxy: false, language: "en")
}
#endif
func unavailable(_ key: String) -> Status { Status(error: key) }
guard let path = socketPath(), path.utf8.count < 104 else {
return unavailable("widget.unavailable")
}
guard let descriptor = connectSocket(path) else { return unavailable("widget.unavailable") }
defer { close(descriptor) }
guard authenticPeer(descriptor, identifier: hostID) else { return unavailable("widget.unavailable") }
var request = ["action": action]
if let value { request["value"] = value }
guard var data = try? JSONSerialization.data(withJSONObject: request) else {
return unavailable("widget.failed")
}
data.append(10)
guard sendRequest(data, descriptor: descriptor) else { return unavailable("widget.failed") }
return readResponse(descriptor: descriptor) ?? unavailable("widget.failed")
#endif
}
+57
View File
@@ -0,0 +1,57 @@
use serde::{Deserialize, Serialize};
use std::future::Future;
#[cfg(target_os = "macos")]
mod server;
#[cfg(target_os = "macos")]
pub use server::{reload, start};
#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Mode {
Rule,
Global,
Direct,
}
impl Mode {
pub const fn as_str(self) -> &'static str {
match self {
Self::Rule => "rule",
Self::Global => "global",
Self::Direct => "direct",
}
}
}
#[derive(Clone, Copy)]
pub enum Action {
Mode(Mode),
Tun(bool),
Proxy(bool),
}
#[derive(Default, Serialize)]
pub struct Status {
pub mode: Option<Mode>,
pub tun: Option<bool>,
pub proxy: Option<bool>,
pub error: Option<String>,
pub language: String,
}
impl Status {
pub fn confirms(&self, action: Action) -> bool {
match action {
Action::Mode(value) => self.mode == Some(value),
Action::Tun(value) => self.tun == Some(value),
Action::Proxy(value) => self.proxy == Some(value),
}
}
}
pub trait Backend: Send + Sync + 'static {
fn snapshot(&self) -> impl Future<Output = Status> + Send;
fn language(&self) -> impl Future<Output = String> + Send;
fn apply(&self, action: Action) -> impl Future<Output = Result<(), String>> + Send;
}
+219
View File
@@ -0,0 +1,219 @@
use crate::{Action, Backend, Mode, Status};
use serde::Deserialize;
use std::{
borrow::Cow,
ffi::{CStr, CString},
fs, mem,
os::fd::AsRawFd as _,
os::unix::fs::PermissionsExt as _,
sync::{
OnceLock,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use tokio::{
io::{AsyncBufReadExt as _, AsyncReadExt as _, AsyncWriteExt as _, BufReader},
net::UnixListener,
time::timeout,
};
struct Native {
path: unsafe extern "C" fn() -> *mut libc::c_char,
authenticate: unsafe extern "C" fn(i32) -> bool,
reload: unsafe extern "C" fn(),
}
static NATIVE: OnceLock<Native> = OnceLock::new();
fn load_native() -> anyhow::Result<Native> {
let executable = std::env::current_exe()?;
let contents = executable
.parent()
.and_then(|p| p.parent())
.ok_or_else(|| anyhow::anyhow!("Not an app bundle"))?;
let path = CString::new(
contents
.join("Frameworks/VergeWidgetBridge.dylib")
.as_os_str()
.as_encoded_bytes(),
)?;
unsafe {
let library = libc::dlopen(path.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
anyhow::ensure!(!library.is_null(), "Widget bridge unavailable");
let path = libc::dlsym(library, c"verge_widget_path".as_ptr());
let authenticate = libc::dlsym(library, c"verge_widget_authenticate".as_ptr());
let reload = libc::dlsym(library, c"verge_widget_reload".as_ptr());
anyhow::ensure!(
!path.is_null() && !authenticate.is_null() && !reload.is_null(),
"Invalid widget bridge"
);
Ok(Native {
path: mem::transmute::<*mut libc::c_void, unsafe extern "C" fn() -> *mut libc::c_char>(path),
authenticate: mem::transmute::<*mut libc::c_void, unsafe extern "C" fn(i32) -> bool>(authenticate),
reload: mem::transmute::<*mut libc::c_void, unsafe extern "C" fn()>(reload),
})
}
}
static MUTATING: AtomicBool = AtomicBool::new(false);
pub fn reload() {
if MUTATING.load(Ordering::Acquire) {
return;
}
if let Some(native) = NATIVE.get() {
unsafe { (native.reload)() };
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Request<'a> {
#[serde(borrow)]
action: Cow<'a, str>,
#[serde(borrow)]
value: Option<RequestValue<'a>>,
}
#[derive(Deserialize)]
#[serde(transparent)]
struct RequestValue<'a>(#[serde(borrow)] Cow<'a, str>);
impl Request<'_> {
fn action(&self) -> Result<Option<Action>, &'static str> {
match (self.action.as_ref(), self.value.as_ref().map(|value| value.0.as_ref())) {
("status", None) => Ok(None),
("mode", Some("rule")) => Ok(Some(Action::Mode(Mode::Rule))),
("mode", Some("global")) => Ok(Some(Action::Mode(Mode::Global))),
("mode", Some("direct")) => Ok(Some(Action::Mode(Mode::Direct))),
("tun", Some(value @ ("true" | "false"))) => Ok(Some(Action::Tun(value == "true"))),
("proxy", Some(value @ ("true" | "false"))) => Ok(Some(Action::Proxy(value == "true"))),
_ => Err("Invalid widget request"),
}
}
}
async fn serve(backend: impl Backend) -> anyhow::Result<()> {
let native = load_native()?;
let raw = unsafe { (native.path)() };
anyhow::ensure!(!raw.is_null(), "App Group container unavailable");
let path = unsafe { CStr::from_ptr(raw).to_string_lossy().into_owned() };
unsafe { libc::free(raw.cast()) };
// A second process must not unlink the live app's listener.
if tokio::net::UnixStream::connect(&path).await.is_ok() {
anyhow::bail!("Widget listener already running");
}
match fs::remove_file(&path) {
Ok(()) => (),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
Err(error) => return Err(error.into()),
}
let listener = UnixListener::bind(&path)?;
fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?;
let _ = NATIVE.set(native);
reload();
let mut last_error = None;
let mut pending = None;
loop {
let (stream, _) = listener.accept().await?;
let Some(native) = NATIVE.get() else { break };
if !unsafe { (native.authenticate)(stream.as_raw_fd()) } {
continue;
}
// Serialize widget mutations; never cancel a backend transaction on client timeout.
let mut stream = BufReader::new(stream);
let mut line = Vec::new();
let read = timeout(
Duration::from_secs(2),
(&mut stream).take(1024).read_until(b'\n', &mut line),
)
.await;
if !matches!(read, Ok(Ok(_))) || line.last() != Some(&b'\n') {
continue;
}
let request = match serde_json::from_slice::<Request>(&line) {
Ok(request) => request,
Err(_) => continue,
};
let action = match request.action() {
Ok(action) => action,
Err(_) => continue,
};
let changed = action.is_some();
// Coalesce hooks across the whole transaction, including errors and disconnected clients.
MUTATING.store(changed, Ordering::Release);
let refresh = scopeguard::guard(changed, |changed| {
MUTATING.store(false, Ordering::Release);
if changed {
reload();
}
});
// Mutations reply without re-reading state so the widget repaints one round trip
// sooner; the status read after the reload confirms the pending action.
let mut reply = match action {
Some(action) => {
match backend.apply(action).await {
Ok(()) => {
last_error = None;
pending = Some(action);
}
Err(error) => {
pending = None;
last_error = Some(error);
}
}
Status::default()
}
None => {
let state = backend.snapshot().await;
if let Some(action) = pending.take()
&& !state.confirms(action)
{
last_error = Some("widget.failed".into());
}
state
}
};
if action.is_some() {
reply.language = backend.language().await;
}
reply.error = last_error.take();
let serialized = serde_json::to_vec(&reply);
last_error = reply.error.take();
let mut bytes = serialized?;
bytes.push(b'\n');
let _ = timeout(Duration::from_secs(2), stream.get_mut().write_all(&bytes)).await;
drop(refresh);
}
Ok(())
}
pub fn start(backend: impl Backend) {
static STARTED: AtomicBool = AtomicBool::new(false);
if STARTED.swap(true, Ordering::Relaxed) {
return;
}
// Darwin 23 is macOS 14; older hosts must never load the WidgetKit bridge.
let mut version = [0u8; 64];
let mut length = version.len();
let result = unsafe {
libc::sysctlbyname(
c"kern.osrelease".as_ptr(),
version.as_mut_ptr().cast(),
&mut length,
std::ptr::null_mut(),
0,
)
};
let major = std::str::from_utf8(&version)
.ok()
.and_then(|v| v.split('.').next()?.parse::<u32>().ok());
if result != 0 || major.is_none_or(|major| major < 23) {
return;
}
tokio::spawn(async move {
if let Err(error) = serve(backend).await {
log::warn!("Widget unavailable: {error:#}");
}
});
}
+2 -1
View File
@@ -43,6 +43,7 @@ export default defineConfig([
'eslint.config.ts',
`vite.config.mts`,
'scripts/*.mjs',
'crates/clash-verge-widget/build/*.mjs',
'tests/*.ts',
'src/polyfills/*.js',
'tests/*.mjs',
@@ -143,7 +144,7 @@ export default defineConfig([
},
},
{
files: ['scripts/*.mjs'],
files: ['scripts/*.mjs', 'crates/clash-verge-widget/build/*.mjs'],
languageOptions: {
globals: {
+22 -22
View File
@@ -10,8 +10,8 @@
"dev:diff": "node scripts/dev.mjs dev",
"dev:trace": "node scripts/dev.mjs trace",
"dev:tauri": "cross-env RUST_BACKTRACE=full tauri dev -f tauri-dev",
"build": "cross-env NODE_OPTIONS='--max-old-space-size=4096' tauri build",
"build:fast": "cross-env NODE_OPTIONS='--max-old-space-size=4096' tauri build -- --profile fast-release",
"build": "node scripts/build.mjs",
"build:fast": "node scripts/build.mjs -- --profile fast-release",
"tauri": "tauri",
"web:dev": "vite",
"web:build": "tsc --noEmit && vite build",
@@ -52,17 +52,17 @@
"@mui/icons-material": "^9.0.1",
"@mui/material": "^9.0.1",
"@tanstack/react-virtual": "^3.13.25",
"@tauri-apps/api": "3.0.0-alpha.0",
"@tauri-apps/plugin-clipboard-manager": "^3.0.0-alpha.0",
"@tauri-apps/plugin-dialog": "^3.0.0-alpha.0",
"@tauri-apps/plugin-fs": "^3.0.0-alpha.0",
"@tauri-apps/plugin-http": "~3.0.0-alpha.0",
"@tauri-apps/plugin-opener": "3.0.0-alpha.0",
"@tauri-apps/plugin-updater": "3.0.0-alpha.0",
"@tauri-apps/api": "2.11.1",
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
"@tauri-apps/plugin-dialog": "^2.7.1",
"@tauri-apps/plugin-fs": "^2.5.1",
"@tauri-apps/plugin-http": "~2.5.9",
"@tauri-apps/plugin-opener": "2.5.4",
"@tauri-apps/plugin-updater": "2.10.1",
"ahooks": "^3.9.7",
"cidr-block": "^2.3.0",
"compare-versions": "^6.1.1",
"dayjs": "1.11.23",
"dayjs": "1.11.21",
"foxact": "^0.3.4",
"foxts": "^5.4.2",
"i18next": "^26.2.0",
@@ -73,11 +73,11 @@
"monaco-yaml": "^5.5.0",
"nanoid": "^6.0.0",
"qrcode.react": "^4.2.0",
"react": "19.3.0",
"react-dom": "19.3.0",
"react-error-boundary": "6.1.5",
"react": "19.2.8",
"react-dom": "19.2.8",
"react-error-boundary": "6.1.2",
"react-hook-form": "^7.76.1",
"react-i18next": "17.0.14",
"react-i18next": "17.0.11",
"react-markdown": "10.1.0",
"react-router": "^8.0.0",
"rehype-raw": "^7.0.0",
@@ -93,15 +93,15 @@
"@biomejs/biome": "^2.4.15",
"@eslint-react/eslint-plugin": "^5.8.5",
"@eslint/js": "^10.0.1",
"@tauri-apps/cli": "3.0.0-alpha.1",
"@tauri-apps/cli": "2.11.4",
"@types/lodash-es": "^4.17.12",
"@types/node": "^24.12.4",
"@types/react": "19.3.0",
"@types/react-dom": "19.3.0",
"@types/react": "19.2.18",
"@types/react-dom": "19.2.4",
"@types/validator": "^13.15.10",
"@vitejs/plugin-legacy": "^8.0.2",
"@vitejs/plugin-react": "^6.0.2",
"@wdio/tauri-service": "1.4.0",
"@wdio/tauri-service": "1.3.0",
"adm-zip": "^0.6.0",
"axios": "^1.16.1",
"cli-color": "^2.0.4",
@@ -121,7 +121,7 @@
"https-proxy-agent": "^9.0.0",
"husky": "^9.1.7",
"jiti": "^2.7.0",
"knip": "6.35.1",
"knip": "6.32.1",
"lint-staged": "^17.0.5",
"sass": "^1.100.0",
"tar": "^7.5.15",
@@ -131,8 +131,8 @@
"vite": "^8.0.14",
"vite-plugin-svgr": "^5.2.0",
"vitest": "^5.0.0",
"webdriverio": "9.31.9",
"ws": "8.21.3"
"webdriverio": "9.30.0",
"ws": "8.21.0"
},
"lint-staged": {
"*.{ts,tsx,js,mjs}": [
@@ -144,5 +144,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.4.2"
"packageManager": "pnpm@12.4.1"
}
+591 -501
View File
File diff suppressed because it is too large Load Diff
-12
View File
@@ -10,15 +10,3 @@ allowBuilds:
unrs-resolver: true
minimumReleaseAgeExclude:
- dayjs@1.11.21
- '@tauri-apps/cli-darwin-arm64@3.0.0-alpha.1'
- '@tauri-apps/cli-darwin-x64@3.0.0-alpha.1'
- '@tauri-apps/cli-linux-arm-gnueabihf@3.0.0-alpha.1'
- '@tauri-apps/cli-linux-arm64-gnu@3.0.0-alpha.1'
- '@tauri-apps/cli-linux-arm64-musl@3.0.0-alpha.1'
- '@tauri-apps/cli-linux-riscv64-gnu@3.0.0-alpha.1'
- '@tauri-apps/cli-linux-x64-gnu@3.0.0-alpha.1'
- '@tauri-apps/cli-linux-x64-musl@3.0.0-alpha.1'
- '@tauri-apps/cli-win32-arm64-msvc@3.0.0-alpha.1'
- '@tauri-apps/cli-win32-ia32-msvc@3.0.0-alpha.1'
- '@tauri-apps/cli-win32-x64-msvc@3.0.0-alpha.1'
- '@tauri-apps/cli@3.0.0-alpha.1'
+62
View File
@@ -0,0 +1,62 @@
import { spawnSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
const root = join(import.meta.dirname, '..')
const forward = () => {
const tauri = spawnSync(
'pnpm',
['exec', 'tauri', 'build', ...process.argv.slice(2)],
{
cwd: root,
stdio: 'inherit',
env: {
...process.env,
NODE_OPTIONS: process.env.NODE_OPTIONS || '--max-old-space-size=4096',
},
shell: process.platform === 'win32',
},
)
process.exit(tauri.status ?? 1)
}
if (process.platform !== 'darwin') forward()
if (process.env.CLASH_VERGE_WIDGET === '0') {
console.warn(
'CLASH_VERGE_WIDGET=0: building without the desktop widget extension.',
)
process.env.APPLE_SIGNING_IDENTITY = '-'
forward()
}
const run = (command, args) => {
const result = spawnSync(command, args, { encoding: 'utf8' })
if (result.error) return ''
return result.stdout
}
let identity = process.env.APPLE_SIGNING_IDENTITY
if (!identity) {
const mac = JSON.parse(
readFileSync(join(root, 'src-tauri/tauri.macos.conf.json'), 'utf8'),
)
identity = mac.bundle?.macOS?.signingIdentity || undefined
}
if (!identity) {
const identities = [
...run('security', ['find-identity', '-v', '-p', 'codesigning']).matchAll(
/\b([A-F0-9]{40}) "([^"]+)"/g,
),
]
if (identities.length === 1) identity = identities[0][2]
}
if (!identity) {
console.error(
'macOS packaging needs the widget extension signed with the host: set APPLE_SIGNING_IDENTITY to a valid certificate, or export CLASH_VERGE_WIDGET=0 to build without the widget.',
)
process.exit(1)
}
process.env.APPLE_SIGNING_IDENTITY = identity
forward()
+1 -1
View File
@@ -49,7 +49,7 @@ const FRONTEND_EXTENSIONS = new Set([
'.vue',
'.json',
])
const BACKEND_EXTENSIONS = new Set(['.rs'])
const BACKEND_EXTENSIONS = new Set(['.rs', '.swift'])
const TS_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'])
+28 -26
View File
@@ -23,15 +23,13 @@ tauri-dev = ["dep:tauri-plugin-devtools"]
tokio-trace = ["clash-verge-logging/tokio-trace"]
chrome-trace = ["clash-verge-logging/chrome-trace"]
clippy = ["tauri/test"]
# The perf-harness feature and its main.rs wiring are parked until
# tauri-plugin-wdio-webdriver publishes a tauri 3 release; restore both
# from git history together with the crate dependency.
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
[package.metadata.bundle]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies]
tauri-build = { version = "3.0.0-alpha.0", features = [] }
tauri-build = { version = "2.6.3", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
@@ -44,12 +42,12 @@ tauri-plugin-clash-verge-sysinfo = { workspace = true }
tauri-plugin-clipboard-manager = { workspace = true }
tauri = { workspace = true, features = [
"protocol-asset",
"devtools",
"tracing",
"tray-icon",
"image-ico",
"image-png",
] }
tauri-runtime-wry = { workspace = true, features = ["devtools"] }
parking_lot = { workspace = true }
anyhow = { workspace = true }
tokio = { workspace = true }
@@ -61,13 +59,13 @@ smartstring = { workspace = true, features = ["serde"] }
bitflags = { workspace = true }
socket2 = { workspace = true }
warp = { version = "0.4.3", features = ["server"] }
open = "5.4.4"
open = "5.4.1"
rfd = { version = "0.16.0", default-features = false, features = ["common-controls-v6"] }
dirs = "7.0.0"
dunce = "1.0.5"
nanoid = "0.5"
chrono = { workspace = true }
boa_engine = "0.22.0"
boa_engine = "0.21.1"
once_cell = { version = "1.21.4", features = ["parking_lot"] }
percent-encoding = "2.3.2"
reqwest = { workspace = true }
@@ -76,37 +74,37 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch
"guard",
] }
network-interface = { version = "2.0.5", features = ["serde"] }
tauri-plugin-shell = "3.0.0-alpha.0"
tauri-plugin-opener = "3.0.0-alpha.0"
tauri-plugin-dialog = "3.0.0-alpha.0"
tauri-plugin-fs = "3.0.0-alpha.0"
tauri-plugin-process = "3.0.0-alpha.0"
tauri-plugin-deep-link = "3.0.0-alpha.0"
tauri-plugin-window-state = "3.0.0-alpha.0"
tauri-plugin-shell = "2.3.5"
tauri-plugin-opener = "2.5.4"
tauri-plugin-dialog = "2.7.2"
tauri-plugin-fs = "2.5.1"
tauri-plugin-process = "2.3.1"
tauri-plugin-deep-link = "2.4.9"
tauri-plugin-window-state = "2.4.1"
zip = "8.6.0"
flate2 = "1.1.10"
flate2 = "1.1.9"
reqwest_dav = "0.3.3"
aes-gcm = { version = "0.11.1" }
aes-gcm = { version = "0.11.0" }
base64 = "0.23.1"
sha2 = "0.11"
getrandom = "0.4.3"
futures = "0.3.34"
gethostname = "1.1.0"
scopeguard = "1.2.0"
tauri-plugin-notification = "3.0.0-alpha.0"
tauri-plugin-notification = "2.3.3"
tokio-stream = "0.1.19"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "3.0.0-alpha.0"
tauri-plugin-http = "2.5.9"
tracing = { workspace = true }
tauri-plugin-devtools = { version = "3.0.0-alpha.0", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", branch = "feat/tauri-v3" }
tauri-plugin-devtools = { version = "2.1.0", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", branch = "main" }
async-trait = "0.1.92"
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.1", version = "2.7.1", features = [
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.6.9", version = "2.6.9", features = [
"client",
] }
arc-swap = "1.9.2"
tokio-rustls = "0.26.5"
rustls = { version = "0.23.45", features = ["ring"] }
tokio-rustls = "0.26.4"
rustls = { version = "0.23.43", features = ["ring"] }
webpki-roots = "1.0.9"
dark-light = "3.0.0"
bytes = "1.12.1"
@@ -116,6 +114,10 @@ tokio-util = { version = "0.7.19", features = ["time"] }
libc = "0.2.189"
[target.'cfg(target_os = "macos")'.dependencies]
clash-verge-widget = { workspace = true }
tauri-plugin-wdio-webdriver = { version = "=1.3.0", optional = true }
core-foundation = "0.9"
system-configuration = "0.7"
objc2 = "0.6.4"
objc2-foundation = { version = "0.3.2", features = [
"NSString",
@@ -147,9 +149,9 @@ windows = { version = "0.62.2", features = ["Win32_Globalization"] }
windows-sys.workspace = true
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-autostart = "3.0.0-alpha.0"
tauri-plugin-global-shortcut = "3.0.0-alpha.0"
tauri-plugin-updater = "3.0.0-alpha.0"
tauri-plugin-autostart = "2.5.1"
tauri-plugin-global-shortcut = "2.3.2"
tauri-plugin-updater = "2.10.1"
[dev-dependencies]
criterion = { workspace = true }
+1
View File
@@ -70,6 +70,7 @@
"dialog:allow-open",
"global-shortcut:allow-is-registered",
"global-shortcut:allow-register",
"global-shortcut:allow-register-all",
"global-shortcut:allow-unregister",
"global-shortcut:allow-unregister-all",
"process:allow-exit",
+6
View File
@@ -36,10 +36,14 @@ impl Handle {
}
pub fn refresh_clash() {
#[cfg(target_os = "macos")]
clash_verge_widget::reload();
Self::send_event(FrontendEvent::RefreshClash);
}
pub fn refresh_verge() {
#[cfg(target_os = "macos")]
clash_verge_widget::reload();
Self::send_event(FrontendEvent::RefreshVerge);
}
@@ -56,6 +60,8 @@ impl Handle {
/// Sent on every transition, so the frontend does not have to poll to notice that the Core
/// stopped or that the Service came back.
pub fn notify_run_state(state: &crate::core::runstate::RunStateView) {
#[cfg(target_os = "macos")]
clash_verge_widget::reload();
let Ok(state) = serde_json::to_value(state) else {
return;
};
+4 -1
View File
@@ -476,7 +476,10 @@ impl CoreManager {
// rather than fail — only if the watcher is actually live; a user toggling while
// offline still fails fast.
#[cfg(target_os = "macos")]
if crate::core::network_watch::is_armed()
let watcher_armed = crate::core::network_watch::is_armed();
#[cfg(not(target_os = "macos"))]
let watcher_armed = false;
if watcher_armed
&& !crate::utils::resolve::is_resolve_done()
&& Config::verge()
.await
+2
View File
@@ -19,6 +19,8 @@ pub mod timer;
pub mod tray;
pub mod updater;
pub mod validate;
#[cfg(target_os = "macos")]
pub mod widget;
pub mod win_uwp;
pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater};
+38 -27
View File
@@ -5,35 +5,53 @@
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use sysproxy::NetworkServiceMonitor;
use core_foundation::{
array::CFArray,
runloop::{CFRunLoop, kCFRunLoopCommonModes},
string::CFString,
};
use std::sync::atomic::{AtomicBool, Ordering};
use system_configuration::dynamic_store::{SCDynamicStore, SCDynamicStoreBuilder, SCDynamicStoreCallBackContext};
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
/// Set once the subscription is live. Startup defers the proxy write to the watcher only then.
static ARMED: AtomicBool = AtomicBool::new(false);
pub fn is_armed() -> bool {
MONITOR.lock().is_some()
ARMED.load(Ordering::Acquire)
}
/// Subscribe to the primary IPv4 service on the main run loop. Armed on return, so a service
/// appearing from here on is never missed.
pub fn start() {
match NetworkServiceMonitor::start(|| {
AsyncHandler::spawn(reapply);
}) {
Ok(monitor) => {
*MONITOR.lock() = Some(monitor);
logging!(
debug,
Type::Core,
"network watch armed; the system proxy is re-applied on network changes"
);
}
Err(error) => logging!(
let store = SCDynamicStoreBuilder::new("clash-verge-rev")
.callback_context(SCDynamicStoreCallBackContext {
callout: on_change,
info: (),
})
.build();
let keys = CFArray::from_CFTypes(&[CFString::from_static_string("State:/Network/Global/IPv4")]);
let Some(source) = store
.filter(|store| store.set_notification_keys(&keys, &CFArray::<CFString>::from_CFTypes(&[])))
.and_then(|store| store.create_run_loop_source())
else {
logging!(
warn,
Type::Core,
"could not watch the network; the proxy is not re-applied on changes: {error}"
),
}
"could not watch the network; the proxy is not re-applied on changes"
);
return;
};
CFRunLoop::get_main().add_source(&source, unsafe { kCFRunLoopCommonModes });
ARMED.store(true, Ordering::Release);
logging!(
debug,
Type::Core,
"network watch armed; the system proxy is re-applied on network changes"
);
}
fn on_change(_: SCDynamicStore, _: CFArray<CFString>, (): &mut ()) {
AsyncHandler::spawn(reapply);
}
async fn reapply() {
@@ -48,17 +66,10 @@ async fn reapply() {
.latest_arc()
.enable_system_proxy
.unwrap_or_default()
|| !proxy_control::has_network_service().await
{
return;
}
if !proxy_control::has_network_service().await {
logging!(
debug,
Type::Core,
"network changed without a service to write the proxy on; waiting for the next change"
);
return;
}
if let Err(error) = manager.apply_proxy_after_start().await {
logging!(
warn,
+5 -4
View File
@@ -385,11 +385,12 @@ async fn current_service_proxy_config(verge: &IVerge) -> Result<MacosProxyConfig
}
/// Whether macOS has a network service to write the proxy on right now.
#[cfg(target_os = "macos")]
pub async fn has_network_service() -> bool {
tokio::task::spawn_blocking(|| sysproxy::Sysproxy::has_network_service().unwrap_or(true))
.await
.unwrap_or(true)
tokio::task::spawn_blocking(
|| !matches!(sysproxy::Sysproxy::get_system_proxy(), Err(error) if is_missing_network_service(&error)),
)
.await
.unwrap_or(true)
}
pub fn is_reportable(error: &anyhow::Error) -> bool {
+3 -113
View File
@@ -564,39 +564,8 @@ fn uninstall_service() -> Result<()> {
#[cfg(target_os = "windows")]
fn install_service() -> Result<()> {
logging!(info, Type::Service, "install service");
let cores = crate::config::IVerge::VALID_CLASH_CORES
.iter()
.map(|core| service_core_path(core, ".exe"))
.collect::<Result<Vec<_>>>()?;
install_windows_service_with_cores(&cores, run_windows_service_installer)
}
#[cfg(target_os = "windows")]
fn install_windows_service_with_cores(
cores: &[PathBuf],
mut run_installer: impl FnMut(&[std::ffi::OsString]) -> Result<()>,
) -> Result<()> {
let cores: Vec<_> = cores.iter().filter(|core| core.is_file()).collect();
if cores.is_empty() {
bail!("no core executable is available; restore a bundled core before installing the service");
}
let mut arguments = vec!["--install-service".into()];
for core in cores {
let digest = sha256_hex(core)?;
arguments.extend([
"--install-core".into(),
core.as_os_str().to_owned(),
"--sha256".into(),
digest.into(),
]);
}
run_installer(&arguments).context("failed to install the service and its cores; choose Repair to retry")
}
#[cfg(target_os = "windows")]
fn run_windows_service_installer(arguments: &[std::ffi::OsString]) -> Result<()> {
use std::process::Output;
logging!(info, Type::Service, "install service");
use deelevate::{PrivilegeLevel, Token};
use runas::Command as RunasCommand;
@@ -614,7 +583,7 @@ fn run_windows_service_installer(arguments: &[std::ffi::OsString]) -> Result<()>
let level = token.privilege_level()?;
let output = match level {
PrivilegeLevel::NotPrivileged => {
let status = RunasCommand::new(&install_path).args(arguments).show(false).status()?;
let status = RunasCommand::new(&install_path).show(false).status()?;
Output {
status,
stdout: Vec::new(),
@@ -623,10 +592,7 @@ fn run_windows_service_installer(arguments: &[std::ffi::OsString]) -> Result<()>
}
_ => {
// StdCommand returns Output directly
StdCommand::new(&install_path)
.args(arguments)
.creation_flags(0x08000000)
.output()?
StdCommand::new(&install_path).creation_flags(0x08000000).output()?
}
};
@@ -2201,82 +2167,6 @@ mod tests {
}
}
#[cfg(target_os = "windows")]
#[test]
fn windows_service_install_combines_service_and_attested_cores() -> anyhow::Result<()> {
use std::ffi::OsString;
let root = TestDirectory::new("scoop install")?;
let cores: Vec<_> = crate::config::IVerge::VALID_CLASH_CORES
.iter()
.map(|name| root.path().join(format!("{name}.exe")))
.collect();
for core in &cores {
std::fs::write(core, b"abc")?;
}
let mut calls = Vec::new();
super::install_windows_service_with_cores(&cores, |arguments| {
calls.push(arguments.to_vec());
Ok(())
})?;
assert_eq!(calls.len(), 1, "service and cores must share one elevation");
let digest = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
let mut expected: Vec<OsString> = vec!["--install-service".into()];
expected.extend(cores.iter().flat_map(|core| {
[
"--install-core".into(),
core.as_os_str().to_owned(),
"--sha256".into(),
digest.into(),
]
}));
assert_eq!(calls[0], expected);
Ok(())
}
#[cfg(target_os = "windows")]
#[test]
fn windows_service_install_skips_unavailable_cores() -> anyhow::Result<()> {
let root = TestDirectory::new("missing-core")?;
let core = root.path().join("verge-mihomo.exe");
let missing = root.path().join("verge-mihomo-alpha.exe");
std::fs::write(&core, b"abc")?;
let cores = [core.clone(), missing.clone(), root.path().to_path_buf()];
let mut calls = Vec::new();
super::install_windows_service_with_cores(&cores, |arguments| {
calls.push(arguments.to_vec());
Ok(())
})?;
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].len(), 5);
assert_eq!(calls[0][0], "--install-service");
assert_eq!(calls[0][2], core.as_os_str());
let error = super::install_windows_service_with_cores(&[missing, root.path().to_path_buf()], |_| {
panic!("no available core must fail before invoking the installer")
})
.expect_err("installation requires at least one available core");
assert!(error.to_string().contains("no core executable"));
Ok(())
}
#[cfg(target_os = "windows")]
#[test]
fn windows_service_install_propagates_installer_failure() -> anyhow::Result<()> {
let root = TestDirectory::new("install-failure")?;
let core = root.path().join("verge-mihomo.exe");
std::fs::write(&core, b"abc")?;
let mut calls = 0;
let result = super::install_windows_service_with_cores(std::slice::from_ref(&core), |_| {
calls += 1;
bail!("installer failed with exit code 1")
});
let error = result.expect_err("installation failure must not be reported as success");
assert!(format!("{error:#}").contains("exit code 1"));
assert!(error.to_string().contains("Repair"));
assert_eq!(calls, 1);
Ok(())
}
fn staging_directory(home: &Path) -> PathBuf {
home.join("Applications/.clash-verge-rev-dev/service-core")
}
+32 -34
View File
@@ -24,7 +24,7 @@ use std::borrow::Cow;
use std::collections::HashMap;
use std::time::Duration;
use tauri::{
AppHandle, DynRuntime,
AppHandle, Wry,
menu::{CheckMenuItem, IsMenuItem, MenuEvent, MenuItem, PredefinedMenuItem, Submenu},
};
@@ -35,7 +35,7 @@ use menu_def::{MenuIds, MenuTexts};
// TODO: 是否需要将可变菜单抽离存储起来,后续直接更新对应菜单实例,无需重新创建菜单(待考虑)
type ProxyMenuItem = (Option<Submenu<DynRuntime>>, Vec<Box<dyn IsMenuItem<DynRuntime>>>);
type ProxyMenuItem = (Option<Submenu<Wry>>, Vec<Box<dyn IsMenuItem<Wry>>>);
const TRAY_CLICK_DEBOUNCE_MS: u64 = 300;
pub const TRAY_ID: &str = "clash-verge-rev-tray";
@@ -440,7 +440,7 @@ fn create_hotkeys(hotkeys: &Option<Vec<String>>) -> HashMap<&str, &str> {
fn create_profile_menu_item(
app_handle: &AppHandle,
profiles_preview: Vec<IProfilePreview<'_>>,
) -> Result<Vec<CheckMenuItem<DynRuntime>>> {
) -> Result<Vec<CheckMenuItem<Wry>>> {
profiles_preview
.into_iter()
.map(|profile| {
@@ -462,9 +462,9 @@ fn create_subcreate_proxy_menu_item(
proxy_mode: &str,
proxy_group_order_map: Option<HashMap<String, usize>>,
proxy_nodes_data: Option<Proxies>,
) -> Vec<Submenu<DynRuntime>> {
let proxy_submenus: Vec<Submenu<DynRuntime>> = {
let mut submenus: Vec<(String, usize, Submenu<DynRuntime>)> = Vec::new();
) -> Vec<Submenu<Wry>> {
let proxy_submenus: Vec<Submenu<Wry>> = {
let mut submenus: Vec<(String, usize, Submenu<Wry>)> = Vec::new();
// TODO: 应用启动时,内核还未启动完全,无法获取代理节点信息
if let Some(proxy_nodes_data) = proxy_nodes_data {
@@ -484,7 +484,7 @@ fn create_subcreate_proxy_menu_item(
let now_proxy = group_data.now.as_deref().unwrap_or_default();
let group_items: Vec<CheckMenuItem<DynRuntime>> = all_proxies
let group_items: Vec<CheckMenuItem<Wry>> = all_proxies
.iter()
.filter_map(|proxy_str| {
let is_selected = *proxy_str == now_proxy;
@@ -515,10 +515,8 @@ fn create_subcreate_proxy_menu_item(
let group_display_name = group_name.to_string();
let group_items_refs: Vec<&dyn IsMenuItem<DynRuntime>> = group_items
.iter()
.map(|item| item as &dyn IsMenuItem<DynRuntime>)
.collect();
let group_items_refs: Vec<&dyn IsMenuItem<Wry>> =
group_items.iter().map(|item| item as &dyn IsMenuItem<Wry>).collect();
if let Ok(submenu) = Submenu::with_id_and_items(
app_handle,
@@ -554,7 +552,7 @@ fn create_subcreate_proxy_menu_item(
fn create_proxy_menu_item(
app_handle: &AppHandle,
show_proxy_groups_inline: bool,
proxy_submenus: Vec<Submenu<DynRuntime>>,
proxy_submenus: Vec<Submenu<Wry>>,
proxies_text: &str,
) -> Result<ProxyMenuItem> {
let (proxies_submenu, inline_proxy_items) = if show_proxy_groups_inline {
@@ -562,13 +560,13 @@ fn create_proxy_menu_item(
None,
proxy_submenus
.into_iter()
.map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem<DynRuntime>>)
.map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem<Wry>>)
.collect(),
)
} else if !proxy_submenus.is_empty() {
let proxy_submenu_refs: Vec<&dyn IsMenuItem<DynRuntime>> = proxy_submenus
let proxy_submenu_refs: Vec<&dyn IsMenuItem<Wry>> = proxy_submenus
.iter()
.map(|submenu| submenu as &dyn IsMenuItem<DynRuntime>)
.map(|submenu| submenu as &dyn IsMenuItem<Wry>)
.collect();
(
@@ -595,7 +593,7 @@ async fn create_tray_menu(
tun_mode_available: bool,
profiles_preview: Vec<IProfilePreview<'_>>,
options: TrayMenuOptions,
) -> Result<tauri::menu::Menu<DynRuntime>> {
) -> Result<tauri::menu::Menu<Wry>> {
let current_proxy_mode = mode.unwrap_or("");
let mut verge_settings = Config::verge().await.latest_arc();
@@ -649,12 +647,12 @@ async fn create_tray_menu(
let hotkeys = create_hotkeys(&verge_settings.hotkeys);
let profile_menu_items: Vec<CheckMenuItem<DynRuntime>> = create_profile_menu_item(app_handle, profiles_preview)?;
let profile_menu_items: Vec<CheckMenuItem<Wry>> = create_profile_menu_item(app_handle, profiles_preview)?;
let texts = MenuTexts::new();
let profile_menu_items_refs: Vec<&dyn IsMenuItem<DynRuntime>> = profile_menu_items
let profile_menu_items_refs: Vec<&dyn IsMenuItem<Wry>> = profile_menu_items
.iter()
.map(|item| item as &dyn IsMenuItem<DynRuntime>)
.map(|item| item as &dyn IsMenuItem<Wry>)
.collect();
let open_window = &MenuItem::with_id(
@@ -707,9 +705,9 @@ async fn create_tray_menu(
outbound_modes_label.as_str(),
true,
&[
rule_mode as &dyn IsMenuItem<DynRuntime>,
global_mode as &dyn IsMenuItem<DynRuntime>,
direct_mode as &dyn IsMenuItem<DynRuntime>,
rule_mode as &dyn IsMenuItem<Wry>,
global_mode as &dyn IsMenuItem<Wry>,
direct_mode as &dyn IsMenuItem<Wry>,
],
)?)
};
@@ -814,7 +812,7 @@ async fn create_tray_menu(
&texts.more,
true,
&[
copy_env as &dyn IsMenuItem<DynRuntime>,
copy_env as &dyn IsMenuItem<Wry>,
close_all_connections,
restart_clash,
restart_app,
@@ -831,13 +829,13 @@ async fn create_tray_menu(
let separator = &PredefinedMenuItem::separator(app_handle)?;
let mut menu_items: Vec<&dyn IsMenuItem<DynRuntime>> = vec![open_window, separator];
let mut menu_items: Vec<&dyn IsMenuItem<Wry>> = vec![open_window, separator];
if show_outbound_modes_inline {
menu_items.extend_from_slice(&[
rule_mode as &dyn IsMenuItem<DynRuntime>,
global_mode as &dyn IsMenuItem<DynRuntime>,
direct_mode as &dyn IsMenuItem<DynRuntime>,
rule_mode as &dyn IsMenuItem<Wry>,
global_mode as &dyn IsMenuItem<Wry>,
direct_mode as &dyn IsMenuItem<Wry>,
]);
} else if let Some(ref outbound_modes) = outbound_modes {
menu_items.push(outbound_modes);
@@ -847,7 +845,7 @@ async fn create_tray_menu(
match tray_proxy_groups_display_mode {
"default" => {
menu_items.extend(proxies_menu.iter().map(|item| item as &dyn IsMenuItem<DynRuntime>));
menu_items.extend(proxies_menu.iter().map(|item| item as &dyn IsMenuItem<_>));
}
"inline" if !inline_proxy_items.is_empty() => {
menu_items.extend(inline_proxy_items.iter().map(|item| item.as_ref()));
@@ -857,14 +855,14 @@ async fn create_tray_menu(
menu_items.extend_from_slice(&[
separator,
system_proxy as &dyn IsMenuItem<DynRuntime>,
tun_mode as &dyn IsMenuItem<DynRuntime>,
system_proxy as &dyn IsMenuItem<Wry>,
tun_mode as &dyn IsMenuItem<Wry>,
separator,
lightweight_mode as &dyn IsMenuItem<DynRuntime>,
open_dir as &dyn IsMenuItem<DynRuntime>,
more as &dyn IsMenuItem<DynRuntime>,
lightweight_mode as &dyn IsMenuItem<Wry>,
open_dir as &dyn IsMenuItem<Wry>,
more as &dyn IsMenuItem<Wry>,
separator,
quit as &dyn IsMenuItem<DynRuntime>,
quit as &dyn IsMenuItem<Wry>,
]);
let menu = tauri::menu::MenuBuilder::new(app_handle).items(&menu_items).build()?;
+83
View File
@@ -0,0 +1,83 @@
use crate::{cmd, config::IVerge, core::handle::Handle, feat, process::AsyncHandler};
use clash_verge_widget::{Action, Backend, Mode, Status};
use tauri_plugin_mihomo::models::ClashMode;
struct AppBackend;
impl Backend for AppBackend {
async fn snapshot(&self) -> Status {
let core = Handle::mihomo().get_base_config().await;
let proxy = {
let manual = cmd::network::get_sys_proxy()
.await
.ok()
.and_then(|v| v.get("enable").and_then(|v| v.as_bool()));
let pac = cmd::network::get_auto_proxy()
.await
.ok()
.and_then(|v| v.get("enable").and_then(|v| v.as_bool()));
match (manual, pac) {
(Some(true), _) | (_, Some(true)) => Some(true),
(Some(false), Some(false)) => Some(false),
_ => None,
}
};
let (mode, tun) = match core {
Ok(config) => (
Some(match config.mode {
ClashMode::Rule => Mode::Rule,
ClashMode::Global => Mode::Global,
ClashMode::Direct => Mode::Direct,
}),
Some(config.tun.enable),
),
_ => (None, None),
};
Status {
mode,
tun,
proxy,
error: None,
language: clash_verge_i18n::current_language(
crate::config::Config::verge().await.data_arc().language.as_deref(),
)
.into_owned(),
}
}
async fn language(&self) -> String {
clash_verge_i18n::current_language(crate::config::Config::verge().await.data_arc().language.as_deref())
.into_owned()
}
async fn apply(&self, action: Action) -> Result<(), String> {
if Handle::global().is_exiting() {
return Err("widget.unavailable".into());
}
match action {
Action::Mode(mode) => feat::change_clash_mode(mode.as_str().into())
.await
.map_err(|_| "widget.failed".into()),
Action::Tun(_) | Action::Proxy(_) => {
let payload = IVerge {
enable_tun_mode: match action {
Action::Tun(value) => Some(value),
_ => None,
},
enable_system_proxy: match action {
Action::Proxy(value) => Some(value),
_ => None,
},
..Default::default()
};
cmd::verge::patch_verge_config(payload)
.await
.map_err(|_| "widget.failed".into())
}
}
}
}
pub fn start() {
AsyncHandler::spawn(|| async { clash_verge_widget::start(AppBackend) });
}
+5 -3
View File
@@ -39,7 +39,7 @@ mod app_init {
}
/// Setup plugins for the Tauri builder
pub fn setup_plugins(builder: tauri::Builder) -> tauri::Builder {
pub fn setup_plugins(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {
#[allow(unused_mut)]
let mut builder = builder
.plugin(tauri_plugin_clash_verge_sysinfo::init())
@@ -116,7 +116,7 @@ mod app_init {
Ok(())
}
pub fn generate_handlers() -> impl Fn(tauri::ipc::Invoke) -> bool + Send + Sync + 'static {
pub fn generate_handlers() -> impl Fn(tauri::ipc::Invoke<tauri::Wry>) -> bool + Send + Sync + 'static {
tauri::generate_handler![
tauri_plugin_clash_verge_sysinfo::commands::get_system_info,
tauri_plugin_clash_verge_sysinfo::commands::get_app_uptime,
@@ -255,7 +255,7 @@ pub fn run() -> std::process::ExitCode {
#[cfg(target_os = "linux")]
utils::linux::workarounds::apply_wayland_webkit_fix();
let builder = app_init::setup_plugins(tauri::Builder::default().runtime(tauri_runtime_wry::Wry::default()))
let builder = app_init::setup_plugins(tauri::Builder::default())
.setup(|app| {
// Logger may not be ready yet, so mirror setup panics to stderr.
fn log_setup_panic(stage: &str, panic: Box<dyn std::any::Any + Send>) {
@@ -341,6 +341,8 @@ pub fn run() -> std::process::ExitCode {
logging!(info, Type::System, "应用就绪");
crate::utils::server::set_commands_ready();
#[cfg(target_os = "macos")]
crate::core::widget::start();
#[cfg(target_os = "macos")]
if let Some(window) = _app_handle.get_webview_window("main") {
+11
View File
@@ -1,8 +1,19 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::process::ExitCode;
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
use std::sync::atomic::{AtomicUsize, Ordering};
#[cfg(all(feature = "perf-harness", target_os = "macos"))]
#[path = "../../scripts/perf/app.rs"]
mod perf;
#[cfg(all(feature = "perf-harness", target_os = "macos"))]
fn main() -> ExitCode {
perf::run()
}
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
fn main() -> ExitCode {
let default_parallelism = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
let worker_limit = std::cmp::min(default_parallelism, 8);
+15
View File
@@ -8,6 +8,8 @@ use crate::{
core::{CoreManager, handle, timer::Timer},
utils::help,
};
#[cfg(target_os = "macos")]
use crate::{module::lightweight, utils::window_manager::WindowManager};
use clash_verge_logging::{Type, logging, logging_error};
pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
@@ -25,6 +27,19 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> {
let link_parsed = Url::parse(param_str)
.map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?;
// Dedicated "raise the window" route (clash-verge://show) for surfaces that
// activate a tray-only host without firing the macOS reopen event.
#[cfg(target_os = "macos")]
if link_parsed.host_str() == Some("show") {
if lightweight::is_in_lightweight_mode() {
lightweight::exit_lightweight_mode().await;
} else {
handle::Handle::global().set_activation_policy_regular();
WindowManager::show_main_window().await;
}
return Ok(());
}
let Some((url, name)) = extract_subscription_info(&link_parsed) else {
logging!(
warn,
+1 -4
View File
@@ -132,10 +132,7 @@ pub fn take_webview_needs_reload() -> bool {
/// reload visible webviews immediately, and defer a hidden main-window reload until activation.
/// Registering this callback replaces Tauri's default automatic reload.
#[cfg(target_os = "macos")]
pub fn on_web_content_process_terminated(
webview: &tauri::Webview,
_termination: &tauri::webview::WebContentProcessTermination,
) {
pub fn on_web_content_process_terminated(webview: &tauri::Webview) {
if handle::Handle::global().is_exiting() {
return;
}
+9 -9
View File
@@ -4,7 +4,7 @@ use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use std::pin::Pin;
use std::time::Duration;
use tauri::{Manager as _, WebviewWindow};
use tauri::{Manager as _, WebviewWindow, Wry};
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowOperationResult {
@@ -50,7 +50,7 @@ impl WindowManager {
handle::Handle::global().set_activation_policy_regular();
}
fn get_main_window_with_state() -> (Option<WebviewWindow>, WindowState) {
fn get_main_window_with_state() -> (Option<WebviewWindow<Wry>>, WindowState) {
let Some(window) = Self::get_main_window() else {
return (None, WindowState::NotExist);
};
@@ -76,7 +76,7 @@ impl WindowManager {
Self::get_main_window_with_state().1
}
pub fn get_main_window() -> Option<WebviewWindow> {
pub fn get_main_window() -> Option<WebviewWindow<Wry>> {
let app_handle = handle::Handle::app_handle();
app_handle.get_webview_window("main")
}
@@ -147,7 +147,7 @@ impl WindowManager {
}
}
fn hide_main_window(window: Option<&WebviewWindow>) -> WindowOperationResult {
fn hide_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(debug, Type::Window, "窗口可见,将隐藏窗口");
if let Some(window) = window {
match window.close() {
@@ -166,7 +166,7 @@ impl WindowManager {
}
}
fn activate_existing_main_window(window: Option<&WebviewWindow>) -> WindowOperationResult {
fn activate_existing_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(debug, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口");
if let Some(window) = window {
Self::activate_window(window)
@@ -176,7 +176,7 @@ impl WindowManager {
}
}
fn activate_window(window: &WebviewWindow) -> WindowOperationResult {
fn activate_window(window: &WebviewWindow<Wry>) -> WindowOperationResult {
logging!(debug, Type::Window, "开始激活窗口");
#[cfg(target_os = "macos")]
Self::set_macos_activation_policy_regular();
@@ -233,15 +233,15 @@ impl WindowManager {
}
}
pub fn is_main_window_visible(window: Option<&WebviewWindow>) -> bool {
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(window: Option<&WebviewWindow>) -> bool {
pub fn is_main_window_focused(window: Option<&WebviewWindow<Wry>>) -> bool {
window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false)
}
fn is_main_window_minimized(window: Option<&WebviewWindow>) -> bool {
fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false)
}
+9 -3
View File
@@ -2,14 +2,20 @@
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"identifier": "io.github.clash-verge-rev.clash-verge-rev",
"productName": "Clash Verge",
"build": {
"beforeBundleCommand": "node crates/clash-verge-widget/build/bundle.mjs"
},
"bundle": {
"targets": ["app", "dmg"],
"macOS": {
"frameworks": [],
"frameworks": ["generated/widget/VergeWidgetBridge.dylib"],
"files": {
"PlugIns/VergeWidget.appex": "generated/widget/VergeWidget.appex"
},
"minimumSystemVersion": "11.0",
"exceptionDomain": "",
"signingIdentity": null,
"entitlements": "packages/macos/entitlements.plist",
"entitlements": "generated/widget/Host.entitlements",
"dmg": {
"background": "images/background.png",
"appPosition": {
@@ -29,7 +35,7 @@
"y": 180
}
},
"infoPlist": "packages/macos/info_merge.plist"
"infoPlist": "generated/widget/Host.plist"
}
}
}
@@ -35,7 +35,7 @@ export const formatConnectionTraffic = (value?: number) => {
? 0
: Math.min(Math.floor(Math.log2(value) / 10), TRAFFIC_UNITS.length - 1)
const data = value / 1024 ** exp
const text = Math.round(data) >= 1000 ? data.toFixed(0) : data.toPrecision(3)
const text = data >= 1000 ? data.toFixed(0) : data.toPrecision(3)
return `${text} ${TRAFFIC_UNITS[exp]}`
}
+1 -2
View File
@@ -108,8 +108,7 @@ export const SystemInfoCard = () => {
goToSettings()
}
} catch (err) {
console.warn('update check failed:', err)
showNotice.warning(err)
showNotice.error(err)
}
})
@@ -31,13 +31,6 @@ export const StackModeSwitch = (props: Props) => {
>
Mixed
</Button>
<Button
variant={value?.toLowerCase() === 'mips' ? 'contained' : 'outlined'}
onClick={() => onChange?.('mips')}
sx={{ textTransform: 'capitalize' }}
>
Mips
</Button>
</ButtonGroup>
)
}
@@ -54,9 +54,8 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
} else {
updateRef.current?.open()
}
} catch (err) {
console.warn('update check failed:', err)
showNotice.warning(err)
} catch (err: any) {
showNotice.error(err)
}
}
+1 -5
View File
@@ -4,7 +4,7 @@ import { ReactNode, isValidElement } from 'react'
import type { FailedOperation } from '@/services/cmds'
import type { TranslationKey } from '@/types/generated/i18n-keys'
type NoticeType = 'success' | 'error' | 'info' | 'warning'
type NoticeType = 'success' | 'error' | 'info'
interface NoticeTranslationDescriptor {
key: string
@@ -47,7 +47,6 @@ type ShowNotice = ((
success: NoticeShortcut
error: NoticeShortcut
info: NoticeShortcut
warning: NoticeShortcut
}
type NoticeSubscriber = () => void
@@ -55,7 +54,6 @@ type NoticeSubscriber = () => void
const DEFAULT_DURATIONS: Readonly<Record<NoticeType, number>> = {
success: 3000,
info: 5000,
warning: 6000,
error: 8000,
}
@@ -511,8 +509,6 @@ export const showNotice: ShowNotice = Object.assign(baseShowNotice, {
baseShowNotice('error', message, ...extras),
info: (message: NoticeContent, ...extras: NoticeExtra[]) =>
baseShowNotice('info', message, ...extras),
warning: (message: NoticeContent, ...extras: NoticeExtra[]) =>
baseShowNotice('warning', message, ...extras),
})
export function hideNotice(id: number) {
+1 -1
View File
@@ -5,7 +5,7 @@ const parseTraffic = (num?: number) => {
const exp =
num < 1 ? 0 : Math.min(Math.floor(Math.log2(num) / 10), UNITS.length - 1)
const dat = num / Math.pow(1024, exp)
const ret = Math.round(dat) >= 1000 ? dat.toFixed(0) : dat.toPrecision(3)
const ret = dat >= 1000 ? dat.toFixed(0) : dat.toPrecision(3)
const unit = UNITS[exp]
return [ret, unit]