This commit is contained in:
sankalp committed 2024-12-01 07:57:46 +05:45
1 parent bcd37ad40d
commit 6fdc91f58c
10 files changed
+246 -261

No files matched your search

@@ -1,11 +1,11 @@
from .battery import BatteryLabel
from .bluetooth import Bluetooth
from .glace import TaskBar
from .idle_indicator import IdleIndicator
from .info import SystemInfo
from .microphone import MicrophoneIndicator
from .network import Network
from .powerprofile import PowerProfile
from .taskbar import TaskBar
from .volume import VolumeIndicator
from .workspace import workspace
@@ -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)
@@ -0,0 +1,112 @@
import json
from typing import TypedDict
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):
title: str
initialClass: str
mapped: bool
hidden: bool
address: str
class TaskBar(Box):
def __init__(self, icon_size: int = 24, **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.icon_resolver = IconResolver()
self.set_visible(False)
self._icon_cache = {}
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(f"event::{event}", lambda *_: self.render())
def render_with_delay(self, *_):
GLib.timeout_add(101, self.render)
def render(self, *_):
self.children = []
active_window_address = self.get_active_window_address()
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.connect(
"button-press-event", self.on_icon_click, client["address"]
)
self.add(button)
self.set_visible(len(self.children) > 0)
if self.children:
self.show_all()
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):
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())
def bake_window_icon(
self, window_class: str, fallback_icon: str = "image-missing"
) -> Image:
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)
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) -> GdkPixbuf.Pixbuf:
try:
return self.icon_theme.load_icon(
icon_name, self.icon_size, Gtk.IconLookupFlags.FORCE_SIZE
)
except Exception:
return self.icon_theme.load_icon(
"image-missing", self.icon_size, Gtk.IconLookupFlags.FORCE_SIZE
)
@@ -37,11 +37,13 @@ def handle_application_search(launcher, query: str):
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",
@@ -13,11 +13,8 @@ class BluetoothMenu:
self.paired_devices = {}
self.available_devices = {}
# Initialize buttons
self.bt_button = self.create_bluetooth_button()
self.scan_button = self.create_scan_button()
# Set the initial style based on the Bluetooth state
self.update_bt_button_style()
def create_bluetooth_button(self):
@@ -38,7 +35,7 @@ class BluetoothMenu:
style="min-height:50px; min-width:50px;",
)
def bt_toggle(self, *args):
def bt_toggle(self, *_):
self.client.toggle_power()
self.update_bt_button_style()
+10 -10
View File
@@ -1,7 +1,7 @@
import json
import os
import subprocess
from typing import List
from typing import Generator, List
from fabric.widgets.box import Box
from fabric.widgets.button import Button
@@ -23,24 +23,24 @@ class EmojiManager:
self.emojis: List[EmojiItem] = []
self.query_cache: dict = {}
def load_emojis(self):
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 []
return
try:
with open(emoji_path, "r") as file:
data = json.load(file)
return [
EmojiItem(emoji_str, item["name"], item["slug"], item["group"])
for emoji_str, item in data.items()
]
for emoji_str, item in data.items():
yield EmojiItem(
emoji_str, item["name"], item["slug"], item["group"]
)
except (json.JSONDecodeError, OSError):
return []
return
def get_emojis(self):
def get_emojis(self) -> List[EmojiItem]:
if not self.emojis:
self.emojis = self.load_emojis()
self.emojis = list(self.load_emojis())
return self.emojis
def query_emojis(self, query: str) -> List[EmojiItem]:
@@ -7,6 +7,11 @@ 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; min-width:50px; min-height:50px;"
)
class PowerMenu:
def __init__(self, launcher):
@@ -17,11 +22,9 @@ class PowerMenu:
v_align="center",
on_clicked=self.toggle_idle_inhibitor,
)
self.idle_button.set_style(
"background-color: transparent;min-width:50px; min-height:50px;"
)
self.idle_button.set_style(IDLE_BUTTON_INACTIVE_STYLE)
def toggle_idle_inhibitor(self, *args):
def toggle_idle_inhibitor(self, *_):
self.idle_inhibitor = not self.idle_inhibitor
script_path = os.path.expanduser(
"~/fabric/assets/scripts/wayland-idle-inhibitor.py"
@@ -32,19 +35,14 @@ class PowerMenu:
["python3", script_path],
lambda output: logger.info(f"Idle inhibitor output: {output}"),
)
self.idle_button.set_style(
"background-color: @surfaceVariant; min-width:50px; min-height:50px; border-radius:100px;"
)
self.idle_button.set_style(IDLE_BUTTON_ACTIVE_STYLE)
else:
exec_shell_command("pkill -f wayland-idle-inhibitor.py")
self.idle_button.set_style(
"background-color: transparent;min-width:50px; min-height:50px;"
)
self.idle_button.set_style(IDLE_BUTTON_INACTIVE_STYLE)
def check_idle_state(self):
return "wayland-idle-inhibitor.py" in exec_shell_command(
"pidof wayland-idle-inhibitor.py"
)
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 = []
@@ -55,35 +53,24 @@ class PowerMenu:
"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,
},
{"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},
]
if query:
power_options = [
# 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 power_options:
for option in filtered_options:
button = Button(
child=Box(
orientation="h",
+15 -18
View File
@@ -14,29 +14,30 @@ 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):
paths = os.getenv("PATH", "").split(":")
bins = []
self.binaries = set()
for path in paths:
bins.extend(self.list_binaries_in_path(path))
self.binaries.update(self.list_binaries_in_path(path))
unique_bins = set(bins)
# Write unique binaries to the cache file
with open(BINS, "w") as f:
f.write("\n".join(unique_bins))
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 show_shell_commands(self, viewport, search_query: str):
@@ -46,14 +47,10 @@ class ShellCommandManager:
results = self.query_binaries(search_query)
self.display_results(viewport, results)
def query_binaries(self, filter_str):
try:
result = subprocess.check_output(
f"cat {BINS} | fzf -f {filter_str} | head -n 16", shell=True, text=True
)
return list(dict.fromkeys(result.splitlines())) # Deduplicate results
except subprocess.CalledProcessError:
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:
+81 -76
View File
@@ -1,25 +1,20 @@
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
from gi.repository import GdkPixbuf
NOTIFICATION_WIDTH = 400
NOTIFICATION_IMAGE_SIZE = 64
@@ -60,77 +55,67 @@ class NotificationWidget(Box):
self._notification = notification
header_container = Box(spacing=8, orientation="h")
header_container.children = (
self.get_icon(notification.app_icon, 16),
Label(
markup=str(
self._notification.summary
if self._notification.summary
else notification.app_name
),
h_align="start",
style="font-weight: 900;",
),
)
header_container.pack_end(
Box(
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(),
),
)
),
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,
),
style="border-radius:100px;",
if image_pixbuf := self._notification.image_pixbuf:
body_container.add(
Image(
pixbuf=image_pixbuf.scale_simple(
NOTIFICATION_IMAGE_SIZE,
NOTIFICATION_IMAGE_SIZE,
GdkPixbuf.InterpType.BILINEAR,
)
)
)
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",
max_chars_width=40,
h_align="start",
)
)
self.add(header_container)
self.add(body_container)
self.add(
@@ -160,15 +145,36 @@ class NotificationWidget(Box):
),
)
def get_icon(self, app_icon, size) -> Image:
match app_icon:
case str(x) if "file://" in x:
return Image(
name="notification-icon",
image_file=app_icon[7:],
icon_size=size,
)
case str(x) if len(x) > 0 and "/" == x[0]:
return Image(
name="notification-icon",
image_file=app_icon,
icon_size=size,
)
case _:
return Image(
name="notification-icon",
icon_name=app_icon if app_icon else "dialog-information-symbolic",
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,17 +182,16 @@ 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)
-18
View File
@@ -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)}