Skip to content

Commit

Permalink
Better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Supernovatux committed Sep 12, 2022
1 parent cef2df5 commit 4af9dcc
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 74 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ assets = [

[dependencies]
display-info = "0.3"
dbus = "0.9.6"
xcb = {version="1.1",features=["randr"]}
clap = { version = "3.2", features = ["derive"] }
log = "0.4"
Expand Down
21 changes: 3 additions & 18 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,9 @@ include!("src/cli_parser.rs");
fn main() -> Result<(), Error> {
let outdir = "completions";
let mut cmd = Cli::into_app();
generate_to(
Bash,
&mut cmd,
"auto-backlight",
outdir,
)?;
generate_to(
Zsh,
&mut cmd,
"auto-backlight",
outdir,
)?;
generate_to(
Fish,
&mut cmd,
"auto-backlight",
outdir,
)?;
generate_to(Bash, &mut cmd, "auto-backlight", outdir)?;
generate_to(Zsh, &mut cmd, "auto-backlight", outdir)?;
generate_to(Fish, &mut cmd, "auto-backlight", outdir)?;

Ok(())
}
75 changes: 44 additions & 31 deletions src/brightness.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use glob::glob;
use log::{debug, error, info};

use std::fs::{read_to_string, write};
use std::{
fs::{read_to_string, write},
io::Error,
};

#[derive(Debug)]
pub struct BrightnessDevices {
Expand All @@ -14,8 +17,15 @@ impl BrightnessDevices {
for entry in glob("/sys/class/backlight/*").expect("Failed to read glob pattern") {
match entry {
Ok(path) => {
let max_brightness = match read_to_string(format!(
"{}/max_brightness",
path.to_str().unwrap()
)) {
Ok(sm) => sm.trim().parse().unwrap(),
Err(_) => continue,
};
let new_dev = BrightnessDevice {
max_brightness: format!("{}/max_brightness", path.to_str().unwrap()),
max_brightness,
brightness: format!("{}/brightness", path.to_str().unwrap()),
};
devices.push(new_dev);
Expand All @@ -25,51 +35,53 @@ impl BrightnessDevices {
}
BrightnessDevices { devices }
}
pub fn get_brightness(&self) -> i16 {
//As of now it averages out.
//Multi-monitor support is to be addeed
let sum: i16 = self
.devices
.iter()
.map(|dev| dev.get_current_brightness_percent())
.sum();
sum / self.devices.len() as i16
pub fn get_brightness(&mut self) -> i16 {
//Multi-monitor support is to be added
match self.devices[0].get_current_brightness_percent() {
Ok(num) => num,
Err(err) => {
error!("{}", err);
self.devices.remove(0);
0
}
}
}
pub fn change_brightness(&self, change: i16) {
self.devices[0].increase_brightness(change)
pub fn change_brightness(&mut self, change: i16) {
match self.devices[0].increase_brightness(change) {
Ok(_) => (),
Err(err) => {
error!("{:?}", err);
self.devices.remove(0);
}
}
}
}

#[derive(Debug)]
pub struct BrightnessDevice {
pub max_brightness: String,
pub brightness: String,
max_brightness: i16,
brightness: String,
}

impl BrightnessDevice {
fn get_max_brightness(&self) -> i16 {
read_to_string(&self.max_brightness)
.unwrap()
.trim()
.parse()
.unwrap()
self.max_brightness
}
fn get_current_brightness(&self) -> i16 {
read_to_string(&self.brightness)
.unwrap()
.trim()
.parse()
.unwrap()
fn get_current_brightness(&self) -> Result<i16, Error> {
match read_to_string(&self.brightness) {
Ok(num) => Ok(num.trim().parse().unwrap()),
Err(err) => Err(err),
}
}
pub fn get_current_brightness_percent(&self) -> i16 {
let ret = (self.get_current_brightness() as f64 * 100.0 / self.get_max_brightness() as f64)
pub fn get_current_brightness_percent(&self) -> Result<i16, Error> {
let ret = (self.get_current_brightness()? as f64 * 100.0 / self.get_max_brightness() as f64)
as i16;
debug!("Current brightness is {}", ret);
ret
Ok(ret)
}
pub fn increase_brightness(&self, change: i16) {
pub fn increase_brightness(&self, change: i16) -> Result<(), Error> {
let change = (change as f64 * self.get_max_brightness() as f64 / 100.0) as i16;
let value = self.get_current_brightness();
let value = self.get_current_brightness()?;
let value_new = if change == 0 {
value
} else if value + change < 0 {
Expand All @@ -81,6 +93,7 @@ impl BrightnessDevice {
};
info!("Brightness changed from {} to {}", value, value_new);
write(&self.brightness, format!("{}", value_new)).expect("permission denied");
Ok(())
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/cli_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,4 @@ pub fn get_offset() -> i16 {
}
fn init_cli() -> Cli {
Cli::parse()
}
}
32 changes: 21 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
use crossbeam_channel::{bounded, tick, select, Sender};
use crossbeam_channel::{bounded, select, tick, Sender};
use log::{debug, info};
use signal_hook::{consts::{TERM_SIGNALS}, iterator::{SignalsInfo,exfiltrator::{WithOrigin}}, low_level::siginfo::Origin};
use std::{sync::{
atomic::{AtomicBool, Ordering},
Arc,
}, time::Duration, thread};
use signal_hook::{
consts::TERM_SIGNALS,
iterator::{exfiltrator::WithOrigin, SignalsInfo},
low_level::siginfo::Origin,
};
use std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
thread,
time::Duration,
};

use crate::{
brightness::BrightnessDevices,
Expand All @@ -31,9 +39,11 @@ pub fn init() {
let status_to_send = brightnessctl_status.clone();
let mut brightness = 0;
let mut change = 0;
let brightness_dev = BrightnessDevices::new();
let mut brightness_dev = BrightnessDevices::new();
let handle = sys_tray::start_knsi(status_to_send, tx.clone());
thread::spawn(|| {sig_handle(tx);});
thread::spawn(|| {
sig_handle(tx);
});
loop {
if brightnessctl_status.load(Ordering::Relaxed) {
let change_new = change_calc(get_limit() as u8);
Expand Down Expand Up @@ -63,19 +73,19 @@ pub fn init() {
None => info!("Received taskbar exit signal"),
}},
Err(err) => log::error!("{}",err),
};
};
info!("Exiting");
break;},
}
}
handle.shutdown();
}

fn sig_handle(tx:Sender<Option<Origin>>) {
fn sig_handle(tx: Sender<Option<Origin>>) {
let sigs = Vec::from(TERM_SIGNALS);
let mut signals = SignalsInfo::<WithOrigin>::new(&sigs).unwrap();
for info in &mut signals {
tx.send(Some(info)).unwrap();
break;
};
}
}
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fs::{File, self};
use std::fs::{self, File};

fn main() {
if File::open("/tmp/auto-backlight.lock").is_ok() {
Expand Down
4 changes: 2 additions & 2 deletions src/screen_capture/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::env::var_os;

use display_info::DisplayInfo;

use self::{wayland::wayland_capture_screen_raw, xorg::xorg_capture_screen_raw};
use self::xorg::xorg_capture_screen_raw;

mod wayland;
mod xorg;
Expand All @@ -21,7 +21,7 @@ fn wayland_detect() -> bool {
}
pub fn capture_screen_raw(display_info: &DisplayInfo) -> Option<Vec<u8>> {
if wayland_detect() {
wayland_capture_screen_raw()
panic!("Wayland not yet tested");
} else {
xorg_capture_screen_raw(display_info)
}
Expand Down
1 change: 1 addition & 0 deletions src/screen_capture/linux/wayland.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![cfg(wayland)]
use dbus::{self, blocking::Connection};

use std::{
Expand Down
8 changes: 7 additions & 1 deletion src/screens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@ pub fn change_calc(lim: u8) -> i16 {
for i in screens {
if i.display_info.is_primary {
trace!("{:?}", i.display_info);
let img = i.capture_raw().unwrap();
let img = match i.capture_raw() {
Some(img) => img,
None => {
log::error!("Unable to capture screenshot!");
continue;
}
};
ch = get_average_brightness(img, i.display_info);
ch = get_value_to_change(lim, ch);
break;
Expand Down
12 changes: 5 additions & 7 deletions src/sys_tray.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
use std::{
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use crossbeam_channel::{Sender};
use crossbeam_channel::Sender;
use ksni;
use signal_hook::low_level::siginfo::Origin;
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc,
};

pub struct SysTray {
running: Arc<AtomicBool>,
Expand Down

0 comments on commit 4af9dcc

Please sign in to comment.