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()
+393
View File
@@ -0,0 +1,393 @@
from fabric.hyprland.service import Hyprland, HyprlandEvent
from fabric.hyprland.widgets import HyprlandWorkspaces, WorkspaceButton
from fabric.system_tray.widgets import SystemTray
from fabric.utils import Gdk, GLib
from fabric.widgets.box import Box
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.datetime import DateTime
from fabric.widgets.eventbox import EventBox
from fabric.widgets.revealer import Revealer
from fabric.widgets.wayland import WaylandWindow as Window
import config.data as data
from modules.panel.components import (
Battery,
TaskBar,
apply_enhanced_system_tray,
)
from services import has_config_changed, on_config_change
from utils.corners import MyCorner
from utils.functions import is_special_workspace_id
from utils.occlusion import check_occlusion, is_mouse_in_region, get_screen_dimensions
def config_dependent(func):
def wrapper(self, *args, **kwargs):
return func(self, *args, **kwargs)
wrapper._config_dependent = True
return wrapper
class Panel(Window):
def __init__(self, **kwargs):
panel_autohide = data.DATA()["panel_autohide"]
panel_position = data.DATA().get("panel_position") or "bottom"
super().__init__(
name="panel-window",
layer="top",
anchor=panel_position,
exclusivity="auto" if not panel_autohide else "none",
pass_through=False,
visible=False,
all_visible=False,
)
self.hide_id = None
self.is_mouse_over_panel_area = False
self.effective_occlusion_size = 40
self.panel_position = panel_position
# Set corner types based on position
if panel_position == "top":
corner_left_type = "top-right"
corner_right_type = "top-left"
# For top position, corner goes first (at top)
corner_left_children = [
MyCorner(corner_left_type),
Box(v_expand=True, v_align="fill"),
]
corner_right_children = [
MyCorner(corner_right_type),
Box(v_expand=True, v_align="fill"),
]
else: # bottom
corner_left_type = "bottom-right"
corner_right_type = "bottom-left"
# For bottom position, corner goes last (at bottom)
corner_left_children = [
Box(v_expand=True, v_align="fill"),
MyCorner(corner_left_type),
]
corner_right_children = [
Box(v_expand=True, v_align="fill"),
MyCorner(corner_right_type),
]
self.corner_left = Box(
name="corner-left",
orientation="v",
h_align="start",
children=corner_left_children,
)
self.corner_right = Box(
name="corner-right",
orientation="v",
h_align="end",
children=corner_right_children,
)
use_12hr = data.DATA()["datetime_12hrs"]
formatter = "%a %-d %b %I:%M %P" if use_12hr else "%a %-d %b %H:%M"
self.datetime = DateTime(
name="date-time", formatters=[formatter], interval=30000
)
self.tray = SystemTray(name="panel-button", spacing=4, icon_size=20)
apply_enhanced_system_tray(self.tray)
self.battery = Battery()
self.taskbar = TaskBar()
self.taskbar.set_visibility_callback(self._rebuild_layout_from_config)
self.workspaces = HyprlandWorkspaces(
name="workspaces",
spacing=4,
buttons_factory=lambda ws_id: (
None
if (
data.DATA()["workspace_hide_special"]
and is_special_workspace_id(ws_id)
)
else WorkspaceButton(id=ws_id, label=str(ws_id))
),
)
self.items = Box()
# Create panel CenterBox with position-based CSS class
self.panel_centerbox = CenterBox(
name="panel",
center_children=self.items,
)
# Add CSS class for top position using GTK style context
if panel_position == "top":
self.panel_centerbox.get_style_context().add_class("panel-top")
self.panel_content = Box(
name="panel-container",
orientation="h",
h_expand=True,
children=[
self.corner_left,
self.panel_centerbox,
self.corner_right,
],
)
# Set revealer transition based on position
transition = "slide-down" if panel_position == "top" else "slide-up"
self.panel_revealer = Revealer(
name="panel-revealer",
transition_type=transition,
transition_duration=350,
child_revealed=False,
child=self.panel_content,
)
self.hover_activator = EventBox(name="hover-activator")
self.hover_activator.set_size_request(-1, 8)
# Arrange children based on position
if panel_position == "top":
panel_children = [self.panel_revealer, self.hover_activator]
else: # bottom
panel_children = [self.hover_activator, self.panel_revealer]
self.main_container = Box(
name="panel-main",
orientation="v",
children=panel_children,
)
self.event_box = EventBox(
name="panel-event-box",
child=self.main_container,
)
self.event_box.connect("enter-notify-event", self._on_mouse_enter)
self.event_box.connect("leave-notify-event", self._on_mouse_leave)
self.children = self.event_box
self.battery.connect(
"notify::visible", lambda *_: self._rebuild_layout_from_config()
)
self._rebuild_layout_from_config()
on_config_change(self._on_config_change)
self._update_panel_visibility()
self.hyprland = Hyprland()
self.hyprland.connect("event::openwindow", self._on_window_event)
self.hyprland.connect("event::closewindow", self._on_window_event)
self.hyprland.connect("event::movewindow", self._on_window_event)
self.hyprland.connect("event::changefloatingmode", self._on_window_event)
self.hyprland.connect("event::fullscreen", self._on_window_event)
self.hyprland.connect("event::workspacev2", self._on_window_event)
if panel_autohide:
self.panel_revealer.set_reveal_child(False)
self.check_occlusion_state()
def _get_enabled_widgets(self):
components = data.DATA()
enabled_widgets = {
"workspace": components["workspace"],
"taskbar": components["taskbar"],
"systray": components["systray"],
"battery": components["battery"],
"datetime": components["datetime"],
}
return enabled_widgets
@config_dependent
def _rebuild_layout_from_config(self):
enabled_widgets = self._get_enabled_widgets()
items = []
if enabled_widgets["workspace"]:
items.append(self.workspaces)
if enabled_widgets["taskbar"]:
items.append(self.taskbar)
if enabled_widgets["systray"]:
items.append(self.tray)
if enabled_widgets["battery"]:
items.append(self.battery)
if enabled_widgets["datetime"]:
items.append(self.datetime)
filtered_items = [w for w in items if w.get_visible()]
self.items.children = filtered_items
if data.DATA()["panel_enabled"]:
self.show_all()
def _update_panel_visibility(self):
panel_enabled = data.DATA()["panel_enabled"]
self.set_visible(panel_enabled)
def _on_mouse_enter(self, widget, event):
self.is_mouse_over_panel_area = True
if self.hide_id:
GLib.source_remove(self.hide_id)
self.hide_id = None
if data.DATA()["panel_autohide"]:
self.panel_revealer.set_reveal_child(True)
return True
def _on_mouse_leave(self, widget, event):
if event.detail == Gdk.NotifyType.INFERIOR:
return False
self.is_mouse_over_panel_area = False
if data.DATA()["panel_autohide"]:
self.delay_hide()
return True
def delay_hide(self):
if self.hide_id:
GLib.source_remove(self.hide_id)
self.hide_id = GLib.timeout_add(250, self.hide_panel_if_not_hovered)
def hide_panel_if_not_hovered(self):
self.hide_id = None
if not self.is_mouse_over_panel_area:
occlusion_region = (self.panel_position, self.effective_occlusion_size)
if check_occlusion(occlusion_region):
self.panel_revealer.set_reveal_child(False)
return False
def _on_window_event(self, _, event: HyprlandEvent):
GLib.idle_add(self.check_occlusion_state)
def check_occlusion_state(self):
try:
# Robust hover check as fallback for high refresh rate monitors
# If GTK events were missed, we verify the mouse position manually
if not self.is_mouse_over_panel_area:
# Determine the region we care about for hover
# If the panel is hidden, it's just the activator area
# If shown, it's the whole panel area
is_revealed = self.panel_revealer.get_reveal_child()
size = (
48 if is_revealed else 8
) # Approximate panel height when revealed
# Get current width of the panel to avoid full-width hover detection
width = self.main_container.get_allocated_width()
if width > 1:
screen_width, screen_height = get_screen_dimensions()
x = (screen_width - width) // 2
y = 0 if self.panel_position == "top" else screen_height - size
occlusion_region = (x, y, width, size)
else:
occlusion_region = (self.panel_position, size)
if is_mouse_in_region(occlusion_region):
self.is_mouse_over_panel_area = True
if self.hide_id:
GLib.source_remove(self.hide_id)
self.hide_id = None
if self.is_mouse_over_panel_area:
if not self.panel_revealer.get_reveal_child():
self.panel_revealer.set_reveal_child(True)
return True
if not data.DATA()["panel_autohide"]:
if not self.panel_revealer.get_reveal_child():
self.panel_revealer.set_reveal_child(True)
return True
# Use actual width for occlusion check too
width = self.main_container.get_allocated_width()
if width > 1:
screen_width, screen_height = get_screen_dimensions()
x = (screen_width - width) // 2
y = (
0
if self.panel_position == "top"
else screen_height - self.effective_occlusion_size
)
occlusion_region = (
x,
y,
width,
self.effective_occlusion_size,
)
else:
occlusion_region = (self.panel_position, self.effective_occlusion_size)
is_occluded_by_window = check_occlusion(occlusion_region)
self.panel_revealer.set_reveal_child(not is_occluded_by_window)
except Exception as e:
from fabric.utils import logger
logger.warning(f"Error in check_occlusion_state: {e}")
return False
@config_dependent
def _on_config_change(self, new_config, old_config):
config_paths = [
"panel.enabled",
"panel.autohide",
"panel.position",
"panel.systray.enabled",
"panel.datetime.enabled",
"panel.datetime.12hrs",
"panel.workspace.enabled",
"panel.workspace.hide_special_ws",
"panel.taskbar.enabled",
"panel.taskbar.icon_size",
"panel.taskbar.hide_empty",
"panel.taskbar.hide_special",
"panel.battery.enabled",
"panel.battery.label",
"panel.battery.hide_on_full",
"panel.battery.icon_size",
]
config_changed = any(
has_config_changed(old_config, new_config, path) for path in config_paths
)
if config_changed:
# Check if position changed (requires application restart)
new_position = data.DATA().get("panel_position") or "bottom"
if new_position != self.panel_position:
# Position change requires full restart due to Wayland limitations
print("Panel position changed - restarting application...")
import os
import sys
# Restart the Python script
os.execv(sys.executable, ["python"] + sys.argv)
return
# Position didn't change, handle other config changes
panel_autohide = data.DATA()["panel_autohide"]
# Set exclusivity based on autohide setting
exclusivity = "none" if panel_autohide else "auto"
self.set_property("exclusivity", exclusivity)
self._update_panel_visibility()
use_12hr = data.DATA()["datetime_12hrs"]
formatter = "%a %-d %b %I:%M %P" if use_12hr else "%a %-d %b %H:%M"
self.datetime.formatters = [formatter]
hide_special = data.DATA()["workspace_hide_special"]
self.workspaces.buttons_factory = lambda ws_id: (
None
if (hide_special and is_special_workspace_id(ws_id))
else WorkspaceButton(id=ws_id, label=str(ws_id))
)
self._rebuild_layout_from_config()
if panel_autohide:
self.check_occlusion_state()