Skip to content

Commit

Permalink
perf(app): optimize CPU and memory usage
Browse files Browse the repository at this point in the history
  • Loading branch information
a145789 committed Jul 14, 2024
1 parent 0a1deeb commit edd7a7f
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 73 deletions.
52 changes: 3 additions & 49 deletions src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,58 +4,12 @@
mod plugins;
mod tray;

use plugins::system_info;
use plugins::window::{self, show_window, MAIN_WINDOW_LABEL};
use sysinfo::{Networks, RefreshKind, System};
use tauri::Manager;
use tauri::{async_runtime, command, generate_context, generate_handler, Builder, WindowEvent};
use tauri::{async_runtime, generate_context, Builder, WindowEvent};
use tauri_plugin_autostart::MacosLauncher;

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct SystemInfo {
memory_usage: f32,
cpu_usage: f32,
network_speed_up: u64,
network_speed_down: u64,
}

#[command]
fn get_sys_info() -> SystemInfo {
let mut sys = System::new_with_specifics(RefreshKind::everything().without_processes());
sys.refresh_all();

// Raw
let total_memory = sys.total_memory();
let used_memory = sys.used_memory();
let memory_usage = used_memory as f32 / total_memory as f32 * 100.0;

// cpu 占用
std::thread::sleep(sysinfo::MINIMUM_CPU_UPDATE_INTERVAL);
sys.refresh_cpu();
let cpu_usage =
sys.cpus().iter().map(|cpu| cpu.cpu_usage()).sum::<f32>() / sys.cpus().len() as f32;

let mut networks = Networks::new_with_refreshed_list();
networks.refresh_list();
let network_speed_up = networks
.iter()
.map(|(_, data)| data.transmitted())
.sum::<u64>()
/ networks.len() as u64;
let network_speed_down = networks
.iter()
.map(|(_, data)| data.received())
.sum::<u64>()
/ networks.len() as u64;

SystemInfo {
memory_usage,
cpu_usage,
network_speed_up,
network_speed_down,
}
}

