feat: implement a simple singleton process

This commit is contained in:
GyDi
2021-12-23 01:35:17 +08:00
parent 7cf8fd800f
commit 34725b517b
5 changed files with 286 additions and 1 deletions

View File

@@ -12,7 +12,11 @@ mod utils;
use crate::{
events::state,
utils::{clash::put_clash_profile, config::read_verge},
utils::{
clash::put_clash_profile,
config::read_verge,
server::{check_singleton, embed_server},
},
};
use std::sync::{Arc, Mutex};
use tauri::{
@@ -21,6 +25,11 @@ use tauri::{
};
fn main() -> std::io::Result<()> {
if check_singleton().is_err() {
println!("app exists");
return Ok(());
}
let sub_menu = SystemTraySubmenu::new(
"出站规则",
SystemTrayMenu::new()
@@ -76,6 +85,9 @@ fn main() -> std::io::Result<()> {
.build(tauri::generate_context!())
.expect("error while running tauri application");
// a simple http server
embed_server(&app.handle());
// init app config
utils::init::init_app(app.package_info());
// run clash sidecar

View File

@@ -5,4 +5,5 @@ pub mod clash;
pub mod config;
pub mod fetch;
pub mod init;
pub mod server;
pub mod sysopt;

View File

@@ -0,0 +1,38 @@
extern crate warp;
use port_scanner::local_port_available;
use tauri::{AppHandle, Manager};
use warp::Filter;
const SERVER_PORT: u16 = 33333;
/// check whether there is already exists
pub fn check_singleton() -> Result<(), ()> {
if !local_port_available(SERVER_PORT) {
tauri::async_runtime::block_on(async {
let url = format!("http://127.0.0.1:{}/commands/visible", SERVER_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: &AppHandle) {
let window = app.get_window("main").unwrap();
let commands = warp::path!("commands" / "visible").map(move || {
window.show().unwrap();
window.set_focus().unwrap();
return format!("ok");
});
tauri::async_runtime::spawn(async move {
warp::serve(commands)
.bind(([127, 0, 0, 1], SERVER_PORT))
.await;
});
}