This commit is contained in:
sankalp committed 2026-07-12 18:56:10 +05:45
1 parent 6b62051f93
commit dc60e20bd7
182 files changed
+18062 -277

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
"""
Modus Panel modules package.
Contains UI components and functionality modules
"""
import importlib
import inspect
import pkgutil
__all__ = []
for module_info in pkgutil.iter_modules(__path__):
module_name = module_info.name
module = importlib.import_module(f"{__name__}.{module_name}")
for attr_name in dir(module):
if not attr_name.startswith("_"):
attr_value = getattr(module, attr_name)
if (
inspect.isclass(attr_value) or inspect.isfunction(attr_value)
) and inspect.getmodule(attr_value) is module:
globals()[attr_name] = attr_value
__all__.append(attr_name)
+82
View File
@@ -0,0 +1,82 @@
from fabric.widgets.box import Box
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from config.data import DATA
from services import BatteryService, DeviceState, has_config_changed, on_config_change
class Battery(Box):
def __init__(self, **kwargs):
self._load_config()
self._icon = Image(icon_name="battery-100", icon_size=self._icon_size)
self._label_widget = Label(label="")
self._label_widget.set_no_show_all(True)
super().__init__(
name="battery",
orientation="h",
spacing=4,
children=[self._icon, self._label_widget],
**kwargs,
)
if not self._show_label:
self._label_widget.hide()
self._service = BatteryService()
self._service.connect("changed", lambda *_: self._update())
on_config_change(self._on_config_change)
self._update()
def _load_config(self):
components = DATA()
self._show_label = components["battery_label"]
self._hide_on_full = components["battery_hide_on_full"]
self._icon_size = components["battery_icon_size"]
def _update(self):
percentage = self._service.get_property("Percentage") or 0
state = self._service.get_property("State") or 0
is_full = int(percentage) >= 100 or DeviceState.get(state) in ("FULLY_CHARGED",)
self.set_visible(not (self._hide_on_full and is_full))
icon_name = self._resolve_icon_name(percentage, state)
self._icon.set_from_icon_name(icon_name, self._icon_size)
self._label_widget.set_visible(self._show_label)
if self._show_label:
self._label_widget.set_label(f"{int(percentage)}%")
def _on_config_change(self, new_config, old_config):
paths = [
"panel.battery.enabled",
"panel.battery.label",
"panel.battery.hide_on_full",
"panel.battery.icon_size",
]
if any(has_config_changed(old_config, new_config, p) for p in paths):
old_show_label = self._show_label
old_hide_on_full = self._hide_on_full
old_icon_size = self._icon_size
self._load_config()
if (
old_show_label != self._show_label
or old_hide_on_full != self._hide_on_full
or old_icon_size != self._icon_size
):
self._update()
def _resolve_icon_name(self, percentage, state) -> str:
pct = int(percentage)
pct = max(0, min(100, pct))
bucket = (pct // 10) * 10
base = f"battery-{bucket:03d}"
if state in {1, 4, 5}: # CHARGING, FULLY_CHARGED, PENDING_CHARGE
return f"{base}-charging"
return f"{base}"
@@ -0,0 +1,251 @@
"""
Enhanced System Tray
Patches icon loading (absolute path support), item filtering, and
hot-reloading of filter config based on `config.json`.
"""
from pathlib import Path
from fabric.system_tray.service import SystemTrayItem as SystemTrayItemService
from fabric.utils import GdkPixbuf, GLib, Gtk, idle_add
import config.data as data
from services.config_watcher import get_all_config, has_config_changed, on_config_change
def _get_filter_from_config(config):
systray_config = config.get("panel", {}).get("systray", {})
hide_list = systray_config.get("hide_items", [])
return set(x.lower() for x in hide_list if isinstance(x, str))
def _should_hide_item(identifier, filter_set, item=None):
if not filter_set:
return False
title = ""
if item and hasattr(item, "title") and item.title:
title = item.title
identifier_str = identifier if identifier else ""
# Check both title and identifier (case-insensitive for convenience)
for pattern in filter_set:
p = pattern.lower()
if p in title.lower() or p in identifier_str.lower():
return True
return False
def apply_enhanced_system_tray(tray_widget):
"""
Patch the system tray widget for advanced icon fallback, config hot-reloading, and item filtering.
This handles the case where the tray might not initially own the DBus name.
"""
# Mark that we've already patched this widget to avoid double-patching
if hasattr(tray_widget, "_enhanced_applied"):
return
tray_widget._enhanced_applied = True
# Set initial filter FIRST
initial_config = get_all_config()
tray_widget._current_filter = _get_filter_from_config(initial_config)
tray_widget._bypass_filter = False
if is_debug():
print(
f"[Systray] Applying enhanced tray with filter: {tray_widget._current_filter}"
)
original_get_preferred_icon_pixbuf = SystemTrayItemService.get_preferred_icon_pixbuf
original_on_item_added = tray_widget.on_item_added
def patched_get_preferred_icon_pixbuf(self, size=None, resize_method="bilinear"):
# enhanced icon selection with theme/path fallback.
try:
size = size or 24
icon_name = self.icon_name
attention_icon_name = self.attention_icon_name
preferred_icon_name = (
attention_icon_name
if (self.status == "NeedsAttention" and attention_icon_name)
else icon_name
)
preferred_icon_pixmap = self.icon_pixmap
if preferred_icon_pixmap is None and preferred_icon_name:
path = Path(preferred_icon_name)
if path.is_absolute() and path.exists():
try:
target = size
return GdkPixbuf.Pixbuf.new_from_file_at_scale(
str(path),
target,
target,
True,
)
except GLib.GError:
return None
if preferred_icon_name:
icon_theme = self.icon_theme
if icon_theme.has_icon(preferred_icon_name):
try:
pixbuf = icon_theme.load_icon(
preferred_icon_name, size, Gtk.IconLookupFlags.FORCE_SIZE
)
if pixbuf:
return pixbuf
except Exception as e:
print(f"[Systray] Theme icon error: {e}")
# Fallback to original/default logic
return original_get_preferred_icon_pixbuf(self, size, resize_method)
except Exception as e:
print(f"[Systray] Error in patched_get_preferred_icon_pixbuf: {e}")
try:
return original_get_preferred_icon_pixbuf(self, size, resize_method)
except Exception as fallback_e:
print(f"[Systray] Fallback also failed: {fallback_e}")
return None
SystemTrayItemService.get_preferred_icon_pixbuf = patched_get_preferred_icon_pixbuf
def patched_on_item_added(watcher_self, item_identifier: str):
"""Intercept item addition to check filter BEFORE widget creation"""
item = tray_widget._watcher.items.get(item_identifier)
title = item.title if item and hasattr(item, "title") and item.title else ""
if is_debug():
print(
f"[Systray] on_item_added called for: {item_identifier} (title: '{title}')"
)
print(f"[Systray] Current filter: {tray_widget._current_filter}")
print(
f"[Systray] Should hide: {_should_hide_item(item_identifier, tray_widget._current_filter, item)}"
)
# Check if should be hidden
if not tray_widget._bypass_filter and _should_hide_item(
item_identifier, tray_widget._current_filter, item
):
if is_debug():
print(
f"[Systray] ✗ Blocking hidden item at registration: {item_identifier}"
)
# Get the item from watcher but don't create widget
item = tray_widget._watcher.items.get(item_identifier)
if item:
# Store None as placeholder to track this hidden item
tray_widget._items[item_identifier] = None
return
if is_debug():
print(f"[Systray] ✓ Allowing item: {item_identifier}")
# Item is not hidden, proceed with normal creation
original_on_item_added(watcher_self, item_identifier)
tray_widget.on_item_added = patched_on_item_added
def sync_visibility():
current_filter = tray_widget._current_filter
app_names = set()
if is_debug():
print("[Systray] === sync_visibility called ===")
print(f"[Systray] Current filter: {current_filter}")
print(f"[Systray] Items in _items: {list(tray_widget._items.keys())}")
for identifier, item_button in list(tray_widget._items.items()):
item = tray_widget._watcher.items.get(identifier)
title_name = (
item.title
if item and hasattr(item, "title") and item.title
else identifier.split("/")[-1]
)
app_names.add(title_name)
# Handle None entries (items that were blocked at registration)
if item_button is None:
should_hide = _should_hide_item(identifier, current_filter, item)
if is_debug():
print(
f"[Systray] Found None entry for {identifier}, should_hide={should_hide}"
)
if not should_hide:
# Item should now be visible, need to create it
if is_debug():
print(
f"[Systray] Creating previously hidden item: {identifier}"
)
# Remove the None placeholder
tray_widget._items.pop(identifier)
# Trigger normal creation by calling original handler
tray_widget._bypass_filter = True
original_on_item_added(None, identifier)
tray_widget._bypass_filter = False
continue
should_hide = _should_hide_item(identifier, current_filter, item)
is_in_parent = item_button.get_parent() is not None
should_be_in_parent = not should_hide
title = item.title if item and hasattr(item, "title") and item.title else ""
if is_debug():
print(
f"[Systray] {identifier} (title: '{title}'): should_hide={should_hide}, is_in_parent={is_in_parent}"
)
if is_in_parent and not should_be_in_parent:
tray_widget.remove(item_button)
if is_debug():
print(f"[Systray] ✗ Hiding: {identifier}")
elif not is_in_parent and should_be_in_parent:
# Re-add to container
container = tray_widget.get_children()
if item_button not in container:
tray_widget.pack_start(item_button, False, False, 0)
item_button.show()
if is_debug():
print(f"[Systray] ✓ Showing: {identifier}")
if app_names and is_debug():
debug_str = ",".join(sorted(app_names))
print(f"[Systray] Tray app identifiers: {debug_str}")
tray_widget.queue_resize()
tray_widget.show_all()
return False
def on_config_changed(new_config, old_config):
if has_config_changed(old_config, new_config, "panel.systray.hide_items"):
tray_widget._current_filter = _get_filter_from_config(new_config)
if is_debug():
print(
f"[Systray] Config changed, new filter: {tray_widget._current_filter}"
)
idle_add(sync_visibility)
# Monitor the watcher's 'changed' signal to handle re-registration after acquiring DBus name
def on_tray_changed(*args):
"""Called when tray items change, including when we take over from another bar"""
if is_debug():
print("[Systray] Tray changed event, syncing visibility")
idle_add(sync_visibility)
tray_widget._watcher.connect("changed", on_tray_changed)
# Initial sync and config watching
idle_add(sync_visibility)
on_config_change(on_config_changed)
if is_debug():
print("[Systray] Enhanced system tray applied successfully")
def is_debug():
return bool(data.DATA()["debug"])
+334
View File
@@ -0,0 +1,334 @@
import json
from fabric.hyprland.service import Hyprland, HyprlandEvent
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from fabric.widgets.image import Image
import config.data as data
from services import has_config_changed, on_config_change
from utils.functions import is_special_workspace_id
from utils.icon_resolver import IconResolver
class TaskBar(Box):
def __init__(self, **kwargs):
super().__init__(
orientation="h",
spacing=6,
name="taskbar",
**kwargs,
)
self.icon_resolver = IconResolver()
self._clients = {}
self._buttons = {}
self._workspace_monitor_source_id = None
self._visibility_callback = None
self._hyprland_connection = Hyprland()
# Connect to Hyprland events
self._hyprland_connection.connect("event::openwindow", self._on_open_window)
self._hyprland_connection.connect("event::closewindow", self._on_close_window)
self._hyprland_connection.connect(
"event::activewindowv2", self._on_active_window
)
self._hyprland_connection.connect("event::movewindow", self._on_move_window)
self._hyprland_connection.connect(
"event::workspacev2", self._on_workspace_changed
)
on_config_change(self._on_config_change)
self._load_config()
self._init_clients()
self._update_visibility()
def _init_clients(self):
"""Initialize clients from current Hyprland state"""
res = self._hyprland_connection.send_command("j/clients")
if not res or not res.reply:
return
try:
clients = json.loads(res.reply.decode("utf-8"))
active_res = self._hyprland_connection.send_command("j/activewindow")
active_address = None
if active_res and active_res.reply:
active_window = json.loads(active_res.reply.decode("utf-8"))
active_address = active_window.get("address")
for client_data in clients:
address = client_data.get("address")
if address:
is_active = address == active_address
self._add_client(address, client_data, is_active)
except Exception as e:
print(f"Error initializing taskbar clients: {e}")
def _on_open_window(self, _, event):
if len(event.data) >= 1:
address = "0x" + event.data[0]
self._update_client_data(address)
def _on_close_window(self, _, event):
if len(event.data) >= 1:
address = "0x" + event.data[0]
self._remove_client(address)
def _on_active_window(self, _, event):
active_address = (
("0x" + event.data[0]) if event.data and event.data[0] else None
)
for key, btn_data in self._buttons.items():
button = btn_data["button"]
if self._group_apps:
# Grouped mode: active if any address in group is active
is_active = active_address in btn_data["addresses"]
else:
# Normal mode: active if address matches key
is_active = key == active_address
if is_active:
button.add_style_class("active")
else:
button.remove_style_class("active")
def _on_move_window(self, _, event):
if len(event.data) >= 1:
address = "0x" + event.data[0]
self._update_client_data(address)
def _update_client_data(self, address):
res = self._hyprland_connection.send_command("j/clients")
if not res or not res.reply:
return
try:
clients = json.loads(res.reply.decode("utf-8"))
for client_data in clients:
if client_data.get("address") == address:
if address in self._clients:
self._clients[address] = client_data
self._update_client_button_properties(address)
else:
self._add_client(address, client_data)
break
except Exception as e:
print(f"Error updating client data: {e}")
def _get_button_key(self, client_data):
if self._group_apps:
return client_data.get("class", "unknown")
return client_data.get("address")
def _add_client(self, address, client_data, is_active=False):
self._clients[address] = client_data
key = self._get_button_key(client_data)
if key in self._buttons:
# Button already exists (only in grouping mode)
if address not in self._buttons[key]["addresses"]:
self._buttons[key]["addresses"].append(address)
if is_active:
self._buttons[key]["button"].add_style_class("active")
else:
# Create new button
client_image = Image()
def on_click(k=key):
addresses = self._buttons[k]["addresses"]
if not addresses:
return
# Cycle behavior: focus the next one if the current active is in this group
active_res = self._hyprland_connection.send_command("j/activewindow")
current_active = None
if active_res and active_res.reply:
active_window = json.loads(active_res.reply.decode("utf-8"))
current_active = active_window.get("address")
target_address = addresses[0]
if current_active in addresses:
idx = (addresses.index(current_active) + 1) % len(addresses)
target_address = addresses[idx]
self._hyprland_connection.send_command(
f"/dispatch focuswindow address:{target_address}"
)
client_button = Button(
image=client_image, on_button_press_event=lambda *_: on_click()
)
if is_active:
client_button.add_style_class("active")
self._buttons[key] = {
"button": client_button,
"image": client_image,
"addresses": [address],
}
self._update_button_visuals(key)
self._update_visibility()
def _remove_client(self, address):
if address not in self._clients:
return
client_data = self._clients[address]
key = self._get_button_key(client_data)
if key in self._buttons:
if address in self._buttons[key]["addresses"]:
self._buttons[key]["addresses"].remove(address)
if not self._buttons[key]["addresses"]:
# Last window of the group/address closed
button = self._buttons[key]["button"]
if button.get_parent() == self:
self.remove(button)
button.destroy()
del self._buttons[key]
else:
# Update visuals (e.g. tooltip)
self._update_button_visuals(key)
del self._clients[address]
self._update_visibility()
def _update_client_button_properties(self, address):
"""Update properties of the button associated with this address"""
if address not in self._clients:
return
key = self._get_button_key(self._clients[address])
self._update_button_visuals(key)
def _update_button_visuals(self, key):
if key not in self._buttons:
return
btn_data = self._buttons[key]
button = btn_data["button"]
image = btn_data["image"]
addresses = btn_data["addresses"]
if not addresses:
return
# Use data from the first address for the icon/title
first_address = addresses[0]
client_data = self._clients.get(first_address, {})
app_id = client_data.get("class", "")
title = client_data.get("title", "")
if self._group_apps and len(addresses) > 1:
title = f"{title} ({len(addresses)})"
image.set_from_pixbuf(
self.icon_resolver.get_icon_pixbuf(app_id, self._icon_size)
)
button.set_tooltip_text(title)
# Also re-check visibility
self._update_button_visibility(key)
def _on_workspace_changed(self, _, event: HyprlandEvent):
for key in list(self._buttons.keys()):
self._update_button_visibility(key)
self._update_visibility()
def _update_button_visibility(self, key):
if key not in self._buttons:
return
btn_data = self._buttons[key]
button = btn_data["button"]
addresses = btn_data["addresses"]
# A grouped button should be visible if ANY of its windows should be visible
should_be_visible = False
for address in addresses:
client_data = self._clients.get(address)
if not client_data:
continue
workspace_id = self._get_workspace_id(client_data)
if workspace_id is not None:
is_special = is_special_workspace_id(workspace_id)
if not (self._hide_special and is_special):
should_be_visible = True
break
button_present = button.get_parent() is not None
if should_be_visible and not button_present:
self.add(button)
elif not should_be_visible and button_present:
self.remove(button)
def _get_workspace_id(self, client_data):
workspace_data = client_data.get("workspace", {})
if isinstance(workspace_data, dict):
return workspace_data.get("id")
elif isinstance(workspace_data, (int, str)):
return workspace_data
return None
def _load_config(self):
self._icon_size = data.DATA()["taskbar_icon_size"]
self._hide_special = data.DATA()["taskbar_hide_special"]
self._group_apps = data.DATA()["taskbar_group_apps"]
def _on_config_change(self, new_config, old_config):
config_paths = [
"panel.taskbar.icon_size",
"panel.taskbar.hide_empty",
"panel.taskbar.hide_special",
"panel.taskbar.group_apps",
]
config_changed = any(
has_config_changed(old_config, new_config, path) for path in config_paths
)
if config_changed:
self._load_config()
# Force full rebuild of buttons on mode change
self._rebuild_all()
def _rebuild_all(self):
"""Clear all and re-initialize based on current config"""
for child in self.get_children():
self.remove(child)
for btn_data in self._buttons.values():
btn_data["button"].destroy()
self._buttons = {}
current_clients = self._clients.copy()
self._clients = {}
for address, client_data in current_clients.items():
active_res = self._hyprland_connection.send_command("j/activewindow")
is_active = False
if active_res and active_res.reply:
active_window = json.loads(active_res.reply.decode("utf-8"))
is_active = address == active_window.get("address")
self._add_client(address, client_data, is_active)
self._update_visibility()
def force_update_for_workspace_change(self):
self._on_workspace_changed(None, None)
def set_visibility_callback(self, callback):
self._visibility_callback = callback
def _update_visibility(self):
has_visible_children = any(child.get_visible() for child in self.get_children())
self.set_visible(has_visible_children)
if self._visibility_callback:
self._visibility_callback()