fn main() {
Builder::default()
.setup(|app| {
Expand All @@ -81,10 +35,10 @@ fn main() {
))
// 自定义的窗口管理插件
.plugin(window::init())
.plugin(system_info::init())
// 系统托盘:https://tauri.app/v1/guides/features/system-tray
.system_tray(tray::menu())
.on_system_tray_event(tray::handler)
.invoke_handler(generate_handler![get_sys_info])
// 让 app 保持在后台运行:https://tauri.app/v1/guides/features/system-tray/#preventing-the-app-from-closing
.on_window_event(|event| match event.event() {
WindowEvent::CloseRequested { api, .. } => {
Expand Down
2 changes: 2 additions & 0 deletions src-tauri/src/plugins/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
pub mod window;

pub mod system_info;
88 changes: 88 additions & 0 deletions src-tauri/src/plugins/system_info.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
use std::sync::Mutex;
use sysinfo::{Networks, RefreshKind, System};

use tauri::{
command, generate_handler,
plugin::{Builder, TauriPlugin},
Manager, Wry,
};

#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SystemInfo {
memory_usage: f32,
cpu_usage: f32,
network_speed_up: u64,
network_speed_down: u64,
}

pub struct SysInfoState {
pub sysinfo: Mutex<SysInfo>,
}
/// A Mute Wrapper for sysinfo crate's System struct
pub struct SysInfo {
pub sys: System,
}

impl Default for SysInfoState {
fn default() -> SysInfoState {
SysInfoState {
sysinfo: Mutex::new(SysInfo {
sys: System::new_with_specifics(RefreshKind::everything().without_processes()),
}),
}
}
}

#[command]
pub fn get_sys_info(state: tauri::State<'_, SysInfoState>) -> SystemInfo {
// 锁定 sysinfo 并将其绑定到一个变量上
let mut sysinfo_guard = state.sysinfo.lock().unwrap();

sysinfo_guard.sys.refresh_memory();
let total_memory = sysinfo_guard.sys.total_memory();
let used_memory = sysinfo_guard.sys.used_memory();
let memory_usage = used_memory as f32 / total_memory as f32 * 100.0;

// // cpu 占用
sysinfo_guard.sys.refresh_cpu();

let cpu_usage = sysinfo_guard
.sys
.cpus()
.iter()
.map(|cpu| cpu.cpu_usage())
.sum::<f32>()
/ sysinfo_guard.sys.cpus().len() as f32;

let mut networks = Networks::new_with_refreshed_list();
networks.refresh_list();
let network_speed_up = networks
.iter()
.map(|(_, data)| data.transmitted())
.sum::<u64>()
/ networks.len() as u64;
let network_speed_down = networks
.iter()
.map(|(_, data)| data.received())
.sum::<u64>()
/ networks.len() as u64;

SystemInfo {
memory_usage,
cpu_usage,
network_speed_up,
network_speed_down,
}
}

pub fn init() -> TauriPlugin<Wry> {
Builder::new("system_info")
.setup(move |app| {
app.manage(SysInfoState::default());

Ok(())
})
.invoke_handler(generate_handler![get_sys_info,])
.build()
}
4 changes: 3 additions & 1 deletion src-tauri/src/plugins/window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ pub async fn create_window(app_handle: AppHandle, label: String, mut options: Wi
#[command]
pub async fn show_window(window: Window) {
window.show().unwrap();
window.unminimize().unwrap();
window.set_focus().unwrap();

window.emit("window-shown", true).unwrap();
}

// 隐藏窗口
#[command]
pub async fn hide_window(window: Window) {
window.hide().unwrap();
window.emit("window-hidden", true).unwrap();
}

pub fn init() -> TauriPlugin<Wry> {
Expand Down
45 changes: 22 additions & 23 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,12 @@ function setElement(id: string, num: number) {
}
}

let timer: number
async function getSystemInfo() {
clearTimeout(timer)

const { cpuUsage, memoryUsage, networkSpeedDown, networkSpeedUp } =
(await invoke("get_sys_info")) as SystemInfo
(await invoke("plugin:system_info|get_sys_info")) as SystemInfo

setElement("#cpu-usage", cpuUsage)
setElement("#memory-usage", memoryUsage)
Expand All @@ -47,57 +50,53 @@ async function getSystemInfo() {
document.querySelector("#network-usage")!.textContent = `↓ ${formatBytes(
networkSpeedDown,
)} / ↑ ${formatBytes(networkSpeedUp)}`
}

let timer: number
function loopGetInfo() {
getSystemInfo()
timer = setInterval(getSystemInfo, 1000)
setTimeout(() => {
getSystemInfo()
}, 1200)
}

function hiddenWindow() {
console.log(222)

invoke("plugin:window|hide_window")
}

window.onload = async () => {
console.log("load")
async function dragWindow() {
await appWindow.startDragging()
}

window.onload = async () => {
listen("tray-click", () => {
invoke("plugin:window|show_window")
clearInterval(timer)
loopGetInfo()
getSystemInfo()
})

listen("screen-center", async () => {
invoke("plugin:window|show_window")
await appWindow.center()
clearInterval(timer)
loopGetInfo()
getSystemInfo()
})

listen("hidden", () => {
clearInterval(timer)
listen("window-hidden", () => {
clearTimeout(timer)
})

await appWindow.setPosition(new LogicalPosition(1730, 810))

window.addEventListener("mousedown", async () => {
await appWindow.startDragging()
})

clearInterval(timer)
loopGetInfo()
getSystemInfo()

// 禁用键盘事件
document.addEventListener("keydown", (e) => e.preventDefault())
// 禁用滚轮和鼠标右键
// // 禁用滚轮和鼠标右键
document.addEventListener("wheel", (e) => e.preventDefault())
document.addEventListener("contextmenu", (e) => e.preventDefault())
// 禁用选择文本
document.addEventListener("selectstart", (e) => e.preventDefault())

// 监听鼠标左键双击
document.addEventListener("dblclick", hiddenWindow)

// biome-ignore lint/style/noNonNullAssertion: <explanation>
document.querySelector(".container")!.addEventListener("mousedown", () => {
dragWindow()
})
}

0 comments on commit edd7a7f

Please sign in to comment.