refactor: cargo clippy

This commit is contained in:
MystiPanda 2024-01-10 17:36:35 +08:00
parent 17d8691300
commit 3a883b9e41
19 changed files with 96 additions and 122 deletions

View File

@ -219,7 +219,7 @@ pub fn open_app_dir() -> CmdResult<()> {
#[tauri::command] #[tauri::command]
pub fn open_core_dir() -> CmdResult<()> { pub fn open_core_dir() -> CmdResult<()> {
let core_dir = wrap_err!(tauri::utils::platform::current_exe())?; let core_dir = wrap_err!(tauri::utils::platform::current_exe())?;
let core_dir = core_dir.parent().ok_or(format!("failed to get core dir"))?; let core_dir = core_dir.parent().ok_or("failed to get core dir")?;
wrap_err!(open::that(core_dir)) wrap_err!(open::that(core_dir))
} }
@ -252,7 +252,7 @@ pub async fn clash_api_get_proxy_delay(
) -> CmdResult<clash_api::DelayRes> { ) -> CmdResult<clash_api::DelayRes> {
match clash_api::get_proxy_delay(name, url).await { match clash_api::get_proxy_delay(name, url).await {
Ok(res) => Ok(res), Ok(res) => Ok(res),
Err(err) => Err(format!("{}", err.to_string())), Err(err) => Err(err.to_string()),
} }
} }

View File

