chore(runtime): sync the profile refactor

This commit is contained in:
Tunglies
2026-12-03 19:42:46 +08:00
54 changed files with 2276 additions and 1670 deletions
+14 -10
View File
@@ -27,7 +27,7 @@ perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
[build-dependencies]
tauri-build = { version = "2.7.6", features = [] }
tauri-build = { version = "2.8.0", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
@@ -64,7 +64,6 @@ tristr = { workspace = true }
socket2 = { workspace = true }
warp = { version = "0.4.4", features = ["server"] }
open = "5.4.5"
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6", "xdg-portal"] }
dirs = "7.0.0"
dunce = "1.0.5"
nanoid = "0.5"
@@ -78,10 +77,10 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", rev = "
network-interface = { version = "2.0.5", features = ["serde"] }
tauri-plugin-shell = "2.6.0"
tauri-plugin-opener = "2.7.3"
tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-dialog = { version = "2.9.0", default-features = false, features = ["gtk3"] }
tauri-plugin-fs = "2.8.0"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
tauri-plugin-window-state = "2.5.1"
zip = { workspace = true }
flate2 = "1.1.11"
reqwest_dav = "0.4.0"
@@ -92,8 +91,8 @@ getrandom = "0.4.3"
futures = { workspace = true }
gethostname = "1.1.0"
tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
tauri-plugin-http = "2.9.0"
tauri-plugin-http = "2.10.0"
backon = { version = "1.7.0", features = ["tokio-sleep"] }
tracing = { workspace = true }
tauri-plugin-devtools = { version = "2.2.3", optional = true }
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
@@ -101,7 +100,7 @@ async-trait = "0.1.92"
clash_verge_service_ipc = { workspace = true, features = ["client"] }
arc-swap = "1.9.5"
tokio-rustls = "0.26.6"
rustls = { version = "0.23.46", features = ["ring"] }
rustls = { version = "0.23.47", features = ["ring"] }
webpki-roots = "1.0.12"
dark-light = "3.0.0"
bytes = "1.12.2"
@@ -114,11 +113,16 @@ specta-typescript = "=0.0.13"
libc = "0.2.191"
[target.'cfg(target_os = "linux")'.dependencies]
gtk = "0.19"
tauri = { workspace = true, features = ["linux-ksni"] }
# Upstream has no session-end signal support on Linux; see crates/clash-verge-signal.
clash-verge-signal = { workspace = true }
[target.'cfg(not(target_os = "linux"))'.dependencies]
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6"] }
[target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-wdio-webdriver = { version = "=1.5.1", optional = true }
tauri-plugin-wdio-webdriver = { version = "=2.0.0-next.0", optional = true }
objc2 = "0.6.5"
objc2-foundation = { version = "0.3.2", features = [
"NSString",
@@ -147,7 +151,7 @@ quick-xml = "0.42.0"
runas = "=1.2.0"
winreg = "0.56.0"
windows-service = "0.8.1"
windows = { version = "0.62.2", features = [
windows = { version = "0.101.0", features = [
"Win32_System_Com",
"Win32_System_Ole",
"Win32_System_TaskScheduler",
+11 -8
View File
@@ -81,6 +81,9 @@ Var VC_RUNTIME_NEEDED
Var ServiceExisted
Var ServiceStartType
Var ServiceWasRunning
Var ExistingVersionKind
Var Webview2DownloadResult
Var Webview2InstallExitCode
Name "${PRODUCTNAME}"
BrandingText "${COPYRIGHT}"
@@ -214,13 +217,13 @@ Function PageReinstall
; Compare this installar version with the existing installation
; and modify the messages presented to the user accordingly
compare_version:
StrCpy $R4 "$(older)"
StrCpy $ExistingVersionKind "$(older)"
${If} $WixMode = 1
ReadRegStr $R0 HKLM "$R6" "DisplayVersion"
${Else}
ReadRegStr $R0 SHCTX "${UNINSTKEY}" "DisplayVersion"
${EndIf}
${IfThen} $R0 == "" ${|} StrCpy $R4 "$(unknown)" ${|}
${IfThen} $R0 == "" ${|} StrCpy $ExistingVersionKind "$(unknown)" ${|}
nsis_tauri_utils::SemverCompare "${VERSION}" $R0
Pop $R0
@@ -895,8 +898,8 @@ Section WebView2
Delete "$TEMP\MicrosoftEdgeWebview2Setup.exe"
DetailPrint "$(webview2Downloading)"
NSISdl::download "https://go.microsoft.com/fwlink/p/?LinkId=2124703" "$TEMP\MicrosoftEdgeWebview2Setup.exe"
Pop $0
${If} $0 == "success"
Pop $Webview2DownloadResult
${If} $Webview2DownloadResult == "success"
DetailPrint "$(webview2DownloadSuccess)"
${Else}
DetailPrint "$(webview2DownloadError)"
@@ -927,8 +930,8 @@ Section WebView2
install_webview2:
DetailPrint "$(installingWebview2)"
; $6 holds the path to the webview2 installer
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $1
${If} $1 = 0
ExecWait "$6 ${WEBVIEW2INSTALLERARGS} /install" $Webview2InstallExitCode
${If} $Webview2InstallExitCode = 0
DetailPrint "$(webview2InstallSuccess)"
${Else}
DetailPrint "$(webview2InstallError)"
@@ -953,8 +956,8 @@ Section WebView2
${If} $R1 != ""
; Chromium updater docs: https://source.chromium.org/chromium/chromium/src/+/main:docs/updater/user_manual.md
; Modified from "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Microsoft EdgeWebView\ModifyPath"
ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $1
${If} $1 = 0
ExecWait `"$R1" /install appguid=${WEBVIEW2APPGUID}&needsadmin=true` $Webview2InstallExitCode
${If} $Webview2InstallExitCode = 0
DetailPrint "$(webview2InstallSuccess)"
${Else}
MessageBox MB_ICONEXCLAMATION|MB_ABORTRETRYIGNORE "$(webview2InstallError)" IDIGNORE ignore IDRETRY update_webview
+3 -3
View File
@@ -4,7 +4,7 @@ use crate::feat;
use crate::utils::dirs;
use crate::{
cmd::StringifyErr as _,
config::{ClashInfo, Config, mihomo_yaml, profiles::profiles_save_file_safe},
config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles},
constants,
core::{
CoreManager, handle,
@@ -59,7 +59,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
match CoreManager::global().change_core(&clash_core).await {
Ok(_) => {
logging_error!(Type::Core, profiles_save_file_safe().await);
logging_error!(Type::Core, save_committed_profiles().await);
match CoreManager::global().restart_core().await {
Ok(_) => {
@@ -88,7 +88,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult<Opt
#[tauri::command]
#[specta::specta]
pub async fn restart_core() -> CmdResult {
logging_error!(Type::Core, profiles_save_file_safe().await);
logging_error!(Type::Core, save_committed_profiles().await);
let result = CoreManager::global()
.restart_core()
.await
+11 -12
View File
@@ -7,9 +7,8 @@ use crate::{
config::{
Config, IProfiles, PrfItem, PrfOption, build_remote_profile,
profiles::{
PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe,
profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe,
profiles_save_file_safe, save_profiles,
PROFILE_WRITE_LOCK, append_profile, cleanup_profile_files, patch_profile_item, reorder_profiles,
save_committed_profiles, save_profiles,
},
read_profile_item_file,
},
@@ -46,7 +45,7 @@ pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
#[tauri::command]
#[specta::specta]
pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
match feat::enhance_profiles().await {
match CoreManager::global().update_config_forced().await {
Ok(outcome) if outcome.is_valid() => {
handle::Handle::refresh_clash();
Ok(outcome)
@@ -80,12 +79,12 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
}
};
if let Err(e) = profiles_append_item_safe(item).await {
if let Err(e) = append_profile(item).await {
logging!(error, Type::Cmd, "[导入订阅] 保存配置失败: {e:#}");
return Err(coded_error("PROFILE_IMPORT_FAILED", e));
}
if let Err(e) = profiles_save_file_safe().await {
if let Err(e) = save_committed_profiles().await {
logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {e:#}");
return Err(coded_error("PROFILE_IMPORT_FAILED", e));
}
@@ -104,7 +103,7 @@ pub async fn import_profile(url: std::string::String, option: Option<PrfOption>)
pub async fn reorder_profile(active_id: std::string::String, over_id: std::string::String) -> CmdResult {
let active_id: String = active_id.into();
let over_id: String = over_id.into();
match profiles_reorder_safe(&active_id, &over_id).await {
match reorder_profiles(&active_id, &over_id).await {
Ok(_) => {
logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id);
Ok(())
@@ -127,9 +126,9 @@ pub async fn reorder_profile(active_id: std::string::String, over_id: std::strin
pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::String>) -> CmdResult {
let item: PrfItem = item.into();
let file_data = file_data.map(String::from);
match profiles_append_item_with_filedata_safe(&item, file_data).await {
match profiles::create_profile(&item, file_data).await {
Ok(_) => {
profiles_save_file_safe()
save_committed_profiles()
.await
.with_error_code("PROFILE_CREATE_FAILED")?;
logging_error!(Type::Timer, Timer::global().refresh().await);
@@ -219,7 +218,7 @@ async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
.edit_draft(|d| d.patch_current(Some(prev_profile)));
Config::profiles().await.apply();
crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = profiles_save_file_safe().await {
if let Err(e) = save_committed_profiles().await {
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
}
});
@@ -247,7 +246,7 @@ async fn handle_success(current_value: Option<&String>) -> CmdResult<ValidationO
// Runtime refresh and tray rebuilding happen after saved node selections are restored.
profiles::activate_selected_nodes();
if let Err(e) = profiles_save_file_safe().await {
if let Err(e) = save_committed_profiles().await {
logging!(warn, Type::Cmd, "异步保存配置文件失败: {e:#}");
}
@@ -433,7 +432,7 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
// Prevent an in-flight restore from overwriting a newer UI or chain selection.
let records_a_selection = profile.selected.is_some();
profiles_patch_item_safe(&index, &profile)
patch_profile_item(&index, &profile)
.await
.with_error_code("PROFILE_UPDATE_FAILED")?;
+3 -3
View File
@@ -3,7 +3,7 @@ use crate::core::notify::NoticeStatus;
use crate::{
config::{
prfitem::{build_merge_profile, build_script_profile},
profiles::{load_profiles, profiles_append_item_to_safe, save_profiles},
profiles::{append_to_profile_index, load_profiles, save_profiles},
runtime::IRuntime,
},
constants::{files, timing},
@@ -142,11 +142,11 @@ impl Config {
if profiles.latest_arc().get_item("Merge").is_err() {
let merge_item = &mut build_merge_profile(Some("Merge".into()));
profiles_append_item_to_safe(&profiles, merge_item).await?;
append_to_profile_index(&profiles, merge_item).await?;
}
if profiles.latest_arc().get_item("Script").is_err() {
let script_item = &mut build_script_profile(Some("Script".into()));
profiles_append_item_to_safe(&profiles, script_item).await?;
append_to_profile_index(&profiles, script_item).await?;
}
Ok(())
}
+1 -1
View File
@@ -14,7 +14,7 @@ mod verge;
pub(crate) use self::config::Config;
pub(crate) use self::prfitem::{
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file,
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, subscription_proxy,
};
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
+44 -81
View File
@@ -45,35 +45,38 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
}
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
profiles::profiles_append_item_safe(item).await?;
profiles::append_profile(item).await?;
item.uid
.clone()
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
}
async fn ensure_companion_items(
merge: &mut Option<String>,
script: &mut Option<String>,
rules: &mut Option<String>,
proxies: &mut Option<String>,
groups: &mut Option<String>,
) -> Result<()> {
if merge.is_none() {
*merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption> {
let mut options = PrfOption {
update_interval: source.and_then(|options| options.update_interval),
merge: source.and_then(|options| options.merge.clone()),
script: source.and_then(|options| options.script.clone()),
rules: source.and_then(|options| options.rules.clone()),
proxies: source.and_then(|options| options.proxies.clone()),
groups: source.and_then(|options| options.groups.clone()),
..PrfOption::default()
};
if options.merge.is_none() {
options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
}
if script.is_none() {
*script = Some(append_companion_item(&mut build_script_profile(None)).await?);
if options.script.is_none() {
options.script = Some(append_companion_item(&mut build_script_profile(None)).await?);
}
if rules.is_none() {
*rules = Some(append_companion_item(&mut from_rules()).await?);
if options.rules.is_none() {
options.rules = Some(append_companion_item(&mut from_rules()).await?);
}
if proxies.is_none() {
*proxies = Some(append_companion_item(&mut from_proxies()).await?);
if options.proxies.is_none() {
options.proxies = Some(append_companion_item(&mut from_proxies()).await?);
}
if groups.is_none() {
*groups = Some(append_companion_item(&mut from_groups()).await?);
if options.groups.is_none() {
options.groups = Some(append_companion_item(&mut from_groups()).await?);
}
Ok(())
Ok(options)
}
async fn from_local(
@@ -84,15 +87,7 @@ async fn from_local(
) -> Result<PrfItem> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let opt_ref = option.as_ref();
let update_interval = opt_ref.and_then(|o| o.update_interval);
let mut merge = opt_ref.and_then(|o| o.merge.clone());
let mut script = opt_ref.and_then(|o| o.script.clone());
let mut rules = opt_ref.and_then(|o| o.rules.clone());
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
let mut groups = opt_ref.and_then(|o| o.groups.clone());
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
let options = prepare_profile_options(option).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
@@ -102,15 +97,7 @@ async fn from_local(
url: None,
selected: None,
extra: None,
option: Some(PrfOption {
update_interval,
merge,
script,
rules,
proxies,
groups,
..PrfOption::default()
}),
option: Some(options),
home: None,
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
@@ -140,7 +127,7 @@ pub(crate) async fn build_remote_profile(
desc: Option<&String>,
option: Option<&PrfOption>,
) -> Result<PrfItem> {
let mut downloaded = download_subscription(url, option).await?;
let mut downloaded = download_subscription(url, option, subscription_proxy(option)).await?;
let uid: String = help::get_uid("R").into();
let file = format!("{uid}.yaml").into();
let name = name
@@ -172,31 +159,28 @@ pub(crate) async fn build_remote_profile(
})
}
pub(crate) async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result<DownloadedSubscription> {
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
let user_agent = option.and_then(|o| o.user_agent.clone());
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
let proxy_type = if self_proxy {
pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType {
if options.and_then(|options| options.self_proxy) == Some(true) {
ProxyType::Localhost
} else if with_proxy {
} else if options.and_then(|options| options.with_proxy) == Some(true) {
ProxyType::System
} else {
ProxyType::None
};
}
}
pub(crate) async fn download_subscription(
url: &str,
option: Option<&PrfOption>,
proxy: ProxyType,
) -> Result<DownloadedSubscription> {
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
let user_agent = option.and_then(|o| o.user_agent.clone());
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
let url = fix_dirty_url(url)?;
let resp = match NetworkManager::new()
.get(
url.as_str(),
proxy_type,
Some(timeout),
user_agent,
accept_invalid_certs,
)
.get(url.as_str(), proxy, Some(timeout), user_agent, accept_invalid_certs)
.await
{
Ok(r) => r,
@@ -232,31 +216,14 @@ pub(crate) async fn prepare_remote_refresh(
downloaded: DownloadedSubscription,
option: Option<&PrfOption>,
) -> Result<RemoteProfileRefresh> {
let mut resolved = PrfOption {
update_interval: option
.and_then(|o| o.update_interval)
.or(downloaded.update_interval_minutes),
merge: option.and_then(|o| o.merge.clone()),
script: option.and_then(|o| o.script.clone()),
rules: option.and_then(|o| o.rules.clone()),
proxies: option.and_then(|o| o.proxies.clone()),
groups: option.and_then(|o| o.groups.clone()),
allow_auto_update: Some(allow_auto_update_enabled(option)),
..PrfOption::default()
};
ensure_companion_items(
&mut resolved.merge,
&mut resolved.script,
&mut resolved.rules,
&mut resolved.proxies,
&mut resolved.groups,
)
.await?;
let mut options = prepare_profile_options(option).await?;
options.update_interval = options.update_interval.or(downloaded.update_interval_minutes);
options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true));
Ok(RemoteProfileRefresh {
extra: downloaded.extra,
home: downloaded.home,
updated: chrono::Local::now().timestamp() as usize,
option: resolved,
option: options,
body: downloaded.body,
})
}
@@ -331,10 +298,6 @@ pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result<String>
Ok(content.into())
}
fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
option.and_then(|o| o.allow_auto_update).unwrap_or(true)
}
/// Fix URLs where query parameters are incorrectly appended to the path segment
///
/// Incorrect Example: https://example.com/path&param1=value1
@@ -416,7 +379,7 @@ mod tests {
update_interval: None,
..option
};
let downloaded = download_subscription(&url, Some(&refresh_option)).await?;
let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?;
let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?;
server.await??;
assert_eq!(item.itype.as_deref(), Some("remote"));
+23 -38
View File
@@ -193,32 +193,6 @@ fn validate_profile_file(file: &str) -> Result<()> {
Ok(())
}
/// Updates fields returned by a remote profile refresh.
async fn apply_remote_refresh(profiles: &mut IProfiles, uid: &str, refresh: RemoteProfileRefresh) -> Result<()> {
let _ = profiles.get_item(uid)?;
if let Some(each) = profiles
.items
.iter_mut()
.flatten()
.find(|item| item.uid.as_deref() == Some(uid))
{
each.extra = refresh.extra;
each.updated = Some(refresh.updated);
each.home = refresh.home;
each.option = PrfOption::merge(each.option.as_ref(), Some(&refresh.option));
let file = each
.file
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, refresh.body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
save_profiles(profiles).await
}
/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone.
/// Returns how many changed so the caller can skip a pointless write.
pub(crate) fn raise_short_update_intervals(profiles: &mut IProfiles, min_minutes: u64) -> usize {
@@ -259,9 +233,9 @@ pub(crate) async fn current_mapping(profiles: &IProfiles) -> Result<Mapping> {
// These helpers serialize asynchronous operations against committed profile data.
use crate::config::Config;
pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option<String>) -> Result<()> {
pub(crate) async fn create_profile(item: &PrfItem, file_data: Option<String>) -> Result<()> {
let item = &mut build_profile(item, file_data).await?;
profiles_append_item_safe(item).await
append_profile(item).await
}
/// Applies `edit` to the committed profiles; commits only when the edit succeeds.
@@ -279,12 +253,12 @@ where
.await
}
pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> {
pub(crate) async fn append_profile(item: &mut PrfItem) -> Result<()> {
let profiles = Config::profiles().await;
profiles_append_item_to_safe(&profiles, item).await
append_to_profile_index(&profiles, item).await
}
pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
pub(super) async fn append_to_profile_index(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
profiles
.with_data_modify(|mut profiles| async move {
append_item(&mut profiles, item).await?;
@@ -293,7 +267,7 @@ pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, it
.await
}
pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> {
pub(crate) async fn patch_profile_item(index: &str, item: &PrfItem) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
patch_item(&mut profiles, index, item).await?;
Ok(profiles)
@@ -301,7 +275,7 @@ pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Res
.await
}
pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> {
pub(crate) async fn reorder_profiles(active_id: &str, over_id: &str) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
if profiles.reorder(active_id, over_id) {
save_profiles(&profiles).await?;
@@ -311,18 +285,29 @@ pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Res
.await
}
pub(crate) async fn profiles_save_file_safe() -> Result<()> {
pub(crate) async fn save_committed_profiles() -> Result<()> {
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
}
pub(crate) async fn apply_remote_refresh_safe(index: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> {
pub(crate) async fn save_remote_refresh(uid: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
let current = profiles.get_item(index)?;
let profile = profiles.get_item_mut(uid)?;
anyhow::ensure!(
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
profile.itype.as_deref() == Some("remote") && profile.url.as_deref() == Some(url),
"profile source changed during refresh"
);
apply_remote_refresh(&mut profiles, index, refresh).await?;
profile.extra = refresh.extra;
profile.updated = Some(refresh.updated);
profile.home = refresh.home;
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
let file = profile
.file
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, refresh.body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
save_profiles(&profiles).await?;
Ok(profiles)
})
.await
+6 -2
View File
@@ -3,7 +3,11 @@ use crate::process::AsyncHandler;
use crate::singleton;
use crate::utils::notification::{NotificationEvent, notify_event};
use crate::utils::window_manager::WindowManager;
use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
use crate::{
config::Config,
core::{CoreManager, handle, lightweight::entry_lightweight_mode},
feat,
};
use anyhow::{Result, bail};
use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging};
@@ -165,7 +169,7 @@ impl Hotkey {
});
}
HotkeyFunction::ReactivateProfiles => {
AsyncHandler::spawn(async move || match feat::enhance_profiles().await {
AsyncHandler::spawn(async move || match CoreManager::global().update_config_forced().await {
Ok(outcome) if outcome.is_valid() => {
handle::Handle::refresh_clash();
notify_event(NotificationEvent::ProfilesReactivated).await;
+32 -31
View File
@@ -296,19 +296,16 @@ impl Tray {
let (_is_custom_icon, icon_bytes) = TrayState::get_tray_icon(verge).await;
let template = {
#[cfg(target_os = "macos")]
{
verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome")
}
#[cfg(not(target_os = "macos"))]
{
false
}
};
let icon = Some(tauri::image::Image::from_bytes(&icon_bytes)?);
logging_error!(Type::Tray, tray.set_icon_with_as_template(icon, template));
#[cfg(target_os = "macos")]
let result = if verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome") {
tray.set_icon_templated(icon)
} else {
tray.set_icon(icon)
};
#[cfg(not(target_os = "macos"))]
let result = tray.set_icon(icon);
logging_error!(Type::Tray, result);
Ok(())
}
@@ -404,26 +401,21 @@ impl Tray {
let icon_bytes = TrayState::get_tray_icon(&verge).await.1;
let icon = tauri::image::Image::from_bytes(&icon_bytes)?;
#[cfg(target_os = "linux")]
let builder = TrayIconBuilder::with_id(TRAY_ID).icon(icon).icon_as_template(false);
let builder = TrayIconBuilder::with_id(TRAY_ID);
#[cfg(target_os = "macos")]
let builder = if verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome") {
builder.icon_templated(icon)
} else {
builder.icon(icon)
};
#[cfg(not(target_os = "macos"))]
let builder = builder.icon(icon);
#[cfg(any(target_os = "macos", target_os = "windows"))]
let show_menu_on_left_click = verge.tray_event.as_ref().is_some_and(|v| v == "tray_menu");
#[cfg(not(target_os = "linux"))]
let mut builder = TrayIconBuilder::with_id(TRAY_ID).icon(icon).icon_as_template(false);
#[cfg(target_os = "macos")]
{
let is_monochrome = verge.tray_icon.as_ref().is_none_or(|v| v == "monochrome");
builder = builder.icon_as_template(is_monochrome);
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
{
if !show_menu_on_left_click {
builder = builder.show_menu_on_left_click(false);
}
}
let builder = builder.show_menu_on_left_click(show_menu_on_left_click);
let tray = builder.build(app_handle)?;
tray.on_tray_icon_event(on_tray_icon_event);
@@ -870,9 +862,14 @@ fn on_tray_icon_event(_tray_icon: &TrayIcon, tray_event: TrayIconEvent) {
return;
}
const CLICK_STATE: MouseButtonState = if cfg!(target_os = "linux") {
MouseButtonState::Up
} else {
MouseButtonState::Down
};
if let TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Down,
button_state: CLICK_STATE,
..
} = tray_event
{
@@ -882,9 +879,13 @@ fn on_tray_icon_event(_tray_icon: &TrayIcon, tray_event: TrayIconEvent) {
}
AsyncHandler::spawn(|| async move {
let verge = Config::verge().await.data_arc();
let verge_tray_event = verge.tray_event.clone().unwrap_or_else(|| "main_window".into());
let verge_tray_action = TrayAction::from(verge_tray_event.as_str());
let configured_event = if cfg!(target_os = "linux") {
None
} else {
Config::verge().await.data_arc().tray_event.clone()
};
let verge_tray_event = configured_event.as_deref().unwrap_or("main_window");
let verge_tray_action = TrayAction::from(verge_tray_event);
logging!(debug, Type::Tray, "tray event: {verge_tray_action:?}");
match verge_tray_action {
TrayAction::SystemProxy => {
+5 -3
View File
@@ -7,6 +7,7 @@ use std::{
sync::LazyLock,
sync::atomic::{AtomicBool, Ordering},
};
use tauri::Manager as _;
use tauri_plugin_shell::ShellExt as _;
use tokio::fs;
use tristr::alias::String;
@@ -27,9 +28,10 @@ async fn validation_fingerprint(yaml: &str) -> u64 {
let mut hasher = DefaultHasher::new();
yaml.hash(&mut hasher);
core.as_str().hash(&mut hasher);
let binary = std::env::current_exe()
.into_iter()
.map(|exe| exe.with_file_name(format!("{}{}", core.as_str(), std::env::consts::EXE_SUFFIX)));
let binary = handle::Handle::app_handle()
.path()
.resolve_external_bin(core.as_str())
.into_iter();
// The test run reads geo databases from the app dir; a geo update must revalidate.
let geo = dirs::app_home_dir().into_iter().flat_map(|dir| {
clash_verge_runtime_bundle::GEO_ASSETS
+1 -6
View File
@@ -2,7 +2,7 @@ use crate::core::notify::{Refresh, announce};
use crate::{
cmd,
config::Config,
core::{CoreManager, handle, tray, validate::ValidationOutcome},
core::{handle, tray},
process::AsyncHandler,
};
use anyhow::Result;
@@ -199,11 +199,6 @@ async fn finish_proxy_switch(stale_proxies: Vec<std::string::String>) {
}
}
/// 增强配置
pub async fn enhance_profiles() -> Result<ValidationOutcome> {
CoreManager::global().update_config_forced().await
}
#[cfg(test)]
mod tests {
use super::*;
+56 -58
View File
@@ -1,11 +1,17 @@
use crate::{
config::{Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::apply_remote_refresh_safe},
config::{
Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh,
subscription_proxy,
},
core::{
CoreManager, handle,
notify::{NoticeStatus, Refresh, announce},
validate::ValidationOutcome,
},
utils::help::{mask_err, mask_url},
utils::{
help::{mask_err, mask_url},
network::ProxyType,
},
};
use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
@@ -48,11 +54,13 @@ async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Op
async fn perform_profile_update(
uid: &str,
url: &str,
opt: Option<&PrfOption>,
option: Option<&PrfOption>,
profile_options: Option<&PrfOption>,
overrides: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
let merged_opt = PrfOption::merge(opt, option);
let options = PrfOption::merge(profile_options, overrides);
let options = options.as_ref();
let configured_proxy = subscription_proxy(options);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
@@ -71,54 +79,44 @@ async fn perform_profile_update(
let result = clash_verge_task::retry::try_strategies(
Strategy::Configured,
[Strategy::Clash, Strategy::System],
|strategy| {
let mut options = merged_opt.clone();
async move {
let (name, success, failure) = match strategy {
Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = download_subscription(url, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
|strategy| async move {
let (name, proxy, elapsed_field, success, failure) = match strategy {
Strategy::Configured => (
"configured",
configured_proxy,
"configured_elapsed",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
ProxyType::Localhost,
"clash_elapsed",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
ProxyType::System,
"system_elapsed",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = download_subscription(url, options, proxy).await;
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
},
)
.await;
@@ -132,8 +130,8 @@ async fn perform_profile_update(
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
"profile source changed during refresh"
);
let refresh = prepare_remote_refresh(downloaded, merged_opt.as_ref()).await?;
apply_remote_refresh_safe(uid, url, refresh).await?;
let refresh = prepare_remote_refresh(downloaded, options).await?;
save_remote_refresh(uid, url, refresh).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
@@ -154,11 +152,11 @@ async fn perform_profile_update(
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> {
let url_opt = should_update_profile(uid, is_manual_trigger).await?;
let subscription = should_update_profile(uid, is_manual_trigger).await?;
let profile_persisted = match url_opt {
Some((url, opt)) => {
perform_profile_update(uid, &url, opt.as_ref(), option, is_manual_trigger).await?;
let profile_persisted = match subscription {
Some((url, profile_options)) => {
perform_profile_update(uid, &url, profile_options.as_ref(), option, is_manual_trigger).await?;
true
}
None => false,
+2 -2
View File
@@ -51,14 +51,14 @@ async fn import_subscription(url: &str, name: Option<&String>) {
};
let uid = item.uid.clone().unwrap_or_default();
if let Err(e) = profiles::profiles_append_item_safe(&mut item).await {
if let Err(e) = profiles::append_profile(&mut item).await {
logging!(error, Type::Config, "failed to import subscription url: {:?}", e);
Config::profiles().await.discard();
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return;
}
if let Err(e) = profiles::profiles_save_file_safe().await {
if let Err(e) = profiles::save_committed_profiles().await {
logging!(error, Type::Config, "failed to save imported subscription: {e:#}");
handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return;
+23
View File
@@ -30,6 +30,29 @@ pub(crate) fn report_error(error: &anyhow::Error) {
}
};
show_error_dialog(&message);
}
#[cfg(target_os = "linux")]
fn show_error_dialog(message: &str) {
use gtk::prelude::DialogExt as _;
// rfd's GTK3 MessageDialog waits indefinitely if its GTK worker fails to initialize.
if gtk::init().is_err() {
return;
}
gtk::MessageDialog::builder()
.message_type(gtk::MessageType::Error)
.title("Clash Verge startup failed")
.text(message)
.buttons(gtk::ButtonsType::Ok)
.build()
.run();
}
#[cfg(not(target_os = "linux"))]
fn show_error_dialog(message: &str) {
let _ = rfd::MessageDialog::new()
.set_level(rfd::MessageLevel::Error)
.set_title("Clash Verge startup failed")