diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..ac958f4d --- /dev/null +++ b/.gitignore @@ -0,0 +1,177 @@ +# Created by https://www.toptal.com/developers/gitignore/api/python +# Edit at https://www.toptal.com/developers/gitignore?templates=python + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + +### Python Patch ### +# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration +poetry.toml + +# ruff +.ruff_cache/ + +# LSP config files +pyrightconfig.json + +# End of https://www.toptal.com/developers/gitignore/api/python +n diff --git a/README.md b/README.md index 4a1031a8..f0d640f0 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ +> [!WARNING] +> This configuration is made by myself, for myself, and with very little concern for other's preferences. This configuration is not meant to be "good", it's just meant to be comfortable for me. Let it also known that this is _VERY_ WIP. +

Hyprland

@@ -16,9 +19,6 @@
-> [!WARNING] -> This configuration is made by myself, for myself, and with very little concern for other's preferences. This configuration is not meant to be "good", it's just meant to be comfortable for me. Let it also known that this is _VERY_ WIP. - > [!NOTE] > This repository is in the alpha stage and primarily for personal use. The organization and configurations may change significantly in the future. diff --git a/assets/rice.png b/assets/rice.png index 943be160..0ed8e642 100644 Binary files a/assets/rice.png and b/assets/rice.png differ diff --git a/config/fabric/assets/config.json b/config/fabric/assets/config.json new file mode 100644 index 00000000..56f99727 --- /dev/null +++ b/config/fabric/assets/config.json @@ -0,0 +1,39 @@ +{ + "commands": [ + { + "command": ":em", + "description": "Copy an emoji", + "handler": "show_emojis" + }, + { + "command": ":sh", + "description": "Run executables from PATH", + "handler": "show_shell_commands" + }, + { + "command": ":wl", + "description": "Set the wallpaper", + "handler": "show_wallpapers" + }, + { + "command": ":nw", + "description": "List of available wifi networks", + "handler": "show_network" + }, + { + "command": ":bt", + "description": "Bluetooth", + "handler": "show_bluetooth_settings" + }, + { + "command": ":ch", + "description": "Copy a clipboard history entry", + "handler": "show_clipboard_history" + }, + { + "command": ":p", + "description": "Shutdown and go sleepy time", + "handler": "show_powermenu" + } + ] +} diff --git a/config/fabric/main.py b/config/fabric/main.py index 5d8a7541..ae81ed08 100644 --- a/config/fabric/main.py +++ b/config/fabric/main.py @@ -1,5 +1,6 @@ import os +import setproctitle from loguru import logger from fabric import Application @@ -10,7 +11,7 @@ from services import Brightness, ScreenRecorder def apply_style(app: Application): logger.info("[Main] CSS applied") - app.set_stylesheet_from_file(get_relative_path("style/main.css")) + app.set_stylesheet_from_file(get_relative_path("styles/main.css")) if __name__ == "__main__": @@ -21,22 +22,16 @@ if __name__ == "__main__": bar = Bar() launcher = Launcher() launcher.hide() - systemOverlay = OSDContainer() + osd = OSDContainer() notif = NotificationPopup() - app = Application( - "fabric-bar", - bar, - launcher, - notif, - systemOverlay, - ) - # Monitor main.css file for changes - main_css_file = monitor_file(get_relative_path("style/main.css")) - main_css_file.connect("changed", lambda *args: apply_style(app)) + app = Application("fabric-bar", bar, launcher, osd) + setproctitle.setproctitle("quickbar") + + css_file = monitor_file(get_relative_path("styles")) + _ = css_file.connect("changed", lambda *_: apply_style(app)) - # Monitor colors.css file for changes color_css_file = monitor_file(f"/home/{os.getlogin()}/.cache/material/colors.css") - color_css_file.connect("changed", lambda *args: apply_style(app)) + _ = color_css_file.connect("changed", lambda *_: apply_style(app)) apply_style(app) diff --git a/config/fabric/modules/bar/bar.py b/config/fabric/modules/bar/bar.py index 5185b721..e565b3fb 100644 --- a/config/fabric/modules/bar/bar.py +++ b/config/fabric/modules/bar/bar.py @@ -1,5 +1,4 @@ from fabric.hyprland.widgets import Language -from fabric.system_tray.widgets import SystemTray from fabric.utils import FormattedString, bulk_replace from fabric.widgets.box import Box from fabric.widgets.button import Button @@ -9,14 +8,14 @@ from fabric.widgets.wayland import WaylandWindow as Window from modules.bar.widgets import ( BatteryLabel, Bluetooth, - HardwareUsage, IdleIndicator, MicrophoneIndicator, Network, PowerProfile, + SystemInfo, + SystemTray, TaskBar, VolumeIndicator, - Weather, workspace, ) @@ -54,9 +53,8 @@ class Bar(Window): self.microphone = MicrophoneIndicator() self.power = PowerProfile() self.workspaces = Button(child=workspace, name="workspaces") - self.info = HardwareUsage() + self.info = SystemInfo() self.idle = IdleIndicator() - self.weather = Weather("Kohalpur") self.applets = Box( name="applets", spacing=4, @@ -80,7 +78,6 @@ class Bar(Window): children=[ self.workspaces, self.info, - self.weather, ], ), center_children=Box( diff --git a/config/fabric/modules/bar/widgets/__init__.py b/config/fabric/modules/bar/widgets/__init__.py index d6901760..e31c7cda 100644 --- a/config/fabric/modules/bar/widgets/__init__.py +++ b/config/fabric/modules/bar/widgets/__init__.py @@ -1,25 +1,24 @@ from .battery import BatteryLabel from .bluetooth import Bluetooth -from .glace import TaskBar from .idle_indicator import IdleIndicator -from .info import HardwareUsage +from .info import SystemInfo from .microphone import MicrophoneIndicator from .network import Network from .powerprofile import PowerProfile +from .systray import SystemTray +from .taskbar import TaskBar from .volume import VolumeIndicator -from .weather import Weather from .workspace import workspace __all__ = [ "BatteryLabel", "Bluetooth", "IdleIndicator", - "HardwareUsage", + "SystemInfo", "MicrophoneIndicator", "Network", "PowerProfile", - "TaskBar", "VolumeIndicator", "workspace", - "Weather", + "TaskBar", ] diff --git a/config/fabric/modules/bar/widgets/battery.py b/config/fabric/modules/bar/widgets/battery.py index fa4a3b87..39ed5549 100644 --- a/config/fabric/modules/bar/widgets/battery.py +++ b/config/fabric/modules/bar/widgets/battery.py @@ -1,6 +1,5 @@ import psutil - -from fabric.utils import invoke_repeater +from fabric import Fabricator from fabric.widgets.box import Box from fabric.widgets.label import Label from snippets import MaterialIcon @@ -36,9 +35,9 @@ class BatteryLabel(Box): def __init__(self, **kwargs): super().__init__(**kwargs) - invoke_repeater(1000, self.update_battery_status, initial_call=True) + Fabricator(interval=1000, poll_from=self.update_battery_status) - def update_battery_status(self): + def update_battery_status(self, *_): battery = psutil.sensors_battery() if battery is None: self.hide() diff --git a/config/fabric/modules/bar/widgets/bluetooth.py b/config/fabric/modules/bar/widgets/bluetooth.py index 6d83d054..a91dd160 100644 --- a/config/fabric/modules/bar/widgets/bluetooth.py +++ b/config/fabric/modules/bar/widgets/bluetooth.py @@ -1,11 +1,11 @@ from fabric.bluetooth import BluetoothClient from fabric.widgets.box import Box -from snippets import MaterialIcon # Import your MaterialIcon function +from snippets import MaterialIcon class Bluetooth(Box): - ICON_ENABLED = "bluetooth" # Use the appropriate Material icon name - ICON_DISABLED = "bluetooth_disabled" # Use the appropriate Material icon name + ICON_ENABLED = "bluetooth" + ICON_DISABLED = "bluetooth_disabled" def __init__(self, **kwargs): super().__init__(**kwargs) @@ -31,5 +31,4 @@ class Bluetooth(Box): self.add(self.bluetooth_icon) def on_destroy(self): - """Disconnect the Bluetooth client when the widget is destroyed.""" self.bluetooth_client.disconnect("changed", self.update_bluetooth_status) diff --git a/config/fabric/modules/bar/widgets/glace.py b/config/fabric/modules/bar/widgets/glace.py deleted file mode 100644 index 518fdde6..00000000 --- a/config/fabric/modules/bar/widgets/glace.py +++ /dev/null @@ -1,97 +0,0 @@ -import gi -from fabric.widgets.box import Box -from fabric.widgets.button import Button -from fabric.widgets.image import Image -from fabric.widgets.wayland import WaylandWindow as Window -from snippets import IconResolver - -gi.require_version("Glace", "0.1") -gi.require_version("Gtk", "3.0") -from gi.repository import Glace, Gtk - - -class TaskBar(Box): - def __init__(self): - self.client_buttons = {} - super().__init__(spacing=10, name="taskbar") - self.icon_resolver = IconResolver() - self._manager = Glace.Manager() - self._manager.connect("client-added", self.on_client_added) - self._manager.connect( - "client-removed", self.on_client_removed - ) # Listen for client removal - - def on_client_added(self, _, client: Glace.Client): - client_image = Image() - client_button = Button( - image=client_image, - on_button_press_event=lambda *_: client.activate(), - ) - self.client_buttons[client.get_id()] = client_button - - client.connect( - "notify::app-id", - lambda *_: client_image.set_from_pixbuf( - self.icon_resolver.get_icon_pixbuf(client.get_app_id(), 24) - ), - ) - - client.connect( - "notify::activated", - lambda *_: ( - client_button.add_style_class("activated") - if client.get_activated() - else client_button.remove_style_class("activated") - ), - ) - tooltip_image = Image(style="padding-bottom: 50px;") - - popover = Window(type="popup", anchor="bottom", child=tooltip_image) - - client_button.connect( - "enter-notify-event", self.on_enter, client, tooltip_image, popover - ) - client_button.connect("leave-notify-event", self.on_leave, popover) - - # client.bind_property("title", client_button, "tooltip-text", 0) - client.connect("close", lambda *_: self.remove(client_button)) - self.add(client_button) - - # After adding a new client, ensure the taskbar is visible - self._update_visibility() - - def on_client_removed(self, _, client: Glace.Client): - # Remove the button associated with the client - client_button = self.client_buttons.pop(client.get_id(), None) - if client_button: - self.remove(client_button) - - # After removing a client, ensure the taskbar visibility is updated - self._update_visibility() - - def on_enter(self, button: Button, event, client, tooltip_image, popover): - x = event.x_root - - def capture_callback(pbuf, user_data): - tooltip_image.set_from_pixbuf( - pbuf.scale_simple(pbuf.get_width() * 0.15, pbuf.get_height() * 0.15, 2) - ) - tooltip_image.set_style(f"padding-bottom: 10px;") - popover.show() if button.is_hovered() else None - - self._manager.capture_client( - client=client, - overlay_cursor=False, - callback=capture_callback, - user_data=None, - ) - - def on_leave(self, button, event, popover: Gtk.Popover): - popover.hide() - - def _update_visibility(self): - # Check if there are any client buttons; if not, hide the taskbar - if len(self.client_buttons) == 0: - self.set_visible(False) - else: - self.set_visible(True) diff --git a/config/fabric/modules/bar/widgets/idle_indicator.py b/config/fabric/modules/bar/widgets/idle_indicator.py index 7a747fbd..886afd14 100644 --- a/config/fabric/modules/bar/widgets/idle_indicator.py +++ b/config/fabric/modules/bar/widgets/idle_indicator.py @@ -1,6 +1,6 @@ +from fabric import Fabricator from fabric.utils import exec_shell_command from fabric.widgets.box import Box -from gi.repository import GLib from snippets import MaterialIcon @@ -10,17 +10,14 @@ class IdleIndicator(Box): def __init__(self, **kwargs): super().__init__(**kwargs) self.idle_icon = self.create_idle_icon() - self.check_idle_status() - - GLib.timeout_add(1000, self.check_idle_status) - + Fabricator(interval=1000, poll_from=self.check_idle_status) self.children = (self.idle_icon,) def create_idle_icon(self): return MaterialIcon(self.ICON_IDLE, size="16px") - def check_idle_status(self): + def check_idle_status(self, *_): try: output = exec_shell_command("pidof wayland-idle-inhibitor.py") output_str = str(output) if output is not None else "" diff --git a/config/fabric/modules/bar/widgets/info.py b/config/fabric/modules/bar/widgets/info.py index 7c0ad615..9e16fbcd 100644 --- a/config/fabric/modules/bar/widgets/info.py +++ b/config/fabric/modules/bar/widgets/info.py @@ -1,5 +1,5 @@ import psutil -from fabric.utils import invoke_repeater +from fabric import Fabricator from fabric.widgets.box import Box from fabric.widgets.button import Button from fabric.widgets.circularprogressbar import CircularProgressBar @@ -8,57 +8,82 @@ from fabric.widgets.overlay import Overlay from snippets import MaterialIcon -class HardwareUsage(Button): - HARDWARE_ITEMS = [ +class SystemInfo(Button): + ICONS = [ ("CPU", "settings_motion_mode"), ("Swap", "swap_horiz"), ("RAM", "memory_alt"), + ("Temp", "thermometer"), ] def __init__(self): - super().__init__(child=self._create_content()) - invoke_repeater(1000, self._update_labels) + super().__init__(child=self._initialize_content()) + Fabricator(poll_from=self._refresh_system_info, interval=1000) - def _create_content(self): + def _initialize_content(self): self.box = Box(orientation="h", name="tray") self.progress_bars = {} self.labels = {} self.icons = {} - for hardware, icon_name in self.HARDWARE_ITEMS: - self.progress_bars[hardware] = self._create_progress_bar() - self.labels[hardware] = Label(style="font-size:14px; margin: 4px;") - self.icons[hardware] = MaterialIcon(icon_name, size="16px") - self._pack_items(hardware) + for system, icon_name in self.ICONS: + self._create_system_item(system, icon_name) return self.box + def _create_system_item(self, system, icon_name): + self.progress_bars[system] = self._create_progress_bar() + self.labels[system] = self._create_label() + self.icons[system] = self._create_icon(icon_name) + + overlay = Overlay(child=self.progress_bars[system], overlays=self.icons[system]) + self.box.pack_start(overlay, False, False, 0) + self.box.pack_start(self.labels[system], False, False, 0) + def _create_progress_bar(self): return CircularProgressBar( name="progress", line_style="round", line_width=1, size=30 ) - def _pack_items(self, hardware): - overlay = Overlay( - child=self.progress_bars[hardware], overlays=self.icons[hardware] - ) - self.box.pack_start(overlay, False, False, 0) - self.box.pack_start(self.labels[hardware], False, False, 0) + def _create_label(self): + return Label(style="font-size:14px; margin: 4px;") - def _update_labels(self): - usages = self._get_hardware_usages() - self._update_progress_bars(usages) + def _create_icon(self, icon_name): + return MaterialIcon(icon_name, size="16px") + + def _refresh_system_info(self, *_): + usages = self._retrieve_system_data() + self._update_tooltip(usages) return True - def _get_hardware_usages(self): + @staticmethod + def _get_device_temperature(): + try: + temps = psutil.sensors_temperatures() + if "coretemp" in temps: + return temps["coretemp"][0].current + elif "cpu_thermal" in temps: + return temps["cpu_thermal"][0].current + return None + except Exception: + return None + + def _retrieve_system_data(self): return { "CPU": round(psutil.cpu_percent()), "RAM": round(psutil.virtual_memory().percent), "Swap": round(psutil.swap_memory().percent), + "Temp": self._get_device_temperature(), } - def _update_progress_bars(self, usages): - for hardware, usage in usages.items(): - self.progress_bars[hardware].value = usage / 100 - self.labels[hardware].set_label(f"{usage}%") - self.progress_bars[hardware].set_tooltip_text(f"{hardware} Usage: {usage}%") + def _update_tooltip(self, usages): + for system, usage in usages.items(): + if usage is None: + usage = 0 + self.labels[system].set_label("N/A") + else: + usage = int(usage) + + self.progress_bars[system].value = usage / 100 + self.labels[system].set_label(f"{usage}") + self.progress_bars[system].set_tooltip_text(f"{system} Usage: {usage}%") diff --git a/config/fabric/modules/bar/widgets/network.py b/config/fabric/modules/bar/widgets/network.py index 8a39d1c7..565ec884 100644 --- a/config/fabric/modules/bar/widgets/network.py +++ b/config/fabric/modules/bar/widgets/network.py @@ -1,7 +1,7 @@ import subprocess import psutil -from fabric.utils import invoke_repeater +from fabric import Fabricator from fabric.widgets.box import Box from snippets import MaterialIcon @@ -9,13 +9,14 @@ from snippets import MaterialIcon class Network(Box): def __init__(self, **kwargs): super().__init__(**kwargs) - self.update_interval = 5000 + self.update_interval = 1000 self.last_status = None - invoke_repeater( - self.update_interval, self.update_network_status, initial_call=True + Fabricator( + interval=self.update_interval, + poll_from=self.update_network_status, ) - def update_network_status(self): + def update_network_status(self, *_): current_status = self.get_network_status() if current_status != self.last_status: self.update_icon(current_status) @@ -68,7 +69,7 @@ class Network(Box): def is_ethernet_connected(self): return any( - self._is_interface_up(interface, ["eth"]) + self._is_interface_up(interface, ["enp", "eth"]) for interface in psutil.net_if_addrs() ) diff --git a/config/fabric/modules/bar/widgets/powerprofile.py b/config/fabric/modules/bar/widgets/powerprofile.py index 39aa982f..c59f2b01 100644 --- a/config/fabric/modules/bar/widgets/powerprofile.py +++ b/config/fabric/modules/bar/widgets/powerprofile.py @@ -1,4 +1,5 @@ -from fabric.utils import exec_shell_command, invoke_repeater +from fabric import Fabricator +from fabric.utils import exec_shell_command from fabric.widgets.box import Box from snippets import MaterialIcon @@ -15,9 +16,9 @@ class PowerProfile(Box): self.profile_icon = None - invoke_repeater(1000, self.update_power_profile, initial_call=True) + Fabricator(interval=1000, poll_from=self.update_power_profile) - def update_power_profile(self): + def update_power_profile(self, *_): profile = self.get_power_profile() self.update_icon(profile) return True diff --git a/config/fabric/modules/bar/widgets/systray.py b/config/fabric/modules/bar/widgets/systray.py new file mode 100644 index 00000000..7ffdf085 --- /dev/null +++ b/config/fabric/modules/bar/widgets/systray.py @@ -0,0 +1,85 @@ +import gi +from gi.repository import Gdk, GdkPixbuf, Gray, Gtk +from loguru import logger + +from fabric.widgets.box import Box +from fabric.widgets.button import Button +from fabric.widgets.image import Image + +gi.require_version("Gray", "0.1") +gi.require_version("Gtk", "3.0") + + +class SystemTray(Box): + + def __init__(self, pixel_size=22, **kwargs) -> None: + super().__init__(name="system-tray", **kwargs) + self.pixel_size = pixel_size + self.watcher = Gray.Watcher() + self.watcher.connect("item-added", self.on_item_added) + + def on_item_added(self, _, identifier: str): + item = self.watcher.get_item_for_identifier(identifier) + item_button = self.do_bake_item_button(item) + item.connect("removed", lambda *args: item_button.destroy()) + item_button.show_all() + self.add(item_button) + + def do_bake_item_button(self, item: Gray.Item) -> Button: + button = Button() + + button.set_tooltip_text(item.get_property("title")) + + # context menu handler + button.connect( + "button-press-event", + lambda button, event: self.on_button_click(button, item, event), + ) + + # get pixel map of item's icon + pixmap = Gray.get_pixmap_for_pixmaps(item.get_icon_pixmaps(), 24) + + # convert the pixmap to a pixbuf + pixbuf: GdkPixbuf.Pixbuf = ( + pixmap.as_pixbuf(self.pixel_size, GdkPixbuf.InterpType.HYPER) + if pixmap is not None + else Gtk.IconTheme() + .get_default() + .load_icon( + item.get_icon_name(), + self.pixel_size, + Gtk.IconLookupFlags.FORCE_SIZE, + ) + ) + + # resize/scale the pixbuf + pixbuf.scale_simple( + self.pixel_size, + self.pixel_size, + GdkPixbuf.InterpType.HYPER, + ) + + image = Image(pixbuf=pixbuf, pixel_size=self.pixel_size) + button.set_image(image) + + return button + + def on_button_click(self, button, item: Gray.Item, event): + match event.button: + case 1: + try: + item.activate(event.x, event.y) + except Exception as e: + logger.error(e) + case 3: + menu = item.get_property("menu") + menu.set_name("system-tray-menu") + if menu: + menu.popup_at_widget( + button, + Gdk.Gravity.SOUTH, + Gdk.Gravity.NORTH, + event, + ) + else: + item.context_menu(event.x, event.y) diff --git a/config/fabric/modules/bar/widgets/taskbar.py b/config/fabric/modules/bar/widgets/taskbar.py index 67291067..298fde29 100644 --- a/config/fabric/modules/bar/widgets/taskbar.py +++ b/config/fabric/modules/bar/widgets/taskbar.py @@ -1,15 +1,13 @@ import json -import os from typing import TypedDict -from gi.repository import GdkPixbuf, GLib, Gtk -from loguru import logger - from fabric.hyprland.widgets import get_hyprland_connection from fabric.utils import exec_shell_command from fabric.widgets.box import Box from fabric.widgets.button import Button from fabric.widgets.image import Image +from gi.repository import GdkPixbuf, GLib, Gtk +from snippets import IconResolver class PagerClient(TypedDict): @@ -31,8 +29,10 @@ class TaskBar(Box): self.connection = get_hyprland_connection() self.icon_size = icon_size self.icon_theme = Gtk.IconTheme.get_default() + self.icon_resolver = IconResolver() self.set_visible(False) + self._icon_cache = {} if self.connection.ready: self.render_with_delay() @@ -45,51 +45,47 @@ class TaskBar(Box): "closewindow", "changefloatingmode", ): - self.connection.connect("event::" + event, lambda *_: self.render(None)) + self.connection.connect(f"event::{event}", lambda *_: self.render()) def render_with_delay(self, *_): GLib.timeout_add(101, self.render) def render(self, *_): self.children = [] - - clients = self.fetch_clients() active_window_address = self.get_active_window_address() - visible_clients = [ - client for client in clients if client["mapped"] and not client["hidden"] - ] - - if visible_clients: - for client in visible_clients: + for client in self.fetch_clients(): + if client["mapped"] and not client["hidden"]: window_class = client["initialClass"].lower() icon = self.bake_window_icon(window_class) button = Button(image=icon, tooltip_text=client["title"]) if client["address"] == active_window_address: - button.set_style( - "background-color: @surfaceVariant; border-radius:100px;" - ) + button.add_style_class("activated") button.connect( "button-press-event", self.on_icon_click, client["address"] ) self.add(button) - self.set_visible(True) + self.set_visible(len(self.children) > 0) + if self.children: self.show_all() - else: - self.set_visible(False) def get_active_window_address(self) -> str: - # Fetch the address of the currently active window active_window_info = json.loads( self.connection.send_command("j/activewindow").reply.decode() ) return active_window_info.get("address", "") def on_icon_click(self, widget, event, address): - exec_shell_command(f"hyprctl dispatch focuswindow address:{address}") + command = ( + "focuswindow" + if event.button == 1 + else "closewindow" if event.button == 3 else None + ) + if command: + exec_shell_command(f"hyprctl dispatch {command} address:{address}") def fetch_clients(self) -> list[PagerClient]: return json.loads(self.connection.send_command("j/clients").reply.decode()) @@ -97,51 +93,21 @@ class TaskBar(Box): def bake_window_icon( self, window_class: str, fallback_icon: str = "image-missing" ) -> Image: - icon_name = self.get_icon_from_desktop_entry(window_class) - - if icon_name: + icon_name = self.icon_resolver.get_icon_name(window_class) or fallback_icon + if icon_name not in self._icon_cache: pixbuf = self.load_icon(icon_name) - else: - pixbuf = self.load_icon(window_class, fallback_icon) - - return Image(pixbuf=pixbuf, size=self.icon_size) - - def get_icon_from_desktop_entry(self, window_class: str) -> str: - for data_dir in GLib.get_system_data_dirs(): - applications_dir = os.path.join(data_dir, "applications") - - if os.path.isdir(applications_dir): - for desktop_file in os.listdir(applications_dir): - if desktop_file.endswith(".desktop"): - file_path = os.path.join(applications_dir, desktop_file) - try: - with open(file_path, "r") as f: - app_name = None - icon_name = None - for line in f: - if line.startswith("Name="): - app_name = line.split("=", 2)[1].strip().lower() - elif line.startswith("Icon=") and app_name: - icon_name = line.split("=", 2)[1].strip() - if window_class in app_name: - return icon_name - except Exception as e: - logger.error(f"Error reading {file_path}: {e}") - return None + self._icon_cache[icon_name] = pixbuf + return Image(pixbuf=self._icon_cache[icon_name], size=self.icon_size) def load_icon( self, icon_name: str, fallback_icon: str = "image-missing" ) -> GdkPixbuf.Pixbuf: try: pixbuf = self.icon_theme.load_icon( - icon_name, - self.icon_size, - Gtk.IconLookupFlags.FORCE_SIZE, + icon_name, self.icon_size, Gtk.IconLookupFlags.FORCE_SIZE ) except Exception: pixbuf = self.icon_theme.load_icon( - fallback_icon, - self.icon_size, - Gtk.IconLookupFlags.FORCE_SIZE, + fallback_icon, self.icon_size, Gtk.IconLookupFlags.FORCE_SIZE ) return pixbuf diff --git a/config/fabric/modules/bar/widgets/volume.py b/config/fabric/modules/bar/widgets/volume.py index 90610c28..e7ded21d 100644 --- a/config/fabric/modules/bar/widgets/volume.py +++ b/config/fabric/modules/bar/widgets/volume.py @@ -1,5 +1,6 @@ +from fabric import Fabricator from fabric.audio.service import Audio -from fabric.utils import exec_shell_command, invoke_repeater +from fabric.utils import exec_shell_command from fabric.widgets.box import Box from fabric.widgets.button import Button from snippets import MaterialIcon @@ -23,7 +24,7 @@ class VolumeIndicator(Box): self.volume_icon_button.connect("button-press-event", self.on_button_press) self.audio_service.connect("changed", self.update_volume_status) - invoke_repeater(1000, self.update_volume_status, initial_call=True) + Fabricator(interval=1000, poll_from=self.update_volume_status) self.children = (self.volume_icon_button,) def create_volume_icon(self): @@ -47,7 +48,7 @@ class VolumeIndicator(Box): def open_audio_settings(self): exec_shell_command("pavucontrol") - def update_volume_status(self, *args): + def update_volume_status(self, *_): current_stream = self.audio_service.speaker if current_stream: self.update_icon(current_stream) @@ -55,7 +56,6 @@ class VolumeIndicator(Box): return True def update_icon(self, stream): - """Update the icon based on the current stream status.""" if stream.muted: icon_name = VOLUME_ICONS["muted"] volume_percentage = 0 @@ -71,7 +71,6 @@ class VolumeIndicator(Box): self.volume_icon_button.set_tooltip_text(tooltip_text) def get_volume_icon(self, volume_level): - """Determine the appropriate icon based on the volume level.""" if volume_level == 0: return VOLUME_ICONS["low"] elif volume_level <= 33: diff --git a/config/fabric/modules/bar/widgets/weather.py b/config/fabric/modules/bar/widgets/weather.py deleted file mode 100644 index 8720c6c0..00000000 --- a/config/fabric/modules/bar/widgets/weather.py +++ /dev/null @@ -1,32 +0,0 @@ -from services import WeatherInfo - -from fabric.utils import invoke_repeater -from fabric.widgets.box import Box -from fabric.widgets.label import Label - - -class Weather(Box): - def __init__( - self, - city: str, - interval: int = 60000, - enable_tooltip=True, - ): - super().__init__(name="tray") - self.enable_tooltip = enable_tooltip - self.city = city - - self.weather_service = WeatherInfo() - - self.weather_label = Label(label="weather") - self.children = self.weather_label - - invoke_repeater(interval, self.update_label, initial_call=True) - - def update_label(self): - res = self.weather_service.simple_weather_info(city=self.city) - self.weather_label.set_label(f"{res["icon"]} {res["temperature"]}") - - if self.enable_tooltip: - self.set_tooltip_text(f"{res["city"]}, {res["condition"]}".strip("'")) - return True diff --git a/config/fabric/modules/launcher/launcher.py b/config/fabric/modules/launcher/launcher.py index 08fc1850..37636106 100644 --- a/config/fabric/modules/launcher/launcher.py +++ b/config/fabric/modules/launcher/launcher.py @@ -1,36 +1,38 @@ -import os - from fabric.utils import ( - exec_shell_command, - exec_shell_command_async, get_desktop_applications, idle_add, + invoke_repeater, remove_handler, ) from fabric.widgets.box import Box +from fabric.widgets.button import Button from fabric.widgets.entry import Entry +from fabric.widgets.label import Label from fabric.widgets.revealer import Revealer from fabric.widgets.scrolledwindow import ScrolledWindow from fabric.widgets.wayland import WaylandWindow as Window -from loguru import logger from modules.launcher.widgets import ( + BluetoothMenu, ClipboardManager, EmojiManager, + PowerMenu, ShellCommandManager, WallpaperManager, + WifiMenu, handle_application_search, ) +from snippets import ( + MaterialIcon, + get_current_uptime, + get_profile_picture_path, + read_config, + username, +) class Launcher(Window): - COMMAND_ICONS = { - "/e": "face-smile-symbolic", - "/c": "edit-copy-symbolic", - "/s": "utilities-terminal-symbolic", - "/w": "image-symbolic", - } - def __init__(self, **kwargs): + self.config = read_config() super().__init__( layer="top", anchor="center", @@ -42,27 +44,45 @@ class Launcher(Window): ) self.all_apps = get_desktop_applications() self.initialize_managers() + self.uptime_label = Label( + label=get_current_uptime(), style="margin-left: 60px;" + ) + self.commands = self.config.get("commands", []) + self.command_map = self.build_command_map() self.setup_ui() self.connect("key-press-event", self.on_key_press) + self.update_uptime_label() def initialize_managers(self): self.clipboard_manager = ClipboardManager(self, self.get_viewport()) self.emoji_manager = EmojiManager(self) self.shell_command_manager = ShellCommandManager(self) self.wallpaper_manager = WallpaperManager() - self.idle_inhibitor = False + self.power_menu = PowerMenu(self) + self.bluetooth_menu = BluetoothMenu(self) + self.network_menu = WifiMenu(self) def setup_ui(self): + self.default_button = Button( + child=MaterialIcon("grid_view"), + h_align="center", + v_align="center", + ) self.scrolled_window = self.create_scrolled_window() self.scrolled_revealer = self.create_revealer() self.search_entry = self.create_search_entry() - + self.additional_box = self.create_additional_box() + self.search_box = Box( + spacing=10, + orientation="h", + children=[self.search_entry, self.default_button], + ) launcher_box = Box( orientation="v", - size=(550, 0), name="launcher", children=[ - Box(spacing=10, orientation="h", children=[self.search_entry]), + self.search_box, + self.additional_box, self.scrolled_revealer, ], ) @@ -70,15 +90,17 @@ class Launcher(Window): self.show_all() def create_search_entry(self): - self.entry = Entry( - placeholder="Search.....", + entry = Entry( + placeholder="Type ':' to list subcommands", h_expand=True, notify_text=lambda entry, *_: self.debounce_search(entry.get_text()), ) - return self.entry + entry.set_icon_from_icon_name(0, "preferences-system-search-symbolic") + return entry def create_scrolled_window(self): return ScrolledWindow( + style=" transition: min-height 50s cubic-bezier(0.42, 0, 0.58, 1);", child=self.get_viewport(), h_scrollbar_policy="never", v_scrollbar_policy="never", @@ -86,9 +108,23 @@ class Launcher(Window): def create_revealer(self): return Revealer( + style=" transition: min-height 50s cubic-bezier(0.42, 0, 0.58, 1);", child=self.scrolled_window, - transition_duration=300, - transition_type="slide-down", + transition_type="crossfade", + ) + + def create_additional_box(self): + return Box( + orientation="h", + spacing=10, + children=[ + Box( + name="profile-pic", + style=f"background-image: url(\"file://{get_profile_picture_path() or ''}\")", + ), + Label(label=username()), + self.uptime_label, + ], ) def get_viewport(self): @@ -96,6 +132,47 @@ class Launcher(Window): self.viewport = Box(spacing=10, orientation="v") return self.viewport + def update_uptime_label(self): + self.uptime_label.set_label(get_current_uptime()) + invoke_repeater( + 60 * 1000, lambda: self.uptime_label.set_label(get_current_uptime()) + ) + + def build_command_map(self): + return {cmd["command"]: cmd["handler"] for cmd in self.commands} + + def debounce_search(self, query: str): + if hasattr(self, "_arranger_handler"): + remove_handler(self._arranger_handler) + self._arranger_handler = idle_add(self.arrange_viewport, query, pin=True) + + def arrange_viewport(self, query: str = ""): + + self.get_viewport().children = [] + dynamic_buttons = [] + for command, handler_name in self.command_map.items(): + if query.startswith(command): + handler = getattr(self, handler_name, None) + if handler: + handler(query[len(command) :].strip()) + return + + if query.startswith(":"): + self.additional_box.set_visible(False) + self.update_dynamic_button([self.default_button]) + self.show_help(query[1:]) + self.scrolled_revealer.reveal() + return + handle_application_search(self, query) + + def update_dynamic_button(self, new_buttons): + if not isinstance(new_buttons, list): + new_buttons = [new_buttons] + for child in self.search_box.children[1:]: + self.search_box.remove(child) + for new_button in new_buttons: + self.search_box.add(new_button) + def on_key_press(self, widget, event): from gi.repository import Gdk @@ -104,88 +181,92 @@ class Launcher(Window): return True return False - def debounce_search(self, query: str): - if hasattr(self, "_arranger_handler"): - remove_handler(self._arranger_handler) - self._arranger_handler = idle_add(self.arrange_viewport, query, pin=True) + def load_commands(self): + return {cmd["command"]: cmd["description"] for cmd in self.commands} - def arrange_viewport(self, query: str = ""): - self.clear_viewport() - command_handlers = { - "/e": self.show_emojis, - "/c": self.show_clipboard_history, - "/s": self.show_shell_commands, - "/w": self.show_wallpapers, - "/idle": self.toggle_idle_inhibitor, - } + def show_help(self, query: str): + filtered_help = [ + (command, description) + for command, description in self.load_commands().items() + if query.lower() in command[1:].lower() + ] - for command, handler in command_handlers.items(): - if query.startswith(command): - self.handle_command(command, query, handler) - return + if not filtered_help: + return + for command, description in filtered_help: + button = Button( + child=self.create_help_button_content(command, description), + name="launcher-item", + ) + self.get_viewport().add(button) - self.reset_search_icon() - handle_application_search(self, query) + def create_help_button_content(self, command, description): + return Box( + orientation="h", + spacing=10, + children=[ + Label(label=command, h_expand=True, h_align="start"), + Label( + label=description, + h_expand=True, + h_align="end", + ), + ], + ) - def clear_viewport(self): - # Clear the children of the viewport - self.get_viewport().children = [] + def toggle(self): + self.set_visible(not self.is_visible()) + if self.is_visible(): + self.update_dynamic_button(self.default_button) + self.search_entry.set_text("") + self.search_entry.grab_focus() - def handle_command(self, command: str, query: str, handler): - icon_name = self.get_command_icon(command) - self.entry.set_icon_from_icon_name(0, icon_name) - handler(query[len(command) :].strip()) + def show_network(self, *_): + self.network_menu.show_wifi_menu(self.viewport) + dynamic_buttons = self.network_menu.get_wifi_buttons() + self.update_dynamic_button(dynamic_buttons) self.scrolled_revealer.reveal() - def get_command_icon(self, command: str) -> str: - return self.COMMAND_ICONS.get(command, "") - - def reset_search_icon(self): - self.entry.set_icon_from_icon_name(0, "preferences-system-search-symbolic") - - # def show_desktop_buttons(self, query: str): - # self.desktop_button_manager.show_desktop_buttons(query) - def show_emojis(self, query: str): self.emoji_manager.show_emojis(self.get_viewport(), query) + dynamic_buttons = self.emoji_manager.get_emoji_buttons() + self.update_dynamic_button(dynamic_buttons) + self.scrolled_revealer.reveal() def show_clipboard_history(self, query: str): self.clipboard_manager.show_clipboard_history(self.get_viewport(), query) + dynamic_buttons = self.clipboard_manager.get_clipboard_buttons() + self.update_dynamic_button(dynamic_buttons) + self.scrolled_revealer.reveal() + + def show_powermenu(self, query: str = ""): + self.power_menu.show_power_menu(self.get_viewport(), query) + dynamic_buttons = self.power_menu.get_power_buttons() + self.update_dynamic_button(dynamic_buttons) + self.scrolled_revealer.reveal() def show_shell_commands(self, query: str): if not query: + dynamic_buttons = self.shell_command_manager.get_shell_buttons() + self.update_dynamic_button(dynamic_buttons) self.scrolled_revealer.unreveal() return self.shell_command_manager.show_shell_commands(self.get_viewport(), query) + dynamic_buttons = self.shell_command_manager.get_shell_buttons() + self.update_dynamic_button(dynamic_buttons) + self.scrolled_revealer.reveal() def show_wallpapers(self, query: str): if query == "random": self.wallpaper_manager.apply_wallpaper_random() else: self.wallpaper_manager.show_wallpaper_thumbnails(self.get_viewport(), query) + dynamic_buttons = self.wallpaper_manager.get_wallpaper_buttons() + self.update_dynamic_button(dynamic_buttons) + self.scrolled_revealer.reveal() - def toggle_idle_inhibitor(self, query: str): - - self.idle_inhibitor = not self.idle_inhibitor - script_path = os.path.expanduser( - "~/fabric/assets/scripts/wayland-idle-inhibitor.py" - ) - - if self.idle_inhibitor and not self.check_idle_state(): - exec_shell_command_async( - ["python3", script_path], - lambda output: logger.info(f"Idle inhibitor output: {output}"), - ) - else: - exec_shell_command("pkill -f wayland-idle-inhibitor.py") - - def check_idle_state(self): - return "wayland-idle-inhibitor.py" in exec_shell_command( - "pidof wayland-idle-inhibitor.py" - ) - - def toggle(self): - self.set_visible(not self.is_visible()) - if self.is_visible(): - self.search_entry.set_text("") - self.search_entry.grab_focus() + def show_bluetooth_settings(self, *_): + self.bluetooth_menu.show_bluetooth_menu(self.viewport) + dynamic_buttons = self.bluetooth_menu.get_bluetooth_buttons() + self.update_dynamic_button(dynamic_buttons) + self.scrolled_revealer.reveal() diff --git a/config/fabric/modules/launcher/widgets/__init__.py b/config/fabric/modules/launcher/widgets/__init__.py index 2ae422b6..81e42e29 100644 --- a/config/fabric/modules/launcher/widgets/__init__.py +++ b/config/fabric/modules/launcher/widgets/__init__.py @@ -1,8 +1,11 @@ from .app import handle_application_search +from .bluetooth import BluetoothMenu from .clipboard import ClipboardManager from .emoji import EmojiManager +from .power_menu import PowerMenu from .shell import ShellCommandManager from .wallpaper import WallpaperManager +from .wifi import WifiMenu __all__ = [ "handle_application_search", @@ -10,4 +13,7 @@ __all__ = [ "EmojiManager", "ShellCommandManager", "WallpaperManager", + "WifiMenu", + "BluetoothMenu", + "PowerMenu", ] diff --git a/config/fabric/modules/launcher/widgets/app.py b/config/fabric/modules/launcher/widgets/app.py index 6869eb63..40c92df9 100644 --- a/config/fabric/modules/launcher/widgets/app.py +++ b/config/fabric/modules/launcher/widgets/app.py @@ -1,4 +1,3 @@ -from fabric.utils import DesktopApp from fabric.widgets.box import Box from fabric.widgets.button import Button from fabric.widgets.image import Image @@ -6,67 +5,59 @@ from fabric.widgets.label import Label def handle_application_search(launcher, query: str): - if not query.strip(): + query = query.strip() + # Reveal the full app list if the query is empty + if not query: + launcher.additional_box.set_visible(True) launcher.scrolled_revealer.unreveal() return + # Hide full app list and search through the available apps + launcher.additional_box.set_visible(False) filtered_apps = [ app for app in launcher.all_apps if query.casefold() in ( - (app.display_name or "") - + " " - + (app.name or "") - + " " - + (app.generic_name or "") + " ".join(filter(None, [app.display_name, app.name, app.generic_name])) ).casefold() ] + # Display filtered apps or hide the search results view if no matches if filtered_apps: - # Limit to the first 6 applications - limited_apps = filtered_apps[:6] launcher.viewport.children = [ - bake_application_slot(launcher, app) for app in limited_apps + Button( + child=Box( + orientation="h", + spacing=10, + children=[ + Image(pixbuf=app.get_icon_pixbuf(), h_align="start", size=68), + Box( + orientation="v", + spacing=10, + children=[ + Label( + name="title", + label=app.display_name or "Unknown", + h_align="start", + v_align="center", + ), + Label( + name="description", + label=app.description or "", + justification="left", + line_wrap="char", + v_align="center", + ), + ], + ), + ], + ), + name="app-item", + on_clicked=lambda *_: (app.launch(), launcher.set_visible(False)), + ) + for app in filtered_apps[:6] # Limit to 6 apps ] launcher.scrolled_revealer.reveal() else: launcher.scrolled_revealer.unreveal() - - -def bake_application_slot(launcher, app: DesktopApp, **kwargs) -> Button: - app_slot = Box( - orientation="h", - spacing=10, - children=[ - Image(pixbuf=app.get_icon_pixbuf(), h_align="start", size=62), - Box( - orientation="v", - spacing=5, - children=[ - Label( - label=app.display_name or "Unknown", - h_expand=True, - name="title", - v_align="center", - h_align="start", - ), - Label( - label=app.description or "", - name="description", - h_expand=True, - v_align="center", - justification="left", - line_wrap="char", - ), - ], - ), - ], - ) - - return Button( - child=app_slot, - name="app-item", - on_clicked=lambda *_: (app.launch(), launcher.set_visible(False)), - **kwargs, - ) diff --git a/config/fabric/modules/launcher/widgets/bluetooth.py b/config/fabric/modules/launcher/widgets/bluetooth.py new file mode 100644 index 00000000..03cd0523 --- /dev/null +++ b/config/fabric/modules/launcher/widgets/bluetooth.py @@ -0,0 +1,91 @@ +from fabric.bluetooth import BluetoothClient +from fabric.widgets.box import Box +from fabric.widgets.button import Button +from fabric.widgets.image import Image +from fabric.widgets.label import Label +from snippets import MaterialIcon + + +class BluetoothMenu: + def __init__(self, launcher): + self.launcher = launcher + self.client = BluetoothClient(on_device_added=self.on_device_added) + self.paired_devices = {} + self.available_devices = {} + + self.bt_button = self.create_bluetooth_button() + self.scan_button = self.create_scan_button() + self.update_bt_button_style() + + def create_bluetooth_button(self): + button = Button( + child=MaterialIcon("bluetooth"), + h_align="center", + v_align="center", + on_clicked=self.bt_toggle, + ) + return button + + def create_scan_button(self): + return Button( + child=MaterialIcon("refresh"), + h_align="center", + v_align="center", + on_clicked=lambda *_: self.client.toggle_scan(), + ) + + def bt_toggle(self, *_): + self.client.toggle_power() + self.update_bt_button_style() + + def update_bt_button_style(self): + style = ( + "background-color: transparent;" + if self.client.enabled + else "background-color: @surfaceVariant; min-height: 50px; min-width: 50px;" + ) + self.bt_button.set_style(style) + + def show_bluetooth_menu(self, viewport): + viewport.children = [] + devices_box = Box(orientation="v", spacing=5) + + # Combine paired and available devices + all_devices = {**self.paired_devices, **self.available_devices} + for address, device in all_devices.items(): + device_button = self.create_device_button(device) + devices_box.add(device_button) + + viewport.add(devices_box) + + def create_device_button(self, device): + connection_status = "Connected" if device.connected else "" + return Button( + child=Box( + orientation="h", + spacing=10, + children=[ + Image(icon_name=device.icon_name, size=32), + Label(label=device.name), + Label(label=connection_status, h_align="end"), + ], + ), + on_clicked=lambda _, device=device: self.connect_to_device(device), + name="launcher-item", + ) + + def connect_to_device(self, device): + device.set_connecting(True) + self.show_bluetooth_menu(self.launcher.viewport) + + def on_device_added(self, client, address): + if device := client.get_device(address): + if device.paired: + self.paired_devices[address] = device + else: + self.available_devices[address] = device + + self.show_bluetooth_menu(self.launcher.viewport) + + def get_bluetooth_buttons(self): + return [self.bt_button, self.scan_button] diff --git a/config/fabric/modules/launcher/widgets/clipboard.py b/config/fabric/modules/launcher/widgets/clipboard.py index c317f414..4b7b5cb2 100644 --- a/config/fabric/modules/launcher/widgets/clipboard.py +++ b/config/fabric/modules/launcher/widgets/clipboard.py @@ -1,11 +1,11 @@ import os import subprocess -from gi.repository import GLib - +from fabric import Fabricator from fabric.widgets.button import Button from fabric.widgets.image import Image from fabric.widgets.label import Label +from snippets import MaterialIcon class ClipboardManager: @@ -13,52 +13,66 @@ class ClipboardManager: self.launcher = launcher self.viewport = viewport self.clipboard_history = [] - self.update_clipboard_history() - self.refresh_ui() - GLib.timeout_add(10000, self.update_clipboard_history) + self._initialize_clipboard_watcher() + + def _initialize_clipboard_watcher(self): + self.wl_paste_watcher = Fabricator( + poll_from="wl-paste --watch echo", stream=True, interval=-1 + ) + self.wl_paste_watcher.connect( + "changed", lambda *_: self.update_clipboard_history() + ) def get_clip_history(self): try: result = subprocess.run( ["cliphist", "list"], capture_output=True, text=True, check=True ) - return [ - {"text": line.strip(), "id": line.split()[0]} - for line in result.stdout.splitlines() - if line.strip() - ][:10] + return self._parse_clip_history(result.stdout) except subprocess.CalledProcessError: return [] + def _parse_clip_history(self, output): + return [ + {"content": line.strip(), "id": line.split()[0]} + for line in output.splitlines() + if line.strip() + ][:10] + def update_clipboard_history(self): new_history = self.get_clip_history() if new_history != self.clipboard_history: self.clipboard_history = new_history self.refresh_ui() - return True def refresh_ui(self): + self._clear_viewport() + self.show_clipboard_history(self.viewport) + + def _clear_viewport(self): for child in self.viewport.children: self.viewport.remove(child) - self.show_clipboard_history(self.viewport, "") def run_command(self, command, input_data=None): try: - if input_data is not None: - input_data = input_data.encode() + input_data = self._ensure_bytes(input_data) return subprocess.run( command, input=input_data, capture_output=True, check=True ) except subprocess.CalledProcessError: return None - def copy_by_id(self, clip_id: str): - result = self.run_command(["cliphist", "decode", clip_id]) - if result: - self.run_command(["wl-copy"], input=result.stdout) + def _ensure_bytes(self, input_data): + if input_data and not isinstance(input_data, bytes): + return input_data.encode() # Ensure input data is in bytes + return input_data - def clear_clipboard(self): - self.run_command(["cliphist", "wipe"]) + def copy_by_id(self, clip_id: str): + command = f"cliphist decode {clip_id} | wl-copy" + try: + subprocess.run(command, shell=True, check=True) + except subprocess.CalledProcessError: + pass def save_cache_file(self, clip_id: str): output_file = f"/tmp/cliphist/{clip_id}.png" @@ -66,28 +80,29 @@ class ClipboardManager: result = self.run_command(["cliphist", "decode", clip_id]) if result: - with open(output_file, "wb") as f: - f.write(result.stdout) + self._write_to_cache(output_file, result.stdout) return output_file return None - def clear_tmp(self): - self.run_command(["rm", "-rf", "/tmp/cliphist/*"]) + def _write_to_cache(self, output_file, data): + with open(output_file, "wb") as f: + f.write(data) - def show_clipboard_history(self, viewport, query: str): - filtered_history = [ - item for item in self.clipboard_history if query in item["text"] - ] + def show_clipboard_history(self, viewport, query=""): + filtered_history = self._filter_clip_history(query) for item in filtered_history: self.add_clipboard_item(viewport, item) - def add_clipboard_item(self, viewport, item): - if "png" in item["text"]: - self.add_image_button(viewport, item) - else: - self.add_label_button(viewport, item) + def _filter_clip_history(self, query): + return [item for item in self.clipboard_history if query in item["content"]] - def add_image_button(self, viewport, item): + def add_clipboard_item(self, viewport, item): + if "png" in item["content"]: + self._add_image_button(viewport, item) + else: + self._add_text_button(viewport, item) + + def _add_image_button(self, viewport, item): output_file = self.save_cache_file(item["id"]) if output_file and os.path.exists(output_file): image_button = Button( @@ -100,18 +115,17 @@ class ClipboardManager: ) image_button.set_style(f"background-image: url('{output_file}');") viewport.add(image_button) - # GLib.timeout_add(3000, lambda: self.cleanup_file(output_file)) - def add_label_button(self, viewport, item): + def _add_text_button(self, viewport, item): label_button = Button( child=Label( - label=item["text"][:55], + label=item["content"][:55], # Truncate text for display h_expand=True, v_align="center", h_align="start", ), on_clicked=lambda _, clip_id=item["id"]: self.handle_clip_click(clip_id), - name="cliphist-item", + name="launcher-item", ) viewport.add(label_button) @@ -119,8 +133,5 @@ class ClipboardManager: self.copy_by_id(clip_id) self.launcher.set_visible(False) - def cleanup_file(self, file_path): - try: - os.remove(file_path) - except FileNotFoundError: - pass + def get_clipboard_buttons(self): + return MaterialIcon("content_paste") diff --git a/config/fabric/modules/launcher/widgets/emoji.py b/config/fabric/modules/launcher/widgets/emoji.py index 1ded6210..f73e7feb 100644 --- a/config/fabric/modules/launcher/widgets/emoji.py +++ b/config/fabric/modules/launcher/widgets/emoji.py @@ -1,15 +1,17 @@ import json import os import subprocess +from typing import Generator, List from fabric.widgets.box import Box from fabric.widgets.button import Button from fabric.widgets.label import Label +from snippets import MaterialIcon class EmojiItem: - def __init__(self, str: str, name: str, slug: str, group: str): - self.str = str + def __init__(self, emoji_str: str, name: str, slug: str, group: str): + self.str = emoji_str self.name = name self.slug = slug self.group = group @@ -18,37 +20,42 @@ class EmojiItem: class EmojiManager: def __init__(self, launcher): self.launcher = launcher - self.emojis = None # Delay loading until first use - self.query_cache = {} + self.emojis: List[EmojiItem] = [] + self.query_cache: dict = {} - def load_emojis(self): - if self.emojis is None: - emoji_path = os.path.expanduser("~/fabric/assets/emoji.json") - try: - with open(emoji_path, "r") as f: - data = json.load(f) - self.emojis = [ - EmojiItem(str, item["name"], item["slug"], item["group"]) - for str, item in data.items() - ] - except Exception as e: - print(f"Error loading emojis: {e}") - self.emojis = [] + def load_emojis(self) -> Generator[EmojiItem, None, None]: + emoji_path = os.path.expanduser("~/fabric/assets/emoji.json") + if not os.path.exists(emoji_path): + return - def query_emojis(self, query: str): - # Return cached results if available + try: + with open(emoji_path, "r") as file: + data = json.load(file) + for emoji_str, item in data.items(): + yield EmojiItem( + emoji_str, item["name"], item["slug"], item["group"] + ) + except (json.JSONDecodeError, OSError): + return + + def get_emojis(self) -> List[EmojiItem]: + if not self.emojis: + self.emojis = list(self.load_emojis()) + return self.emojis + + def query_emojis(self, query: str) -> List[EmojiItem]: if query in self.query_cache: return self.query_cache[query] - self.load_emojis() # Ensure emojis are loaded - + emojis = self.get_emojis() filtered_emojis = [ - e - for e in self.emojis - if query in e.name or query in e.slug or query in e.group - ][:44] + emoji + for emoji in emojis + if query.lower() in emoji.name.lower() + or query.lower() in emoji.slug.lower() + or query.lower() in emoji.group.lower() + ][:48] - # Cache the results self.query_cache[query] = filtered_emojis return filtered_emojis @@ -58,24 +65,28 @@ class EmojiManager: def show_emojis(self, viewport, query: str): filtered_emojis = self.query_emojis(query) - row = Box(orientation="h", spacing=10) + self._display_emoji_grid(viewport, filtered_emojis) - for emoji_item in filtered_emojis: - button = self.bake_emoji_slot(emoji_item) + def _display_emoji_grid(self, viewport, emojis: List[EmojiItem]): + row = Box(orientation="h", spacing=10) + for emoji in emojis: + button = self._create_emoji_button(emoji) row.add(button) - if len(row.children) >= 11: + if len(row.children) >= 12: viewport.add(row) row = Box(orientation="h", spacing=10) if row.children: viewport.add(row) - def bake_emoji_slot(self, emoji: EmojiItem, **kwargs) -> Button: + def _create_emoji_button(self, emoji: EmojiItem) -> Button: return Button( child=Label(label=emoji.str, h_pack="start"), tooltip_text=f"Copy {emoji.name}", on_clicked=lambda *_: self.copy_emoji(emoji), name="emoji-item", - **kwargs, ) + + def get_emoji_buttons(self): + return MaterialIcon("mood") diff --git a/config/fabric/modules/launcher/widgets/power_menu.py b/config/fabric/modules/launcher/widgets/power_menu.py new file mode 100644 index 00000000..f24eb5c8 --- /dev/null +++ b/config/fabric/modules/launcher/widgets/power_menu.py @@ -0,0 +1,102 @@ +import os + +from fabric.utils import exec_shell_command, exec_shell_command_async +from fabric.widgets.box import Box +from fabric.widgets.button import Button +from fabric.widgets.label import Label +from loguru import logger +from snippets import MaterialIcon + +IDLE_BUTTON_ACTIVE_STYLE = "background-color: @surfaceVariant; min-width:50px; min-height:50px; border-radius:100px;" +IDLE_BUTTON_INACTIVE_STYLE = "background-color: transparent;" + + +class PowerMenu: + def __init__(self, launcher): + self.launcher = launcher + self.idle_inhibitor = False + self.idle_button = Button( + child=MaterialIcon("schedule"), + v_align="center", + on_clicked=self.toggle_idle_inhibitor, + ) + self.idle_button.set_style(IDLE_BUTTON_INACTIVE_STYLE) + + def toggle_idle_inhibitor(self, *_): + self.idle_inhibitor = not self.idle_inhibitor + script_path = os.path.expanduser( + "~/fabric/assets/scripts/wayland-idle-inhibitor.py" + ) + + if self.idle_inhibitor and not self.check_idle_state(): + exec_shell_command_async( + ["python3", script_path], + lambda output: logger.info(f"Idle inhibitor output: {output}"), + ) + self.idle_button.set_style(IDLE_BUTTON_ACTIVE_STYLE) + else: + exec_shell_command("pkill -f wayland-idle-inhibitor.py") + self.idle_button.set_style(IDLE_BUTTON_INACTIVE_STYLE) + + def check_idle_state(self): + pid_check = exec_shell_command("pidof wayland-idle-inhibitor.py") + return "wayland-idle-inhibitor.py" in pid_check + + def show_power_menu(self, viewport, query: str = ""): + viewport.children = [] + + power_options = [ + { + "label": "Shutdown", + "icon": "power_settings_new", + "action": self.shutdown, + }, + {"label": "Logout", "icon": "logout", "action": self.logout}, + {"label": "Reboot", "icon": "restart_alt", "action": self.reboot}, + {"label": "Suspend", "icon": "sleep", "action": self.suspend}, + {"label": "Lock", "icon": "lock", "action": self.lock}, + ] + + # Filter power options based on the query using a generator + filtered_options = ( + ( + option + for option in power_options + if query.lower() in option["label"].lower() + ) + if query + else power_options + ) + + for option in filtered_options: + button = Button( + child=Box( + orientation="h", + spacing=10, + children=[ + MaterialIcon(option["icon"], size="28px"), + Label(label=option["label"], h_align="start"), + ], + ), + on_clicked=lambda _, action=option["action"]: action(), + name="launcher-item", + ) + viewport.add(button) + + def shutdown(self): + exec_shell_command("systemctl poweroff") + + def reboot(self): + exec_shell_command("systemctl reboot") + + def suspend(self): + exec_shell_command("systemctl suspend") + + def logout(self): + exec_shell_command("hyprctl dispatch logout") + + def lock(self): + exec_shell_command("hyprlock --immediate") + + def get_power_buttons(self): + return self.idle_button diff --git a/config/fabric/modules/launcher/widgets/shell.py b/config/fabric/modules/launcher/widgets/shell.py index 32f0caca..729c6544 100644 --- a/config/fabric/modules/launcher/widgets/shell.py +++ b/config/fabric/modules/launcher/widgets/shell.py @@ -3,44 +3,43 @@ import subprocess from fabric.widgets.button import Button from fabric.widgets.label import Label +from snippets import MaterialIcon CACHE_DIR = os.getenv( "XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache", "fabric") ) -BINS_PATH = os.path.join(CACHE_DIR, "binaries") +BINS = os.path.join(CACHE_DIR, "binaries") class ShellCommandManager: def __init__(self, launcher): self.launcher = launcher + self.binaries = set() # Use a set to store unique binaries self.reload_binaries() def reload_binaries(self): - """Reload the binaries from the PATH environment variable.""" paths = os.getenv("PATH", "").split(":") - unique_bins = set() + self.binaries = set() for path in paths: - unique_bins.update(self.list_binaries_in_path(path)) + self.binaries.update(self.list_binaries_in_path(path)) - self.save_binaries_to_cache(unique_bins) + # Write unique binaries to the cache file + with open(BINS, "w") as f: + f.write("\n".join(self.binaries)) def list_binaries_in_path(self, path): if not os.path.exists(path): return [] try: - return ( - subprocess.check_output(f"ls {path}", shell=True, text=True) - .strip() - .splitlines() - ) - except subprocess.CalledProcessError: + return [ + entry + for entry in os.listdir(path) + if os.access(os.path.join(path, entry), os.X_OK) + ] + except OSError: return [] - def save_binaries_to_cache(self, binaries): - with open(BINS_PATH, "w") as f: - f.write("\n".join(binaries)) - def show_shell_commands(self, viewport, search_query: str): if not search_query: return @@ -48,12 +47,10 @@ class ShellCommandManager: results = self.query_binaries(search_query) self.display_results(viewport, results) - def query_binaries(self, filter_str): - try: - with open(BINS_PATH) as f: - return [line.strip() for line in f if filter_str in line][:16] - except FileNotFoundError: - return [] + def query_binaries(self, filter_str: str): + # Use a generator to filter binaries on demand + filtered_bins = (cmd for cmd in self.binaries if filter_str in cmd) + return list(dict.fromkeys(filtered_bins))[:16] # Deduplicate and limit to 16 def display_results(self, viewport, results): for command in results: @@ -64,7 +61,7 @@ class ShellCommandManager: h_align="start", ), on_clicked=lambda _, cmd=command: self.execute_command(cmd), - name="sh-item", + name="launcher-item", ) viewport.add(button) @@ -76,3 +73,6 @@ class ShellCommandManager: print(e.output) finally: self.launcher.set_visible(False) + + def get_shell_buttons(self): + return MaterialIcon("terminal") diff --git a/config/fabric/modules/launcher/widgets/wallpaper.py b/config/fabric/modules/launcher/widgets/wallpaper.py index c285af90..a0e99000 100644 --- a/config/fabric/modules/launcher/widgets/wallpaper.py +++ b/config/fabric/modules/launcher/widgets/wallpaper.py @@ -1,23 +1,58 @@ import os +import threading from pathlib import Path -from loguru import logger - -from fabric.utils import exec_shell_command_async +from fabric.utils import exec_shell_command, exec_shell_command_async from fabric.widgets.box import Box from fabric.widgets.button import Button +from loguru import logger +from snippets import MaterialIcon class WallpaperManager: + IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp"} + THUMBNAIL_SIZE = "x64" + THUMBNAIL_ASPECT_RATIO = "1:1" + WALLPAPER_SCRIPT_PATH = os.path.expanduser("~/dotfiles/hypr/scripts/wallpaper.py") + def __init__(self): self.wallpaper_dir = Path.home() / "Pictures" / "wallpapers" self.thumbnail_dir = ( - Path.home() / ".cache" / "fabric" / "thumbnails" / "wallpaper" + Path.home() / ".cache" / "fabric" / "thumbnails" / "wallpapers" ) self.thumbnail_dir.mkdir(parents=True, exist_ok=True) + self.theme_toggle_button = self.create_theme_toggle_button() + self._update_button_style() + + def create_theme_toggle_button(self): + button = Button( + child=MaterialIcon("contrast"), + v_align="center", + on_clicked=self.toggle_dark_mode, + ) + return button + + def toggle_dark_mode(self, *_): + command = os.path.expanduser("~/fabric/assets/scripts/dark-theme.sh --toggle") + exec_shell_command(command) + self._update_button_style() + + def check_dark_mode_state(self): + result = exec_shell_command( + "gsettings get org.gnome.desktop.interface color-scheme" + ) + return result.strip().replace("'", "") == "prefer-dark" + + def _update_button_style(self): + style = ( + "background-color: @surfaceVariant; border-radius:100px; min-height:50px; min-width:50px;" + if self.check_dark_mode_state() + else "background-color: transparent; border-radius:100px;" + ) + self.theme_toggle_button.set_style(style) def show_wallpaper_thumbnails(self, viewport, search_term: str = ""): - wallpapers = self._get_wallpapers(search_term)[:24] + wallpapers = self._get_wallpapers(search_term) self._populate_viewport(viewport, wallpapers) def _get_wallpapers(self, search_term: str): @@ -25,24 +60,27 @@ class WallpaperManager: f for f in self.wallpaper_dir.iterdir() if f.is_file() - and f.suffix.lower() in {".png", ".jpg", ".jpeg", ".webp"} - and (not search_term or search_term.lower() in f.name.lower()) + and f.suffix.lower() in self.IMAGE_EXTENSIONS + and self._matches_search(f, search_term) ] + def _matches_search(self, file, search_term: str): + return not search_term or search_term.lower() in file.name.lower() + def _populate_viewport(self, viewport, wallpapers): viewport.children.clear() - row = Box(orientation="h", spacing=10) + row = Box(orientation="h", spacing=10, style="margin:5px;") - for i, wallpaper in enumerate(wallpapers): + for i, wallpaper in enumerate(wallpapers[:24]): # Limit to 24 wallpapers thumbnail_path = self._generate_thumbnail(wallpaper) thumbnail_button = self._create_wallpaper_thumbnail( thumbnail_path, wallpaper ) row.add(thumbnail_button) - if (i + 1) % 8 == 0: + if (i + 1) % 6 == 0: viewport.add(row) - row = Box(orientation="h", spacing=10) + row = Box(orientation="h", spacing=10, style="margin:5px;") if row.children: viewport.add(row) @@ -50,31 +88,34 @@ class WallpaperManager: def _generate_thumbnail(self, wallpaper_path): thumbnail_path = self.thumbnail_dir / wallpaper_path.name if not thumbnail_path.exists(): - self._create_thumbnail(wallpaper_path, thumbnail_path) + threading.Thread( + target=self._create_thumbnail, + args=(wallpaper_path, thumbnail_path), + daemon=True, + ).start() return thumbnail_path def _create_thumbnail(self, wallpaper_path, thumbnail_path): + logger.debug(f"Generating thumbnail for {wallpaper_path}") exec_shell_command_async( [ "magick", str(wallpaper_path), "-resize", - "x32", + self.THUMBNAIL_SIZE, "-gravity", "Center", "-extent", - "1:1", + self.THUMBNAIL_ASPECT_RATIO, str(thumbnail_path), ], lambda *args: logger.debug(args), ) def _create_wallpaper_thumbnail(self, thumbnail_path, wallpaper_path): + thumbnail_style = self._thumbnail_style(thumbnail_path) thumbnail_box = Box( - orientation="h", - h_align="center", - v_align="center", - style=self._thumbnail_style(thumbnail_path), + orientation="h", h_align="center", v_align="center", style=thumbnail_style ) return Button( child=thumbnail_box, @@ -86,14 +127,13 @@ class WallpaperManager: def _thumbnail_style(self, thumbnail_path): return ( - f"background-image: url('{thumbnail_path}'); " - "min-width: 32px; min-height: 32px; " + f"background-image: url('{thumbnail_path }'); " + "min-width: 64px; min-height: 64px; " "background-repeat: no-repeat; " "background-size: cover; background-position: center;" ) def _select_wallpaper(self, wallpaper_path): - logger.info(f"Selected wallpaper: {wallpaper_path}") self._apply_wallpaper(wallpaper_path) def _apply_wallpaper(self, wallpaper_path): @@ -103,12 +143,13 @@ class WallpaperManager: self._execute_wallpaper_script("-R") def _execute_wallpaper_script(self, *args): - script_path = os.path.expanduser("~/dotfiles/hypr/scripts/wallpaper.py") try: exec_shell_command_async( - ["python3", script_path, *args], - lambda output: logger.info(f"{output}"), + ["python3", self.WALLPAPER_SCRIPT_PATH, *args], + lambda output: logger.info(f"Wallpaper script output: {output}"), ) - logger.info(f"Wallpaper applied with args: {args}") except Exception as e: - logger.error(f"Error applying wallpaper: {e}") + logger.error(f"Error executing wallpaper script: {e}") + + def get_wallpaper_buttons(self): + return self.theme_toggle_button diff --git a/config/fabric/modules/launcher/widgets/wifi.py b/config/fabric/modules/launcher/widgets/wifi.py new file mode 100644 index 00000000..0b8ee2a2 --- /dev/null +++ b/config/fabric/modules/launcher/widgets/wifi.py @@ -0,0 +1,99 @@ +from fabric.widgets.box import Box +from fabric.widgets.button import Button +from fabric.widgets.image import Image +from fabric.widgets.label import Label +from services import NetworkClient +from snippets import MaterialIcon + + +class WifiMenu: + def __init__(self, launcher): + self.launcher = launcher + self.client = NetworkClient() + self.paired_devices = {} + self.available_devices = {} + + self.wifi_toggle_button = Button( + child=MaterialIcon("signal_wifi_4_bar"), + h_align="center", + v_align="center", + on_clicked=self.toggle_wifi, + ) + self.update_wifi_button_style() + + self.rescan_button = Button( + child=MaterialIcon("refresh"), + h_align="center", + v_align="center", + on_clicked=self.scan_for_networks, + ) + + self.client.device_ready.connect(self.on_device_added) + + def update_wifi_button_style(self): + if self.check_wifi_state(): + self.wifi_toggle_button.set_style("background-color: transparent;") + else: + self.wifi_toggle_button.set_style( + "background-color: @surfaceVariant; border-radius:100px; min-height:50px; min-width:50px;" + ) + + def check_wifi_state(self): + return self.client.wifi_device.enabled if self.client.wifi_device else False + + def show_wifi_menu(self, viewport): + viewport.children = [] + + devices_box = Box(orientation="v", spacing=5) + + # Iterate over the list of available access points + for ap in self.client.wifi_device.access_points: + is_connected = ap["ssid"] == self.client.wifi_device.ssid # Compare SSID + + device_button = Button( + child=Box( + orientation="h", + spacing=10, + children=[ + Image(icon_name=ap["icon-name"], size=32), + Label(label=ap["ssid"]), # Show SSID + Box( + orientation="h", + children=[ + Label( + label="Connected" if is_connected else "", + h_align="end", + ), + ], + ), + ], + ), + on_clicked=lambda _, ap=ap: ( + self.connect_to_ap(ap, is_connected), + self.launcher.set_visible(False), + ), + name="launcher-item", + ) + devices_box.add(device_button) + + viewport.add(devices_box) + + def connect_to_ap(self, ap, is_connected): + if not is_connected: + self.client.connect_wifi_bssid(ap["bssid"]) + + def on_device_added(self, client): + self.show_wifi_menu(self.launcher.viewport) + + def scan_for_networks(self, button): + self.client.wifi_device.scan() + self.show_wifi_menu(self.launcher.viewport) + + def toggle_wifi(self, button): + self.update_wifi_button_style() + if self.client.wifi_device: + self.client.wifi_device.toggle_wifi() + self.show_wifi_menu(self.launcher.viewport) + + def get_wifi_buttons(self): + return [self.wifi_toggle_button, self.rescan_button] diff --git a/config/fabric/modules/notifications.py b/config/fabric/modules/notifications.py index 28d6c0cb..948b68e6 100644 --- a/config/fabric/modules/notifications.py +++ b/config/fabric/modules/notifications.py @@ -1,29 +1,21 @@ -from typing import cast - import gi gi.require_version("GdkPixbuf", "2.0") -from gi.repository import GdkPixbuf -from loguru import logger -from fabric import Application from fabric.notifications import ( Notification, NotificationAction, NotificationCloseReason, Notifications, ) -from fabric.utils import get_relative_path, invoke_repeater +from fabric.utils import invoke_repeater from fabric.widgets.box import Box from fabric.widgets.button import Button from fabric.widgets.image import Image from fabric.widgets.label import Label from fabric.widgets.revealer import Revealer -from fabric.widgets.wayland import WaylandWindow - -NOTIFICATION_WIDTH = 400 -NOTIFICATION_IMAGE_SIZE = 64 -NOTIFICATION_TIMEOUT = 5 * 1000 # 10 seconds +from fabric.widgets.wayland import WaylandWindow as Window +from gi.repository import GdkPixbuf, GLib class ActionButton(Button): @@ -51,7 +43,6 @@ class ActionButton(Button): class NotificationWidget(Box): def __init__(self, notification: Notification, **kwargs): super().__init__( - size=(NOTIFICATION_WIDTH, -1), name="notification", spacing=8, orientation="v", @@ -60,91 +51,82 @@ class NotificationWidget(Box): self._notification = notification + header_container = Box(spacing=8, orientation="h") + header_container.children = ( + self.get_icon(notification.app_icon, notification.app_name, 25), + Label( + markup=str( + self._notification.summary + if self._notification.summary + else notification.app_name + ), + h_align="start", + style="font-weight: 900;", + ellipsization="end", + ), + ) + + header_container.pack_end( + Box( + v_align="start", + children=( + Button( + image=Image( + icon_name="close-symbolic", + icon_size=16, + style_classes="close-button", + ), + style_classes="close-button", + v_align="center", + h_align="end", + on_clicked=lambda *_: self._notification.close( + "dismissed-by-user" + ), + ), + ), + ), + False, + False, + 0, + ) + body_container = Box(spacing=4, orientation="h") # Use provided image if available, otherwise use "notification-symbolic" icon - image = ( - Image( - pixbuf=self._notification.image_pixbuf.scale_simple( - NOTIFICATION_IMAGE_SIZE, - NOTIFICATION_IMAGE_SIZE, - GdkPixbuf.InterpType.BILINEAR, + if image_pixbuf := self._notification.image_pixbuf: + body_container.add( + Image( + pixbuf=image_pixbuf.scale_simple( + 64, 64, GdkPixbuf.InterpType.BILINEAR + ) ), - style="border-radius:100px;", ) - if self._notification.image_pixbuf - else Image( - icon_name="notification-symbolic", - icon_size=40, - style="border-radius:100px;", - ) - ) - body_container.add(image) body_container.add( - Box( - spacing=4, - orientation="v", - children=[ - Box( - orientation="h", - children=[ - Label( - label=self._notification.summary, - ellipsization="middle", - ) - .build() - .add_style_class("summary") - .unwrap(), - ], - h_expand=True, - v_expand=True, - ).build( - lambda box, _: box.pack_end( - Button( - image=Image( - icon_name="window-close-symbolic", - icon_size=18, - ), - v_align="center", - h_align="end", - on_clicked=lambda *_: self._notification.close(), - ), - False, - False, - 0, - ) - ), - Label( - label=self._notification.body, - line_wrap="word-char", - v_align="start", - max_chars_width=40, - h_align="start", - ) - .build() - .add_style_class("body") - .unwrap(), - ], - h_expand=True, - v_expand=True, + Label( + markup=self._notification.body, + line_wrap="word-char", + v_align="start", + ellipsization="end", + max_chars_width=40, + h_align="start", ) ) + actions_container = Box( + spacing=4, + orientation="h", + name="notification-action-buttons", + children=[ + ActionButton(action, i, len(self._notification.actions)) + for i, action in enumerate(self._notification.actions) + ], + h_expand=True, + ) + + self.add(header_container) self.add(body_container) - - self.add( - Box( - spacing=4, - orientation="h", - name="notification_action_button", - children=[ - ActionButton(action, i, len(self._notification.actions)) - for i, action in enumerate(self._notification.actions) - ], - h_expand=True, - ) - ) + self.add(actions_container) # Destroy this widget once the notification is closed self._notification.connect( @@ -154,21 +136,48 @@ class NotificationWidget(Box): self.destroy(), ), invoke_repeater( - NOTIFICATION_TIMEOUT, + 5 * 1000, lambda: self._notification.close("expired"), initial_call=False, ), ) + def get_icon(self, app_icon, app_name, size) -> Image: + + # Attempt to load file-based icons + if isinstance(app_icon, str) and app_icon.strip(): + if app_icon.startswith("file://") or app_icon.startswith("/"): + file_path = app_icon[7:] if app_icon.startswith("file://") else app_icon + try: + pixbuf = GdkPixbuf.Pixbuf.new_from_file(file_path) + scaled_pixbuf = pixbuf.scale_simple( + size, size, GdkPixbuf.InterpType.BILINEAR + ) + return Image(name="notification-icon", pixbuf=scaled_pixbuf) + except Exception as e: + print(f"DEBUG: Failed to load image from {file_path}: {e}") + + if app_icon and not app_icon.startswith(("file://", "/")): + icon_name = app_icon + elif app_name and app_name.strip() not in ["notify-send", ""]: + icon_name = app_name.strip() + else: + icon_name = "dialog-information-symbolic" + + print(f"DEBUG: icon_name={icon_name}") + + # Return a symbolic icon as fallback + return Image(name="notification-icon", icon_name=icon_name, icon_size=size) + class NotificationRevealer(Revealer): def __init__(self, notification: Notification, **kwargs): - self.not_box = NotificationWidget(notification) + self.notif_box = NotificationWidget(notification) self._notification = notification super().__init__( child=Box( style="margin: 12px;", - children=[self.not_box], + children=[self.notif_box], ), transition_duration=500, transition_type="crossfade", @@ -176,21 +185,20 @@ class NotificationRevealer(Revealer): self.connect( "notify::child-revealed", - lambda *args: self.destroy() if not self.get_child_revealed() else None, + lambda *_: self.destroy() if not self.get_child_revealed() else None, ) self._notification.connect("closed", self.on_resolved) def on_resolved( - self, notification: Notification, closed_reason: NotificationCloseReason + self, + notification: Notification, + reason: NotificationCloseReason, ): - logger.info( - f"Notification {notification.id} resolved with reason: {closed_reason}" - ) self.set_reveal_child(False) -class NotificationPopup(WaylandWindow): +class NotificationPopup(Window): def __init__(self): self._server = Notifications() self.notifications = Box( diff --git a/config/fabric/modules/osd.py b/config/fabric/modules/osd.py index de34ecac..1b09a305 100644 --- a/config/fabric/modules/osd.py +++ b/config/fabric/modules/osd.py @@ -1,30 +1,31 @@ import time +from typing import ClassVar, Literal -from fabric import Application from fabric.audio import Audio -from fabric.utils import get_relative_path from fabric.widgets.box import Box -from fabric.widgets.image import Image +from fabric.widgets.revealer import Revealer from fabric.widgets.scale import Scale, ScaleMark from fabric.widgets.wayland import WaylandWindow as Window from gi.repository import GLib, GObject -from services import Brightness -from snippets import Animator +from services.brightness import Brightness +from snippets import Animator, MaterialIcon class AnimatedScale(Scale): def __init__(self, **kwargs): super().__init__(**kwargs) - self.animator = Animator( - bezier_curve=(0.34, 1.56, 0.64, 1.0), - duration=0.8, - min_value=self.min_value, - max_value=self.value, - tick_widget=self, - notify_value=lambda p, *_: self.set_value(p.value), - ) + self.animator = None # Lazily initialized def animate_value(self, value: float): + if not self.animator: + self.animator = Animator( + bezier_curve=(0.34, 1.56, 0.64, 1.0), + duration=0.8, + min_value=self.min_value, + max_value=self.value, + tick_widget=self, + notify_value=lambda p, *_: self.set_value(p.value), + ) self.animator.pause() self.animator.min_value = self.value self.animator.max_value = value @@ -33,10 +34,17 @@ class AnimatedScale(Scale): class BrightnessOSDContainer(Box): def __init__(self, **kwargs): - super().__init__(**kwargs, orientation="h", spacing=12, name="osd-container") + super().__init__(**kwargs, orientation="h", spacing=12, name="osd") self.brightness_service = Brightness() - self.icon = self._create_icon("display-brightness-symbolic", 28) - self.scale = self._create_brightness_scale() + self.icon = MaterialIcon(icon_name="brightness_7", size="28px") + self.scale = AnimatedScale( + marks=(ScaleMark(value=i) for i in range(0, 101, 10)), + value=70, + min_value=0, + max_value=100, + increments=(1, 1), + orientation="h", + ) self.add(self.icon) self.add(self.scale) @@ -45,13 +53,57 @@ class BrightnessOSDContainer(Box): self.scale.connect("value-changed", lambda *_: self.update_brightness()) self.brightness_service.connect("screen", self.on_brightness_changed) - def _create_icon(self, icon_name: str, pixel_size: int) -> Image: - icon = Image(icon_name=icon_name) - icon.set_pixel_size(pixel_size) - return icon + def update_brightness(self) -> None: + current_brightness = self.brightness_service.screen_brightness + if current_brightness != 0: + normalized_brightness = self._normalize_brightness(current_brightness) + self.scale.animate_value(normalized_brightness) + self.update_icon(normalized_brightness) - def _create_brightness_scale(self) -> AnimatedScale: - return AnimatedScale( + def update_icon(self, brightness_percentage: float) -> None: + icon_name = self.get_brightness_icon(brightness_percentage) + self.icon.set_label(icon_name) + + def on_brightness_changed(self, _sender: any, value: float, *_args) -> None: + normalized_brightness = self._normalize_brightness(value) + self.scale.animate_value(normalized_brightness) + self.update_icon(normalized_brightness) + + def _normalize_brightness(self, brightness: float) -> float: + return (brightness / self.brightness_service.max_screen) * 100 + + def get_brightness_icon(self, brightness_percentage: float) -> str: + brightness_icons = [ + "brightness_1", + "brightness_2", + "brightness_3", + "brightness_4", + "brightness_5", + "brightness_6", + "brightness_7", + ] + thresholds = [ + 100 / (1.6 ** (len(brightness_icons) - i - 1)) + for i in range(len(brightness_icons)) + ] + + for i, threshold in enumerate(thresholds): + if brightness_percentage < threshold: + return brightness_icons[i] + + return brightness_icons[-1] + + +class AudioOSDContainer(Box): + __gsignals__: ClassVar[dict] = { + "volume-changed": (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()), + } + + def __init__(self, **kwargs): + super().__init__(**kwargs, orientation="h", spacing=13, name="osd") + self.audio = Audio() + self.icon = MaterialIcon(icon_name="volume_up", size="28px") + self.scale = AnimatedScale( marks=(ScaleMark(value=i) for i in range(1, 100, 10)), value=70, min_value=0, @@ -60,30 +112,6 @@ class BrightnessOSDContainer(Box): orientation="h", ) - def update_brightness(self): - current_brightness = self.brightness_service.screen_brightness - if current_brightness != 0: - normalized_brightness = ( - current_brightness / self.brightness_service.max_screen - ) * 101 - self.scale.animate_value(normalized_brightness) - - def on_brightness_changed(self, sender, value, *args): - normalized_brightness = (value / self.brightness_service.max_screen) * 101 - self.scale.animate_value(normalized_brightness) - - -class AudioOSDContainer(Box): - __gsignals__ = { - "volume-changed": (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()), - } - - def __init__(self, **kwargs): - super().__init__(**kwargs, orientation="h", spacing=13, name="osd-container") - self.audio = Audio() - self.icon = self._create_icon("audio-volume-medium-symbolic", 29) - self.scale = self._create_audio_scale() - self.add(self.icon) self.add(self.scale) self.sync_with_audio() @@ -91,21 +119,6 @@ class AudioOSDContainer(Box): self.scale.connect("value-changed", self.on_volume_changed) self.audio.connect("notify::speaker", self.on_audio_speaker_changed) - def _create_icon(self, icon_name: str, pixel_size: int) -> Image: - icon = Image(icon_name=icon_name) - icon.set_pixel_size(pixel_size) - return icon - - def _create_audio_scale(self) -> AnimatedScale: - return AnimatedScale( - marks=(ScaleMark(value=i) for i in range(1, 100, 10)), - value=70, - min_value=0, - max_value=100, - increments=(1, 1), - orientation="h", - ) - def sync_with_audio(self): if self.audio.speaker: volume = round(self.audio.speaker.volume) @@ -115,7 +128,7 @@ class AudioOSDContainer(Box): def on_volume_changed(self, *_): if self.audio.speaker: volume = self.scale.value - if 1 <= volume <= 100: + if 0 <= volume <= 100: self.audio.speaker.set_volume(volume) self.update_icon(volume) self.emit("volume-changed") @@ -133,15 +146,19 @@ class AudioOSDContainer(Box): def update_icon(self, volume): icon_name = self._get_audio_icon_name(volume) - self.icon.set_from_icon_name(icon_name) + self.icon.set_label(icon_name) def _get_audio_icon_name(self, volume: int) -> str: - if volume >= 81: - return "audio-volume-high-symbolic" - elif volume < 51: - return "audio-volume-low-symbolic" + if volume == 101: + return "sound_detection_loud_sound" + elif volume >= 67: + return "volume_up" + elif volume >= 34: + return "volume_down" + elif volume >= 1: + return "volume_mute" else: - return "audio-volume-medium-symbolic" + return "volume_off" class OSDContainer(Window): @@ -149,23 +166,30 @@ class OSDContainer(Window): self.audio_container = AudioOSDContainer() self.brightness_container = BrightnessOSDContainer() + self.timeout = 1000 + + self.revealer = Revealer( + transition_type="slide-up", + transition_duration=100, + child_revealed=False, + ) + self.main_box = Box( orientation="v", spacing=13, - children=[self.audio_container, self.brightness_container], + children=[self.revealer], ) super().__init__( - **kwargs, - layer="top", + layer="overlay", anchor="bottom", child=self.main_box, visible=False, + pass_through=True, + keyboard_mode="on-demand", + **kwargs, ) - self.audio_container.set_visible(False) - self.brightness_container.set_visible(False) - self.last_activity_time = time.time() self.audio_container.audio.connect("notify::speaker", self.show_audio) @@ -177,17 +201,20 @@ class OSDContainer(Window): GLib.timeout_add(100, self.check_inactivity) def show_audio(self, *_): - self.show_box(self.audio_container) + self.show_box(box_to_show="audio") self.reset_inactivity_timer() def show_brightness(self, *_): - self.show_box(self.brightness_container) + self.show_box(box_to_show="brightness") self.reset_inactivity_timer() - def show_box(self, box_to_show): - self.audio_container.set_visible(box_to_show == self.audio_container) - self.brightness_container.set_visible(box_to_show == self.brightness_container) + def show_box(self, box_to_show: Literal["audio", "brightness"]): self.set_visible(True) + if box_to_show == "audio": + self.revealer.children = self.audio_container + elif box_to_show == "brightness": + self.revealer.children = self.brightness_container + self.revealer.set_reveal_child(True) self.reset_inactivity_timer() def start_hide_timer(self): @@ -197,6 +224,6 @@ class OSDContainer(Window): self.last_activity_time = time.time() def check_inactivity(self): - if time.time() - self.last_activity_time >= 2: + if time.time() - self.last_activity_time >= (self.timeout / 1000): self.start_hide_timer() return True diff --git a/config/fabric/ruff.toml b/config/fabric/ruff.toml new file mode 100644 index 00000000..2e2889de --- /dev/null +++ b/config/fabric/ruff.toml @@ -0,0 +1,10 @@ +line-length = 88 +indent-width = 4 + +[lint] +# ignore gi imports not begin at the top of the file +ignore = ["E402"] + +[format] +quote-style = "double" +indent-style = "space" \ No newline at end of file diff --git a/config/fabric/services/__init__.py b/config/fabric/services/__init__.py index 4b5927ad..1df3d07e 100644 --- a/config/fabric/services/__init__.py +++ b/config/fabric/services/__init__.py @@ -1,5 +1,12 @@ from .brightness import Brightness from .screen_record import ScreenRecorder from .weather import WeatherInfo +from .wifi import NetworkClient, Wifi -__all__ = ["Brightness", "ScreenRecorder", "WeatherInfo"] +__all__ = [ + "Brightness", + "ScreenRecorder", + "WeatherInfo", + "NetworkClient", + "Wifi", +] diff --git a/config/fabric/services/weather.py b/config/fabric/services/weather.py deleted file mode 100644 index 01cc22a1..00000000 --- a/config/fabric/services/weather.py +++ /dev/null @@ -1,18 +0,0 @@ -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)} diff --git a/config/fabric/services/wifi.py b/config/fabric/services/wifi.py new file mode 100644 index 00000000..b7ec7b27 --- /dev/null +++ b/config/fabric/services/wifi.py @@ -0,0 +1,249 @@ +from typing import List, Literal + +import gi +from fabric.core.service import Property, Service, Signal +from fabric.utils import bulk_connect, exec_shell_command_async +from gi.repository import Gio +from loguru import logger + +try: + gi.require_version("NM", "1.0") + from gi.repository import NM +except ValueError: + logger.error("Failed to start network manager") + + +class Wifi(Service): + @Signal + def changed(self) -> None: ... + + @Signal + def enabled(self) -> bool: ... + + def __init__(self, client: NM.Client, device: NM.DeviceWifi, **kwargs): + self._client: NM.Client = client + self._device: NM.DeviceWifi = device + self._ap: NM.AccessPoint | None = None + self._ap_signal: int | None = None + super().__init__(**kwargs) + + self._client.connect( + "notify::wireless-enabled", + lambda *args: self.notifier("enabled", args), + ) + if self._device: + bulk_connect( + self._device, + { + "notify::active-access-point": lambda *args: self._activate_ap(), + "access-point-added": lambda *args: self.emit("changed"), + "access-point-removed": lambda *args: self.emit("changed"), + "state-changed": lambda *args: self.ap_update(), + }, + ) + self._activate_ap() + + def ap_update(self): + self.emit("changed") + for sn in [ + "enabled", + "internet", + "strength", + "frequency", + "access-points", + "ssid", + "state", + "icon-name", + ]: + self.notify(sn) + + def _activate_ap(self): + if self._ap: + self._ap.disconnect(self._ap_signal) + self._ap = self._device.get_active_access_point() + if not self._ap: + return + + self._ap_signal = self._ap.connect( + "notify::strength", lambda *args: self.ap_update() + ) # type: ignore + + def toggle_wifi(self): + self._client.wireless_set_enabled(not self._client.wireless_get_enabled()) + + # def set_active_ap(self, ap): + # self._device.access + + def scan(self): + self._device.request_scan_async( + None, + lambda device, result: [ + device.request_scan_finish(result), + self.emit("changed"), + ], + ) + + def notifier(self, name: str, *args): + self.notify(name) + self.emit("changed") + return + + @Property(bool, "read-write", default_value=False) + def enabled(self) -> bool: # type: ignore + return bool(self._client.wireless_get_enabled()) + + @enabled.setter + def enabled(self, value: bool): + self._client.wireless_set_enabled(value) + + @Property(int, "readable") + def strength(self): + return self._ap.get_strength() if self._ap else -1 + + @Property(str, "readable") + def icon_name(self): + if not self._ap: + return "network-wireless-disabled-symbolic" + + if self.internet == "activated": + return { + 80: "network-wireless-signal-excellent-symbolic", + 60: "network-wireless-signal-good-symbolic", + 40: "network-wireless-signal-ok-symbolic", + 20: "network-wireless-signal-weak-symbolic", + 00: "network-wireless-signal-none-symbolic", + }.get( + min(80, 20 * round(self._ap.get_strength() / 20)), + "network-wireless-no-route-symbolic", + ) + if self.internet == "activating": + return "network-wireless-acquiring-symbolic" + + return "network-wireless-offline-symbolic" + + @Property(int, "readable") + def frequency(self): + return self._ap.get_frequency() if self._ap else -1 + + @Property(int, "readable") + def internet(self): + return { + NM.ActiveConnectionState.ACTIVATED: "activated", + NM.ActiveConnectionState.ACTIVATING: "activating", + NM.ActiveConnectionState.DEACTIVATING: "deactivating", + NM.ActiveConnectionState.DEACTIVATED: "deactivated", + }.get( + self._device.get_active_connection().get_state(), + "unknown", + ) + + @Property(object, "readable") + def access_points(self) -> List[object]: + points: list[NM.AccessPoint] = self._device.get_access_points() + + def make_ap_dict(ap: NM.AccessPoint): + return { + "bssid": ap.get_bssid(), + # "address": ap.get_ + "last_seen": ap.get_last_seen(), + "ssid": ( + NM.utils_ssid_to_utf8(ap.get_ssid().get_data()) + if ap.get_ssid() + else "Unknown" + ), + "active-ap": self._ap, + "strength": ap.get_strength(), + "frequency": ap.get_frequency(), + "icon-name": { + 80: "network-wireless-signal-excellent-symbolic", + 60: "network-wireless-signal-good-symbolic", + 40: "network-wireless-signal-ok-symbolic", + 20: "network-wireless-signal-weak-symbolic", + 00: "network-wireless-signal-none-symbolic", + }.get( + min(80, 20 * round(ap.get_strength() / 20)), + "network-wireless-no-route-symbolic", + ), + } + + return list(map(make_ap_dict, points)) + + @Property(str, "readable") + def ssid(self): + if not self._ap: + return "Disconnected" + ssid = self._ap.get_ssid().get_data() + return NM.utils_ssid_to_utf8(ssid) if ssid else "Unknown" + + @Property(int, "readable") + def state(self): + return { + NM.DeviceState.UNMANAGED: "unmanaged", + NM.DeviceState.UNAVAILABLE: "unavailable", + NM.DeviceState.DISCONNECTED: "disconnected", + NM.DeviceState.PREPARE: "prepare", + NM.DeviceState.CONFIG: "config", + NM.DeviceState.NEED_AUTH: "need_auth", + NM.DeviceState.IP_CONFIG: "ip_config", + NM.DeviceState.IP_CHECK: "ip_check", + NM.DeviceState.SECONDARIES: "secondaries", + NM.DeviceState.ACTIVATED: "activated", + NM.DeviceState.DEACTIVATING: "deactivating", + NM.DeviceState.FAILED: "failed", + }.get(self._device.get_state(), "unknown") + + +class NetworkClient(Service): + @Signal + def device_ready(self) -> None: ... + + def __init__(self, **kwargs): + self._client: NM.Client | None = None + self.wifi_device: Wifi | None = None + super().__init__(**kwargs) + NM.Client.new_async( + cancellable=None, + callback=self._init_network_client, + **kwargs, + ) + + def _init_network_client(self, client: NM.Client, task: Gio.Task, **kwargs): + self._client = client + wifi_device: NM.DeviceWifi = self._get_device(NM.DeviceType.WIFI) # type: ignore + # eth_device: NM.DeviceEthernet = self._get_device(NM.DeviceType.ETHERNET) # type: ignore + + if wifi_device: + self.wifi_device = Wifi(self._client, wifi_device) + self.emit("device-ready") + + # if eth_device: + # self.eth_device = Ethernet(self._client, eth_device) + + def _get_device(self, device_type) -> NM.Device | None: + devices: List[NM.Device] = self._client.get_devices() # type: ignore + return next((x for x in devices if x.get_device_type() == device_type), None) + + def get_primary_device(self) -> Literal["wifi", "wired"] | None: + if not self._client: + return None + return ( + "wifi" + if "wireless" + in str(self._client.get_primary_connection().get_connection_type()) + else ( + "wired" + if "ethernet" + in str(self._client.get_primary_connection().get_connection_type()) + else None + ) + ) + + def connect_wifi_bssid(self, bssid): + # We are using nmcli here, idk im lazy + exec_shell_command_async( + f"nmcli device wifi connect {bssid}", lambda *args: print(args) + ) + + @Property(str, "readable") + def primary_device(self) -> Literal["wifi", "wired"] | None: + return self.get_primary_device() diff --git a/config/fabric/snippets/__init__.py b/config/fabric/snippets/__init__.py index 145d0875..d6986d37 100644 --- a/config/fabric/snippets/__init__.py +++ b/config/fabric/snippets/__init__.py @@ -1,9 +1,19 @@ from .animator import Animator +from .functions import ( + get_current_uptime, + get_profile_picture_path, + read_config, + username, +) from .icon import MaterialIcon from .icon_resolver import IconResolver __all__ = [ "Animator", "MaterialIcon", + "read_config", + "get_profile_picture_path", + "username", "IconResolver", + "get_current_uptime", ] diff --git a/config/fabric/snippets/functions.py b/config/fabric/snippets/functions.py new file mode 100644 index 00000000..f9606e31 --- /dev/null +++ b/config/fabric/snippets/functions.py @@ -0,0 +1,43 @@ +import json +import os +import time + +import psutil +from gi.repository import GLib +from loguru import logger + + +def read_config(): + home_dir = GLib.get_home_dir() + config_path = f"{home_dir}/fabric/assets/config.json" + + with open(config_path, "r") as file: + # Load JSON data into a Python dictionary + data = json.load(file) + return data + + +def get_current_uptime(): + uptime = time.time() - psutil.boot_time() + uptime_hours, remainder = divmod(uptime, 3600) + uptime_minutes, _ = divmod(remainder, 60) + return ( + f"Up: {int(uptime_hours)} {'hours' if uptime_hours != 1 else 'hour'}, " + f"{int(uptime_minutes)} {'minutes' if uptime_minutes != 1 else 'minute'}" + ) + + +def get_profile_picture_path() -> str | None: + path = os.path.expanduser("~/Pictures/Other/face.jpg") + if not os.path.exists(path): + path = os.path.expanduser("~/.face") + if not os.path.exists(path): + logger.warning( + "can't fetch a user profile picture, add a profile picture image at ~/.face or at ~/Pictures/Other/profile.jpg" + ) + path = None + return path + + +def username(): + return os.getlogin().title() diff --git a/config/fabric/style/main.css b/config/fabric/style/main.css deleted file mode 100644 index afceb86c..00000000 --- a/config/fabric/style/main.css +++ /dev/null @@ -1,499 +0,0 @@ -@import url(../../.cache/material/colors.css); -* { - all: unset; - color: @foreground; - font-size: 16px; - font-family: "Product Sans", Roboto, "Font Awesome 6 Free", Helvetica, Arial, - sans-serif; -} - -#bar { - background-color: @surface; - padding: 3px; -} -#bar label { - font-weight: bold; -} -#start-container, -#center-container, -#end-container { - padding-top: 6px; - padding-bottom: 6px; - margin-left: 12px; - margin-right: 12px; -} - -#progress { - color: transparent; - background-color: transparent; -} - -#material_icon, -#material_icon * { - all: unset; - font-family: "Material Symbols Outlined", "Material Symbols Sharp"; -} -#progress { - border: solid 0px @outlineVariant; -} - -#logo { - font-size: 18px; - background-color: @surfaceContainer; - border-radius: 100px; - padding: 0px; - min-width: 35px; -} - -#logo:hover { - background-color: mix(@secondaryContainer, @onSecondaryContainer, 0.05); - box-shadow: 00px 3px 3px -2px rgba(0, 0, 0, 0.2); -} - -#logo:active { - background-image: radial-gradient( - circle, - mix(@secondaryContainer, @onSecondaryContainer, 0.1) 10%, - transparent 0% - ); - box-shadow: none; -} - -#workspaces { - border-radius: 100px; - font-weight: bold; - font-style: normal; - color: @onSurface; - background: @surfaceContainer; - padding: 0px 10px 0px 10px; -} - -#datetime { - background-color: @surfaceContainer; - border-radius: 100px; - padding: 8px; -} - -#battery { - background-color: @surfaceContainer; - border-radius: 100px; - padding: 2px 10px 2px 10px; -} - -#battery label { - color: @onSurface; - font-size: 16px; - font-weight: 300; -} - -#battery .icon { - color: @onSurface; -} - -#battery.critical { - background-color: @error; -} - -#battery.critical label, -#battery.critical .icon { - color: @onError; -} - -#tray { - background-color: @surfaceContainer; - border-radius: 100px; - padding: 2px 10px 0px 10px; -} - -#tray > button { - margin: 0px; - padding: 0px; -} - -#tray image { - color: @onSurface; -} - -#progress { - color: lighter(@outlineVariant); - border: 2px solid @onSecondaryContainer; -} - -#applets { - background-color: @surfaceContainer; - border-radius: 100px; - padding: 2px 10px 2px 10px; - margin: 0px; -} - -#applets .icon { - color: @onSurface; - font-weight: 900; -} - -#applets > button { - color: @onSurface; - margin: 0px; - padding: 0px; -} - -menu { - border-radius: 10px; - background-color: @surfaceContainer; -} - -menu > menuitem { - border-radius: 0px; - padding: 6px; - margin-left: 2px; - margin-right: 2px; - color: @onSurface; -} - -menu > menuitem:first-child { - margin-top: 1px; - border-radius: 8px 8px 0px 0px; -} - -menu > menuitem:last-child { - margin-bottom: 1px; - border-radius: 0px 0px 8px 8px; -} - -menu > menuitem:hover { - background-color: mix(@onSurface, @surface, 0.85); -} - -tooltip { - background-color: @surfaceContainer; - border-radius: 11px; - outline: none; - border: none; - box-shadow: none; -} - -tooltip label { - color: @onSurface; - outline: none; - border: none; - box-shadow: none; - font-weight: normal; -} - -#panel-button { - margin: 0px 2px 0px 2px; - padding: 0px 5px 0px 5px; - border-style: solid; - border-width: 2px; - border-radius: 10px; - border-color: transparent; -} - -#panel-button.activated { - background-color: alpha(white, 0.15); - border-style: solid; - border-color: transparent; - border-bottom-style: solid; - border-bottom-color: alpha(white, 0.5); -} - -#taskbar { - border-radius: 100px; - font-weight: bold; - font-style: normal; - color: @onSurface; - background: @surfaceContainer; - padding-left: 4px; - padding-right: 4px; -} - -#taskbar > button { - padding: 0px 5px; - margin: 4px 0px; - margin-right: 3px; - border-radius: 100px; - border: 0px; -} -#taskbar > button:last-child { - margin-right: 0px; -} - -#launcher { - margin: 18px; - border: 1px solid @outlineVariant; - background-color: @surface; - border-radius: 24px; - padding: 18px; -} - -#launcher button { - border-radius: 11px; - background-color: transparent; - background-image: none; - box-shadow: none; -} - -#launcher button:focus { - box-shadow: inset 0 0 0 1px @primary; - background-color: @background; - color: @foreground; -} - -#launcher button:hover { - box-shadow: inset 0 0 0 1px @background; - background-color: @background; -} - -#launcher entry { - transition: all 0.1s ease; - border-radius: 11px; - color: @foreground; - background-color: @surfaceContainer; - box-shadow: inset 0 0 0 @background; - padding: 10px; - margin: 12px; -} - -#launcher entry:focus { - box-shadow: inset 0 0 0 1px @primary; - background-color: @background; -} - -#launcher entry:hover { - box-shadow: inset 0 0 0 1px @background; - background-color: @background; -} - -#launcher entry selection { - color: @outline; - background-color: transparent; -} - -#launcher button#app-item { - border-radius: 11px; - color: @foreground; - background-color: transparent; - background-image: none; - box-shadow: none; - transition: 200ms; - padding: 7px; -} - -#launcher button#app-item:hover #title, -#launcher button#app-item:focus #title { - color: @primary; -} - -#launcher button#app-item:hover #description, -#launcher button#app-item:focus #description { - color: @inversePrimary; -} - -#launcher button#app-item:hover image, -#launcher button#app-item:focus image { - -gtk-icon-shadow: 2px 2px @primary; -} - -#launcher button#app-item:active { - background-color: @primaryContainer; - border-radius: 11px; - box-shadow: inset 0 0 0 1px rgba(158, 142, 130, 0.04); -} - -#launcher button#app-item:active #title { - color: @foreground; -} - -#launcher button#fav-item { - border-radius: 10px; - padding: 10px; - background-image: none; - box-shadow: none; -} - -#launcher button#fav-item:hover image, -#launcher button#fav-item:focus image { - -gtk-icon-shadow: 2px 2px @primary; -} - -#launcher button#fav-item:active { - background-color: transparent; - border-radius: 11px; - box-shadow: inset 0 0 0 1px rgba(158, 142, 130, 0.04); -} - -#launcher button#emoji-item { - border-radius: 11px; - background-color: transparent; - background-image: none; - box-shadow: none; - padding: 0px; -} - -#launcher button#emoji-item:disabled { - color: mix(@onSurface, transparent, 0.38); -} - -#launcher button#emoji-item label { - font-size: 27px; -} - -#launcher button#emoji-item:hover, -#launcher button#emoji-item:focus { - text-shadow: 2px 2px 2px @primary; -} - -#launcher button#wall-item { - border-radius: 11px; - background-color: transparent; - background-image: none; - box-shadow: none; - padding: 7px; -} - -#launcher button#wall-item:disabled { - color: mix(@onSurface, transparent, 0.38); -} - -#launcher button#wall-item:hover, -#launcher button#wall-item:focus { - background-color: mix(@onSurfaceVariant, @surface, 0.9); -} - -#launcher button#cliphist-item { - border-radius: 11px; - background-color: transparent; - background-image: none; - box-shadow: none; -} - -#launcher button#cliphist-item:disabled { - color: mix(@onSurface, transparent, 0.38); -} - -#launcher button#cliphist-item:hover, -#launcher button#cliphist-item:focus { - text-shadow: 2px 2px 2px @primary; -} - -#launcher button#cliphist-img-item { - background-size: cover; - background-position: center; - background-repeat: no-repeat; - border-radius: 8px; - min-width: 70px; - min-height: 70px; -} - -#launcher button#cliphist-img-item:hover, -#launcher button#cliphist-img-item:focus { - text-shadow: 2px 2px 2px @primary; -} - -#launcher button#sh-item { - border-radius: 11px; - background-color: transparent; - background-image: none; - box-shadow: none; -} - -#launcher button#sh-item:disabled { - color: mix(@onSurface, transparent, 0.38); -} - -#launcher button#sh-item:hover, -#launcher button#sh-item:focus { - text-shadow: 2pt 2pt 2pt @primary; -} - -#launcher button#help-item { - border-radius: 11px; - background-color: transparent; - background-image: none; - box-shadow: none; -} - -#launcher button#help-item:hover label, -#launcher button#help-item:focus label { - text-shadow: 2px 2px 2px @primary; -} - -#osd-container { - background: @surfaceContainer; - padding: 12px; - border-radius: 14px; - margin-bottom: 16px; -} - -#osd-container scale { - min-width: 150px; -} - -#osd-container slider { - color: @onPrimary; - background-color: @primary; - background-size: 20px 20px; - min-width: 5px; - min-height: 14px; - border-radius: 100px; - padding: 0px; - background-repeat: no-repeat; - background-position: center; - margin-left: 0px; - margin-right: 0px; - margin-top: -16px; - margin-bottom: -16px; - box-shadow: - -4px 0px 0px 1px @surfaceContainer, - 4px 0px 0px 1px @surfaceContainer; -} - -#osd-container trough { - background: @secondaryContainer; - min-height: 10px; - margin-right: 4px; - border-radius: 100px; -} - -#osd-container highlight { - border-radius: 100px 0px 0px 100px; - background: @primary; -} - -#notification { - padding: 16px; - border: solid 1px @outlineVariant; - border-radius: 20px; - margin-bottom: 12px; - background-color: @surfaceContainerLow; - min-width: 400px; -} - -#notification .summary { - font-size: 20px; - font-weight: bold; -} - -#notification .body { - color: darker(@foreground); - font-weight: normal; -} - -#notification_action_button button.start-action { - margin-left: 0; -} - -#notification_action_button button.end-action { - margin-right: 0; -} - -#notification_action_button button { - padding: 0.6rem; - font-weight: 600; - border-radius: 3rem; - background-color: @outlineVariant; -} - -#notification_action_button button:hover { - background-color: lighter(@outlineVariant); -} diff --git a/config/fabric/styles/bar.css b/config/fabric/styles/bar.css new file mode 100644 index 00000000..1e3d4137 --- /dev/null +++ b/config/fabric/styles/bar.css @@ -0,0 +1,198 @@ +#bar { + background-color: @surface; + padding: 3px; +} + +#bar label { + font-weight: bold; +} + +/* + * ── bar moudles ─────────────────────────────────────────────────────── +*/ + +#start-container, +#center-container, +#end-container { + padding-top: 6px; + padding-bottom: 6px; + margin-left: 12px; + margin-right: 12px; +} + +/* + * ── workspace ───────────────────────────────────────────────────────── +*/ + +#workspaces { + border-radius: 100px; + font-style: normal; + background: @surfaceContainer; + padding: 0px 10px 0px 10px; +} + +/* + * ── Clock ───────────────────────────────────────────────────────────── +*/ + +#datetime { + background-color: @surfaceContainer; + border-radius: 100px; + padding: 8px; +} + +/* + * ── battery ─────────────────────────────────────────────────────────── +*/ + +#battery { + background-color: @surfaceContainer; + border-radius: 100px; + padding: 2px 10px 2px 10px; +} + +#battery label { + color: @onSurface; + font-size: 16px; + font-weight: 300; +} + +#battery .icon { + color: @onSurface; +} + +#battery.critical { + background-color: @error; +} + +#battery.critical label, +#battery.critical .icon { + color: @onError; +} + +/* + * ── tray ────────────────────────────────────────────────────────────── +*/ + +#tray { + background-color: @surfaceContainer; + border-radius: 100px; + padding: 2px 10px 0px 10px; +} + +#tray > button { + margin: 0px; + padding: 0px; +} + +menu { + background-color: @surfaceContainer; +} + +menu > menuitem { + border-radius: 12px; + padding: 10px; + margin-left: 2px; + margin-right: 2px; +} + +menu > menuitem:hover { + background-color: mix(@onSurface, @surface, 0.85); +} + +/* + * ── applets ─────────────────────────────────────────────────────────── +*/ + +#applets { + background-color: @surfaceContainer; + border-radius: 100px; + padding: 2px 10px 2px 10px; + margin: 0px; +} + +#applets .icon { + color: @onSurface; + font-weight: 900; +} + +#applets > button { + color: @onSurface; + margin: 0px; + padding: 0px; +} + +/* + * ── taskbar ─────────────────────────────────────────────────────────── +*/ + +#taskbar { + border-radius: 100px; + font-weight: bold; + font-style: normal; + color: @onSurface; + background: @surfaceContainer; + padding-left: 4px; + padding-right: 4px; +} + +#taskbar .activated { + border-radius: 100px; + background: @surfaceVariant; +} + +#taskbar > button { + padding: 0px 4px; + margin: 4px 0px; + border-radius: 100px; + border: 0px; +} +#taskbar > button:last-child { + margin-right: 0px; +} + +#progress { + color: lighter(@outlineVariant); + border: 2px solid @onSecondaryContainer; +} + +/* + * ── system tray ─────────────────────────────────────────────────────── +*/ + +#system-tray { + background-color: @surfaceContainer; + border-radius: 100px; + padding: 2px 10px 0 10px; +} + +#system-tray > button { + margin: 0px; + padding: 0px; +} + +#system-tray-menu > menuitem menu, +#system-tray-menu { + background-color: @surfaceContainer; + border-radius: 12px; + padding: 10px; +} + +#system-tray-menu > menuitem menu > menuitem, +#system-tray-menu > menuitem { + margin: 5px 0px; + background-color: @surfaceContainer; + padding: 0.3em 0.5em; + border-radius: 10px; +} + +#system-tray-menu > menuitem menu > menuitem:disabled, +#system-tray-menu > menuitem:disabled { + background-color: transparent; +} + +#system-tray-menu > menuitem menu > menuitem:hover, +#system-tray-menu > menuitem:hover, +#submenu-button:hover { + background-color: mix(@onSurface, @surface, 0.85); +} diff --git a/config/fabric/styles/launcher.css b/config/fabric/styles/launcher.css new file mode 100644 index 00000000..683996d9 --- /dev/null +++ b/config/fabric/styles/launcher.css @@ -0,0 +1,146 @@ +#launcher { + margin: 18px; + border: 1px solid @outlineVariant; + background-color: @surface; + border-radius: 24px; + padding: 18px; + min-width: 480px; +} + +#launcher entry { + transition: all 0.1s ease; + border-radius: 11px; + padding: 10px; + margin: 12px; + box-shadow: inset 0 0 0 1px @outlineVariant; +} + +#launcher entry:focus { + background-color: @background; +} + +#launcher entry:hover { + background-color: @background; +} + +#launcher entry selection { + color: @outline; + background-color: transparent; +} + +#profile-pic { + background-color: transparent; + background-position: center; + background-repeat: no-repeat; + background-size: cover; + border-radius: 100px; + padding: 20px; + margin: 4px; +} + +#launcher button#app-item { + border-radius: 11px; + background-color: transparent; + background-image: none; + box-shadow: none; + transition: 200ms; + padding: 7px; +} + +#launcher button#app-item:hover #title, +#launcher button#app-item:focus #title { + color: @primar; +} + +#launcher button#app-item:hover #description, +#launcher button#app-item:focus #description { + color: @inversePrimary; +} + +#launcher button#app-item:hover image, +#launcher button#app-item:focus image { + -gtk-icon-shadow: 2px 2px @primary; +} + +#launcher button#app-item:active { + background-color: @primaryContainer; + border-radius: 11px; + box-shadow: inset 0 0 0 1px rgba(158, 142, 130, 0.04); +} + +#launcher button#app-item:active #title { + color: @foreground; +} + +#launcher button#emoji-item { + border-radius: 11px; + background-color: transparent; + background-image: none; + box-shadow: none; + padding: 0px; +} + +#launcher button#emoji-item:disabled { + color: mix(@onSurface, transparent, 0.38); +} + +#launcher button#emoji-item label { + font-size: 24px; +} + +#launcher button#emoji-item:hover, +#launcher button#emoji-item:focus { + text-shadow: 2px 2px 2px @primary; +} + +#launcher button#cliphist-img-item { + background-size: cover; + background-position: center; + background-repeat: no-repeat; + border-radius: 8px; + min-width: 70px; + min-height: 70px; +} + +#launcher button#cliphist-img-item:hover, +#launcher button#cliphist-img-item:focus { + box-shadow: 2px 2px 2px @primary; +} + +#launcher button#launcher-item { + border-radius: 11px; + background-color: transparent; + background-image: none; + box-shadow: none; +} + +#launcher button#launcher-item:disabled { + color: mix(@onSurface, transparent, 0.38); +} + +#launcher button#launcher-item:hover, +#launcher button#launcher-item:focus { + text-shadow: 2pt 2pt 2pt @primary; +} + +#launcher button#wall-item { + border-radius: 0px; + background-color: transparent; + background-image: none; + box-shadow: none; + padding: 5px; +} + +#launcher button#wall-item:disabled { + color: mix(@onSurface, transparent, 0.38); +} + +#launcher button#wall-item:hover, +#launcher button#wall-item:focus { + box-shadow: 2pt 2pt 2pt @primary; +} + +.activated { + background-color: @surfaceVariant; + border-radius: 100px; +} diff --git a/config/fabric/styles/main.css b/config/fabric/styles/main.css new file mode 100644 index 00000000..79ebe208 --- /dev/null +++ b/config/fabric/styles/main.css @@ -0,0 +1,43 @@ +@import url(../../.cache/material/colors.css); +@import "launcher.css"; +@import "bar.css"; +@import "notification.css"; +@import "osd.css"; + +* { + all: unset; + color: @foreground; + font-size: 16px; + font-family: "Product Sans", Roboto, "Font Awesome 6 Free", Helvetica, Arial, + sans-serif; +} + +/* + * ── tooltip ─────────────────────────────────────────────────────────── +*/ + +tooltip { + background-color: @surfaceContainer; + border-radius: 11px; + outline: none; + border: none; + box-shadow: none; +} + +tooltip label { + color: @onSurface; + outline: none; + border: none; + box-shadow: none; + font-weight: normal; +} + +/* + * ── icon ────────────────────────────────────────────────────────────── +*/ + +#material_icon, +#material_icon * { + all: unset; + font-family: "Material Symbols Outlined", "Material Symbols Sharp"; +} diff --git a/config/fabric/styles/notification.css b/config/fabric/styles/notification.css new file mode 100644 index 00000000..88d79b72 --- /dev/null +++ b/config/fabric/styles/notification.css @@ -0,0 +1,47 @@ +#notification { + padding: 16px; + border: solid 1px @outlineVariant; + border-radius: 20px; + margin-bottom: 12px; + background-color: @surfaceContainerLow; + min-width: 350px; +} + +.notification-header .summary { + font-size: 0.92rem; + font-weight: bold; +} + +.notification-body .body { + color: darker(@foreground); + font-weight: 600; + font-size: 0.92rem; +} + +#notification .close-button:hover { + background: alpha(@foreground, 0.2); + transition: background 0.15s ease-in-out; + border-radius: 100px; +} + +#notification-action-button button.start-action { + margin-left: 0; +} + +#notification-action-button button.end-action { + margin-right: 0; +} + +#notification-action-buttons button { + padding: 0.6rem; + font-weight: 600; + border-radius: 100px; + background-color: transparent; +} +#notification-action-buttons button:hover { + background-color: lighter(@outlineVariant); +} + +#notification-icon { + margin-right: 5px; +} diff --git a/config/fabric/styles/osd.css b/config/fabric/styles/osd.css new file mode 100644 index 00000000..866978b2 --- /dev/null +++ b/config/fabric/styles/osd.css @@ -0,0 +1,41 @@ +#osd { + background: @surfaceContainer; + padding: 12px 20px; + border-radius: 100px; + margin-bottom: 16px; +} + +#osd scale { + min-width: 150px; +} + +#osd slider { + color: @onPrimary; + background-color: @primary; + background-size: 20px 20px; + min-width: 5px; + min-height: 14px; + border-radius: 100px; + padding: 0px; + background-repeat: no-repeat; + background-position: center; + margin-left: 0px; + margin-right: 0px; + margin-top: -16px; + margin-bottom: -16px; + box-shadow: + -4px 0px 0px 1px @surfaceContainer, + 4px 0px 0px 1px @surfaceContainer; +} + +#osd trough { + background: @secondaryContainer; + min-height: 10px; + margin-right: 4px; + border-radius: 100px; +} + +#osd highlight { + border-radius: 100px 0px 0px 100px; + background: @primary; +}