mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 08:45:41 +08:00
chore: format rust code
This commit is contained in:
@@ -5,55 +5,55 @@ use std::{fs, path::PathBuf};
|
||||
|
||||
/// read data from yaml as struct T
|
||||
pub fn read_yaml<T: DeserializeOwned + Default>(path: PathBuf) -> T {
|
||||
if !path.exists() {
|
||||
log::error!(target: "app", "file not found \"{}\"", path.display());
|
||||
return T::default();
|
||||
}
|
||||
|
||||
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
|
||||
|
||||
match serde_yaml::from_str::<T>(&yaml_str) {
|
||||
Ok(val) => val,
|
||||
Err(_) => {
|
||||
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
|
||||
T::default()
|
||||
if !path.exists() {
|
||||
log::error!(target: "app", "file not found \"{}\"", path.display());
|
||||
return T::default();
|
||||
}
|
||||
|
||||
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
|
||||
|
||||
match serde_yaml::from_str::<T>(&yaml_str) {
|
||||
Ok(val) => val,
|
||||
Err(_) => {
|
||||
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
|
||||
T::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// read mapping from yaml fix #165
|
||||
pub fn read_merge_mapping(path: PathBuf) -> Mapping {
|
||||
let map = Mapping::new();
|
||||
let map = Mapping::new();
|
||||
|
||||
if !path.exists() {
|
||||
log::error!(target: "app", "file not found \"{}\"", path.display());
|
||||
return map;
|
||||
}
|
||||
|
||||
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
|
||||
|
||||
match serde_yaml::from_str::<Value>(&yaml_str) {
|
||||
Ok(mut val) => {
|
||||
crate::log_if_err!(val.apply_merge());
|
||||
val.as_mapping().unwrap_or(&map).to_owned()
|
||||
if !path.exists() {
|
||||
log::error!(target: "app", "file not found \"{}\"", path.display());
|
||||
return map;
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
|
||||
map
|
||||
|
||||
let yaml_str = fs::read_to_string(&path).unwrap_or("".into());
|
||||
|
||||
match serde_yaml::from_str::<Value>(&yaml_str) {
|
||||
Ok(mut val) => {
|
||||
crate::log_if_err!(val.apply_merge());
|
||||
val.as_mapping().unwrap_or(&map).to_owned()
|
||||
}
|
||||
Err(_) => {
|
||||
log::error!(target: "app", "failed to read yaml file \"{}\"", path.display());
|
||||
map
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// save the data to the file
|
||||
/// can set `prefix` string to add some comments
|
||||
pub fn save_yaml<T: Serialize>(path: PathBuf, data: &T, prefix: Option<&str>) -> Result<()> {
|
||||
let data_str = serde_yaml::to_string(data)?;
|
||||
let data_str = serde_yaml::to_string(data)?;
|
||||
|
||||
let yaml_str = match prefix {
|
||||
Some(prefix) => format!("{prefix}{data_str}"),
|
||||
None => data_str,
|
||||
};
|
||||
let yaml_str = match prefix {
|
||||
Some(prefix) => format!("{prefix}{data_str}"),
|
||||
None => data_str,
|
||||
};
|
||||
|
||||
let path_str = path.as_os_str().to_string_lossy().to_string();
|
||||
fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
|
||||
let path_str = path.as_os_str().to_string_lossy().to_string();
|
||||
fs::write(path, yaml_str.as_bytes()).context(format!("failed to save file \"{path_str}\""))
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use std::env::temp_dir;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{
|
||||
api::path::{home_dir, resource_dir},
|
||||
Env, PackageInfo,
|
||||
api::path::{home_dir, resource_dir},
|
||||
Env, PackageInfo,
|
||||
};
|
||||
|
||||
#[cfg(not(feature = "verge-dev"))]
|
||||
@@ -26,89 +26,89 @@ pub static mut APP_VERSION: &str = "v1.1.1";
|
||||
/// initialize portable flag
|
||||
#[allow(unused)]
|
||||
pub unsafe fn init_portable_flag() {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use tauri::utils::platform::current_exe;
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use tauri::utils::platform::current_exe;
|
||||
|
||||
let exe = current_exe().unwrap();
|
||||
let dir = exe.parent().unwrap();
|
||||
let dir = PathBuf::from(dir).join(".config/PORTABLE");
|
||||
let exe = current_exe().unwrap();
|
||||
let dir = exe.parent().unwrap();
|
||||
let dir = PathBuf::from(dir).join(".config/PORTABLE");
|
||||
|
||||
if dir.exists() {
|
||||
PORTABLE_FLAG = true;
|
||||
if dir.exists() {
|
||||
PORTABLE_FLAG = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// get the verge app home dir
|
||||
pub fn app_home_dir() -> PathBuf {
|
||||
#[cfg(target_os = "windows")]
|
||||
unsafe {
|
||||
use tauri::utils::platform::current_exe;
|
||||
#[cfg(target_os = "windows")]
|
||||
unsafe {
|
||||
use tauri::utils::platform::current_exe;
|
||||
|
||||
if !PORTABLE_FLAG {
|
||||
home_dir().unwrap().join(".config").join(APP_DIR)
|
||||
} else {
|
||||
let app_exe = current_exe().unwrap();
|
||||
let app_exe = dunce::canonicalize(app_exe).unwrap();
|
||||
let app_dir = app_exe.parent().unwrap();
|
||||
PathBuf::from(app_dir).join(".config").join(APP_DIR)
|
||||
if !PORTABLE_FLAG {
|
||||
home_dir().unwrap().join(".config").join(APP_DIR)
|
||||
} else {
|
||||
let app_exe = current_exe().unwrap();
|
||||
let app_exe = dunce::canonicalize(app_exe).unwrap();
|
||||
let app_dir = app_exe.parent().unwrap();
|
||||
PathBuf::from(app_dir).join(".config").join(APP_DIR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
home_dir().unwrap().join(".config").join(APP_DIR)
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
home_dir().unwrap().join(".config").join(APP_DIR)
|
||||
}
|
||||
|
||||
/// get the resources dir
|
||||
pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
|
||||
let res_dir = resource_dir(package_info, &Env::default())
|
||||
.unwrap()
|
||||
.join("resources");
|
||||
let res_dir = resource_dir(package_info, &Env::default())
|
||||
.unwrap()
|
||||
.join("resources");
|
||||
|
||||
unsafe {
|
||||
RESOURCE_DIR = Some(res_dir.clone());
|
||||
unsafe {
|
||||
RESOURCE_DIR = Some(res_dir.clone());
|
||||
|
||||
let ver = package_info.version.to_string();
|
||||
let ver_str = format!("v{ver}");
|
||||
APP_VERSION = Box::leak(Box::new(ver_str));
|
||||
}
|
||||
let ver = package_info.version.to_string();
|
||||
let ver_str = format!("v{ver}");
|
||||
APP_VERSION = Box::leak(Box::new(ver_str));
|
||||
}
|
||||
|
||||
res_dir
|
||||
res_dir
|
||||
}
|
||||
|
||||
/// profiles dir
|
||||
pub fn app_profiles_dir() -> PathBuf {
|
||||
app_home_dir().join("profiles")
|
||||
app_home_dir().join("profiles")
|
||||
}
|
||||
|
||||
/// logs dir
|
||||
pub fn app_logs_dir() -> PathBuf {
|
||||
app_home_dir().join("logs")
|
||||
app_home_dir().join("logs")
|
||||
}
|
||||
|
||||
pub fn clash_path() -> PathBuf {
|
||||
app_home_dir().join(CLASH_CONFIG)
|
||||
app_home_dir().join(CLASH_CONFIG)
|
||||
}
|
||||
|
||||
pub fn verge_path() -> PathBuf {
|
||||
app_home_dir().join(VERGE_CONFIG)
|
||||
app_home_dir().join(VERGE_CONFIG)
|
||||
}
|
||||
|
||||
pub fn profiles_path() -> PathBuf {
|
||||
app_home_dir().join(PROFILE_YAML)
|
||||
app_home_dir().join(PROFILE_YAML)
|
||||
}
|
||||
|
||||
pub fn profiles_temp_path() -> PathBuf {
|
||||
#[cfg(not(feature = "debug-yml"))]
|
||||
return temp_dir().join(PROFILE_TEMP);
|
||||
#[cfg(not(feature = "debug-yml"))]
|
||||
return temp_dir().join(PROFILE_TEMP);
|
||||
|
||||
#[cfg(feature = "debug-yml")]
|
||||
return app_home_dir().join(PROFILE_TEMP);
|
||||
#[cfg(feature = "debug-yml")]
|
||||
return app_home_dir().join(PROFILE_TEMP);
|
||||
}
|
||||
|
||||
pub fn clash_pid_path() -> PathBuf {
|
||||
unsafe { RESOURCE_DIR.clone().unwrap().join("clash.pid") }
|
||||
unsafe { RESOURCE_DIR.clone().unwrap().join("clash.pid") }
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
@@ -116,23 +116,23 @@ static SERVICE_PATH: &str = "clash-verge-service.exe";
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn service_path() -> PathBuf {
|
||||
unsafe {
|
||||
let res_dir = RESOURCE_DIR.clone().unwrap();
|
||||
res_dir.join(SERVICE_PATH)
|
||||
}
|
||||
unsafe {
|
||||
let res_dir = RESOURCE_DIR.clone().unwrap();
|
||||
res_dir.join(SERVICE_PATH)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn service_log_file() -> PathBuf {
|
||||
use chrono::Local;
|
||||
use chrono::Local;
|
||||
|
||||
let log_dir = app_logs_dir().join("service");
|
||||
let log_dir = app_logs_dir().join("service");
|
||||
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||
let log_file = format!("{}.log", local_time);
|
||||
let log_file = log_dir.join(log_file);
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||
let log_file = format!("{}.log", local_time);
|
||||
let log_file = log_dir.join(log_file);
|
||||
|
||||
std::fs::create_dir_all(&log_dir).unwrap();
|
||||
std::fs::create_dir_all(&log_dir).unwrap();
|
||||
|
||||
log_file
|
||||
log_file
|
||||
}
|
||||
|
||||
@@ -6,67 +6,67 @@ use std::str::FromStr;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub fn get_now() -> usize {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as _
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs() as _
|
||||
}
|
||||
|
||||
const ALPHABET: [char; 62] = [
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
|
||||
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
|
||||
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
|
||||
'V', 'W', 'X', 'Y', 'Z',
|
||||
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
|
||||
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
|
||||
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', '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}")
|
||||
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.find(key).and_then(|idx| {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
target.find(key).and_then(|idx| {
|
||||
let idx = idx + key.len();
|
||||
let value = &target[idx..];
|
||||
|
||||
match value.split(';').nth(0) {
|
||||
Some(value) => value.trim().parse(),
|
||||
None => value.trim().parse(),
|
||||
}
|
||||
.ok()
|
||||
})
|
||||
match value.split(';').nth(0) {
|
||||
Some(value) => value.trim().parse(),
|
||||
None => value.trim().parse(),
|
||||
}
|
||||
.ok()
|
||||
})
|
||||
}
|
||||
|
||||
/// open file
|
||||
/// use vscode by default
|
||||
pub fn open_file(path: PathBuf) -> Result<()> {
|
||||
// use vscode first
|
||||
if let Ok(code) = which::which("code") {
|
||||
let mut command = Command::new(&code);
|
||||
// use vscode first
|
||||
if let Ok(code) = which::which("code") {
|
||||
let mut command = Command::new(&code);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
if let Err(err) = command.creation_flags(0x08000000).arg(&path).spawn() {
|
||||
log::error!(target: "app", "failed to open with VScode `{err}`");
|
||||
open::that(path)?;
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
if let Err(err) = command.creation_flags(0x08000000).arg(&path).spawn() {
|
||||
log::error!(target: "app", "failed to open with VScode `{err}`");
|
||||
open::that(path)?;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
if let Err(err) = command.arg(&path).spawn() {
|
||||
log::error!(target: "app", "failed to open with VScode `{err}`");
|
||||
open::that(path)?;
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
if let Err(err) = command.arg(&path).spawn() {
|
||||
log::error!(target: "app", "failed to open with VScode `{err}`");
|
||||
open::that(path)?;
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
open::that(path)?;
|
||||
Ok(())
|
||||
open::that(path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
@@ -96,27 +96,27 @@ macro_rules! wrap_err {
|
||||
/// return the string literal error
|
||||
#[macro_export]
|
||||
macro_rules! ret_err {
|
||||
($str: expr) => {
|
||||
return Err($str.into())
|
||||
};
|
||||
($str: expr) => {
|
||||
return Err($str.into())
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_value() {
|
||||
let test_1 = "upload=111; download=2222; total=3333; expire=444";
|
||||
let test_2 = "attachment; filename=Clash.yaml";
|
||||
let test_1 = "upload=111; download=2222; total=3333; expire=444";
|
||||
let test_2 = "attachment; filename=Clash.yaml";
|
||||
|
||||
assert_eq!(parse_str::<usize>(test_1, "upload=").unwrap(), 111);
|
||||
assert_eq!(parse_str::<usize>(test_1, "download=").unwrap(), 2222);
|
||||
assert_eq!(parse_str::<usize>(test_1, "total=").unwrap(), 3333);
|
||||
assert_eq!(parse_str::<usize>(test_1, "expire=").unwrap(), 444);
|
||||
assert_eq!(
|
||||
parse_str::<String>(test_2, "filename=").unwrap(),
|
||||
format!("Clash.yaml")
|
||||
);
|
||||
assert_eq!(parse_str::<usize>(test_1, "upload=").unwrap(), 111);
|
||||
assert_eq!(parse_str::<usize>(test_1, "download=").unwrap(), 2222);
|
||||
assert_eq!(parse_str::<usize>(test_1, "total=").unwrap(), 3333);
|
||||
assert_eq!(parse_str::<usize>(test_1, "expire=").unwrap(), 444);
|
||||
assert_eq!(
|
||||
parse_str::<String>(test_2, "filename=").unwrap(),
|
||||
format!("Clash.yaml")
|
||||
);
|
||||
|
||||
assert_eq!(parse_str::<usize>(test_1, "aaa="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "upload1="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "expire1="), None);
|
||||
assert_eq!(parse_str::<usize>(test_2, "attachment="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "aaa="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "upload1="), None);
|
||||
assert_eq!(parse_str::<usize>(test_1, "expire1="), None);
|
||||
assert_eq!(parse_str::<usize>(test_2, "attachment="), None);
|
||||
}
|
||||
|
||||
@@ -12,94 +12,94 @@ use tauri::PackageInfo;
|
||||
|
||||
/// initialize this instance's log file
|
||||
fn init_log() -> Result<()> {
|
||||
let log_dir = dirs::app_logs_dir();
|
||||
if !log_dir.exists() {
|
||||
let _ = fs::create_dir_all(&log_dir);
|
||||
}
|
||||
let log_dir = dirs::app_logs_dir();
|
||||
if !log_dir.exists() {
|
||||
let _ = fs::create_dir_all(&log_dir);
|
||||
}
|
||||
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||
let log_file = format!("{}.log", local_time);
|
||||
let log_file = log_dir.join(log_file);
|
||||
let local_time = Local::now().format("%Y-%m-%d-%H%M%S").to_string();
|
||||
let log_file = format!("{}.log", local_time);
|
||||
let log_file = log_dir.join(log_file);
|
||||
|
||||
let time_format = "{d(%Y-%m-%d %H:%M:%S)} - {m}{n}";
|
||||
let stdout = ConsoleAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(time_format)))
|
||||
.build();
|
||||
let tofile = FileAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(time_format)))
|
||||
.build(log_file)?;
|
||||
let time_format = "{d(%Y-%m-%d %H:%M:%S)} - {m}{n}";
|
||||
let stdout = ConsoleAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(time_format)))
|
||||
.build();
|
||||
let tofile = FileAppender::builder()
|
||||
.encoder(Box::new(PatternEncoder::new(time_format)))
|
||||
.build(log_file)?;
|
||||
|
||||
let config = Config::builder()
|
||||
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||
.appender(Appender::builder().build("file", Box::new(tofile)))
|
||||
.logger(
|
||||
Logger::builder()
|
||||
.appenders(["file", "stdout"])
|
||||
.additive(false)
|
||||
.build("app", LevelFilter::Info),
|
||||
)
|
||||
.build(Root::builder().appender("stdout").build(LevelFilter::Info))?;
|
||||
let config = Config::builder()
|
||||
.appender(Appender::builder().build("stdout", Box::new(stdout)))
|
||||
.appender(Appender::builder().build("file", Box::new(tofile)))
|
||||
.logger(
|
||||
Logger::builder()
|
||||
.appenders(["file", "stdout"])
|
||||
.additive(false)
|
||||
.build("app", LevelFilter::Info),
|
||||
)
|
||||
.build(Root::builder().appender("stdout").build(LevelFilter::Info))?;
|
||||
|
||||
log4rs::init_config(config)?;
|
||||
log4rs::init_config(config)?;
|
||||
|
||||
Ok(())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Initialize all the files from resources
|
||||
pub fn init_config() -> Result<()> {
|
||||
let _ = init_log();
|
||||
let _ = init_log();
|
||||
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let profiles_dir = dirs::app_profiles_dir();
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let profiles_dir = dirs::app_profiles_dir();
|
||||
|
||||
if !app_dir.exists() {
|
||||
let _ = fs::create_dir_all(&app_dir);
|
||||
}
|
||||
if !profiles_dir.exists() {
|
||||
let _ = fs::create_dir_all(&profiles_dir);
|
||||
}
|
||||
if !app_dir.exists() {
|
||||
let _ = fs::create_dir_all(&app_dir);
|
||||
}
|
||||
if !profiles_dir.exists() {
|
||||
let _ = fs::create_dir_all(&profiles_dir);
|
||||
}
|
||||
|
||||
// target path
|
||||
let clash_path = app_dir.join("config.yaml");
|
||||
let verge_path = app_dir.join("verge.yaml");
|
||||
let profile_path = app_dir.join("profiles.yaml");
|
||||
// target path
|
||||
let clash_path = app_dir.join("config.yaml");
|
||||
let verge_path = app_dir.join("verge.yaml");
|
||||
let profile_path = app_dir.join("profiles.yaml");
|
||||
|
||||
if !clash_path.exists() {
|
||||
fs::File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
|
||||
}
|
||||
if !verge_path.exists() {
|
||||
fs::File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
|
||||
}
|
||||
if !profile_path.exists() {
|
||||
fs::File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
|
||||
}
|
||||
Ok(())
|
||||
if !clash_path.exists() {
|
||||
fs::File::create(clash_path)?.write(tmpl::CLASH_CONFIG)?;
|
||||
}
|
||||
if !verge_path.exists() {
|
||||
fs::File::create(verge_path)?.write(tmpl::VERGE_CONFIG)?;
|
||||
}
|
||||
if !profile_path.exists() {
|
||||
fs::File::create(profile_path)?.write(tmpl::PROFILES_CONFIG)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// initialize app
|
||||
pub fn init_resources(package_info: &PackageInfo) {
|
||||
// create app dir
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let res_dir = dirs::app_resources_dir(package_info);
|
||||
// create app dir
|
||||
let app_dir = dirs::app_home_dir();
|
||||
let res_dir = dirs::app_resources_dir(package_info);
|
||||
|
||||
if !app_dir.exists() {
|
||||
let _ = fs::create_dir_all(&app_dir);
|
||||
}
|
||||
|
||||
// copy the resource file
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
let _ = fs::copy(mmdb_tmpl, mmdb_path);
|
||||
}
|
||||
|
||||
// copy the wintun.dll
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let wintun_path = app_dir.join("wintun.dll");
|
||||
let wintun_tmpl = res_dir.join("wintun.dll");
|
||||
if !wintun_path.exists() && wintun_tmpl.exists() {
|
||||
let _ = fs::copy(wintun_tmpl, wintun_path);
|
||||
if !app_dir.exists() {
|
||||
let _ = fs::create_dir_all(&app_dir);
|
||||
}
|
||||
|
||||
// copy the resource file
|
||||
let mmdb_path = app_dir.join("Country.mmdb");
|
||||
let mmdb_tmpl = res_dir.join("Country.mmdb");
|
||||
if !mmdb_path.exists() && mmdb_tmpl.exists() {
|
||||
let _ = fs::copy(mmdb_tmpl, mmdb_path);
|
||||
}
|
||||
|
||||
// copy the wintun.dll
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let wintun_path = app_dir.join("wintun.dll");
|
||||
let wintun_tmpl = res_dir.join("wintun.dll");
|
||||
if !wintun_path.exists() && wintun_tmpl.exists() {
|
||||
let _ = fs::copy(wintun_tmpl, wintun_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,110 +1,110 @@
|
||||
use crate::{
|
||||
core::{tray, Core},
|
||||
data::Data,
|
||||
utils::init,
|
||||
utils::server,
|
||||
core::{tray, Core},
|
||||
data::Data,
|
||||
utils::init,
|
||||
utils::server,
|
||||
};
|
||||
use tauri::{App, AppHandle, Manager};
|
||||
|
||||
/// handle something when start app
|
||||
pub fn resolve_setup(app: &App) {
|
||||
let _ = app
|
||||
.tray_handle()
|
||||
.set_menu(tray::Tray::tray_menu(&app.app_handle()));
|
||||
let _ = app
|
||||
.tray_handle()
|
||||
.set_menu(tray::Tray::tray_menu(&app.app_handle()));
|
||||
|
||||
init::init_resources(app.package_info());
|
||||
init::init_resources(app.package_info());
|
||||
|
||||
let silent_start = {
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
let singleton = verge.app_singleton_port.clone();
|
||||
let silent_start = {
|
||||
let global = Data::global();
|
||||
let verge = global.verge.lock();
|
||||
let singleton = verge.app_singleton_port.clone();
|
||||
|
||||
// setup a simple http server for singleton
|
||||
server::embed_server(&app.app_handle(), singleton);
|
||||
// setup a simple http server for singleton
|
||||
server::embed_server(&app.app_handle(), singleton);
|
||||
|
||||
verge.enable_silent_start.clone().unwrap_or(false)
|
||||
};
|
||||
verge.enable_silent_start.clone().unwrap_or(false)
|
||||
};
|
||||
|
||||
// core should be initialized after init_app fix #122
|
||||
let core = Core::global();
|
||||
core.init(app.app_handle());
|
||||
// core should be initialized after init_app fix #122
|
||||
let core = Core::global();
|
||||
core.init(app.app_handle());
|
||||
|
||||
if !silent_start {
|
||||
create_window(&app.app_handle());
|
||||
}
|
||||
if !silent_start {
|
||||
create_window(&app.app_handle());
|
||||
}
|
||||
}
|
||||
|
||||
/// reset system proxy
|
||||
pub fn resolve_reset() {
|
||||
let core = Core::global();
|
||||
let mut sysopt = core.sysopt.lock();
|
||||
crate::log_if_err!(sysopt.reset_sysproxy());
|
||||
drop(sysopt);
|
||||
let core = Core::global();
|
||||
let mut sysopt = core.sysopt.lock();
|
||||
crate::log_if_err!(sysopt.reset_sysproxy());
|
||||
drop(sysopt);
|
||||
|
||||
let mut service = core.service.lock();
|
||||
crate::log_if_err!(service.stop());
|
||||
let mut service = core.service.lock();
|
||||
crate::log_if_err!(service.stop());
|
||||
}
|
||||
|
||||
/// create main window
|
||||
pub fn create_window(app_handle: &AppHandle) {
|
||||
if let Some(window) = app_handle.get_window("main") {
|
||||
let _ = window.unminimize();
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
return;
|
||||
}
|
||||
|
||||
let builder = tauri::window::WindowBuilder::new(
|
||||
app_handle,
|
||||
"main".to_string(),
|
||||
tauri::WindowUrl::App("index.html".into()),
|
||||
)
|
||||
.title("Clash Verge")
|
||||
.center()
|
||||
.fullscreen(false)
|
||||
.min_inner_size(600.0, 520.0);
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use crate::utils::winhelp;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
use window_shadows::set_shadow;
|
||||
use window_vibrancy::apply_blur;
|
||||
|
||||
match builder
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.inner_size(800.0, 636.0)
|
||||
.build()
|
||||
{
|
||||
Ok(_) => {
|
||||
let app_handle = app_handle.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
|
||||
if let Some(window) = app_handle.get_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = set_shadow(&window, true);
|
||||
|
||||
if !winhelp::is_win11() {
|
||||
let _ = apply_blur(&window, None);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "{err}"),
|
||||
if let Some(window) = app_handle.get_window("main") {
|
||||
let _ = window.unminimize();
|
||||
let _ = window.show();
|
||||
let _ = window.set_focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::log_if_err!(builder.decorations(true).inner_size(800.0, 642.0).build());
|
||||
let builder = tauri::window::WindowBuilder::new(
|
||||
app_handle,
|
||||
"main".to_string(),
|
||||
tauri::WindowUrl::App("index.html".into()),
|
||||
)
|
||||
.title("Clash Verge")
|
||||
.center()
|
||||
.fullscreen(false)
|
||||
.min_inner_size(600.0, 520.0);
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
crate::log_if_err!(builder
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.inner_size(800.0, 636.0)
|
||||
.build());
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
use crate::utils::winhelp;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
use window_shadows::set_shadow;
|
||||
use window_vibrancy::apply_blur;
|
||||
|
||||
match builder
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.inner_size(800.0, 636.0)
|
||||
.build()
|
||||
{
|
||||
Ok(_) => {
|
||||
let app_handle = app_handle.clone();
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
|
||||
if let Some(window) = app_handle.get_window("main") {
|
||||
let _ = window.show();
|
||||
let _ = set_shadow(&window, true);
|
||||
|
||||
if !winhelp::is_win11() {
|
||||
let _ = apply_blur(&window, None);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(err) => log::error!(target: "app", "{err}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
crate::log_if_err!(builder.decorations(true).inner_size(800.0, 642.0).build());
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
crate::log_if_err!(builder
|
||||
.decorations(false)
|
||||
.transparent(true)
|
||||
.inner_size(800.0, 636.0)
|
||||
.build());
|
||||
}
|
||||
|
||||
@@ -13,32 +13,32 @@ const SERVER_PORT: u16 = 11233;
|
||||
|
||||
/// check whether there is already exists
|
||||
pub fn check_singleton() -> Result<(), ()> {
|
||||
let verge = Verge::new();
|
||||
let port = verge.app_singleton_port.unwrap_or(SERVER_PORT);
|
||||
let verge = Verge::new();
|
||||
let port = verge.app_singleton_port.unwrap_or(SERVER_PORT);
|
||||
|
||||
if !local_port_available(port) {
|
||||
tauri::async_runtime::block_on(async {
|
||||
let url = format!("http://127.0.0.1:{}/commands/visible", port);
|
||||
reqwest::get(url).await.unwrap();
|
||||
Err(())
|
||||
})
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
if !local_port_available(port) {
|
||||
tauri::async_runtime::block_on(async {
|
||||
let url = format!("http://127.0.0.1:{}/commands/visible", port);
|
||||
reqwest::get(url).await.unwrap();
|
||||
Err(())
|
||||
})
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The embed server only be used to implement singleton process
|
||||
/// maybe it can be used as pac server later
|
||||
pub fn embed_server(app_handle: &AppHandle, port: Option<u16>) {
|
||||
let app_handle = app_handle.clone();
|
||||
let port = port.unwrap_or(SERVER_PORT);
|
||||
let app_handle = app_handle.clone();
|
||||
let port = port.unwrap_or(SERVER_PORT);
|
||||
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let commands = warp::path!("commands" / "visible").map(move || {
|
||||
resolve::create_window(&app_handle);
|
||||
return format!("ok");
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let commands = warp::path!("commands" / "visible").map(move || {
|
||||
resolve::create_window(&app_handle);
|
||||
return format!("ok");
|
||||
});
|
||||
|
||||
warp::serve(commands).bind(([127, 0, 0, 1], port)).await;
|
||||
});
|
||||
|
||||
warp::serve(commands).bind(([127, 0, 0, 1], port)).await;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,69 +1,69 @@
|
||||
#![cfg(target_os = "windows")]
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
//!
|
||||
//! From https://github.com/tauri-apps/window-vibrancy/blob/dev/src/windows.rs
|
||||
//!
|
||||
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
System::{LibraryLoader::*, SystemInformation::*},
|
||||
};
|
||||
|
||||
fn get_function_impl(library: &str, function: &str) -> Option<FARPROC> {
|
||||
assert_eq!(library.chars().last(), Some('\0'));
|
||||
assert_eq!(function.chars().last(), Some('\0'));
|
||||
|
||||
let module = unsafe { LoadLibraryA(library.as_ptr()) };
|
||||
if module == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(unsafe { GetProcAddress(module, function.as_ptr()) })
|
||||
}
|
||||
|
||||
macro_rules! get_function {
|
||||
($lib:expr, $func:ident) => {
|
||||
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')).map(|f| unsafe {
|
||||
std::mem::transmute::<::windows_sys::Win32::Foundation::FARPROC, $func>(f)
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns a tuple of (major, minor, buildnumber)
|
||||
fn get_windows_ver() -> Option<(u32, u32, u32)> {
|
||||
type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
|
||||
let handle = get_function!("ntdll.dll", RtlGetVersion);
|
||||
if let Some(rtl_get_version) = handle {
|
||||
unsafe {
|
||||
let mut vi = OSVERSIONINFOW {
|
||||
dwOSVersionInfoSize: 0,
|
||||
dwMajorVersion: 0,
|
||||
dwMinorVersion: 0,
|
||||
dwBuildNumber: 0,
|
||||
dwPlatformId: 0,
|
||||
szCSDVersion: [0; 128],
|
||||
};
|
||||
|
||||
let status = (rtl_get_version)(&mut vi as _);
|
||||
|
||||
if status >= 0 {
|
||||
Some((vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_win11() -> bool {
|
||||
let v = get_windows_ver().unwrap_or_default();
|
||||
v.2 >= 22000
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_version() {
|
||||
dbg!(get_windows_ver().unwrap_or_default());
|
||||
}
|
||||
#![cfg(target_os = "windows")]
|
||||
#![allow(non_snake_case)]
|
||||
#![allow(non_camel_case_types)]
|
||||
|
||||
//!
|
||||
//! From https://github.com/tauri-apps/window-vibrancy/blob/dev/src/windows.rs
|
||||
//!
|
||||
|
||||
use windows_sys::Win32::{
|
||||
Foundation::*,
|
||||
System::{LibraryLoader::*, SystemInformation::*},
|
||||
};
|
||||
|
||||
fn get_function_impl(library: &str, function: &str) -> Option<FARPROC> {
|
||||
assert_eq!(library.chars().last(), Some('\0'));
|
||||
assert_eq!(function.chars().last(), Some('\0'));
|
||||
|
||||
let module = unsafe { LoadLibraryA(library.as_ptr()) };
|
||||
if module == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(unsafe { GetProcAddress(module, function.as_ptr()) })
|
||||
}
|
||||
|
||||
macro_rules! get_function {
|
||||
($lib:expr, $func:ident) => {
|
||||
get_function_impl(concat!($lib, '\0'), concat!(stringify!($func), '\0')).map(|f| unsafe {
|
||||
std::mem::transmute::<::windows_sys::Win32::Foundation::FARPROC, $func>(f)
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns a tuple of (major, minor, buildnumber)
|
||||
fn get_windows_ver() -> Option<(u32, u32, u32)> {
|
||||
type RtlGetVersion = unsafe extern "system" fn(*mut OSVERSIONINFOW) -> i32;
|
||||
let handle = get_function!("ntdll.dll", RtlGetVersion);
|
||||
if let Some(rtl_get_version) = handle {
|
||||
unsafe {
|
||||
let mut vi = OSVERSIONINFOW {
|
||||
dwOSVersionInfoSize: 0,
|
||||
dwMajorVersion: 0,
|
||||
dwMinorVersion: 0,
|
||||
dwBuildNumber: 0,
|
||||
dwPlatformId: 0,
|
||||
szCSDVersion: [0; 128],
|
||||
};
|
||||
|
||||
let status = (rtl_get_version)(&mut vi as _);
|
||||
|
||||
if status >= 0 {
|
||||
Some((vi.dwMajorVersion, vi.dwMinorVersion, vi.dwBuildNumber))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_win11() -> bool {
|
||||
let v = get_windows_ver().unwrap_or_default();
|
||||
v.2 >= 22000
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_version() {
|
||||
dbg!(get_windows_ver().unwrap_or_default());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user