From eb1aef6d08b5e4df916570f540c28ade0e7d11d5 Mon Sep 17 00:00:00 2001 From: Brandon Elam Barker Date: Mon, 22 Jul 2024 03:23:31 -0400 Subject: [PATCH] add battery finder (#303) * add battery finder; add flake.nix for nix users to build penrose * remove nix files --- .gitignore | 4 +++ crates/penrose_ui/src/bar/widgets/sys.rs | 38 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/.gitignore b/.gitignore index 2de1f4f9..b63d36b0 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,7 @@ Cargo.lock node_modules/ xephyr.log + +# Ignore nix user files +**/*.nix +**/flake.lock diff --git a/crates/penrose_ui/src/bar/widgets/sys.rs b/crates/penrose_ui/src/bar/widgets/sys.rs index 676475a6..4ae30b8e 100644 --- a/crates/penrose_ui/src/bar/widgets/sys.rs +++ b/crates/penrose_ui/src/bar/widgets/sys.rs @@ -4,6 +4,44 @@ pub mod helpers { use penrose::util::{spawn_for_output, spawn_for_output_with_args}; use std::fs; + use std::path::PathBuf; + + /// This finds the first battery (BAT) file it finds; so far only + /// confirmed working on Linux. + pub fn battery_file_search() -> Option { + let battery_paths = vec![ + // Linux + "/sys/class/power_supply", + // OpenBSD + "/var/run/apm", + // FreeBSD and DragonFlyBSD + "/dev", + // illumos + "/dev/battery", + ]; + + battery_paths + .into_iter() + .filter_map(|base_path| { + let base_path = PathBuf::from(base_path); + if base_path.exists() && base_path.is_dir() { + fs::read_dir(base_path).ok() + } else { + None + } + }) + .flat_map(|read_dir| read_dir.filter_map(Result::ok)) + .filter_map(|entry| { + let file_name = entry.file_name(); + let file_name_str = file_name.to_str()?; + if file_name_str.starts_with("BAT") && file_name_str[3..].parse::().is_ok() { + Some(file_name_str.to_string()) + } else { + None + } + }) + .next() + } /// Fetch the requested battery's charge as a percentage of its total along with an indicator /// of whether it is charging or discharging.