chore: trim excessive comments

This commit is contained in:
wonfen
2026-08-19 07:27:43 +08:00
parent 42b91b6294
commit 807f9a206d
103 changed files with 293 additions and 2517 deletions
+2 -26
View File
@@ -6,27 +6,20 @@ use tauri_plugin_mihomo::models::WsConnectionId;
use tokio::sync::mpsc;
use tokio::time::Instant;
/// Mihomo WebSocket 流的有界队列容量,避免异常场景下内存无限增长。
/// Bounds memory use if the consumer falls behind the WebSocket.
const MIHOMO_WS_STREAM_BUFFER_SIZE: usize = 8;
/// 断开 Mihomo WebSocket 连接时使用的关闭码(RFC 6455 标准正常关闭)。
const MIHOMO_WS_STREAM_CLOSE_CODE: u64 = 1000;
/// `/traffic` 即时速率事件(字节/秒)。
#[derive(Debug, Clone, Copy)]
pub struct TrafficSpeedEvent {
pub up: u64,
pub down: u64,
}
/// Mihomo WebSocket 流消费状态。
pub enum StreamConsumeState<T> {
/// 收到一条业务事件。
Event(T),
/// 连接关闭或消息流结束。
Closed,
/// 在超时时间内未收到有效事件,需要重连。
Stale,
/// 上层请求退出消费循环。
ExitRequested,
}
@@ -34,13 +27,9 @@ enum InternalWsEvent<T> {
Data(T),
}
/// Mihomo WebSocket 订阅句柄(通用事件流)。
pub struct MihomoWsEventStream<T> {
/// 当前订阅连接 ID,用于主动断开。
pub connection_id: WsConnectionId,
/// 当前订阅消息接收器。
receiver: mpsc::Receiver<InternalWsEvent<T>>,
/// 最近一次收到有效事件的时间戳。
last_valid_event_at: Instant,
}
@@ -61,19 +50,15 @@ fn parse_traffic_event(data: &[u8]) -> Option<InternalWsEvent<TrafficSpeedEvent>
fn try_send_internal_event<T>(message_tx: &mpsc::Sender<InternalWsEvent<T>>, event: InternalWsEvent<T>) {
if let Err(err) = message_tx.try_send(event) {
match err {
// 队列满时丢弃本次事件,下一次事件会继续覆盖更新。
// A later real-time sample supersedes one dropped from a full queue.
tokio::sync::mpsc::error::TrySendError::Full(_) => {}
// 任务已结束时通道可能关闭,忽略即可。
tokio::sync::mpsc::error::TrySendError::Closed(_) => {}
}
}
}
/// 建立 `/traffic` WebSocket 订阅(通用流)。
pub async fn connect_traffic_stream() -> Result<MihomoWsEventStream<TrafficSpeedEvent>> {
// 使用有界 mpsc 通道承接回调事件,限制消息积压上限。
let (message_tx, message_rx) = mpsc::channel::<InternalWsEvent<TrafficSpeedEvent>>(MIHOMO_WS_STREAM_BUFFER_SIZE);
// 建立 Mihomo `/traffic` WebSocket 订阅。
let connection_id = handle::Handle::mihomo()
.ws_traffic({
let message_tx = message_tx.clone();
@@ -93,11 +78,6 @@ pub async fn connect_traffic_stream() -> Result<MihomoWsEventStream<TrafficSpeed
}
impl<T> MihomoWsEventStream<T> {
/// 等待下一次可用事件或结束状态。
///
/// # Arguments
/// * `stale_timeout` - 无有效事件超时时间
/// * `should_exit` - 上层退出判定函数
pub async fn next_event<F>(&mut self, stale_timeout: Duration, should_exit: F) -> StreamConsumeState<T>
where
F: Fn() -> bool,
@@ -132,10 +112,6 @@ impl<T> MihomoWsEventStream<T> {
}
}
/// 断开指定 Mihomo WebSocket 连接。
///
/// # Arguments
/// * `connection_id` - 目标连接 ID
pub async fn disconnect_connection(connection_id: WsConnectionId) {
if let Err(err) = handle::Handle::mihomo()
.disconnect(connection_id, Some(MIHOMO_WS_STREAM_CLOSE_CODE))
+1 -16
View File
@@ -24,7 +24,6 @@ pub static PROFILE_YAML: &str = "profiles.yaml";
/// Marks that the one-shot raise of too-short auto-update intervals has already run.
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
/// init portable flag
pub fn init_portable_flag() -> Result<()> {
use tauri::utils::platform::current_exe;
@@ -40,7 +39,6 @@ pub fn init_portable_flag() -> Result<()> {
Ok(())
}
/// get the verge app home dir
pub fn app_home_dir() -> Result<PathBuf> {
use tauri::utils::platform::current_exe;
@@ -54,7 +52,7 @@ pub fn app_home_dir() -> Result<PathBuf> {
return Ok(PathBuf::from(app_dir).join(".config").join(APP_ID));
}
// 避免在Handle未初始化时崩溃
// Directory helpers can run before the Tauri handle is initialized.
let app_handle = handle::Handle::app_handle();
match app_handle.path().data_dir() {
@@ -88,9 +86,7 @@ pub fn preinit_app_data_dir() -> Result<PathBuf> {
Ok(root.join(APP_ID))
}
/// get the resources dir
pub fn app_resources_dir() -> Result<PathBuf> {
// 避免在Handle未初始化时崩溃
let app_handle = handle::Handle::app_handle();
match app_handle.path().resource_dir() {
@@ -102,12 +98,10 @@ pub fn app_resources_dir() -> Result<PathBuf> {
}
}
/// profiles dir
pub fn app_profiles_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join("profiles"))
}
/// icons dir
pub fn app_icons_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join("icons"))
}
@@ -131,29 +125,24 @@ pub fn find_target_icons(target: &str) -> Result<Option<String>> {
icon_path.map(|path| path_to_str(&path).map(|s| s.into())).transpose()
}
/// logs dir
pub fn app_logs_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join("logs"))
}
/// service logs dir
#[cfg(target_os = "macos")]
pub fn service_logs_root_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join("service-logs"))
}
/// service logs dir
#[cfg(not(target_os = "macos"))]
pub fn service_logs_root_dir() -> Result<PathBuf> {
app_logs_dir()
}
// latest verge log
pub fn app_latest_log() -> Result<PathBuf> {
Ok(app_logs_dir()?.join("latest.log"))
}
/// local backups dir
pub fn local_backup_dir() -> Result<PathBuf> {
let dir = app_home_dir()?.join(BACKUP_DIR);
fs::create_dir_all(&dir)?;
@@ -222,18 +211,14 @@ pub fn get_encryption_key() -> Result<Vec<u8>> {
let key_path = app_dir.join(".encryption_key");
if key_path.exists() {
// Read existing key
fs::read(&key_path).map_err(|e| anyhow::anyhow!("Failed to read encryption key: {}", e))
} else {
// Generate and save new key
let mut key = vec![0u8; 32];
getrandom::fill(&mut key)?;
// Ensure directory exists
if let Some(parent) = key_path.parent() {
fs::create_dir_all(parent).map_err(|e| anyhow::anyhow!("Failed to create key directory: {}", e))?;
}
// Save key
fs::write(&key_path, &key).map_err(|e| anyhow::anyhow!("Failed to save encryption key: {}", e))?;
Ok(key)
}
+3 -27
View File
@@ -9,7 +9,6 @@ use std::{
str::FromStr,
};
/// read data from yaml as struct T
pub async fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
if !tokio::fs::try_exists(path).await.unwrap_or(false) {
bail!("file not found \"{}\"", path.display());
@@ -20,7 +19,6 @@ pub async fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
Ok(with_encryption(|| async { serde_yaml_ng::from_str::<T>(&yaml_str) }).await?)
}
/// read mapping from yaml
pub async fn read_mapping(path: &PathBuf) -> Result<Mapping> {
if !tokio::fs::try_exists(path).await.unwrap_or(false) {
bail!("file not found \"{}\"", path.display());
@@ -30,7 +28,6 @@ pub async fn read_mapping(path: &PathBuf) -> Result<Mapping> {
.await
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
// YAML语法检查
match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&yaml_str) {
Ok(mut val) => {
val.apply_merge()
@@ -52,13 +49,10 @@ pub async fn read_mapping(path: &PathBuf) -> Result<Mapping> {
}
}
/// read mapping from yaml fix #165
pub async fn read_seq_map(path: &PathBuf) -> Result<SeqMap> {
read_yaml(path).await
}
/// save the data to the file
/// can set `prefix` string to add some comments
pub async fn save_yaml<T: Serialize + Sync>(path: &PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
@@ -90,14 +84,11 @@ const ALPHABET: [char; 62] = [
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
];
/// generate the uid
pub fn get_uid(prefix: &str) -> String {
let id = nanoid!(11, &ALPHABET);
format!("{prefix}{id}")
}
/// parse the string
/// xxx=123123; => 123123
pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
target.split(';').map(str::trim).find_map(|s| {
let mut parts = s.splitn(2, '=');
@@ -108,18 +99,13 @@ pub fn parse_str<T: FromStr>(target: &str, key: &str) -> Option<T> {
})
}
/// Mask sensitive parts of a subscription URL for safe logging.
/// Examples:
/// - `https://example.com/api/v1/clash?token=abc123` → `https://example.com/api/v1/clash?token=***`
/// - `https://example.com/abc123def456ghi789/clash` → `https://example.com/***/clash`
/// Masks query values and token-like path segments for logging.
pub fn mask_url(url: &str) -> String {
// Split off query string
let (path_part, query_part) = match url.find('?') {
Some(pos) => (&url[..pos], Some(&url[pos + 1..])),
None => (url, None),
};
// Extract scheme+host prefix (everything up to the first '/' after "://")
let host_end = path_part
.find("://")
.and_then(|scheme_end| {
@@ -134,7 +120,6 @@ pub fn mask_url(url: &str) -> String {
let mut result = scheme_and_host.to_owned();
// Mask path segments that look like tokens (longer than 16 chars)
if !path.is_empty() {
let masked: Vec<&str> = path
.split('/')
@@ -143,7 +128,6 @@ pub fn mask_url(url: &str) -> String {
result.push_str(&masked.join("/"));
}
// Keep query param keys, mask values
if let Some(query) = query_part {
result.push('?');
let masked_query: Vec<String> = query
@@ -159,11 +143,7 @@ pub fn mask_url(url: &str) -> String {
result
}
/// Mask all URLs embedded in an error/log string for safe logging.
///
/// Scans the string for `http://` or `https://` and replaces each URL
/// (terminated by whitespace or `)`, `]`, `"`, `'`) with its masked form.
/// Text between URLs is copied verbatim.
/// Masks every HTTP(S) URL embedded in a log string while preserving surrounding text.
pub fn mask_err(err: &str) -> String {
let mut result = String::with_capacity(err.len());
let mut remaining = err;
@@ -194,9 +174,8 @@ pub fn mask_err(err: &str) -> String {
result
}
/// get the last part of the url, if not found, return empty string
pub fn get_last_part_and_decode(url: &str) -> Option<String> {
let path = url.split('?').next().unwrap_or(""); // Splits URL and takes the path part
let path = url.split('?').next().unwrap_or("");
let segments: Vec<&str> = path.split('/').collect();
let last_segment = segments.last()?;
@@ -207,7 +186,6 @@ pub fn get_last_part_and_decode(url: &str) -> Option<String> {
)
}
/// open file
pub fn open_file(path: PathBuf) -> Result<()> {
open::that_detached(path.as_os_str())?;
Ok(())
@@ -245,7 +223,6 @@ pub fn linux_elevator() -> String {
match Command::new("which").arg("pkexec").output() {
Ok(output) => {
if !output.stdout.is_empty() {
// Convert the output to a string slice
if let Ok(path) = std::str::from_utf8(&output.stdout) {
path.trim().to_string()
} else {
@@ -260,7 +237,6 @@ pub fn linux_elevator() -> String {
}
#[cfg(target_os = "windows")]
/// copy the file to the dist path and return the dist path
pub fn snapshot_path(original_path: &Path) -> Result<PathBuf> {
let temp_dir = original_path
.parent()
+3 -24
View File
@@ -1,4 +1,3 @@
// #[cfg(not(feature = "tracing"))]
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
constants,
@@ -43,7 +42,6 @@ async fn delete_snapshot_logs(log_dir: &Path) -> Result<()> {
}
// TODO flexi_logger 提供了最大保留天数,或许我们应该用内置删除log文件
/// 删除log文件
pub async fn delete_log() -> Result<()> {
let log_dir = dirs::app_logs_dir()?;
let service_log_dir = dirs::service_log_dir()?;
@@ -63,7 +61,6 @@ pub async fn delete_log() -> Result<()> {
verge.auto_log_clean.unwrap_or(0)
};
// 1: 1天, 2: 7天, 3: 30天, 4: 90天
let day = match auto_log_clean {
1 => 1,
2 => 7,
@@ -74,7 +71,6 @@ pub async fn delete_log() -> Result<()> {
logging!(info, Type::Setup, "try to delete log files, day: {}", day);
// %Y-%m-%d to NaiveDateTime
let parse_time_str = |s: &str| {
let sa: Vec<&str> = s.split('-').collect();
if sa.len() != 4 {
@@ -320,14 +316,12 @@ async fn migrate_legacy_macos_logs() -> Result<()> {
Ok(())
}
/// 初始化DNS配置文件
pub(super) async fn init_dns_config() -> Result<()> {
use serde_yaml_ng::Value;
// 创建DNS子配置
let dns_config = serde_yaml_ng::Mapping::from_iter([
("enable".into(), Value::Bool(true)),
// 与前端 DNS 默认一致,并供 dns.ipv6 锁定使用
// Must match the frontend default used for authoritative `dns.ipv6`.
("ipv6".into(), Value::Bool(true)),
("listen".into(), Value::String(":53".into())),
("enhanced-mode".into(), Value::String("fake-ip".into())),
@@ -410,13 +404,11 @@ pub(super) async fn init_dns_config() -> Result<()> {
),
]);
// 获取默认DNS和host配置
let default_dns_config = serde_yaml_ng::Mapping::from_iter([
("dns".into(), Value::Mapping(dns_config)),
("hosts".into(), Value::Mapping(serde_yaml_ng::Mapping::new())),
]);
// 检查DNS配置文件是否存在
let app_dir = dirs::app_home_dir()?;
let dns_path = app_dir.join(constants::files::DNS_CONFIG);
@@ -428,7 +420,6 @@ pub(super) async fn init_dns_config() -> Result<()> {
Ok(())
}
/// 确保目录结构存在
async fn ensure_directories() -> Result<()> {
let directories = [
("app_home", dirs::app_home_dir()?),
@@ -449,7 +440,6 @@ async fn ensure_directories() -> Result<()> {
Ok(())
}
/// 初始化配置文件
async fn initialize_config_files() -> Result<()> {
if let Ok(path) = dirs::clash_path()
&& !path.exists()
@@ -481,7 +471,6 @@ async fn initialize_config_files() -> Result<()> {
logging!(info, Type::Setup, "Created profiles config at {:?}", path);
}
// 验证并修正verge配置
IVerge::validate_and_fix_config()
.await
.map_err(|e| anyhow::anyhow!("Failed to validate verge config: {}", e))?;
@@ -489,14 +478,8 @@ async fn initialize_config_files() -> Result<()> {
Ok(())
}
/// Initialize all the config files
/// before tauri setup
/// Initializes configuration required before Tauri setup.
pub async fn init_config() -> Result<()> {
// We do not need init_portable_flag here anymore due to lib.rs will to the things
// let _ = dirs::init_portable_flag();
// We do not need init_log here anymore due to resolve will to the things
#[cfg(target_os = "macos")]
migrate_legacy_macos_logs().await?;
@@ -514,8 +497,7 @@ pub async fn init_config() -> Result<()> {
Ok(())
}
/// initialize app resources
/// after tauri setup
/// Initializes application resources after Tauri setup.
pub async fn init_resources() -> Result<()> {
let app_dir = dirs::app_home_dir()?;
let res_dir = dirs::app_resources_dir()?;
@@ -529,8 +511,6 @@ pub async fn init_resources() -> Result<()> {
let file_list = ["Country.mmdb", "geoip.dat", "geosite.dat"];
// copy the resource file
// if the source file is newer than the destination file, copy it over
for file in file_list.iter() {
let src_path = res_dir.join(file);
let dest_path = app_dir.join(file);
@@ -559,7 +539,6 @@ pub async fn init_resources() -> Result<()> {
Ok(())
}
/// initialize url scheme
#[cfg(target_os = "windows")]
pub fn init_scheme() -> Result<()> {
use tauri::utils::platform::current_exe;
+9 -37
View File
@@ -4,17 +4,15 @@ use tauri::webview::PageLoadEvent;
use tauri::{Theme, WebviewWindow};
use crate::{config::Config, core::handle, utils::resolve::window_script::build_window_initial_script};
use clash_verge_logging::{Type, logging_error};
// logging 仅在 macOS 的渲染进程恢复逻辑中使用
#[cfg(target_os = "macos")]
use clash_verge_logging::logging;
use clash_verge_logging::{Type, logging_error};
const DARK_BACKGROUND_COLOR: Color = Color(46, 48, 61, 255); // #2E303D
const LIGHT_BACKGROUND_COLOR: Color = Color(245, 245, 245, 255); // #F5F5F5
const DARK_BACKGROUND_HEX: &str = "#2E303D";
const LIGHT_BACKGROUND_HEX: &str = "#F5F5F5";
// 定义默认窗口尺寸常量
const DEFAULT_WIDTH: f64 = 940.0;
const DEFAULT_HEIGHT: f64 = 700.0;
@@ -46,7 +44,6 @@ fn restore_default_size_if_needed(window: &WebviewWindow) {
logging_error!(Type::Window, window.center());
}
/// 构建新的 WebView 窗口
pub async fn build_new_window() -> Result<WebviewWindow, String> {
let app_handle = handle::Handle::app_handle();
@@ -112,7 +109,7 @@ pub async fn build_new_window() -> Result<WebviewWindow, String> {
Ok(window) => {
logging_error!(Type::Window, window.set_background_color(Some(background_color)));
restore_default_size_if_needed(&window);
// 全新窗口的页面即为最新状态,丢弃旧窗口遗留的待重载标记,避免多余 reload
// A new page supersedes any reload marker left by the old window.
#[cfg(target_os = "macos")]
take_webview_needs_reload();
Ok(window)
@@ -121,40 +118,19 @@ pub async fn build_new_window() -> Result<WebviewWindow, String> {
}
}
/// 渲染进程死亡、页面待重载标记(macOS)
///
/// 渲染进程在窗口不可见时被系统终止后置位,由下次激活窗口的路径取走并执行 reload。
/// Defers recovery of a terminated hidden main webview until its next activation.
#[cfg(target_os = "macos")]
static WEBVIEW_NEEDS_RELOAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// 取出并清除"页面待重载"标记
///
/// # Returns
/// * `bool` - 渲染进程是否曾在窗口不可见时被系统终止、页面需要 reload
#[cfg(target_os = "macos")]
pub fn take_webview_needs_reload() -> bool {
WEBVIEW_NEEDS_RELOAD.swap(false, std::sync::atomic::Ordering::SeqCst)
}
/// WebView 渲染进程被系统终止后的恢复处理(macOS)
///
/// macOS 在内存压力下可能杀掉 WKWebView 的 WebContent 渲染进程:
/// 1. 页面内容层消失,窗口打开后表现为白屏;
/// 2. 前端 JS 状态随之丢失,无法调用 `ws_disconnect` 清理 Mihomo WebSocket 订阅,
/// 孤儿订阅持续把大于 1KB 的 payload(如 `/connections` 全量快照)塞进 tauri 的
/// `ChannelDataIpcQueue`,且没有存活的页面来取走,导致主进程内存无限增长。
///
/// 恢复策略:
/// * 窗口可见(前台被杀的罕见场景)——立即 reload 恢复页面;
/// * 窗口隐藏/最小化(托盘常驻的常见场景)——只置位待重载标记,等用户下次打开
/// 窗口时再 reload。系统正是因内存压力才杀掉不可见窗口的渲染进程,此时立即
/// 重建渲染进程既浪费内存,也可能形成"系统杀→拉起→再杀"的循环。
///
/// 注意:应用层注册 `on_web_content_process_terminate` 后会覆盖 tauri-runtime-wry
/// 的默认自动 reload 行为,因此页面死亡状态会一直保持到我们主动 reload。
///
/// # Arguments
/// * `webview` - 渲染进程被终止的 WebView
/// macOS may kill hidden WebContent under memory pressure. Clean orphaned Mihomo subscriptions,
/// 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) {
if handle::Handle::global().is_exiting() {
@@ -171,18 +147,16 @@ pub fn on_web_content_process_terminated(webview: &tauri::Webview) {
let window = webview.window();
let is_user_visible = window.is_visible().unwrap_or(false) && !window.is_minimized().unwrap_or(false);
// 懒重载标记仅供主窗口;其它 webview(update-splash)无消费通道,不可见时直接 reload 兜底
// Only the main window has a path that consumes the deferred marker.
let is_main_window = webview.label() == "main";
let reload_now = is_user_visible || !is_main_window;
if !reload_now {
// 主窗口不可见:置标记,延迟到下次 activate_window / reload_main_window_if_needed 再 reload
WEBVIEW_NEEDS_RELOAD.store(true, std::sync::atomic::Ordering::SeqCst);
logging!(info, Type::Window, "窗口不可见,页面将在下次打开窗口时重载");
}
// 清理全部 Mihomo WS 订阅,阻断 ChannelDataIpcQueue 泄漏(托盘速率任务约 1s 后自重连)。
// reload 必须与清理同任务、排在其后,否则清理可能误清重载后新页面的订阅(竞态)。
// Clean before reload so cleanup cannot remove subscriptions created by the new page.
let webview = webview.clone();
crate::process::AsyncHandler::spawn(move || async move {
if let Err(err) = handle::Handle::mihomo().clear_all_ws_connections().await {
@@ -196,9 +170,7 @@ pub fn on_web_content_process_terminated(webview: &tauri::Webview) {
});
}
/// 消费待重载标记并 reload 主窗口(macOS)。
/// 兜底原生取消最小化(Dock 缩略图/调度中心/窗口菜单)只触发 Focused(true)、不走
/// activate_window 的情况。与 activate_window 共用 swap 标记,先取先得、不重复 reload。
/// Consumes the shared marker for native unminimize paths that bypass `activate_window`.
#[cfg(target_os = "macos")]
pub fn reload_main_window_if_needed() {
if !take_webview_needs_reload() {
+1 -16
View File
@@ -1,19 +1,4 @@
/// Macro to generate singleton pattern for structs
///
/// Usage:
/// ```rust,ignore
/// use crate::utils::singleton::singleton;
///
/// struct MyStruct {
/// value: i32,
/// }
/// impl MyStruct {
/// fn new() -> Self {
/// MyStruct { value: 0 }
/// }
/// }
/// singleton!(MyStruct, INSTANCE);
/// ```
/// Implements `global()` using the supplied `OnceCell` static.
#[macro_export]
macro_rules! singleton {
($struct_name:ty, $instance_name:ident) => {
+1 -12
View File
@@ -1,10 +1,6 @@
//! 网络速率格式化工具
/// 速率显示升档阈值:保证显示值不超过三位数(显示层约定,与换算基数无关)
/// Promote units before the rendered value exceeds three digits.
const SPEED_DISPLAY_THRESHOLD: f64 = 1000.0;
/// 速率展示单位顺序
const SPEED_UNITS: [&str; 5] = ["B/s", "K/s", "M/s", "G/s", "T/s"];
/// 预计算 1024 的幂次方,避免运行时重复计算 pow
const SCALES: [f64; 5] = [
1.0,
1024.0,
@@ -13,10 +9,6 @@ const SCALES: [f64; 5] = [
1024.0 * 1024.0 * 1024.0 * 1024.0,
];
/// 将字节/秒格式化为可读速率字符串
///
/// # Arguments
/// * `bytes_per_sec` - 每秒字节数
pub fn format_bytes_per_second(bytes_per_sec: u64) -> String {
if bytes_per_sec < SPEED_DISPLAY_THRESHOLD as u64 {
return format!("{bytes_per_sec}B/s");
@@ -47,7 +39,6 @@ mod tests {
fn format_handles_byte_boundaries() {
assert_eq!(format_bytes_per_second(0), "0B/s");
assert_eq!(format_bytes_per_second(999), "999B/s");
// 1000 >= SPEED_DISPLAY_THRESHOLD,升档为 K/s(保证不超过三位数)
assert_eq!(format_bytes_per_second(1000), "1.0K/s");
assert_eq!(format_bytes_per_second(1024), "1.0K/s");
}
@@ -55,7 +46,6 @@ mod tests {
#[test]
fn format_handles_decimal_and_integer_rules() {
assert_eq!(format_bytes_per_second(9 * 1024), "9.0K/s");
// 9.999 K/s:rounded_1dp = 10.0,不满足 < 10,应显示整数 "10K/s"
assert_eq!(format_bytes_per_second(10 * 1024 - 1), "10K/s");
assert_eq!(format_bytes_per_second(10 * 1024), "10K/s");
assert_eq!(format_bytes_per_second(123 * 1024), "123K/s");
@@ -63,7 +53,6 @@ mod tests {
#[test]
fn format_handles_unit_promotion_after_rounding() {
// 999.5 K/s 四舍五入为 1000,≥ SPEED_DISPLAY_THRESHOLD,升档为 1.0M/s
assert_eq!(format_bytes_per_second(999 * 1024 + 512), "1.0M/s");
assert_eq!(format_bytes_per_second(1024 * 1024), "1.0M/s");
assert_eq!(format_bytes_per_second(1536 * 1024), "1.5M/s");
-8
View File
@@ -1,6 +1,3 @@
//! Some config file template
/// template for new a profile item
pub const ITEM_LOCAL: &str = "# Profile Template for Clash Verge
proxies: []
@@ -10,7 +7,6 @@ proxy-groups: []
rules: []
";
/// enhanced profile
pub const ITEM_MERGE: &str = "# Profile Enhancement Merge Template for Clash Verge
profile:
@@ -21,7 +17,6 @@ pub const ITEM_MERGE_EMPTY: &str = "# Profile Enhancement Merge Template for Cla
";
/// enhanced profile
pub const ITEM_SCRIPT: &str = "// Define main function (script entry)
function main(config, profileName) {
@@ -29,7 +24,6 @@ function main(config, profileName) {
}
";
/// enhanced profile
pub const ITEM_RULES: &str = "# Profile Enhancement Rules Template for Clash Verge
prepend: []
@@ -39,7 +33,6 @@ append: []
delete: []
";
/// enhanced profile
pub const ITEM_PROXIES: &str = "# Profile Enhancement Proxies Template for Clash Verge
prepend: []
@@ -49,7 +42,6 @@ append: []
delete: []
";
/// enhanced profile
pub const ITEM_GROUPS: &str = "# Profile Enhancement Groups Template for Clash Verge
prepend: []
+5 -46
View File
@@ -1,7 +1,4 @@
//! macOS 托盘速率富文本渲染模块
//!
//! 通过 objc2 调用 NSAttributedString 实现托盘速率的富文本显示,
//! 支持等宽字体、跟随菜单栏外观配色、两行定宽布局。
//! macOS tray speed rendering via `NSAttributedString`.
use std::cell::RefCell;
@@ -17,36 +14,24 @@ use objc2_app_kit::{
};
use objc2_foundation::{NSAttributedString, NSDictionary, NSNumber, NSString};
/// 富文本渲染使用的字号(适配两行在托盘栏的高度)
const TRAY_FONT_SIZE: f64 = 9.5;
/// 两行文本的固定行高,避免不同菜单栏高度/缩放下使用系统默认行高导致裁剪
/// Fixed metrics prevent clipping across menu-bar scales.
const TRAY_LINE_HEIGHT: f64 = 10.0;
/// 两行文本的行间距
const TRAY_LINE_SPACING: f64 = 0.0;
/// 两行文本整体行高倍数(用于进一步压缩文本块高度)
const TRAY_LINE_HEIGHT_MULTIPLE: f64 = 1.00;
/// 文本块段前偏移(用于将两行文本整体下移)
const TRAY_PARAGRAPH_SPACING_BEFORE: f64 = 0.0;
/// 基线基准位移按字体上沿比例生成(避免硬编码常量)
const TRAY_BASELINE_OFFSET_GLYPH_HEIGHT_RATIO: f64 = 3.0;
/// Tauri tray-icon 将图标缩放为 18pt;这里额外预留图标、图文间距与系统内边距
/// Tauri uses an 18pt icon; reserve room for the icon and system padding.
const TRAY_STATUS_ITEM_EXTRA_WIDTH: f64 = 30.0;
/// 典型 6 字符速率文本的最小宽度,避免 0B/s 等短文本让状态项反复收缩
/// Avoid status-item width jitter for short values such as `0B/s`.
const TRAY_STATUS_ITEM_MIN_LENGTH: f64 = 58.0;
/// AppKit 的 NSVariableStatusItemLength。清空速率标题后恢复系统按图标自适应
const NS_VARIABLE_STATUS_ITEM_LENGTH: f64 = -1.0;
thread_local! {
static LAST_DISPLAY_STR: RefCell<String> = const { RefCell::new(String::new()) };
}
/// 将上行/下行速率格式化为两行定宽文本
///
/// # Arguments
/// * `up` - 上行速率(字节/秒)
/// * `down` - 下行速率(字节/秒)
fn format_tray_speed(up: u64, down: u64) -> String {
// 上行放在第一行,下行放在第二行;通过上下布局表达方向,不再显示箭头字符。
let up_str = format_bytes_per_second(up);
let down_str = format_bytes_per_second(down);
format!("{:>6}\n{:>6}", up_str, down_str)
@@ -54,11 +39,8 @@ fn format_tray_speed(up: u64, down: u64) -> String {
fn build_attributes(button_height: f64) -> Retained<NSDictionary<NSString, AnyObject>> {
unsafe {
// 等宽系统字体,确保数字不跳动
let font = NSFont::monospacedSystemFontOfSize_weight(TRAY_FONT_SIZE, NSFontWeightRegular);
// 与 NSStatusBarButton 原生标题一致,并按每块屏幕的菜单栏外观动态解析颜色
let color = NSColor::controlTextColor();
// 段落样式:右对齐,保证定宽视觉一致
let para_style = NSMutableParagraphStyle::new();
para_style.setAlignment(NSTextAlignment::Right);
para_style.setLineBreakMode(NSLineBreakMode::ByClipping);
@@ -83,11 +65,6 @@ fn build_attributes(button_height: f64) -> Retained<NSDictionary<NSString, AnyOb
}
}
/// 创建带属性的富文本
///
/// # Arguments
/// * `text` - 富文本字符串内容
/// * `attrs` - 可选富文本属性字典(None 表示用默认属性)
fn create_attributed_string(
text: &NSString,
attrs: Option<&NSDictionary<NSString, AnyObject>>,
@@ -111,15 +88,7 @@ fn sync_click_target_frame(button: &NSStatusBarButton) {
}
}
/// 在主线程下设置 NSStatusItem 按钮的标题内容
///
/// 依赖 Tauri `with_inner_tray_icon` 保证回调在主线程执行;
/// 若意外在非主线程调用,`MainThreadMarker::new()` 返回 `None` 并记录警告。
///
/// # Arguments
/// * `status_item` - macOS 托盘 NSStatusItem 引用
/// * `text` - 标题字符串内容
/// * `show_speed` - 是否以速率富文本样式绘制;false 时清空为普通空标题
/// `with_inner_tray_icon` should run this on the main thread; fail safely if it does not.
fn apply_status_item_attributed_title(status_item: &NSStatusItem, text: &NSString, show_speed: bool) {
let Some(mtm) = MainThreadMarker::new() else {
logging!(warn, Type::Tray, "托盘速率富文本设置跳过:非主线程调用");
@@ -141,12 +110,6 @@ fn apply_status_item_attributed_title(status_item: &NSStatusItem, text: &NSStrin
sync_click_target_frame(&button);
}
/// 将速率以富文本形式设置到 NSStatusItem 的按钮上
///
/// # Arguments
/// * `status_item` - macOS 托盘 NSStatusItem 引用
/// * `up` - 上行速率(字节/秒)
/// * `down` - 下行速率(字节/秒)
pub fn set_speed_attributed_title(status_item: &NSStatusItem, up: u64, down: u64) {
let speed_text = format_tray_speed(up, down);
LAST_DISPLAY_STR.with(|last| {
@@ -160,10 +123,6 @@ pub fn set_speed_attributed_title(status_item: &NSStatusItem, up: u64, down: u64
});
}
/// 清除 NSStatusItem 按钮上的富文本速率显示
///
/// # Arguments
/// * `status_item` - macOS 托盘 NSStatusItem 引用
pub fn clear_speed_attributed_title(status_item: &NSStatusItem) {
LAST_DISPLAY_STR.with(|last| {
last.borrow_mut().clear();
+2 -37
View File
@@ -6,39 +6,25 @@ use std::pin::Pin;
use std::time::Duration;
use tauri::{Manager as _, WebviewWindow, Wry};
/// 窗口操作结果
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowOperationResult {
/// 窗口已显示并获得焦点
Shown,
/// 窗口已隐藏
Hidden,
/// 创建了新窗口
Created,
/// 摧毁了窗口
Destroyed,
/// 操作失败
Failed,
/// 无需操作
NoAction,
}
/// 窗口状态
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum WindowState {
/// 窗口可见且有焦点
VisibleFocused,
/// 窗口可见但无焦点
VisibleUnfocused,
/// 窗口最小化
Minimized,
/// 窗口隐藏
Hidden,
/// 窗口不存在
NotExist,
}
// 窗口操作防抖机制
const WINDOW_OPERATION_DEBOUNCE_MS: u64 = 625;
static WINDOW_OPERATION_LIMITER: Lazy<Limiter> = Lazy::new(|| {
Limiter::new(
@@ -55,7 +41,6 @@ fn should_handle_window_operation() -> bool {
allow
}
/// 统一的窗口管理器
pub struct WindowManager;
impl WindowManager {
@@ -112,15 +97,12 @@ impl WindowManager {
}
}
/// 获取主窗口实例
pub fn get_main_window() -> Option<WebviewWindow<Wry>> {
let app_handle = handle::Handle::app_handle();
app_handle.get_webview_window("main")
}
/// 智能显示主窗口
pub async fn show_main_window() -> WindowOperationResult {
// 防抖检查
if !should_handle_window_operation() {
return WindowOperationResult::NoAction;
}
@@ -161,7 +143,6 @@ impl WindowManager {
}
}
/// 切换主窗口显示状态(显示/隐藏)
pub async fn toggle_main_window() -> WindowOperationResult {
if !should_handle_window_operation() {
return WindowOperationResult::NoAction;
@@ -178,10 +159,8 @@ impl WindowManager {
}
}
// 窗口不存在时创建新窗口
async fn handle_not_exist_toggle() -> WindowOperationResult {
logging!(info, Type::Window, "窗口不存在,将创建新窗口");
// 由于已经有防抖保护,直接调用内部方法
if Self::create_window(true).await {
WindowOperationResult::Created
} else {
@@ -189,7 +168,6 @@ impl WindowManager {
}
}
// 隐藏主窗口
fn hide_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(info, Type::Window, "窗口可见,将隐藏窗口");
if let Some(window) = window {
@@ -209,7 +187,6 @@ impl WindowManager {
}
}
// 激活已存在的主窗口
fn activate_existing_main_window(window: Option<&WebviewWindow<Wry>>) -> WindowOperationResult {
logging!(info, Type::Window, "窗口存在但被隐藏或最小化,将激活窗口");
if let Some(window) = window {
@@ -220,14 +197,12 @@ impl WindowManager {
}
}
/// 激活窗口(取消最小化、显示、设置焦点)
fn activate_window(window: &WebviewWindow<Wry>) -> WindowOperationResult {
logging!(info, Type::Window, "开始激活窗口");
#[cfg(target_os = "macos")]
Self::set_macos_activation_policy_regular();
// 渲染进程曾被系统终止:先 reload,并把 show+focus 交给 on_page_load(Finished),
// 内容就绪再显示,避免白屏闪烁。reload 成功才 defer,失败则走下方直接显示。
// After renderer termination, defer show/focus until reload finishes to avoid a white flash.
#[allow(unused_mut)]
let mut defer_show_to_page_load = false;
#[cfg(target_os = "macos")]
@@ -241,7 +216,6 @@ impl WindowManager {
let mut operations_successful = true;
// 1. 如果窗口最小化,先取消最小化
if window.is_minimized().unwrap_or(false) {
logging!(info, Type::Window, "窗口已最小化,正在取消最小化");
if let Err(e) = window.unminimize() {
@@ -250,7 +224,6 @@ impl WindowManager {
}
}
// 2/3. 显示 + 焦点(reload 分支跳过,交给 on_page_load)
if !defer_show_to_page_load {
if let Err(e) = window.show() {
logging!(warn, Type::Window, "显示窗口失败: {}", e);
@@ -264,11 +237,9 @@ impl WindowManager {
#[cfg(target_os = "windows")]
{
// Windows 尝试额外的激活方法
if let Err(e) = window.set_always_on_top(true) {
logging!(debug, Type::Window, "设置置顶失败(非关键错误): {}", e);
}
// 立即取消置顶
if let Err(e) = window.set_always_on_top(false) {
logging!(debug, Type::Window, "取消置顶失败(非关键错误): {}", e);
}
@@ -283,23 +254,19 @@ impl WindowManager {
}
}
/// 检查窗口是否可见
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<Wry>>) -> bool {
window.map(|w| w.is_focused().unwrap_or(false)).unwrap_or(false)
}
/// 检查窗口是否最小化
pub fn is_main_window_minimized(window: Option<&WebviewWindow<Wry>>) -> bool {
window.map(|w| w.is_minimized().unwrap_or(false)).unwrap_or(false)
}
/// 创建新窗口,防抖避免重复调用
/// 窗口创建后保持隐藏,由前端 index.html 在 overlay 渲染后调用 show,避免主题闪烁
/// Keep new windows hidden until the frontend overlay renders, avoiding a theme flash.
pub fn create_window(should_create: bool) -> Pin<Box<dyn Future<Output = bool> + Send>> {
Box::pin(async move {
logging!(info, Type::Window, "开始创建主窗口, should_create={}", should_create);
@@ -325,7 +292,6 @@ impl WindowManager {
})
}
/// 摧毁窗口
pub fn destroy_main_window() -> WindowOperationResult {
if let Some(window) = Self::get_main_window() {
let _ = window.destroy();
@@ -340,7 +306,6 @@ impl WindowManager {
WindowOperationResult::Failed
}
/// 获取详细的窗口状态信息
fn get_window_status_info() -> String {
let (window, state) = Self::get_main_window_with_state();
let is_visible = Self::is_main_window_visible(window.as_ref());