Undo formatting

This commit is contained in:
Pinguin2001 2024-11-06 18:54:38 +01:00
parent 5bc740aaae
commit a381e0c260

View File

@ -1,12 +1,20 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::Instant;
use sysinfo::{ use sysinfo::{
CpuExt, DiskExt, NetworkExt, NetworksExt, PidExt, ProcessExt, ProcessStatus, System, SystemExt, System,
ProcessStatus,
NetworksExt,
NetworkExt,
DiskExt,
SystemExt,
CpuExt,
ProcessExt,
PidExt,
}; };
use tauri::State; use tauri::State;
use std::sync::Mutex;
use std::collections::HashMap;
use std::time::Instant;
struct AppState { struct AppState {
sys: Mutex<System>, sys: Mutex<System>,
@ -20,16 +28,8 @@ impl AppState {
sys.refresh_all(); sys.refresh_all();
// Initialize network stats // Initialize network stats
let initial_rx = sys let initial_rx = sys.networks().iter().map(|(_, data)| data.total_received()).sum();
.networks() let initial_tx = sys.networks().iter().map(|(_, data)| data.total_transmitted()).sum();
.iter()
.map(|(_, data)| data.total_received())
.sum();
let initial_tx = sys
.networks()
.iter()
.map(|(_, data)| data.total_transmitted())
.sum();
Self { Self {
sys: Mutex::new(sys), sys: Mutex::new(sys),
@ -76,18 +76,13 @@ pub struct SystemStats {
} }
#[tauri::command] #[tauri::command]
async fn get_processes( async fn get_processes(state: State<'_, AppState>) -> Result<(Vec<ProcessInfo>, SystemStats), String> {
state: State<'_, AppState>,
) -> Result<(Vec<ProcessInfo>, SystemStats), String> {
let processes_data; let processes_data;
let system_stats; let system_stats;
// Scope for system lock // Scope for system lock
{ {
let mut sys = state let mut sys = state.sys.lock().map_err(|_| "Failed to lock system state")?;
.sys
.lock()
.map_err(|_| "Failed to lock system state")?;
sys.refresh_all(); sys.refresh_all();
sys.refresh_networks(); sys.refresh_networks();
sys.refresh_disks_list(); sys.refresh_disks_list();
@ -112,23 +107,12 @@ async fn get_processes(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// Calculate total network I/O // Calculate total network I/O
let mut last_update = state let mut last_update = state.last_network_update.lock().map_err(|_| "Failed to lock network state")?;
.last_network_update
.lock()
.map_err(|_| "Failed to lock network state")?;
let elapsed = last_update.0.elapsed().as_secs_f64(); let elapsed = last_update.0.elapsed().as_secs_f64();
let current_time = Instant::now(); let current_time = Instant::now();
let current_rx: u64 = sys let current_rx: u64 = sys.networks().iter().map(|(_, data)| data.total_received()).sum();
.networks() let current_tx: u64 = sys.networks().iter().map(|(_, data)| data.total_transmitted()).sum();
.iter()
.map(|(_, data)| data.total_received())
.sum();
let current_tx: u64 = sys
.networks()
.iter()
.map(|(_, data)| data.total_transmitted())
.sum();
let network_stats = ( let network_stats = (
((current_rx - last_update.1) as f64 / elapsed) as u64, ((current_rx - last_update.1) as f64 / elapsed) as u64,
@ -138,9 +122,7 @@ async fn get_processes(
*last_update = (current_time, current_rx, current_tx); *last_update = (current_time, current_rx, current_tx);
// Calculate total disk usage - only for physical disks // Calculate total disk usage - only for physical disks
let disk_stats = sys let disk_stats = sys.disks().iter()
.disks()
.iter()
.filter(|disk| { .filter(|disk| {
// Filter for physical disks - typically those mounted at "/" // Filter for physical disks - typically those mounted at "/"
disk.mount_point() == std::path::Path::new("/") disk.mount_point() == std::path::Path::new("/")
@ -149,7 +131,7 @@ async fn get_processes(
( (
acc.0 + disk.total_space(), acc.0 + disk.total_space(),
acc.1 + disk.total_space() - disk.available_space(), acc.1 + disk.total_space() - disk.available_space(),
acc.2 + disk.available_space(), acc.2 + disk.available_space()
) )
}); });
@ -158,14 +140,9 @@ async fn get_processes(
memory_total: sys.total_memory(), memory_total: sys.total_memory(),
memory_used: sys.used_memory(), memory_used: sys.used_memory(),
memory_free: sys.total_memory() - sys.used_memory(), memory_free: sys.total_memory() - sys.used_memory(),
memory_cached: sys.total_memory() memory_cached: sys.total_memory() - (sys.used_memory() + (sys.total_memory() - sys.used_memory())),
- (sys.used_memory() + (sys.total_memory() - sys.used_memory())),
uptime: sys.uptime(), uptime: sys.uptime(),
load_avg: [ load_avg: [sys.load_average().one, sys.load_average().five, sys.load_average().fifteen],
sys.load_average().one,
sys.load_average().five,
sys.load_average().fifteen,
],
network_rx_bytes: network_stats.0, network_rx_bytes: network_stats.0,
network_tx_bytes: network_stats.1, network_tx_bytes: network_stats.1,
disk_total_bytes: disk_stats.0, disk_total_bytes: disk_stats.0,
@ -175,29 +152,25 @@ async fn get_processes(
} // sys lock is automatically dropped here } // sys lock is automatically dropped here
// Now lock the process cache // Now lock the process cache
let mut process_cache = state let mut process_cache = state.process_cache.lock().map_err(|_| "Failed to lock process cache")?;
.process_cache
.lock()
.map_err(|_| "Failed to lock process cache")?;
// Build the process info list // Build the process info list
let processes = processes_data let processes = processes_data
.into_iter() .into_iter()
.map( .map(|(pid, name, cmd, user_id, cpu_usage, memory, status, ppid)| {
|(pid, name, cmd, user_id, cpu_usage, memory, status, ppid)| { let static_info = process_cache.entry(pid).or_insert_with(|| {
let static_info = process_cache ProcessStaticInfo {
.entry(pid)
.or_insert_with(|| ProcessStaticInfo {
name: name.clone(), name: name.clone(),
command: cmd.join(" "), command: cmd.join(" "),
user: user_id.unwrap_or_else(|| "-".to_string()), user: user_id.unwrap_or_else(|| "-".to_string()),
}
}); });
let status_str = match status { let status_str = match status {
ProcessStatus::Run => "Running", ProcessStatus::Run => "Running",
ProcessStatus::Sleep => "Sleeping", ProcessStatus::Sleep => "Sleeping",
ProcessStatus::Idle => "Idle", ProcessStatus::Idle => "Idle",
_ => "Unknown", _ => "Unknown"
}; };
ProcessInfo { ProcessInfo {
@ -211,8 +184,7 @@ async fn get_processes(
command: static_info.command.clone(), command: static_info.command.clone(),
threads: None, threads: None,
} }
}, })
)
.collect(); .collect();
Ok((processes, system_stats)) Ok((processes, system_stats))
@ -220,10 +192,7 @@ async fn get_processes(
#[tauri::command] #[tauri::command]
async fn kill_process(pid: u32, state: State<'_, AppState>) -> Result<bool, String> { async fn kill_process(pid: u32, state: State<'_, AppState>) -> Result<bool, String> {
let sys = state let sys = state.sys.lock().map_err(|_| "Failed to lock system state")?;
.sys
.lock()
.map_err(|_| "Failed to lock system state")?;
if let Some(process) = sys.process(sysinfo::Pid::from(pid as usize)) { if let Some(process) = sys.process(sysinfo::Pid::from(pid as usize)) {
Ok(process.kill()) Ok(process.kill())
} else { } else {