update
This commit is contained in:
1 parent
5893be66cc
commit
d4af480bbd
6 files changed
+217
-83
No files matched your search
@@ -1,9 +1,5 @@
|
||||
from .brightness import Brightness
|
||||
from .material_icon import MaterialIcon
|
||||
from .screen_record import ScreenRecorder
|
||||
from .weather import WeatherInfo
|
||||
|
||||
__all__ = [
|
||||
"Brightness",
|
||||
"MaterialIcon",
|
||||
"ScreenRecorder",
|
||||
]
|
||||
__all__ = ["Brightness", "ScreenRecorder", "WeatherInfo"]
|
||||
@@ -1,99 +1,115 @@
|
||||
import os
|
||||
|
||||
from gi.repository import GLib
|
||||
import subprocess
|
||||
|
||||
from fabric.core.service import Property, Service, Signal
|
||||
from fabric.utils import exec_shell_command, exec_shell_command_async, monitor_file
|
||||
|
||||
# In the future, use GUdev to get ehe brightness devices
|
||||
from fabric.utils import exec_shell_command, monitor_file
|
||||
from gi.repository import GLib
|
||||
from loguru import logger # Import loguru logger
|
||||
|
||||
|
||||
# BUG This will open a new file every single time for some
|
||||
# reason, seems like brightnessctil does not stop function after completion
|
||||
# Helper function to execute brightnessctl asynchronously
|
||||
def exec_brightnessctl_async(args: str):
|
||||
exec_shell_command_async(f"brightnessctl {args}", lambda _: None)
|
||||
# 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,
|
||||
)
|
||||
|
||||
# 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}")
|
||||
|
||||
|
||||
screen = str(exec_shell_command("ls -w1 /sys/class/backlight")).split("\n")[0]
|
||||
leds = str(exec_shell_command("ls -w1 /sys/class/leds")).split("\n")
|
||||
|
||||
kbd = ""
|
||||
if "tpacpi::kbd_backlight" in leds:
|
||||
kbd = "tpacpi::kbd_backlight"
|
||||
# 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__(
|
||||
"Playerctl is not installed, please install it first",
|
||||
*args,
|
||||
"Brightness control not available or missing dependencies", *args
|
||||
)
|
||||
|
||||
|
||||
class Brightness(Service):
|
||||
# __gsignals__ = SignalContainer(
|
||||
# Signal("screen", "run-first", None, (int,)),
|
||||
# Signal("kbd", "run-first", None, (int,)),
|
||||
# )
|
||||
# Service to manage screen brightness levels.
|
||||
|
||||
@Signal
|
||||
def screen(self, value: int) -> None: ...
|
||||
|
||||
@Signal
|
||||
def kbd(self, value: int) -> None: ...
|
||||
def screen(self, value: int) -> None:
|
||||
"""Signal emitted when screen brightness changes."""
|
||||
pass # Implement as needed for your application
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self.screen_backlight_path = "/sys/class/backlight/" + screen
|
||||
self.kbd_backlight_path = "/sys/class/leds/" + kbd
|
||||
self.max_kbd = -1
|
||||
self.max_screen = -1
|
||||
|
||||
if os.path.exists(self.screen_backlight_path + "/max_brightness"):
|
||||
with open(self.screen_backlight_path + "/max_brightness") as f:
|
||||
self.max_screen = int(f.read())
|
||||
if os.path.exists(self.kbd_backlight_path + "/max_brightness"):
|
||||
with open(self.kbd_backlight_path + "/max_brightness") as f:
|
||||
self.max_kbd = int(f.read())
|
||||
|
||||
self.screen_monitor = monitor_file(self.screen_backlight_path + "/brightness")
|
||||
self.screen_monitor.connect(
|
||||
"changed",
|
||||
lambda _, file, *args: self.emit( # type: ignore
|
||||
"screen",
|
||||
round(int(file.load_bytes()[0].get_data())),
|
||||
),
|
||||
)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@Property(int, "read-write")
|
||||
def screen_brightness(self) -> int: # type: ignore
|
||||
return (
|
||||
int(
|
||||
os.read(
|
||||
os.open(self.screen_backlight_path + "/brightness", os.O_RDONLY), 6
|
||||
),
|
||||
)
|
||||
if os.path.exists(self.screen_backlight_path + "/brightness")
|
||||
else -1
|
||||
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)
|
||||
|
||||
# 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()))
|
||||
),
|
||||
)
|
||||
|
||||
# Log the initialization of the service
|
||||
logger.info(f"Brightness service initialized for device: {screen_device}")
|
||||
|
||||
def _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 -1 # Return -1 if file doesn't exist, indicating an error.
|
||||
|
||||
@Property(int, "read-write")
|
||||
def screen_brightness(self) -> int:
|
||||
# Property to get or set the screen brightness.
|
||||
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 -1 # Return -1 if file doesn't exist, indicating error.
|
||||
|
||||
@screen_brightness.setter
|
||||
def screen_brightness(self, value: int):
|
||||
if value < 0 or value > self.max_screen:
|
||||
return 0 if value < 0 else self.max_screen
|
||||
try:
|
||||
exec_brightnessctl_async(f"--device '{screen}' set {value}")
|
||||
self.emit("screen", int((value / self.max_screen) * 100)) # type: ignore
|
||||
except GLib.Error as e: # type: ignore
|
||||
print(e.message)
|
||||
# Setter for screen brightness property.
|
||||
if not (0 <= value <= self.max_screen):
|
||||
value = max(0, min(value, self.max_screen))
|
||||
|
||||
def set_kbd(self, value: int):
|
||||
if not kbd:
|
||||
return -1
|
||||
if value < 0 or value > self.max_kbd:
|
||||
return None
|
||||
try:
|
||||
exec_brightnessctl_async(f"--device '{kbd}' set {value}")
|
||||
self.emit("kbd", value) # type: ignore
|
||||
except GLib.Error as e: # type: ignore
|
||||
print(e.message)
|
||||
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})")
|
||||
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}")
|
||||
@@ -0,0 +1,18 @@
|
||||
import urllib.request
|
||||
|
||||
|
||||
class WeatherInfo:
|
||||
def simple_weather_info(self, city: str):
|
||||
try:
|
||||
url = f"http://wttr.in/{city.capitalize()}?format='%l,%c,%t,%C'"
|
||||
contents = urllib.request.urlopen(url).read().decode("utf-8")
|
||||
|
||||
data = str(contents).split(",")
|
||||
return {
|
||||
"city": data[0].strip(),
|
||||
"icon": data[1].strip(),
|
||||
"temperature": data[2].strip(),
|
||||
"condition": data[3].strip(),
|
||||
}
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
@@ -1,3 +1,9 @@
|
||||
from .animator import Animator
|
||||
from .icon import MaterialIcon
|
||||
from .icon_resolver import IconResolver
|
||||
|
||||
__all__ = ["Animator"]
|
||||
__all__ = [
|
||||
"Animator",
|
||||
"MaterialIcon",
|
||||
"IconResolver",
|
||||
]
|
||||
@@ -1,18 +1,16 @@
|
||||
# material_icon.py
|
||||
|
||||
from fabric.widgets.label import Label
|
||||
|
||||
|
||||
def MaterialIcon(icon_name: str, size: str = "24px", props: dict = None):
|
||||
label_props = {
|
||||
"label": icon_name, # Directly use the provided icon name
|
||||
"label": icon_name, # Directly use the provided icon name
|
||||
"name": "material_icon",
|
||||
"style": f"font-size: {size}; ", # Set font family for Material Icons
|
||||
"h_align": "center", # Align horizontally
|
||||
"v_align": "center" # Align vertically
|
||||
"h_align": "center", # Align horizontally
|
||||
"v_align": "center", # Align vertically
|
||||
}
|
||||
|
||||
if props:
|
||||
label_props.update(props)
|
||||
|
||||
return Label(**label_props)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
|
||||
import gi
|
||||
|
||||
gi.require_version("Gtk", "3.0")
|
||||
from gi.repository import GLib, Gtk
|
||||
from loguru import logger
|
||||
|
||||
# TODO WIP
|
||||
# Idea: nearest string matching algorithm
|
||||
# if already exists: retrieve from json
|
||||
# if found: stor in json: app_id -> icon_name
|
||||
# if not found: store in json -> misisng-icon
|
||||
|
||||
|
||||
CACHE_DIR = str(GLib.get_user_cache_dir()) + "/fabric"
|
||||
ICON_CACHE_FILE = CACHE_DIR + "/icons.json"
|
||||
if not os.path.exists(CACHE_DIR):
|
||||
os.makedirs(CACHE_DIR)
|
||||
|
||||
|
||||
class IconResolver:
|
||||
def __init__(self, default_applicaiton_icon: str = "image-missing"):
|
||||
if os.path.exists(ICON_CACHE_FILE):
|
||||
f = open(ICON_CACHE_FILE)
|
||||
try:
|
||||
self._icon_dict = json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
logger.info("[ICONS] Cache file does not exist or is corrupted")
|
||||
f.close()
|
||||
else:
|
||||
self._icon_dict = {}
|
||||
|
||||
self.default_applicaiton_icon = default_applicaiton_icon
|
||||
|
||||
def get_icon_name(self, app_id: str):
|
||||
if app_id in self._icon_dict:
|
||||
return self._icon_dict[app_id]
|
||||
new_icon = self._compositor_find_icon(app_id)
|
||||
logger.info(
|
||||
f"[ICONS] found new icon: '{new_icon}' for app id: '{app_id}', storing..."
|
||||
)
|
||||
self._store_new_icon(app_id, new_icon)
|
||||
return new_icon
|
||||
|
||||
def get_icon_pixbuf(self, app_id: str, size: int = 16):
|
||||
return Gtk.IconTheme.get_default().load_icon(
|
||||
self.get_icon_name(app_id),
|
||||
size,
|
||||
Gtk.IconLookupFlags.FORCE_SIZE,
|
||||
)
|
||||
|
||||
def _store_new_icon(self, app_id: str, icon: str):
|
||||
self._icon_dict[app_id] = icon
|
||||
with open(ICON_CACHE_FILE, "w") as f:
|
||||
json.dump(self._icon_dict, f)
|
||||
f.close()
|
||||
|
||||
def _get_icon_from_desktop_file(self, desktop_file_path: str):
|
||||
# TODO: get icon in the [Desktop Entry] section only
|
||||
with open(desktop_file_path) as f:
|
||||
for line in f.readlines():
|
||||
if "Icon=" in line:
|
||||
return "".join(line[5:].split())
|
||||
return self.default_applicaiton_icon
|
||||
|
||||
def _get_desktop_file(self, app_id: str) -> str | None:
|
||||
data_dirs = GLib.get_system_data_dirs()
|
||||
for data_dir in data_dirs:
|
||||
data_dir = data_dir + "/applications/"
|
||||
if os.path.exists(data_dir):
|
||||
# Do name resolving here
|
||||
|
||||
files = os.listdir(data_dir)
|
||||
matching = [
|
||||
s for s in files if "".join(app_id.lower().split()) in s.lower()
|
||||
]
|
||||
if matching:
|
||||
return data_dir + matching[0]
|
||||
|
||||
for word in list(filter(None, re.split(r"-|\.|_|\s", app_id))):
|
||||
matching = [s for s in files if word.lower() in s.lower()]
|
||||
if matching:
|
||||
return data_dir + matching[0]
|
||||
|
||||
return None
|
||||
|
||||
def _compositor_find_icon(self, app_id: str):
|
||||
if Gtk.IconTheme.get_default().has_icon(app_id):
|
||||
return app_id
|
||||
if Gtk.IconTheme.get_default().has_icon(app_id + "-desktop"):
|
||||
return app_id + "-desktop"
|
||||
desktop_file = self._get_desktop_file(app_id)
|
||||
return (
|
||||
self._get_icon_from_desktop_file(desktop_file)
|
||||
if desktop_file
|
||||
else self.default_applicaiton_icon
|
||||
)
|
||||
Reference in new issue
Block a user