This commit is contained in:
sankalp committed 2024-11-15 18:26:25 +05:45
1 parent b94984d0e3
commit 8cdd6d9797
41 files changed
+553 -43

No files matched your search

+6 -4
View File
@@ -1,16 +1,16 @@
from fabric.hyprland.widgets import Language
from fabric.system_tray.widgets import SystemTray
from fabric.utils import FormattedString, bulk_replace, exec_shell_command
from fabric.utils import FormattedString, bulk_replace
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.datetime import DateTime
from fabric.widgets.wayland import WaylandWindow as Window
from icon import MaterialIcon
from modules.bar.widgets import (
BatteryLabel,
Bluetooth,
HardwareUsage,
IdleIndicator,
MicrophoneIndicator,
Network,
PowerProfile,
@@ -44,7 +44,7 @@ class Bar(Window):
)
self.date_time = DateTime(formatters=["%-I:%M 󰧞 %a %d %b"], name="datetime")
self.system_tray = SystemTray(name="tray", spacing=4, icon_size=18)
self.TaskBar = TaskBar(icon_size=18)
self.taskbar = TaskBar(icon_size=18)
self.volume = VolumeIndicator()
self.network = Network()
self.bluetooth = Bluetooth()
@@ -53,6 +53,7 @@ class Bar(Window):
self.power = PowerProfile()
self.workspaces = Button(child=workspace, name="workspaces")
self.info = HardwareUsage()
self.idle = IdleIndicator()
self.applets = Box(
name="applets",
spacing=4,
@@ -63,6 +64,7 @@ class Bar(Window):
self.network,
self.volume,
self.microphone,
self.idle,
],
)
self.children = CenterBox(
@@ -81,7 +83,7 @@ class Bar(Window):
spacing=8,
orientation="h",
children=[
self.TaskBar,
self.taskbar,
],
),
end_children=Box(
+54
View File
@@ -0,0 +1,54 @@
import gi
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
from .icon_resolver import IconResolver
gi.require_version("Glace", "0.1")
from gi.repository import Glace
class OpenAppsBar(Box):
def __init__(self):
self.client_buttons = {}
super().__init__(spacing=10)
self.icon_resolver = IconResolver()
self._manager = Glace.Manager()
self._manager.connect("client-added", self.on_client_added)
def on_active_window(self, _, event):
print(event.data)
print(self.client_buttons)
# client_buttons[]
def on_client_added(self, _, client: Glace.Client):
client_image = Image()
client_button = Button(
name="panel-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)
),
print(client.get_id()),
],
)
client.connect(
"notify::activated",
lambda *_: (
client_button.add_style_class("activated")
if client.get_activated()
else client_button.remove_style_class("activated")
),
)
client.bind_property("title", client_button, "tooltip-text", 0)
client.connect("close", lambda *_: self.remove(client_button))
self.add(client_button)
+100
View File
@@ -0,0 +1,100 @@
import json
import os
import re
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk
from loguru import logger
# TODO WIP
# Idea: nearest string matching algorithm
# if already exists: retrieve from json
# if found: stor in json: app_id -> icon_name
# if not found: store in json -> misisng-icon
CACHE_DIR = str(GLib.get_user_cache_dir()) + "/fabric"
ICON_CACHE_FILE = CACHE_DIR + "/icons.json"
if not os.path.exists(CACHE_DIR):
os.makedirs(CACHE_DIR)
class IconResolver:
def __init__(self, default_applicaiton_icon: str = "application-x-symbolic"):
if os.path.exists(ICON_CACHE_FILE):
f = open(ICON_CACHE_FILE)
try:
self._icon_dict = json.load(f)
except json.JSONDecodeError:
logger.info("[ICONS] Cache file does not exist or is corrupted")
f.close()
else:
self._icon_dict = {}
self.default_applicaiton_icon = default_applicaiton_icon
def get_icon_name(self, app_id: str):
if app_id in self._icon_dict:
return self._icon_dict[app_id]
new_icon = self._compositor_find_icon(app_id)
logger.info(
f"[ICONS] found new icon: '{new_icon}' for app id: '{app_id}', storing..."
)
self._store_new_icon(app_id, new_icon)
return new_icon
def get_icon_pixbuf(self, app_id: str, size: int = 16):
return Gtk.IconTheme.get_default().load_icon(
self.get_icon_name(app_id),
size,
Gtk.IconLookupFlags.FORCE_SIZE,
)
def _store_new_icon(self, app_id: str, icon: str):
self._icon_dict[app_id] = icon
with open(ICON_CACHE_FILE, "w") as f:
json.dump(self._icon_dict, f)
f.close()
def _get_icon_from_desktop_file(self, desktop_file_path: str):
# TODO: get icon in the [Desktop Entry] section only
with open(desktop_file_path) as f:
for line in f.readlines():
if "Icon=" in line:
return "".join(line[5:].split())
return self.default_applicaiton_icon
def _get_desktop_file(self, app_id: str) -> str | None:
data_dirs = GLib.get_system_data_dirs()
for data_dir in data_dirs:
data_dir = data_dir + "/applications/"
if os.path.exists(data_dir):
# Do name resolving here
files = os.listdir(data_dir)
matching = [
s for s in files if "".join(app_id.lower().split()) in s.lower()
]
if matching:
return data_dir + matching[0]
for word in list(filter(None, re.split(r"-|\.|_|\s", app_id))):
matching = [s for s in files if word.lower() in s.lower()]
if matching:
return data_dir + matching[0]
return None
def _compositor_find_icon(self, app_id: str):
if Gtk.IconTheme.get_default().has_icon(app_id):
return app_id
if Gtk.IconTheme.get_default().has_icon(app_id + "-desktop"):
return app_id + "-desktop"
desktop_file = self._get_desktop_file(app_id)
return (
self._get_icon_from_desktop_file(desktop_file)
if desktop_file
else self.default_applicaiton_icon
)
@@ -1,5 +1,6 @@
from .battery import *
from .bluetooth import *
from .idle_indicator import *
from .info import *
from .microphone import *
from .network import *
+25 -8
View File
@@ -1,19 +1,37 @@
import psutil
from fabric.utils import invoke_repeater
from fabric.widgets.box import Box
from fabric.widgets.label import Label
from icon import MaterialIcon
from services.icon import MaterialIcon
class BatteryLabel(Box):
ICONS_CHARGING = [
"battery_charging_20", "battery_charging_20", "battery_charging_20", "battery_charging_30", "battery_charging_30",
"battery_charging_50", "battery_charging_60", "battery_charging_80", "battery_charging_80",
"battery_charging_90", "battery_charging_full"
"battery_charging_20",
"battery_charging_20",
"battery_charging_20",
"battery_charging_30",
"battery_charging_30",
"battery_charging_50",
"battery_charging_60",
"battery_charging_80",
"battery_charging_80",
"battery_charging_90",
"battery_charging_full",
]
ICONS_NOT_CHARGING = [
"battery_alret", "battery_1_bar", "battery_1_bar", "battery_2_bar", "battery_2_bar",
"battery_3_bar", "battery_4_bar", "battery_4_bar", "battery_5_bar",
"battery_6_bar", "battery_full"
"battery_alert",
"battery_1_bar",
"battery_1_bar",
"battery_2_bar",
"battery_2_bar",
"battery_3_bar",
"battery_4_bar",
"battery_4_bar",
"battery_5_bar",
"battery_6_bar",
"battery_full",
]
def __init__(self, **kwargs):
@@ -40,4 +58,3 @@ class BatteryLabel(Box):
self.show() if battery_percent < 100 else self.hide()
return True
@@ -1,6 +1,7 @@
from fabric.bluetooth import BluetoothClient
from fabric.widgets.box import Box
from icon import MaterialIcon # Import your MaterialIcon function
from services.icon import MaterialIcon # Import your MaterialIcon function
class Bluetooth(Box):
ICON_ENABLED = "bluetooth" # Use the appropriate Material icon name
@@ -32,4 +33,3 @@ class Bluetooth(Box):
def on_destroy(self):
"""Disconnect the Bluetooth client when the widget is destroyed."""
self.bluetooth_client.disconnect("changed", self.update_bluetooth_status)
@@ -0,0 +1,132 @@
import json
from typing import TypedDict
from fabric.hyprland.widgets import get_hyprland_connection
from fabric.utils import DesktopApp, exec_shell_command, get_desktop_applications
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
class PagerClient(TypedDict):
title: str
initialClass: str
mapped: bool
hidden: bool
address: str
class TaskBar(Box):
def __init__(self, icon_size: int = 18, **kwargs):
super().__init__(
orientation="h",
spacing=7,
name="taskbar",
**kwargs,
)
self.connection = get_hyprland_connection()
self.icon_size = icon_size
self.icon_theme = Gtk.IconTheme.get_default()
self.set_visible(False)
if self.connection.ready:
self.render_with_delay()
else:
self.connection.connect("event::ready", lambda *_: self.render_with_delay())
for event in (
"activewindow",
"openwindow",
"closewindow",
"changefloatingmode",
):
self.connection.connect("event::" + event, lambda *_: self.render(None))
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:
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:101px;"
)
button.connect(
"button-press-event", self.on_icon_click, client["address"]
)
self.add(button)
self.set_visible(True)
self.show_all()
else:
self.set_visible(False)
def get_active_window_address(self) -> str:
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}")
def fetch_clients(self) -> list[PagerClient]:
return json.loads(self.connection.send_command("j/clients").reply.decode())
def bake_window_icon(
self, window_class: str, fallback_icon: str = "image-missing"
) -> Image:
icon = self.get_application_icon(window_class, fallback_icon)
return Image(pixbuf=icon, size=self.icon_size)
def get_application_icon(
self, window_class: str, fallback_icon: str
) -> GdkPixbuf.Pixbuf:
app = self.get_app_by_window_class(window_class)
if app:
pixbuf = app.get_icon_pixbuf()
if pixbuf:
return pixbuf
return self.load_icon(fallback_icon)
def get_app_by_window_class(self, window_class: str) -> DesktopApp | None:
all_apps = get_desktop_applications()
for app in all_apps:
if window_class.lower() in (app.display_name or "").lower():
return app
return None
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,
)
except Exception:
pixbuf = self.icon_theme.load_icon(
fallback_icon,
self.icon_size,
Gtk.IconLookupFlags.FORCE_SIZE,
)
return pixbuf
@@ -0,0 +1,41 @@
from fabric.utils import exec_shell_command
from fabric.widgets.box import Box
from gi.repository import GLib
from services.icon import MaterialIcon
class IdleIndicator(Box):
ICON_IDLE = "schedule"
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)
self.children = (self.idle_icon,)
def create_idle_icon(self):
return MaterialIcon(self.ICON_IDLE, size="16px")
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 ""
is_idle = bool(output_str.strip())
self.update_idle_status(is_idle)
except Exception as e:
print(f"Error checking idle status: {e}")
self.update_idle_status(False)
return True
def update_idle_status(self, is_idle):
if is_idle:
self.idle_icon.set_label(self.ICON_IDLE)
self.idle_icon.set_visible(True)
else:
self.idle_icon.set_visible(False)
+13 -7
View File
@@ -1,17 +1,19 @@
import psutil
from fabric.utils import invoke_repeater
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.circularprogressbar import CircularProgressBar
from fabric.widgets.label import Label
from fabric.widgets.overlay import Overlay
from fabric.widgets.circularprogressbar import CircularProgressBar
from icon import MaterialIcon # Import your updated MaterialIcon function
from services.icon import MaterialIcon
class HardwareUsage(Button):
HARDWARE_ITEMS = [
("CPU", "settings_motion_mode"), # Pass the Material icon name directly
("CPU", "settings_motion_mode"),
("Swap", "swap_horiz"),
("RAM", "memory"),
("RAM", "memory_alt"),
]
def __init__(self):
@@ -33,16 +35,21 @@ class HardwareUsage(Button):
return self.box
def _create_progress_bar(self):
return CircularProgressBar(name="progress", pie=True, size=30)
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])
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 _update_labels(self):
usages = self._get_hardware_usages()
self._update_progress_bars(usages)
return True
def _get_hardware_usages(self):
return {
@@ -56,4 +63,3 @@ class HardwareUsage(Button):
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}%")
@@ -1,12 +1,13 @@
from fabric.audio.service import Audio
from fabric.widgets.box import Box
from icon import MaterialIcon # Import your MaterialIcon function
from services.icon import MaterialIcon # Import your MaterialIcon function
class MicrophoneIndicator(Box):
ICON_MUTED = "mic_off"
ICON_UNMUTED = "mic"
def __init__(self, **kwargs):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.audio_service = Audio()
self.microphone_icon = self.create_microphone_icon()
@@ -32,4 +33,3 @@ class MicrophoneIndicator(Box):
self.microphone_icon.set_visible(False)
return True
+20 -11
View File
@@ -1,15 +1,19 @@
import subprocess
import psutil
from fabric.utils import invoke_repeater
from fabric.widgets.box import Box
from icon import MaterialIcon
import subprocess
from services.icon import MaterialIcon
class Network(Box):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.update_interval = 5000
self.last_status = None
invoke_repeater(self.update_interval, self.update_network_status, initial_call=True)
invoke_repeater(
self.update_interval, self.update_network_status, initial_call=True
)
def update_network_status(self):
current_status = self.get_network_status()
@@ -24,7 +28,7 @@ class Network(Box):
def get_network_status(self):
if self.is_ethernet_connected():
return "network_ethernet"
return "lan"
if self.is_wifi_connected():
return self.get_wifi_strength_icon()
return "signal_wifi_off"
@@ -47,23 +51,28 @@ class Network(Box):
def check_wifi_strength(self):
try:
result = subprocess.run(['iwconfig'], capture_output=True, text=True)
result = subprocess.run(["iwconfig"], capture_output=True, text=True)
for line in result.stdout.splitlines():
if 'Signal level' in line:
signal_level = line.split('Signal level=')[1].split(' ')[0]
return int(signal_level.strip().replace('dBm', ''))
if "Signal level" in line:
signal_level = line.split("Signal level=")[1].split(" ")[0]
return int(signal_level.strip().replace("dBm", ""))
return None
except Exception:
return None
def is_wifi_connected(self):
return any(self._is_interface_up(interface, ["wlan", "wifi"]) for interface in psutil.net_if_addrs())
return any(
self._is_interface_up(interface, ["wlan", "wifi"])
for interface in psutil.net_if_addrs()
)
def is_ethernet_connected(self):
return any(self._is_interface_up(interface, ["eth"]) for interface in psutil.net_if_addrs())
return any(
self._is_interface_up(interface, ["eth"])
for interface in psutil.net_if_addrs()
)
def _is_interface_up(self, interface, keywords):
if any(substring in interface.lower() for substring in keywords):
return psutil.net_if_stats().get(interface, {}).isup
return False
@@ -0,0 +1,149 @@
from fabric.utils import bulk_connect, exec_shell_command_async
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.eventbox import EventBox
from fabric.widgets.label import Label
from fabric.widgets.revealer import Revealer
class PowerMenu(EventBox):
def __init__(self):
super().__init__(name="power-event")
icons_map = {
"power-lock": "",
"power-suspend": "",
"power-logout": "",
"power-reboot": "",
"power-shutdown": "",
}
self.buttons = {
name: Button(name=name, child=Label(label=f"{icon}"))
for name, icon in icons_map.items()
}
self.power_box = Box(
name="power-box",
orientation="h",
children=[
self.buttons[name]
for name in [
"power-lock",
"power-suspend",
"power-logout",
"power-reboot",
]
],
)
self.accept_button = Button(name="accept", child=Label(label="✔"))
self.cancel_button = Button(name="cancel", child=Label(label="✘"))
self.revealer_buttons_box = Box(
name="confirm-box",
orientation="h",
children=[self.accept_button, self.cancel_button],
)
self.revealer = Revealer(
name="power-revealer",
transition_type="slide-right",
transition_duration=300,
child=self.power_box,
reveal_child=False,
)
self.shutdown_box = Box(
name="shutdown-box",
orientation="h",
children=[self.buttons["power-shutdown"]],
)
self.super_box = Box(
name="super-box",
orientation="h",
children=[self.revealer, self.shutdown_box],
)
self.confirm_revealer = Revealer(
name="confirm-revealer",
transition_type="slide-right",
transition_duration=300,
child=self.revealer_buttons_box,
reveal_child=False,
)
self.full_power = Box(
name="full-power",
orientation="h",
children=[self.super_box, self.confirm_revealer],
)
self.add(self.full_power)
self.buttons["self"] = self
self.current_command = None
self.confirmation_active = False
for btn in self.buttons.values():
bulk_connect(
btn,
{
"button-press-event": self.on_button_press,
"enter-notify-event": self.on_button_hover,
"leave-notify-event": self.on_button_unhover,
},
)
self.accept_button.connect("button-press-event", self.on_accept_press)
self.cancel_button.connect("button-press-event", self.on_cancel_press)
def on_button_hover(self, button, event):
if button == self and not self.confirmation_active:
self.revealer.set_reveal_child(True)
def on_button_unhover(self, button, event):
if button == self and not self.confirmation_active:
self.revealer.set_reveal_child(False)
def on_button_press(self, button, event):
commands = {
self.buttons["power-lock"]: "hyprlock",
self.buttons[
"power-suspend"
]: "hyprctl dispatch exec hyprlock && systemctl suspend",
self.buttons["power-logout"]: "hyprctl dispatch exit",
self.buttons["power-reboot"]: "systemctl reboot",
self.buttons["power-shutdown"]: "systemctl poweroff",
}
if button in commands:
if button != self.buttons["power-lock"]:
self.current_command = commands[button]
self.revealer.set_reveal_child(False)
self.confirm_revealer.set_reveal_child(True)
self.shutdown_box.hide()
self.confirmation_active = True
else:
exec_shell_command_async(commands[button], lambda *_: None)
return True
def on_accept_press(self, button, event):
if self.current_command:
exec_shell_command_async(self.current_command, lambda *_: None)
self.current_command = None
self.confirm_revealer.set_reveal_child(False)
self.revealer.set_reveal_child(True)
self.shutdown_box.show()
self.confirmation_active = False
return True
def on_cancel_press(self, button, event):
self.current_command = None
self.confirm_revealer.set_reveal_child(False)
self.revealer.set_reveal_child(True)
self.shutdown_box.show()
self.confirmation_active = False
return True
@@ -1,6 +1,6 @@
from fabric.utils import exec_shell_command, invoke_repeater
from fabric.widgets.box import Box
from icon import MaterialIcon
from services.icon import MaterialIcon
PROFILE_ICONS = {
"power-saver": "data_saver_on",
@@ -8,6 +8,7 @@ PROFILE_ICONS = {
"performance": "mode_heat",
}
class PowerProfile(Box):
def __init__(self, **kwargs):
super().__init__(**kwargs)
@@ -40,5 +41,3 @@ class PowerProfile(Box):
if self.profile_icon:
self.profile_icon.hide()
self.profile_icon = None
+3 -2
View File
@@ -2,13 +2,14 @@ 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 loguru import logger
class PagerClient(TypedDict):
+2 -3
View File
@@ -2,7 +2,7 @@ from fabric.audio.service import Audio
from fabric.utils import exec_shell_command, invoke_repeater
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from icon import MaterialIcon
from services.icon import MaterialIcon
VOLUME_ICONS = {
"muted": "volume_off",
@@ -12,6 +12,7 @@ VOLUME_ICONS = {
"high": "volume_up",
}
class VolumeIndicator(Box):
def __init__(self, **kwargs):
super().__init__(**kwargs)
@@ -26,7 +27,6 @@ class VolumeIndicator(Box):
self.children = (self.volume_icon_button,)
def create_volume_icon(self):
"""Create a button with a Material icon for volume."""
icon = MaterialIcon(VOLUME_ICONS["muted"], size="16px")
button = Button(child=icon)
button.icon_widget = icon
@@ -80,4 +80,3 @@ class VolumeIndicator(Box):
return VOLUME_ICONS["medium-high"]
else:
return VOLUME_ICONS["high"]