tony / oxwm

Branch: 7c10ebe
Switch branches/tags
master
tonybanters Added ram block 93d1e6e 2025-10-07
79 lines · 2.1 KB Raw Blame History
1 use super::Block;
2 use anyhow::Result;
3 use std::fs;
4 use std::time::Duration;
5
6 pub struct Ram {
7 format: String,
8 interval: Duration,
9 color: u32,
10 }
11
12 impl Ram {
13 pub fn new(format: &str, interval_secs: u64, color: u32) -> Self {
14 Self {
15 format: format.to_string(),
16 interval: Duration::from_secs(interval_secs),
17 color,
18 }
19 }
20
21 fn get_memory_info(&self) -> Result<(u64, u64, f32)> {
22 let meminfo = fs::read_to_string("/proc/meminfo")?;
23 let mut total: u64 = 0;
24 let mut available: u64 = 0;
25
26 for line in meminfo.lines() {
27 if line.starts_with("MemTotal:") {
28 total = line
29 .split_whitespace()
30 .nth(1)
31 .and_then(|s| s.parse().ok())
32 .unwrap_or(0)
33 } else if line.starts_with("MemAvailable:") {
34 available = line
35 .split_whitespace()
36 .nth(1)
37 .and_then(|s| s.parse().ok())
38 .unwrap_or(0)
39 }
40 }
41
42 let used = total.saturating_sub(available);
43 let used_gb = used as f32 / 1024.0 / 1024.0;
44 let total_gb = total as f32 / 1024.0 / 1024.0;
45 let percentage = if total > 0 {
46 (used as f32 / total as f32) * 100.0
47 } else {
48 0.0
49 };
50
51 Ok((used, total, percentage))
52 }
53 }
54
55 impl Block for Ram {
56 fn content(&mut self) -> Result<String> {
57 let (used, total, percentage) = self.get_memory_info()?;
58
59 let used_gb = used as f32 / 1024.0 / 1024.0;
60 let total_gb = total as f32 / 1024.0 / 1024.0;
61
62 let result = self
63 .format
64 .replace("{used}", &format!("{:.1}", used_gb))
65 .replace("{total}", &format!("{:.1}", total_gb))
66 .replace("{percent}", &format!("{:.1}", percentage))
67 .replace("{}", &format!("{:.1}", used_gb));
68
69 Ok(result)
70 }
71
72 fn interval(&self) -> Duration {
73 self.interval
74 }
75
76 fn color(&self) -> u32 {
77 self.color
78 }
79 }