This commit is contained in:
sankalp committed 2025-06-07 15:11:26 +05:45
1 parent f53b335793
commit e1a85413c2
105 files changed
+6137 -27999

No files matched your search

+46 -51
View File
@@ -1,92 +1,82 @@
import os
import subprocess
from fabric.core.service import Property, Service, Signal
from fabric.utils import exec_shell_command, monitor_file
from fabric.utils import exec_shell_command_async, monitor_file
from gi.repository import GLib
from loguru import logger # Import loguru logger
from loguru import logger
# Helper function to execute brightnessctl asynchronously
def exec_brightnessctl_async(args: str):
# Executes brightnessctl command asynchronously, ensuring no resource leaks.
try:
# Use subprocess.Popen to run the command without blocking
process = subprocess.Popen(
f"brightnessctl {args}",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if not helpers.executable_exists("brightnessctl"):
logger.error(f"Command brightnessctl not found")
# Wait for the process to complete
stdout, stderr = process.communicate()
if process.returncode != 0:
logger.error(f"Error executing brightnessctl: {stderr.decode().strip()}")
else:
logger.debug(
f"brightnessctl output: {stdout.decode().strip()}"
) # Optional: Log the output
except Exception as e:
logger.exception(f"Exception in exec_brightnessctl_async: {e}")
exec_shell_command_async(f"brightnessctl {args}", lambda _: None)
# Discover screen backlight device
try:
screen_device = str(exec_shell_command("ls -w1 /sys/class/backlight")).split("\n")[
0
]
except IndexError:
screen_device = None
class NoBrightnessError(ImportError):
# Raised when brightness-related dependencies are missing.
def __init__(self, *args):
super().__init__(
"Brightness control not available or missing dependencies", *args
)
screen_device = os.listdir("/sys/class/backlight")
screen_device = screen_device[0] if screen_device else ""
except FileNotFoundError:
logger.error(
f"No backlight devices found, brightness control disabled"
)
screen_device = ""
class Brightness(Service):
# Service to manage screen brightness levels.
"""Service to manage screen brightness levels."""
instance = None
@staticmethod
def get_initial():
if Brightness.instance is None:
Brightness.instance = Brightness()
return Brightness.instance
@Signal
def screen(self, value: int) -> None:
"""Signal emitted when screen brightness changes."""
pass # Implement as needed for your application
# Implement as needed for your application
def __init__(self, **kwargs):
super().__init__(**kwargs)
if not screen_device:
raise NoBrightnessError()
# Path for screen backlight control
self.screen_backlight_path = f"/sys/class/backlight/{screen_device}"
# Initialize maximum brightness level
self.max_screen = self._read_max_brightness(self.screen_backlight_path)
self.max_screen = self.do_read_max_brightness(self.screen_backlight_path)
if screen_device == "":
return
# Monitor screen brightness file
self.screen_monitor = monitor_file(f"{self.screen_backlight_path}/brightness")
self.screen_monitor.connect(
"changed",
lambda _, file, *args: self.emit(
"screen", round(int(file.load_bytes()[0].get_data()))
"screen",
round(int(file.load_bytes()[0].get_data())),
),
)
# Log the initialization of the service
logger.info(f"Brightness service initialized for device: {screen_device}")
logger.info(
f"Brightness service initialized for device: {screen_device}"
)
def _read_max_brightness(self, path: str) -> int:
def do_read_max_brightness(self, path: str) -> int:
# Reads the maximum brightness value from the specified path.
max_brightness_path = os.path.join(path, "max_brightness")
if os.path.exists(max_brightness_path):
with open(max_brightness_path) as f:
return int(f.read().strip())
return int(f.readline())
return -1 # Return -1 if file doesn't exist, indicating an error.
@Property(int, "read-write")
@@ -95,8 +85,10 @@ class Brightness(Service):
brightness_path = os.path.join(self.screen_backlight_path, "brightness")
if os.path.exists(brightness_path):
with open(brightness_path) as f:
return int(f.read().strip())
logger.warning(f"Brightness file does not exist: {brightness_path}")
return int(f.readline())
logger.warning(
f"Brightness file does not exist: {brightness_path}"
)
return -1 # Return -1 if file doesn't exist, indicating error.
@screen_brightness.setter
@@ -108,8 +100,11 @@ class Brightness(Service):
try:
exec_brightnessctl_async(f"--device '{screen_device}' set {value}")
self.emit("screen", int((value / self.max_screen) * 100))
logger.info(f"Set screen brightness to {value} (out of {self.max_screen})")
logger.info(
f"Set screen brightness to {value} "
f"(out of {self.max_screen})"
)
except GLib.Error as e:
logger.error(f"Error setting screen brightness: {e.message}")
except Exception as e:
logger.exception(f"Unexpected error setting screen brightness: {e}")
logger.exception(f"Unexpected error setting screen brightness: {e}")