tony / oxwm

Branch: 3c01997
Switch branches/tags
master
tonybtw updated justfile for easier Xephyr testing, added default value for battery. 0415a48 2025-12-14
72 lines · 1.8 KB Raw Blame History
1 use super::Block;
2 use crate::errors::BlockError;
3 use std::fs;
4 use std::time::Duration;
5
6 pub struct Battery {
7 format_charging: String,
8 format_discharging: String,
9 format_full: String,
10 interval: Duration,
11 color: u32,
12 battery_path: String,
13 }
14
15 impl Battery {
16 pub fn new(
17 format_charging: &str,
18 format_discharging: &str,
19 format_full: &str,
20 interval_secs: u64,
21 color: u32,
22 battery_name: Option<String>,
23 ) -> Self {
24 Self {
25 format_charging: format_charging.to_string(),
26 format_discharging: format_discharging.to_string(),
27 format_full: format_full.to_string(),
28 interval: Duration::from_secs(interval_secs),
29 color,
30 battery_path: format!(
31 "/sys/class/power_supply/{}",
32 battery_name.unwrap_or_else(|| "BAT0".to_string())
33 ),
34 }
35 }
36
37 fn read_file(&self, filename: &str) -> Result<String, BlockError> {
38 let path = format!("{}/{}", self.battery_path, filename);
39 Ok(fs::read_to_string(path)?.trim().to_string())
40 }
41
42 fn get_capacity(&self) -> Result<u32, BlockError> {
43 Ok(self.read_file("capacity")?.parse()?)
44 }
45
46 fn get_status(&self) -> Result<String, BlockError> {
47 self.read_file("status")
48 }
49 }
50
51 impl Block for Battery {
52 fn content(&mut self) -> Result<String, BlockError> {
53 let capacity = self.get_capacity()?;
54 let status = self.get_status()?;
55
56 let format = match status.as_str() {
57 "Charging" => &self.format_charging,
58 "Full" => &self.format_full,
59 _ => &self.format_discharging,
60 };
61
62 Ok(format.replace("{}", &capacity.to_string()))
63 }
64
65 fn interval(&self) -> Duration {
66 self.interval
67 }
68
69 fn color(&self) -> u32 {
70 self.color
71 }
72 }