Browse Source

feat: light mode wip (#96)

* 关闭窗口释放UI资源

* windows 还有左键点击事件

* 兼容enhance profile

* bug 修复
ctaoist 3 years ago
parent
commit
5164aec37b

+ 10 - 2
src-tauri/src/core/mod.rs

@@ -48,9 +48,10 @@ pub struct Core {
 impl Core {
 impl Core {
   pub fn new() -> Core {
   pub fn new() -> Core {
     let clash = Clash::new();
     let clash = Clash::new();
-    let verge = Verge::new();
+    let mut verge = Verge::new();
     let profiles = Profiles::new();
     let profiles = Profiles::new();
     let service = Service::new();
     let service = Service::new();
+    verge.launch_flag = Some(true);
 
 
     Core {
     Core {
       clash: Arc::new(Mutex::new(clash)),
       clash: Arc::new(Mutex::new(clash)),
@@ -382,7 +383,14 @@ impl Core {
       result.error.map(|err| log::error!("{err}"));
       result.error.map(|err| log::error!("{err}"));
     });
     });
 
 
-    window.emit("script-handler", payload).unwrap();
+    let mut verge = self.verge.lock();
+    let silent_start = verge.enable_silent_start.clone();
+    if silent_start.unwrap_or(false) && verge.launch_flag.unwrap_or(false) {
+      window.emit("script-handler-close", payload).unwrap();
+      verge.launch_flag = Some(false);
+    } else {
+      window.emit("script-handler", payload).unwrap();
+    }
 
 
     Ok(())
     Ok(())
   }
   }

+ 4 - 0
src-tauri/src/core/verge.rs

@@ -37,6 +37,10 @@ pub struct Verge {
   /// enable proxy guard
   /// enable proxy guard
   pub enable_proxy_guard: Option<bool>,
   pub enable_proxy_guard: Option<bool>,
 
 
+  /// launch flag
+  #[serde(skip_serializing)]
+  pub launch_flag: Option<bool>,
+
   /// set system proxy bypass
   /// set system proxy bypass
   pub system_proxy_bypass: Option<String>,
   pub system_proxy_bypass: Option<String>,
 
 

+ 36 - 19
src-tauri/src/main.rs

@@ -44,10 +44,23 @@ fn main() -> std::io::Result<()> {
     .on_system_tray_event(move |app_handle, event| match event {
     .on_system_tray_event(move |app_handle, event| match event {
       SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
       SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
         "open_window" => {
         "open_window" => {
-          let window = app_handle.get_window("main").unwrap();
-          window.unminimize().unwrap();
-          window.show().unwrap();
-          window.set_focus().unwrap();
+          tauri::window::WindowBuilder::new(
+            app_handle,
+            "main".to_string(),
+            tauri::WindowUrl::App("index.html".into()),
+          )
+          .title("Clash Verge")
+          .center()
+          .decorations(false)
+          .fullscreen(false)
+          .inner_size(800.0, 636.0)
+          .min_inner_size(600.0, 520.0)
+          .build()
+          .err()
+          .and_then(|e| {
+            log::error!("{e}");
+            Some(0)
+          });
         }
         }
         "system_proxy" => {
         "system_proxy" => {
           let core = app_handle.state::<core::Core>();
           let core = app_handle.state::<core::Core>();
@@ -91,10 +104,23 @@ fn main() -> std::io::Result<()> {
       },
       },
       #[cfg(target_os = "windows")]
       #[cfg(target_os = "windows")]
       SystemTrayEvent::LeftClick { .. } => {
       SystemTrayEvent::LeftClick { .. } => {
-        let window = app_handle.get_window("main").unwrap();
-        window.unminimize().unwrap();
-        window.show().unwrap();
-        window.set_focus().unwrap();
+        tauri::window::WindowBuilder::new(
+          app_handle,
+          "main".to_string(),
+          tauri::WindowUrl::App("index.html".into()),
+        )
+        .title("Clash Verge")
+        .center()
+        .decorations(false)
+        .fullscreen(false)
+        .inner_size(800.0, 636.0)
+        .min_inner_size(600.0, 520.0)
+        .build()
+        .err()
+        .and_then(|e| {
+          log::error!("{e}");
+          Some(0)
+        });
       }
       }
       _ => {}
       _ => {}
     })
     })
@@ -156,17 +182,8 @@ fn main() -> std::io::Result<()> {
     .build(tauri::generate_context!())
     .build(tauri::generate_context!())
     .expect("error while running tauri application")
     .expect("error while running tauri application")
     .run(|app_handle, e| match e {
     .run(|app_handle, e| match e {
-      tauri::RunEvent::WindowEvent { label, event, .. } => match event {
-        tauri::WindowEvent::CloseRequested { api, .. } => {
-          let app_handle = app_handle.clone();
-          api.prevent_close();
-          app_handle.get_window(&label).unwrap().hide().unwrap();
-        }
-        _ => {}
-      },
-      tauri::RunEvent::ExitRequested { .. } => {
-        resolve::resolve_reset(app_handle);
-        api::process::kill_children();
+      tauri::RunEvent::ExitRequested { api, .. } => {
+        api.prevent_exit();
       }
       }
       tauri::RunEvent::Exit => {
       tauri::RunEvent::Exit => {
         resolve::resolve_reset(app_handle);
         resolve::resolve_reset(app_handle);

+ 1 - 1
src/components/layout/layout-control.tsx

@@ -30,7 +30,7 @@ const LayoutControl = () => {
       <Button
       <Button
         size="small"
         size="small"
         sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
         sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
-        onClick={() => appWindow.hide()}
+        onClick={() => appWindow.close()}
       >
       >
         <CloseRounded fontSize="small" />
         <CloseRounded fontSize="small" />
       </Button>
       </Button>

+ 1 - 1
src/pages/_layout.tsx

@@ -35,7 +35,7 @@ const Layout = () => {
 
 
   useEffect(() => {
   useEffect(() => {
     window.addEventListener("keydown", (e) => {
     window.addEventListener("keydown", (e) => {
-      if (e.key === "Escape") appWindow.hide();
+      if (e.key === "Escape") appWindow.close();
     });
     });
 
 
     listen("verge://refresh-clash-config", async () => {
     listen("verge://refresh-clash-config", async () => {

+ 18 - 9
src/services/enhance.ts

@@ -1,4 +1,5 @@
-import { emit, listen } from "@tauri-apps/api/event";
+import { emit, listen, Event } from "@tauri-apps/api/event";
+import { appWindow } from "@tauri-apps/api/window";
 import { CmdType } from "./types";
 import { CmdType } from "./types";
 import ignoreCase from "../utils/ignore-case";
 import ignoreCase from "../utils/ignore-case";
 
 
@@ -124,21 +125,29 @@ class Enhance {
     return this.resultMap.get(uid);
     return this.resultMap.get(uid);
   }
   }
 
 
+  async enhanceHandler(event: Event<unknown>) {
+    const payload = event.payload as CmdType.EnhancedPayload;
+
+    const result = await this.runner(payload).catch((err: any) => ({
+      data: null,
+      status: "error",
+      error: err.message,
+    }));
+
+    emit(payload.callback, JSON.stringify(result)).catch(console.error);
+  }
   // setup the handler
   // setup the handler
   setup() {
   setup() {
     if (this.isSetup) return;
     if (this.isSetup) return;
     this.isSetup = true;
     this.isSetup = true;
 
 
     listen("script-handler", async (event) => {
     listen("script-handler", async (event) => {
-      const payload = event.payload as CmdType.EnhancedPayload;
-
-      const result = await this.runner(payload).catch((err: any) => ({
-        data: null,
-        status: "error",
-        error: err.message,
-      }));
+      await this.enhanceHandler(event);
+    });
 
 
-      emit(payload.callback, JSON.stringify(result)).catch(console.error);
+    listen("script-handler-close", async (event) => {
+      await this.enhanceHandler(event);
+      appWindow.close();
     });
     });
   }
   }