Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Brightness control #4

Merged
merged 8 commits into from
Mar 8, 2023
Merged

Add Brightness control #4

merged 8 commits into from
Mar 8, 2023

Conversation

p3nj
Copy link
Contributor

@p3nj p3nj commented Feb 27, 2023

This is my first time working with rust, so if anything can be improved, please tell me.

I add a blight package to let users control the backlight.
It's tested on my laptop with multiple external screens running and worked flawlessly.
Sadly, I don't have an external monitor that can be adjusted the backlight from the drivers.
The brightness icon heavily depends on the theme files. For now, I'm using Adwaita's display-brightness-symbolic icon.
if desire to have different icon between different level of the brightness,
perhaps have to do something like this

        // in some themes they have this notification display.
        let icon_prefix = "notification-display-brightness";
        let mut icon_name = String::new();

        if brightness > 0.0 && brightness <= 82.5
        {
            icon_name = format!("{}-low", icon_prefix);
        } 
        else if brightness > 82.5 && brightness <= 165.0 {
            icon_name = format!("{}-medium", icon_prefix);
        }
        else if brightness > 165.0 {
            icon_name = format!("{}-medium", icon_prefix);
        }

What changed

General

  • Update README.md file with brightness instruction
  • Add parameters of brightness control
  • Add function to control brightness using blight package.

Package

  • Added blight = "0.4.1"

Issue related

#1

@ErikReider
Copy link
Owner

Sorry for the delay. I'll look at this this afternoon. If I forget, ping me! :)

@ErikReider
Copy link
Owner

ErikReider commented Mar 7, 2023

Doesn't seem to work on my system. It failed to write to the brightness file. In the blight README, it states that the user needs to be in the video group and some udev rules may be needed.

https://github.com/VoltaireNoir/blight/blob/main/src/utils/setup.rs

