use crate::error::{ Error, Result }; use crate::facility::{ FacilityMap, FacilityType }; use crate::facility::envsys::EnvSys; use crate::module::{ CreatableModule, Module }; use std::time::Duration; pub struct BatteryModule { is_visible: bool, full_threshold: f32, } impl CreatableModule for BatteryModule { const REQUIRED_FACILITIES: FacilityType = FacilityType::ENVSYS; fn new(facilities: &mut FacilityMap) -> Result { let envsys: &mut EnvSys = facilities.get().ok_or(Error::custom( "Battery module can't access envsys facility."))?; let mut is_visible = false; for name in envsys.device_iter() { if Self::is_battery_device(name) { if Self::is_present(envsys, name)? { is_visible = true; } } } let full_threshold = 96.5 / 100.0; Ok(BatteryModule { is_visible, full_threshold }) } } impl Module for BatteryModule { fn format(&mut self, facilities: &mut FacilityMap) -> Result { let envsys: &mut EnvSys = facilities.get().ok_or(Error::custom( "Battery module can't access envsys facility."))?; /* When there's more than one battery, we want to present them in an * order which is both stable and predictable. Their device names are also * user-visible via envstat(8), so lexicographic ordering will be fine for * both needs. Anyway, to make that happen, we collect and sort the ones * we're interested in in advance. */ let mut devices = Vec::new(); for name in envsys.device_iter() { if Self::is_battery_device(name) { if Self::is_present(envsys, name)? { devices.push(name); } } } devices.sort(); self.is_visible = !devices.is_empty(); let mut text = String::new(); for name in &devices { if !text.is_empty() { text.push_str(" "); } let is_charging = Self::is_charging(envsys, name)?; let ratio = Self::ratio(envsys, name)?; let is_full = ratio >= self.full_threshold; if is_full && ! is_charging { text.push_str("\u{1F333}100"); } else { let percentage = (ratio * 100.0).round() as i32; if is_charging { text.push_str(&format!("\u{2668}{}%", percentage)); } else { text.push_str(&format!("\u{1f343}{}%", percentage)); } } } Ok(text) } fn sleep_duration(&self) -> Option { None } fn is_visible(&self) -> bool { self.is_visible } } impl BatteryModule { fn is_battery_device(name: &str) -> bool { name.starts_with("acpibat") } fn is_present(envsys: &EnvSys, device_name: &str) -> Result { Ok(envsys.get_current_value(device_name, "present")? != 0) } fn is_charging(envsys: &EnvSys, device_name: &str) -> Result { Ok(envsys.get_current_value(device_name, "charging")? != 0) } fn ratio(envsys: &EnvSys, device_name: &str) -> Result { let current_charge = envsys.get_current_value(device_name, "charge")?; let maximum_charge = envsys.get_maximum_value(device_name, "charge")?; Ok(current_charge as f32 / maximum_charge as f32) } }