@ -65,8 +65,8 @@ impl IClashTemp {
let config = &self.0; let config = &self.0;
ClashInfo { ClashInfo {
port: Self::guard_mixed_port(&config), port: Self::guard_mixed_port(config),
server: Self::guard_client_ctrl(&config), server: Self::guard_client_ctrl(config),
secret: config.get("secret").and_then(|value| match value { secret: config.get("secret").and_then(|value| match value {
Value::String(val_str) => Some(val_str.clone()), Value::String(val_str) => Some(val_str.clone()),
Value::Bool(val_bool) => Some(val_bool.to_string()), Value::Bool(val_bool) => Some(val_bool.to_string()),
@ -98,7 +98,7 @@ impl IClashTemp {
Some(val_str) => { Some(val_str) => {
let val_str = val_str.trim(); let val_str = val_str.trim();
let val = match val_str.starts_with(":") { let val = match val_str.starts_with(':') {
true => format!("127.0.0.1{val_str}"), true => format!("127.0.0.1{val_str}"),
false => val_str.to_owned(), false => val_str.to_owned(),
}; };

View File

@ -8,7 +8,7 @@ use sysproxy::Sysproxy;
use super::Config; use super::Config;
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize, Default)]
pub struct PrfItem { pub struct PrfItem {
pub uid: Option<String>, pub uid: Option<String>,
@ -101,24 +101,6 @@ impl PrfOption {
} }
} }
impl Default for PrfItem {
fn default() -> Self {
PrfItem {
uid: None,
itype: None,
name: None,
desc: None,
file: None,
url: None,
selected: None,
extra: None,
updated: None,
option: None,
file_data: None,
}
}
}
impl PrfItem { impl PrfItem {
/// From partial item /// From partial item
/// must contain `itype` /// must contain `itype`
@ -188,7 +170,7 @@ impl PrfItem {
let opt_ref = option.as_ref(); let opt_ref = option.as_ref();
let with_proxy = opt_ref.map_or(false, |o| o.with_proxy.unwrap_or(false)); let with_proxy = opt_ref.map_or(false, |o| o.with_proxy.unwrap_or(false));
let self_proxy = opt_ref.map_or(false, |o| o.self_proxy.unwrap_or(false)); let self_proxy = opt_ref.map_or(false, |o| o.self_proxy.unwrap_or(false));
let user_agent = opt_ref.map_or(None, |o| o.user_agent.clone()); let user_agent = opt_ref.and_then(|o| o.user_agent.clone());
let mut builder = reqwest::ClientBuilder::new().use_rustls_tls().no_proxy(); let mut builder = reqwest::ClientBuilder::new().use_rustls_tls().no_proxy();
@ -213,27 +195,24 @@ impl PrfItem {
} }
// 使用系统代理 // 使用系统代理
else if with_proxy { else if with_proxy {
match Sysproxy::get_system_proxy() { if let Ok(p @ Sysproxy { enable: true, .. }) = Sysproxy::get_system_proxy() {
Ok(p @ Sysproxy { enable: true, .. }) => { let proxy_scheme = format!("http://{}:{}", p.host, p.port);
let proxy_scheme = format!("http://{}:{}", p.host, p.port);
if let Ok(proxy) = reqwest::Proxy::http(&proxy_scheme) { if let Ok(proxy) = reqwest::Proxy::http(&proxy_scheme) {
builder = builder.proxy(proxy); builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::https(&proxy_scheme) {
builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::all(&proxy_scheme) {
builder = builder.proxy(proxy);
}
} }
_ => {} if let Ok(proxy) = reqwest::Proxy::https(&proxy_scheme) {
}; builder = builder.proxy(proxy);
}
if let Ok(proxy) = reqwest::Proxy::all(&proxy_scheme) {
builder = builder.proxy(proxy);
}
}
} }
let version = match VERSION.get() { let version = match VERSION.get() {
Some(v) => format!("clash-verge/v{}", v), Some(v) => format!("clash-verge/v{}", v),
None => format!("clash-verge/unknown"), None => "clash-verge/unknown".to_string(),
}; };
builder = builder.user_agent(user_agent.unwrap_or(version)); builder = builder.user_agent(user_agent.unwrap_or(version));

View File

@ -37,13 +37,13 @@ impl IProfiles {
profiles.items = Some(vec![]); profiles.items = Some(vec![]);
} }
// compatible with the old old old version // compatible with the old old old version
profiles.items.as_mut().map(|items| { if let Some(items) = profiles.items.as_mut() {
for item in items.iter_mut() { for item in items.iter_mut() {
if item.uid.is_none() { if item.uid.is_none() {
item.uid = Some(help::get_uid("d")); item.uid = Some(help::get_uid("d"));
} }
} }
}); }
profiles profiles
} }
Err(err) => { Err(err) => {
@ -152,17 +152,19 @@ impl IProfiles {
self.items = Some(vec![]); self.items = Some(vec![]);
} }
self.items.as_mut().map(|items| items.push(item)); if let Some(items) = self.items.as_mut() {
items.push(item)
}
self.save_file() self.save_file()
} }
/// reorder items /// reorder items
pub fn reorder(&mut self, active_id: String, over_id: String) -> Result<()> { pub fn reorder(&mut self, active_id: String, over_id: String) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]); let mut items = self.items.take().unwrap_or_default();
let mut old_index = None; let mut old_index = None;
let mut new_index = None; let mut new_index = None;
for i in 0..items.len() { for (i, _) in items.iter().enumerate() {
if items[i].uid == Some(active_id.clone()) { if items[i].uid == Some(active_id.clone()) {
old_index = Some(i); old_index = Some(i);
} }
@ -182,7 +184,7 @@ impl IProfiles {
/// update the item value /// update the item value
pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> { pub fn patch_item(&mut self, uid: String, item: PrfItem) -> Result<()> {
let mut items = self.items.take().unwrap_or(vec![]); let mut items = self.items.take().unwrap_or_default();
for each in items.iter_mut() { for each in items.iter_mut() {
if each.uid == Some(uid.clone()) { if each.uid == Some(uid.clone()) {
@ -255,11 +257,11 @@ impl IProfiles {
let current = self.current.as_ref().unwrap_or(&uid); let current = self.current.as_ref().unwrap_or(&uid);
let current = current.clone(); let current = current.clone();
let mut items = self.items.take().unwrap_or(vec![]); let mut items = self.items.take().unwrap_or_default();
let mut index = None; let mut index = None;
// get the index // get the index
for i in 0..items.len() { for (i, _) in items.iter().enumerate() {
if items[i].uid == Some(uid.clone()) { if items[i].uid == Some(uid.clone()) {
index = Some(i); index = Some(i);
break; break;
@ -267,19 +269,19 @@ impl IProfiles {
} }
if let Some(index) = index { if let Some(index) = index {
items.remove(index).file.map(|file| { if let Some(file) = items.remove(index).file {
let _ = dirs::app_profiles_dir().map(|path| { let _ = dirs::app_profiles_dir().map(|path| {
let path = path.join(file); let path = path.join(file);
if path.exists() { if path.exists() {
let _ = fs::remove_file(path); let _ = fs::remove_file(path);
} }
}); });
}); }
} }
// delete the original uid // delete the original uid
if current == uid { if current == uid {
self.current = match items.len() > 0 { self.current = match !items.is_empty() {
true => items[0].uid.clone(), true => items[0].uid.clone(),
false => None, false => None,
}; };
@ -299,7 +301,7 @@ impl IProfiles {
Some(file) => dirs::app_profiles_dir()?.join(file), Some(file) => dirs::app_profiles_dir()?.join(file),
None => bail!("failed to get the file field"), None => bail!("failed to get the file field"),
}; };
return Ok(help::read_merge_mapping(&file_path)?); return help::read_merge_mapping(&file_path);
} }
bail!("failed to find the current profile \"uid:{current}\""); bail!("failed to find the current profile \"uid:{current}\"");
} }

View File

@ -83,12 +83,12 @@ fn clash_client_info() -> Result<(String, HeaderMap)> {
/// 缩短clash的日志 /// 缩短clash的日志
pub fn parse_log(log: String) -> String { pub fn parse_log(log: String) -> String {
if log.starts_with("time=") && log.len() > 33 { if log.starts_with("time=") && log.len() > 33 {
return (&log[33..]).to_owned(); return (log[33..]).to_owned();
} }
if log.len() > 9 { if log.len() > 9 {
return (&log[9..]).to_owned(); return (log[9..]).to_owned();
} }
return log; log
} }
/// 缩短clash -t的错误输出 /// 缩短clash -t的错误输出
@ -105,7 +105,7 @@ pub fn parse_check_output(log: String) -> String {
}; };
if mr > m { if mr > m {
return (&log[e..mr]).to_owned(); return (log[e..mr]).to_owned();
} }
} }
@ -113,7 +113,7 @@ pub fn parse_check_output(log: String) -> String {
let r = log.find("path=").or(Some(log.len())); let r = log.find("path=").or(Some(log.len()));
if let (Some(l), Some(r)) = (l, r) { if let (Some(l), Some(r)) = (l, r) {
return (&log[(l + 6)..(r - 1)]).to_owned(); return (log[(l + 6)..(r - 1)]).to_owned();
} }
log log

View File

@ -35,12 +35,12 @@ impl CoreManager {
.map(|pid| { .map(|pid| {
let mut system = System::new(); let mut system = System::new();
system.refresh_all(); system.refresh_all();
system.process(Pid::from_u32(pid)).map(|proc| { if let Some(proc) = system.process(Pid::from_u32(pid)) {
if proc.name().contains("clash") { if proc.name().contains("clash") {
log::debug!(target: "app", "kill old clash process"); log::debug!(target: "app", "kill old clash process");
proc.kill(); proc.kill();
} }
}); }
}); });
tauri::async_runtime::spawn(async { tauri::async_runtime::spawn(async {
@ -68,7 +68,7 @@ impl CoreManager {
if !output.status.success() { if !output.status.success() {
let error = clash_api::parse_check_output(output.stdout.clone()); let error = clash_api::parse_check_output(output.stdout.clone());
let error = match error.len() > 0 { let error = match !error.is_empty() {
true => error, true => error,
false => output.stdout.clone(), false => output.stdout.clone(),
}; };
@ -110,7 +110,7 @@ impl CoreManager {
use super::win_service; use super::win_service;
// 服务模式 // 服务模式
let enable = { Config::verge().latest().enable_service_mode.clone() }; let enable = { Config::verge().latest().enable_service_mode };
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
*self.use_service_mode.lock() = enable; *self.use_service_mode.lock() = enable;

View File

@ -28,7 +28,7 @@ impl Handle {
self.app_handle self.app_handle
.lock() .lock()
.as_ref() .as_ref()
.map_or(None, |a| a.get_window("main")) .and_then(|a| a.get_window("main"))
} }
pub fn refresh_clash() { pub fn refresh_clash() {

View File

@ -65,17 +65,17 @@ impl Hotkey {
} }
let f = match func.trim() { let f = match func.trim() {
"open_dashboard" => || feat::open_dashboard(), "open_dashboard" => feat::open_dashboard,
"clash_mode_rule" => || feat::change_clash_mode("rule".into()), "clash_mode_rule" => || feat::change_clash_mode("rule".into()),
"clash_mode_global" => || feat::change_clash_mode("global".into()), "clash_mode_global" => || feat::change_clash_mode("global".into()),
"clash_mode_direct" => || feat::change_clash_mode("direct".into()), "clash_mode_direct" => || feat::change_clash_mode("direct".into()),
"clash_mode_script" => || feat::change_clash_mode("script".into()), "clash_mode_script" => || feat::change_clash_mode("script".into()),
"toggle_system_proxy" => || feat::toggle_system_proxy(), "toggle_system_proxy" => feat::toggle_system_proxy,
"enable_system_proxy" => || feat::enable_system_proxy(), "enable_system_proxy" => feat::enable_system_proxy,
"disable_system_proxy" => || feat::disable_system_proxy(), "disable_system_proxy" => feat::disable_system_proxy,
"toggle_tun_mode" => || feat::toggle_tun_mode(), "toggle_tun_mode" => feat::toggle_tun_mode,
"enable_tun_mode" => || feat::enable_tun_mode(), "enable_tun_mode" => feat::enable_tun_mode,
"disable_tun_mode" => || feat::disable_tun_mode(), "disable_tun_mode" => feat::disable_tun_mode,
_ => bail!("invalid function \"{func}\""), _ => bail!("invalid function \"{func}\""),
}; };
@ -86,7 +86,7 @@ impl Hotkey {
} }
fn unregister(&self, hotkey: &str) -> Result<()> { fn unregister(&self, hotkey: &str) -> Result<()> {
self.get_manager()?.unregister(&hotkey)?; self.get_manager()?.unregister(hotkey)?;
log::info!(target: "app", "unregister hotkey {hotkey}"); log::info!(target: "app", "unregister hotkey {hotkey}");
Ok(()) Ok(())
} }
@ -110,7 +110,7 @@ impl Hotkey {
Ok(()) Ok(())
} }
fn get_map_from_vec<'a>(hotkeys: &'a Vec<String>) -> HashMap<&'a str, &'a str> { fn get_map_from_vec(hotkeys: &Vec<String>) -> HashMap<&str, &str> {
let mut map = HashMap::new(); let mut map = HashMap::new();
hotkeys.iter().for_each(|hotkey| { hotkeys.iter().for_each(|hotkey| {

View File

@ -53,7 +53,7 @@ impl Sysopt {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
( (
verge.enable_system_proxy.clone().unwrap_or(false), verge.enable_system_proxy.unwrap_or(false),
verge.system_proxy_bypass.clone(), verge.system_proxy_bypass.clone(),
) )
}; };
@ -66,7 +66,7 @@ impl Sysopt {
}; };
if enable { if enable {
let old = Sysproxy::get_system_proxy().map_or(None, |p| Some(p)); let old = Sysproxy::get_system_proxy().ok();
current.set_system_proxy()?; current.set_system_proxy()?;
*self.old_sysproxy.lock() = old; *self.old_sysproxy.lock() = old;
@ -93,7 +93,7 @@ impl Sysopt {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
( (
verge.enable_system_proxy.clone().unwrap_or(false), verge.enable_system_proxy.unwrap_or(false),
verge.system_proxy_bypass.clone(), verge.system_proxy_bypass.clone(),
) )
}; };
@ -142,7 +142,7 @@ impl Sysopt {
/// init the auto launch /// init the auto launch
pub fn init_launch(&self) -> Result<()> { pub fn init_launch(&self) -> Result<()> {
let enable = { Config::verge().latest().enable_auto_launch.clone() }; let enable = { Config::verge().latest().enable_auto_launch };
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
let app_exe = current_exe()?; let app_exe = current_exe()?;
@ -233,7 +233,7 @@ impl Sysopt {
drop(auto_launch); drop(auto_launch);
return self.init_launch(); return self.init_launch();
} }
let enable = { Config::verge().latest().enable_auto_launch.clone() }; let enable = { Config::verge().latest().enable_auto_launch };
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
let auto_launch = auto_launch.as_ref().unwrap(); let auto_launch = auto_launch.as_ref().unwrap();
@ -271,9 +271,9 @@ impl Sysopt {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.latest(); let verge = verge.latest();
( (
verge.enable_system_proxy.clone().unwrap_or(false), verge.enable_system_proxy.unwrap_or(false),
verge.enable_proxy_guard.clone().unwrap_or(false), verge.enable_proxy_guard.unwrap_or(false),
verge.proxy_guard_duration.clone().unwrap_or(10), verge.proxy_guard_duration.unwrap_or(10),
verge.system_proxy_bypass.clone(), verge.system_proxy_bypass.clone(),
) )
}; };

View File

@ -40,7 +40,7 @@ impl Timer {
let timer_map = self.timer_map.lock(); let timer_map = self.timer_map.lock();
let delay_timer = self.delay_timer.lock(); let delay_timer = self.delay_timer.lock();
Config::profiles().latest().get_items().map(|items| { if let Some(items) = Config::profiles().latest().get_items() {
items items
.iter() .iter()
.filter_map(|item| { .filter_map(|item| {
@ -61,7 +61,7 @@ impl Timer {
} }
} }
}) })
}); }
Ok(()) Ok(())
} }

View File

@ -114,9 +114,9 @@ pub fn use_sort(config: Mapping, enable_filter: bool) -> Mapping {
.chain(DEFAULT_FIELDS) .chain(DEFAULT_FIELDS)
.for_each(|key| { .for_each(|key| {
let key = Value::from(key); let key = Value::from(key);
config.get(&key).map(|value| { if let Some(value) = config.get(&key) {
ret.insert(key, value.clone()); ret.insert(key, value.clone());
}); }
}); });
if !enable_filter { if !enable_filter {
@ -134,9 +134,9 @@ pub fn use_sort(config: Mapping, enable_filter: bool) -> Mapping {
config_keys.difference(&supported_keys).for_each(|&key| { config_keys.difference(&supported_keys).for_each(|&key| {
let key = Value::from(key); let key = Value::from(key);
config.get(&key).map(|value| { if let Some(value) = config.get(&key) {
ret.insert(key, value.clone()); ret.insert(key, value.clone());
}); }
}); });
} }
@ -150,7 +150,7 @@ pub fn use_keys(config: &Mapping) -> Vec<String> {
.map(|s| { .map(|s| {
let mut s = s.to_string(); let mut s = s.to_string();
s.make_ascii_lowercase(); s.make_ascii_lowercase();
return s; s
}) })
.collect() .collect()
} }

View File

@ -27,9 +27,9 @@ pub fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
let verge = verge.latest(); let verge = verge.latest();
( (
verge.clash_core.clone(), verge.clash_core.clone(),
verge.enable_tun_mode.clone().unwrap_or(false), verge.enable_tun_mode.unwrap_or(false),
verge.enable_builtin_enhanced.clone().unwrap_or(true), verge.enable_builtin_enhanced.unwrap_or(true),
verge.enable_clash_fields.clone().unwrap_or(true), verge.enable_clash_fields.unwrap_or(true),
) )
}; };
@ -38,18 +38,18 @@ pub fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
let profiles = Config::profiles(); let profiles = Config::profiles();
let profiles = profiles.latest(); let profiles = profiles.latest();
let current = profiles.current_mapping().unwrap_or(Mapping::new()); let current = profiles.current_mapping().unwrap_or_default();
let chain = match profiles.chain.as_ref() { let chain = match profiles.chain.as_ref() {
Some(chain) => chain Some(chain) => chain
.iter() .iter()
.filter_map(|uid| profiles.get_item(uid).ok()) .filter_map(|uid| profiles.get_item(uid).ok())
.filter_map(|item| <Option<ChainItem>>::from(item)) .filter_map(<Option<ChainItem>>::from)
.collect::<Vec<ChainItem>>(), .collect::<Vec<ChainItem>>(),
None => vec![], None => vec![],
}; };
let valid = profiles.valid.clone().unwrap_or(vec![]); let valid = profiles.valid.clone().unwrap_or_default();
(current, chain, valid) (current, chain, valid)
}; };

View File

@ -47,7 +47,7 @@ pub fn use_script(script: String, config: Mapping) -> Result<(Mapping, Vec<(Stri
if result == "\"\"" { if result == "\"\"" {
anyhow::bail!("main function should return object"); anyhow::bail!("main function should return object");
} }
return Ok(serde_json::from_str::<Mapping>(result.as_str())?); Ok(serde_json::from_str::<Mapping>(result.as_str())?)
}); });
let mut out = outputs.lock().unwrap(); let mut out = outputs.lock().unwrap();

View File

@ -62,7 +62,7 @@ pub fn change_clash_mode(mode: String) {
// 切换系统代理 // 切换系统代理
pub fn toggle_system_proxy() { pub fn toggle_system_proxy() {
let enable = Config::verge().draft().enable_system_proxy.clone(); let enable = Config::verge().draft().enable_system_proxy;
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
@ -110,7 +110,7 @@ pub fn disable_system_proxy() {
// 切换tun模式 // 切换tun模式
pub fn toggle_tun_mode() { pub fn toggle_tun_mode() {
let enable = Config::verge().data().enable_tun_mode.clone(); let enable = Config::verge().data().enable_tun_mode;
let enable = enable.unwrap_or(false); let enable = enable.unwrap_or(false);
tauri::async_runtime::spawn(async move { tauri::async_runtime::spawn(async move {
@ -164,14 +164,14 @@ pub async fn patch_clash(patch: Mapping) -> Result<()> {
let mixed_port = patch.get("mixed-port"); let mixed_port = patch.get("mixed-port");
let enable_random_port = Config::verge().latest().enable_random_port.unwrap_or(false); let enable_random_port = Config::verge().latest().enable_random_port.unwrap_or(false);
if mixed_port.is_some() && !enable_random_port { if mixed_port.is_some() && !enable_random_port {
let changed = mixed_port.clone().unwrap() let changed = mixed_port.unwrap()
!= Config::verge() != Config::verge()
.latest() .latest()
.verge_mixed_port .verge_mixed_port
.unwrap_or(Config::clash().data().get_mixed_port()); .unwrap_or(Config::clash().data().get_mixed_port());
// 检查端口占用 // 检查端口占用
if changed { if changed {
if let Some(port) = mixed_port.clone().unwrap().as_u64() { if let Some(port) = mixed_port.unwrap().as_u64() {
if !port_scanner::local_port_available(port as u16) { if !port_scanner::local_port_available(port as u16) {
Config::clash().discard(); Config::clash().discard();
bail!("port already in use"); bail!("port already in use");

View File

@ -25,7 +25,10 @@ fn main() -> std::io::Result<()> {
#[allow(unused_mut)] #[allow(unused_mut)]
let mut builder = tauri::Builder::default() let mut builder = tauri::Builder::default()
.system_tray(SystemTray::new()) .system_tray(SystemTray::new())
.setup(|app| Ok(resolve::resolve_setup(app))) .setup(|app| {
resolve::resolve_setup(app);
Ok(())
})
.on_system_tray_event(core::tray::Tray::on_system_tray_event) .on_system_tray_event(core::tray::Tray::on_system_tray_event)
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
// common // common
@ -133,13 +136,13 @@ fn main() -> std::io::Result<()> {
if label == "main" { if label == "main" {
match event { match event {
tauri::WindowEvent::Destroyed => { tauri::WindowEvent::Destroyed => {
let _ = resolve::save_window_size_position(&app_handle, true); let _ = resolve::save_window_size_position(app_handle, true);
} }
tauri::WindowEvent::CloseRequested { .. } => { tauri::WindowEvent::CloseRequested { .. } => {
let _ = resolve::save_window_size_position(&app_handle, true); let _ = resolve::save_window_size_position(app_handle, true);
} }
tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => { tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => {
let _ = resolve::save_window_size_position(&app_handle, false); let _ = resolve::save_window_size_position(app_handle, false);
} }
_ => {} _ => {}
} }

View File

@ -92,14 +92,6 @@ pub fn clash_pid_path() -> Result<PathBuf> {
Ok(app_home_dir()?.join("clash.pid")) Ok(app_home_dir()?.join("clash.pid"))
} }
#[cfg(target_os = "linux")]
pub fn local_applications_dir() -> Result<PathBuf> {
use tauri::api::path::home_dir;
Ok(home_dir()
.ok_or(anyhow::anyhow!("failed to get home dir"))?
.join(".local/share/applications"))
}
#[cfg(windows)] #[cfg(windows)]
pub fn service_dir() -> Result<PathBuf> { pub fn service_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join("service")) Ok(app_home_dir()?.join("service"))

View File

@ -14,7 +14,7 @@ pub fn read_yaml<T: DeserializeOwned>(path: &PathBuf) -> Result<T> {
bail!("file not found \"{}\"", path.display()); bail!("file not found \"{}\"", path.display());
} }
let yaml_str = fs::read_to_string(&path) let yaml_str = fs::read_to_string(path)
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?; .with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
serde_yaml::from_str::<T>(&yaml_str).with_context(|| { serde_yaml::from_str::<T>(&yaml_str).with_context(|| {
@ -89,11 +89,11 @@ pub fn open_file(app: tauri::AppHandle, path: PathBuf) -> Result<()> {
let code = "code"; let code = "code";
let _ = match Program::from_str(code) { let _ = match Program::from_str(code) {
Ok(code) => open(&app.shell_scope(), &path.to_string_lossy(), Some(code)), Ok(code) => open(&app.shell_scope(), path.to_string_lossy(), Some(code)),
Err(err) => { Err(err) => {
log::error!(target: "app", "Can't find VScode `{err}`"); log::error!(target: "app", "Can't find VScode `{err}`");
// default open // default open
open(&app.shell_scope(), &path.to_string_lossy(), None) open(&app.shell_scope(), path.to_string_lossy(), None)
} }
}; };

View File

@ -79,7 +79,7 @@ pub fn delete_log() -> Result<()> {
let auto_log_clean = { let auto_log_clean = {
let verge = Config::verge(); let verge = Config::verge();
let verge = verge.data(); let verge = verge.data();
verge.auto_log_clean.clone().unwrap_or(0) verge.auto_log_clean.unwrap_or(0)
}; };
let day = match auto_log_clean { let day = match auto_log_clean {
@ -130,10 +130,8 @@ pub fn delete_log() -> Result<()> {
Ok(()) Ok(())
}; };
for file in fs::read_dir(&log_dir)? { for file in fs::read_dir(&log_dir)?.flatten() {
if let Ok(file) = file { let _ = process_file(file);
let _ = process_file(file);
}
} }
Ok(()) Ok(())
} }
@ -310,14 +308,14 @@ pub fn init_scheme() -> Result<()> {
let app_exe = current_exe()?; let app_exe = current_exe()?;
let app_exe = dunce::canonicalize(app_exe)?; let app_exe = dunce::canonicalize(app_exe)?;
let app_exe = app_exe.to_string_lossy().to_owned(); let app_exe = app_exe.to_string_lossy().into_owned();
let hkcu = RegKey::predef(HKEY_CURRENT_USER); let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let (clash, _) = hkcu.create_subkey("Software\\Classes\\Clash")?; let (clash, _) = hkcu.create_subkey("Software\\Classes\\Clash")?;
clash.set_value("", &"Clash Verge")?; clash.set_value("", &"Clash Verge")?;
clash.set_value("URL Protocol", &"Clash Verge URL Scheme Protocol")?; clash.set_value("URL Protocol", &"Clash Verge URL Scheme Protocol")?;
let (default_icon, _) = hkcu.create_subkey("Software\\Classes\\Clash\\DefaultIcon")?; let (default_icon, _) = hkcu.create_subkey("Software\\Classes\\Clash\\DefaultIcon")?;
default_icon.set_value("", &format!("{app_exe}"))?; default_icon.set_value("", &app_exe)?;
let (command, _) = hkcu.create_subkey("Software\\Classes\\Clash\\Shell\\Open\\Command")?; let (command, _) = hkcu.create_subkey("Software\\Classes\\Clash\\Shell\\Open\\Command")?;
command.set_value("", &format!("{app_exe} \"%1\""))?; command.set_value("", &format!("{app_exe} \"%1\""))?;

View File

@ -86,7 +86,7 @@ pub fn resolve_setup(app: &mut App) {
log::trace!("init system tray"); log::trace!("init system tray");
log_err!(tray::Tray::update_systray(&app.app_handle())); log_err!(tray::Tray::update_systray(&app.app_handle()));
let silent_start = { Config::verge().data().enable_silent_start.clone() }; let silent_start = { Config::verge().data().enable_silent_start };
if !silent_start.unwrap_or(false) { if !silent_start.unwrap_or(false) {
create_window(&app.app_handle()); create_window(&app.app_handle());
} }
@ -249,8 +249,8 @@ pub async fn resolve_scheme(param: String) {
self_proxy: None, self_proxy: None,
update_interval: None, update_interval: None,
}; };
if let Ok(item) = PrfItem::from_url(&url, None, None, Some(option)).await { if let Ok(item) = PrfItem::from_url(url, None, None, Some(option)).await {
if let Ok(_) = Config::profiles().data().append_item(item) { if Config::profiles().data().append_item(item).is_ok() {
notification::Notification::new(crate::utils::dirs::APP_ID) notification::Notification::new(crate::utils::dirs::APP_ID)
.title("Clash Verge") .title("Clash Verge")
.body("Import profile success") .body("Import profile success")