Files
wldash/src/widgets/backlight.rs
T

93 lines
2.4 KiB
Rust
Raw Normal View History

2023-01-11 23:54:52 +01:00
use std::{
2023-11-10 14:00:48 +01:00
fs::{self, OpenOptions},
io::{Write, Error, ErrorKind},
2023-01-11 23:54:52 +01:00
path::{Path, PathBuf},
};
use crate::{
color::Color,
2023-11-10 14:00:48 +01:00
event::PointerButton,
2023-02-02 23:52:59 +01:00
fonts::FontMap,
2023-01-12 00:13:27 +01:00
widgets::bar_widget::{BarWidget, BarWidgetImpl},
2023-01-11 23:54:52 +01:00
};
fn read_file_as_u64(path: &Path) -> Result<u64, Error> {
let mut s = fs::read_to_string(path)?;
s.pop();
s.parse::<u64>()
.map_err(|_e| Error::new(ErrorKind::Other, "unable to parse value"))
}
2023-11-10 14:00:48 +01:00
fn write_file_as_u64(path: &Path, value: u64) -> Result<(), Error> {
let mut file = OpenOptions::new().write(true).open(path)?;
file.write_fmt(format_args!("{}", value))
}
2023-01-11 23:54:52 +01:00
pub struct Backlight {
device_path: PathBuf,
cur: u64,
max: u64,
2023-11-10 14:00:48 +01:00
dirty: bool
2023-01-11 23:54:52 +01:00
}
impl Backlight {
fn update(&mut self) {
self.cur = read_file_as_u64(self.device_path.join("brightness").as_path()).unwrap();
self.max = read_file_as_u64(self.device_path.join("max_brightness").as_path()).unwrap();
}
2023-02-02 23:52:59 +01:00
pub fn new(path: &str, fm: &mut FontMap, font: &'static str, size: f32) -> BarWidget {
2023-01-12 00:13:27 +01:00
let mut dev = Backlight {
2023-01-11 23:54:52 +01:00
device_path: Path::new("/sys/class/backlight").to_path_buf().join(path),
cur: 0,
max: 0,
2023-11-10 14:00:48 +01:00
dirty: true,
2023-01-11 23:54:52 +01:00
};
dev.update();
2023-02-02 23:52:59 +01:00
BarWidget::new(Box::new(dev), fm, font, size)
2023-01-11 23:54:52 +01:00
}
2023-02-12 17:02:44 +01:00
pub fn detect(path: &str) -> bool {
let path = Path::new("/sys/class/backlight").to_path_buf().join(path);
match read_file_as_u64(path.join("brightness").as_path()) {
Ok(_) => true,
Err(_) => false,
}
}
2023-11-10 14:00:48 +01:00
pub fn set(&mut self, brightness: f32) {
let val = (self.max as f32 * brightness) as u64;
write_file_as_u64(self.device_path.join("brightness").as_path(), val);
self.cur = read_file_as_u64(self.device_path.join("brightness").as_path()).unwrap();
}
2023-01-11 23:54:52 +01:00
}
impl BarWidgetImpl for Backlight {
fn name(&self) -> &'static str {
"backlight"
}
2023-11-10 14:00:48 +01:00
fn get_dirty(&self) -> bool {
self.dirty
}
2023-02-06 18:34:07 +01:00
fn value(&mut self) -> f32 {
2023-01-11 23:54:52 +01:00
if self.cur > self.max {
// what.
return 1.0;
}
2023-11-10 14:00:48 +01:00
self.dirty = false;
2023-01-11 23:54:52 +01:00
self.cur as f32 / self.max as f32
}
fn color(&self) -> Color {
2023-02-02 23:52:59 +01:00
Color::WHITE
2023-01-11 23:54:52 +01:00
}
2023-11-10 14:00:48 +01:00
fn click(&mut self, pos: f32, btn: PointerButton) {
self.dirty = true;
match btn {
PointerButton::Left => self.set(pos),
_ => (),
};
}
2023-01-11 23:54:52 +01:00
}