Comment on lines 305 to 316
(OsdTypes::BrightnessRaise, _) => {
change_brightness(BrightnessChangeType::Raise);
for window in self.windows.borrow().to_owned() {
window.changed_brightness();
}
}
(OsdTypes::BrightnessLower, _) => {
change_brightness(BrightnessChangeType::Lower);
for window in self.windows.borrow().to_owned() {
window.changed_brightness();
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Format with rustfmt

Comment on lines 159 to 176
pub fn changed_brightness(&self) {
self.clear_osd();

let bl = Device::new(None).unwrap();
let brightness = bl.current() as f64;

// Using the icon from Adwaita for now?
let icon_name = "display-brightness-symbolic";

let icon = self.build_icon_widget(&icon_name);
let progress = self.build_progress_widget(brightness / 255.0);

self.container.add(&icon);
self.container.add(&progress.bar);

self.run_timeout();
}

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format with rustfmt

src/utils.rs Outdated
Comment on lines 166 to 183
pub fn change_brightness(change_type: BrightnessChangeType) {

const BRIGHTNESS_CHANGE_DELTA: u16 = 5;
match change_type {
BrightnessChangeType::Raise => {
match change_bl(BRIGHTNESS_CHANGE_DELTA, Change::Regular, Direction::Inc, None) {
Err(e) => eprintln!("Brightness Error: {}", e),
_ => ()
}
}
BrightnessChangeType::Lower => {
match change_bl(BRIGHTNESS_CHANGE_DELTA, Change::Regular, Direction::Dec, None) {
Err(e) => eprintln!("Brightness Error: {}", e),
_ => ()
}
}
}
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

format with rustfmt

@ErikReider
Copy link
Owner

ErikReider commented Mar 7, 2023

Here's a patch with a few fixes:

Adds lower brightness limit and fixes progress bar not moving for some devices :)

diff --git a/src/application.rs b/src/application.rs
index 3f91cf8..9f301cd 100644
--- a/src/application.rs
+++ b/src/application.rs
@@ -122,7 +122,7 @@ impl SwayOSDApplication {
 			"Shows brightness osd and raises or loweres all available sources of brightness device",
 			Some("raise|lower"),
 		);
-        
+
 		// Parse args
 		app.connect_handle_local_options(|app, args| -> i32 {
 			let variant = args.to_variant();
@@ -303,16 +303,18 @@ impl SwayOSDApplication {
 					}
 				}
 				(OsdTypes::BrightnessRaise, _) => {
-					change_brightness(BrightnessChangeType::Raise);
-                    for window in self.windows.borrow().to_owned() {
-                        window.changed_brightness();
-                    }
+					if let Ok(Some(device)) = change_brightness(BrightnessChangeType::Raise) {
+						for window in self.windows.borrow().to_owned() {
+							window.changed_brightness(&device);
+						}
+					}
 				}
 				(OsdTypes::BrightnessLower, _) => {
-					change_brightness(BrightnessChangeType::Lower);
-                    for window in self.windows.borrow().to_owned() {
-                        window.changed_brightness();
-                    }
+					if let Ok(Some(device)) = change_brightness(BrightnessChangeType::Lower) {
+						for window in self.windows.borrow().to_owned() {
+							window.changed_brightness(&device);
+						}
+					}
 				}
 				(OsdTypes::CapsLock, led) => {
 					let state = get_caps_lock_state(led);
diff --git a/src/osd_window.rs b/src/osd_window.rs
index 6e5aa0e..11e613a 100644
--- a/src/osd_window.rs
+++ b/src/osd_window.rs
@@ -156,17 +156,16 @@ impl SwayosdWindow {
 		self.run_timeout();
 	}
 
-	pub fn changed_brightness(&self) {
+	pub fn changed_brightness(&self, device: &Device) {
 		self.clear_osd();
 
-		let bl = Device::new(None).unwrap();
-        let brightness = bl.current() as f64;
-
-        // Using the icon from Adwaita for now?
-        let icon_name = "display-brightness-symbolic";
-			
+		// Using the icon from Adwaita for now?
+		let icon_name = "display-brightness-symbolic";
 		let icon = self.build_icon_widget(&icon_name);
-		let progress = self.build_progress_widget(brightness / 255.0);
+
+		let brightness = device.current() as f64;
+		let max = device.max() as f64;
+		let progress = self.build_progress_widget(brightness / max);
 
 		self.container.add(&icon);
 		self.container.add(&progress.bar);
diff --git a/src/utils.rs b/src/utils.rs
index 7184082..7f6bd1b 100644
--- a/src/utils.rs
+++ b/src/utils.rs
@@ -5,9 +5,9 @@ use std::{
 	io::{prelude::*, BufReader},
 };
 
+use blight::{change_bl, err::BlibError, Change, Device, Direction};
 use pulse::volume::Volume;
 use pulsectl::controllers::{types::DeviceInfo, DeviceControl, SinkController, SourceController};
-use blight:: { change_bl, Change, Direction };
 
 pub fn get_caps_lock_state(led: Option<String>) -> bool {
 	const BASE_PATH: &str = "/sys/class/leds";
@@ -163,22 +163,27 @@ pub fn change_source_volume(change_type: VolumeChangeType) -> Option<DeviceInfo>
 	}
 }
 
-pub fn change_brightness(change_type: BrightnessChangeType) {
-
+pub fn change_brightness(change_type: BrightnessChangeType) -> Result<Option<Device>, BlibError> {
 	const BRIGHTNESS_CHANGE_DELTA: u16 = 5;
-	match change_type {
-	BrightnessChangeType::Raise => {
-            match change_bl(BRIGHTNESS_CHANGE_DELTA, Change::Regular, Direction::Inc, None) {
-                Err(e) => eprintln!("Brightness Error: {}", e),
-                _ => ()
-            }
-		}
-	BrightnessChangeType::Lower => {
-            match change_bl(BRIGHTNESS_CHANGE_DELTA, Change::Regular, Direction::Dec, None) {
-                Err(e) => eprintln!("Brightness Error: {}", e),
-                _ => ()
+	let direction = match change_type {
+		BrightnessChangeType::Raise => Direction::Inc,
+		BrightnessChangeType::Lower => {
+			let device = Device::new(None)?;
+			let change = device.calculate_change(BRIGHTNESS_CHANGE_DELTA, Direction::Dec) as f64;
+			let max = device.max() as f64;
+			// Limits the lowest brightness to 5%
+			if change / max < (BRIGHTNESS_CHANGE_DELTA as f64) * 0.01 {
+				return Ok(Some(device));
 			}
+			Direction::Dec
+		}
+	};
+	match change_bl(BRIGHTNESS_CHANGE_DELTA, Change::Regular, direction, None) {
+		Err(e) => {
+			eprintln!("Brightness Error: {}", e);
+			Err(e)
 		}
+		_ => Ok(Some(Device::new(None)?)),
 	}
 }

@ErikReider
Copy link
Owner

Then you'll also need to update the README with additional instructions for setting up the permissions.

I just needed to add my user to the video group and the rules to /etc/udev/rules.d/99-swayosd.rules:

ACTION=="add", SUBSYSTEM=="backlight", RUN+="/bin/chgrp video /sys/class/backlight/%k/brightness"
ACTION=="add", SUBSYSTEM=="backlight", RUN+="/bin/chmod g+w /sys/class/backlight/%k/brightness"

@p3nj
Copy link
Contributor Author

p3nj commented Mar 7, 2023

I've modified the files and the methods.
Also add a small instruction in README.md for adding user to video group.

README.md Outdated
Comment on lines 42 to 43
Some devices may not have permission to write `/sys/class/backlight/*/brightness`.
Workaround will be adding a rule inside `udev`:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also mention the command to add the user to video group :)

@ErikReider
Copy link
Owner

GTK requires the adwaita icons to be installed so that icon should work :)

Too bad that they don't provide more brightness icons...

@p3nj
Copy link
Contributor Author

p3nj commented Mar 8, 2023

GTK requires the adwaita icons to be installed so that icon should work :)

Too bad that they don't provide more brightness icons...

Sorry, forgot to commit the change.

Some of the themes have multiple icons available, probably could replace it with Font Emoji or something else?

Copy link
Owner

@ErikReider ErikReider left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Appreciate the help! :)

@ErikReider ErikReider merged commit 3bc700a into ErikReider:main Mar 8, 2023
@ErikReider
Copy link
Owner

Some of the themes have multiple icons available, probably could replace it with Font Emoji or something else?

I'd prefer using icons. The one used right now works good enough :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants