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

+24
View File
@@ -0,0 +1,24 @@
"""
Modus OSD 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):
attr_value = getattr(module, attr_name)
if (
isinstance(attr_value, type)
and (attr_name.endswith("OSDContainer") or attr_name == "AnimatedScale")
and inspect.getmodule(attr_value) is module
):
globals()[attr_name] = attr_value
__all__.append(attr_name)
@@ -0,0 +1,29 @@
from functools import partial
from fabric.widgets.scale import Scale
from utils.animator import Animator, cubic_bezier
class AnimatedScale(Scale):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.animator = (
Animator(
duration=0.8,
timing_function=partial(cubic_bezier, 0.34, 1.56, 0.64, 1.0),
min_value=self.min_value,
max_value=self.value,
tick_widget=self,
notify_value=lambda anim: self.set_value(anim.value),
)
.build()
.play()
.unwrap()
)
def animate_value(self, value: float):
self.animator.pause()
self.animator.min_value = self.value
self.animator.max_value = value
self.animator.play()
+161
View File
@@ -0,0 +1,161 @@
from fabric.widgets.image import Image
from fabric.widgets.scale import ScaleMark
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.animated_scale import AnimatedScale
from modules.osd.components.base import BaseOSDContainer
from services import Audio
class AudioOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.audio = Audio(controller_name="fabric-osd")
self._last_volume = None
self._last_muted = None
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
self.icon = Image(icon_name="audio-volume-medium-symbolic", icon_size=26)
self.scale = AnimatedScale(
marks=(ScaleMark(value=i) for i in range(1, 100, 10)),
value=70,
min_value=0,
max_value=100,
inverted=False,
increments=(1, 1),
orientation=self.get_orientation(),
on_state_flags_changed=lambda sc, *_: (
self.unfocus() if not (sc.get_state_flags() & 2) else None,
),
on_value_changed=lambda *_: self.is_hovered()
and self._on_user_volume_change(),
)
self.children = self.icon, self.scale
def _connect_specific_signals(self):
# Connect to audio service changed signal (catches all audio changes including mute)
self.audio.connect("changed", self._on_audio_changed)
self.audio.connect(
"notify::speaker",
self._on_speaker_ready,
)
# If speaker already exists, connect now
if self.audio.speaker:
self._on_speaker_ready()
def _on_speaker_ready(self, *_):
"""Called when audio speaker is ready."""
speaker = self.audio.speaker
if not speaker:
return
# Initialize state
self._last_volume = round(speaker.volume)
self._last_muted = speaker.muted
# Connect to speaker signals
speaker.connect("notify::volume", self._on_volume_changed)
speaker.connect("notify::is-muted", self._on_mute_changed)
# Initial update
self.scale.animate_value(speaker.volume)
self._update_volume_display()
def _on_audio_changed(self, *_):
"""Handle general audio service changes (includes mute changes)."""
if not self.audio.speaker:
return
# Check if mute state changed
current_muted = self.audio.speaker.muted
if self._last_muted is None or current_muted != self._last_muted:
self._last_muted = current_muted
self._update_volume_display()
# Trigger parent OSD to show
if self.osd:
self.osd.show_audio_osd()
def _on_volume_changed(self, speaker, *_):
"""Handle volume changes from the system."""
if not speaker or self.is_hovered():
# User is dragging slider, don't update
return
new_volume = round(speaker.volume)
# Only animate if volume actually changed
if self._last_volume is None or abs(new_volume - self._last_volume) > 0:
self._last_volume = new_volume
self.scale.animate_value(new_volume)
self._update_volume_display(new_volume)
# Trigger parent OSD to show
if self.osd:
self.osd.show_audio_osd()
def _on_mute_changed(self, speaker, *_):
"""Handle mute state changes."""
if not speaker:
return
new_muted = speaker.muted
# Only update if mute state changed
if self._last_muted is None or self._last_muted != new_muted:
self._last_muted = new_muted
self._update_volume_display()
# Trigger parent OSD to show
if self.osd:
self.osd.show_audio_osd()
def _on_user_volume_change(self):
"""Called when user drags the slider."""
if not self.audio.speaker or not self.is_hovered():
return
new_volume = self.scale.value
self.audio.speaker.set_volume(new_volume)
self._last_volume = round(new_volume)
self._update_volume_display(new_volume)
def _update_volume_display(self, volume=None):
"""Update icon and scale styling based on volume and mute state."""
if not self.audio.speaker:
return
current_volume = (
round(self.audio.speaker.volume) if volume is None else round(volume)
)
is_muted = self.audio.speaker.muted
# Update muted styling
if is_muted or current_volume == 0:
self.scale.add_style_class("muted")
self.icon.set_from_icon_name("audio-volume-muted-symbolic", 26)
else:
self.scale.remove_style_class("muted")
# Update icon based on volume level
if current_volume >= 80:
icon_name = "audio-volume-high-symbolic"
elif current_volume < 50:
icon_name = "audio-volume-low-symbolic"
else:
icon_name = "audio-volume-medium-symbolic"
self.icon.set_from_icon_name(icon_name, 26)
def update(self, *_):
"""Override to update display before showing OSD."""
# Update the display with current speaker state
if self.audio.speaker:
speaker = self.audio.speaker
self._last_volume = round(speaker.volume)
self._last_muted = speaker.muted
self.scale.animate_value(speaker.volume)
self._update_volume_display()
# Call parent's update to show the OSD
super().update()
+155
View File
@@ -0,0 +1,155 @@
import contextlib
from abc import abstractmethod
from fabric.utils import Gdk, GLib, idle_add, invoke_repeater, remove_handler, time
from fabric.widgets.box import Box
from fabric.widgets.wayland import WaylandWindow as Window
class BaseOSDContainer(Box):
MAX_VISIBLE_TIME = 6.0 # Increased for safety: 1.7s focus + 1.7s unfocus + margin
COOLDOWN_MS = 200 # Minimum time between OSD triggers (milliseconds)
def __init__(self, window: Window, **kwargs):
super().__init__(**kwargs, spacing=12, name="osd-container")
self.last_handler: int = 0
self.window = window
self.osd = None
self.show_timestamp: float = 0.0
self.watchdog_handler: int = 0
self._update_in_progress = False # Prevent concurrent updates
self._is_hovered = False
self._last_trigger_time: float = 0.0 # Track last trigger time for cooldown
# Defer signal connection until window is initialized
idle_add(self._setup_window_signals)
def _setup_window_signals(self):
self.window.add_events(
Gdk.EventMask.ENTER_NOTIFY_MASK | Gdk.EventMask.LEAVE_NOTIFY_MASK
)
self.window.connect("enter-notify-event", self._on_enter_notify)
self.window.connect("leave-notify-event", self._on_leave_notify)
return False
def _on_enter_notify(self, widget, event):
if event.detail != Gdk.NotifyType.INFERIOR:
self._is_hovered = True
def _on_leave_notify(self, widget, event):
if event.detail != Gdk.NotifyType.INFERIOR:
self._is_hovered = False
def is_hovered(self):
return self._is_hovered
def remove_last_handler(self):
if self.last_handler:
with contextlib.suppress(Exception):
remove_handler(self.last_handler)
self.last_handler = 0
def remove_watchdog_handler(self):
if self.watchdog_handler:
with contextlib.suppress(Exception):
GLib.source_remove(self.watchdog_handler)
self.watchdog_handler = 0
def cleanup_all_handlers(self):
"""Clean up all handlers and reset state."""
self.remove_last_handler()
self.remove_watchdog_handler()
self.show_timestamp = 0.0
self._update_in_progress = False
def watchdog_force_hide(self, *_):
"""Failsafe timer to force-hide OSD if normal sequence fails."""
if not self.window.get_visible():
self.cleanup_all_handlers()
return False
# Check if we've exceeded maximum visible time
elapsed = time.time() - self.show_timestamp
if elapsed >= self.MAX_VISIBLE_TIME:
if not self.is_hovered():
self.window.hide()
self.cleanup_all_handlers()
return False
else:
# Still hovered, check again in 1 second
return True
return True # Keep checking
def update(self, *_):
# Prevent concurrent updates
if self._update_in_progress:
return
# Check cooldown to prevent spam
current_time = time.time()
time_since_last_trigger = (
current_time - self._last_trigger_time
) * 1000 # Convert to ms
if time_since_last_trigger < self.COOLDOWN_MS:
return # Still in cooldown period, ignore this trigger
self._last_trigger_time = current_time
self._update_in_progress = True
# Clean up any existing timers
self.cleanup_all_handlers()
# Record show time and display window
self.show_timestamp = time.time()
self.window.show()
# Start animation sequence
self.focus()
# Schedule unfocus after focus animation completes
self.last_handler = invoke_repeater(1700, self.unfocus, initial_call=False)
# Start watchdog timer (checks every second)
self.watchdog_handler = GLib.timeout_add(1000, self.watchdog_force_hide)
self._update_in_progress = False
def focus(self, *_):
self.style_classes = "focused"
return False
def unfocus(self, *_):
if not self.window.get_visible():
self.cleanup_all_handlers()
return False
self.style_classes = ()
self.remove_last_handler()
# Schedule hide after unfocus animation
self.last_handler = invoke_repeater(1700, self.unpop, initial_call=False)
return False
def unpop(self, *_):
if not self.window.get_visible():
self.cleanup_all_handlers()
return False
if not self.is_hovered():
self.window.hide()
self.cleanup_all_handlers()
else:
# User is hovering, check again in 500ms
self.last_handler = invoke_repeater(500, self.unpop, initial_call=False)
return False
@abstractmethod
def _setup_specific_components(self):
pass
@abstractmethod
def _connect_specific_signals(self):
pass
+127
View File
@@ -0,0 +1,127 @@
from fabric.utils import GLib
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.base import BaseOSDContainer
from services.battery import BatteryService
class BatteryOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.battery = BatteryService()
self._initialized = False # Track if initial setup is complete
self._last_state = None
self._last_percentage = None
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
self.icon = Image(icon_name="battery-symbolic", icon_size=26)
self.label = Label()
# Defer initialization to allow services to initialize
GLib.timeout_add(100, self._initialize_state)
self.children = self.icon, self.label
def _connect_specific_signals(self):
self.battery.connect("changed", self._on_battery_changed)
def _initialize_state(self):
"""Initialize the battery state after component setup."""
self._last_state = self.battery.get_property("State")
self._last_percentage = self.battery.get_property("Percentage")
self._update_battery_display()
# Mark as initialized after initial state is set
GLib.timeout_add(500, self._mark_initialized)
return False
def _mark_initialized(self):
"""Mark the component as fully initialized."""
self._initialized = True
return False
def _on_battery_changed(self, *args):
"""Handle battery state changes."""
if not self._initialized:
return
if not self.is_hovered():
current_state = self.battery.get_property("State")
current_percentage = self.battery.get_property("Percentage")
# Only show OSD for meaningful changes
should_show = False
# State changes (charging/discharging/full)
if current_state != self._last_state:
should_show = True
# Battery level warnings (crossing thresholds)
elif current_percentage is not None and self._last_percentage is not None:
# Show on low battery (crossing 20% threshold going down)
if (
self._last_percentage > 20
and current_percentage <= 20
or self._last_percentage > 98
and current_percentage <= 10
or self._last_percentage < 100
and current_percentage >= 100
):
should_show = True
self._last_state = current_state
self._last_percentage = current_percentage
if should_show:
self._update_battery_display()
self.show_battery_osd()
def _update_battery_display(self):
"""Update display based on current battery state."""
state = self.battery.get_property("State")
percentage = self.battery.get_property("Percentage")
icon_name = self.battery.get_property("IconName")
if percentage is None:
percentage = 0
# Determine icon
if icon_name:
self.update_icon(icon_name)
else:
self.update_icon("battery-symbolic")
# Format the label
if state == 4: # Fully charged
self.update_label(f"Battery Full ({percentage:.0f}%)")
elif state == 1: # Charging
self.update_label(f"Charging ({percentage:.0f}%)")
elif percentage <= 10:
self.update_label(f"Battery Critical ({percentage:.0f}%)")
elif percentage <= 20:
self.update_label(f"Battery Low ({percentage:.0f}%)")
else:
self.update_label(f"Battery: {percentage:.0f}%")
def update_icon(self, icon_name: str):
"""Update the battery icon."""
self.icon.set_from_icon_name(icon_name, 26)
def update_label(self, text: str):
"""Update the battery label."""
self.label.set_text(text)
def show_battery_osd(self):
"""Trigger the OSD to show."""
if self.osd:
self.osd.show_battery_osd()
else:
self.update()
def update(self, *_):
"""Override to update display before showing OSD."""
self._update_battery_display()
super().update()
+107
View File
@@ -0,0 +1,107 @@
from fabric.widgets.image import Image
from fabric.widgets.scale import ScaleMark
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.animated_scale import AnimatedScale
from modules.osd.components.base import BaseOSDContainer
from services import Brightness
class BrightnessOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.brightness = Brightness.get_initial()
self._last_brightness = None # Track to avoid duplicate updates
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
self.icon = Image(icon_name="display-brightness-symbolic", icon_size=26)
current_brightness = self.brightness.screen_brightness
brightness_percentage = (
int((current_brightness / self.brightness.max_screen) * 100)
if self.brightness.max_screen > 0
else 50
)
self._last_brightness = brightness_percentage
self.scale = AnimatedScale(
marks=(ScaleMark(value=i) for i in range(1, 100, 10)),
value=brightness_percentage,
min_value=0,
max_value=100,
inverted=False,
increments=(1, 1),
orientation=self.get_orientation(),
on_state_flags_changed=lambda sc, *_: (
self.unfocus() if not (sc.get_state_flags() & 2) else None
),
on_value_changed=lambda *_: self.is_hovered() and self._update_brightness(),
)
self.children = self.icon, self.scale
def _connect_specific_signals(self):
self.brightness.connect(
"brightness_changed",
self._on_brightness_changed,
)
def _on_brightness_changed(self, _, value):
"""Handle brightness changes from the service."""
if self.is_hovered():
# User is interacting with the slider, don't update
return
brightness_percentage = int((value / self.brightness.max_screen) * 100)
# Only update if brightness actually changed
if (
self._last_brightness is None
or abs(brightness_percentage - self._last_brightness) > 0
):
self._last_brightness = brightness_percentage
self._update_icon(brightness_percentage)
self.scale.animate_value(brightness_percentage)
self.show_brightness_osd()
def show_brightness_osd(self):
"""Trigger the OSD to show the brightness container."""
if self.osd:
self.osd.show_brightness_osd()
else:
self.update()
def _update_icon(self, brightness_percentage: int):
"""Update icon based on brightness level."""
self.icon.set_from_icon_name(
"display-brightness-high-symbolic"
if brightness_percentage >= 80
else "display-brightness-low-symbolic"
if brightness_percentage < 50
else "display-brightness-medium-symbolic",
26,
)
def _update_brightness(self):
"""Update brightness when user drags the slider."""
if self.is_hovered():
new_brightness = int((self.scale.value / 100) * self.brightness.max_screen)
self.brightness.screen_brightness = new_brightness
self._last_brightness = int(self.scale.value)
self._update_icon(int(self.scale.value))
def update(self, *_):
"""Override to update display before showing OSD."""
# Update the display before showing
if self.brightness.screen_brightness is not None:
brightness_percentage = int(
(self.brightness.screen_brightness / self.brightness.max_screen) * 100
)
self._last_brightness = brightness_percentage
self.scale.animate_value(brightness_percentage)
self._update_icon(brightness_percentage)
# Call parent's update to show the OSD
super().update()
+65
View File
@@ -0,0 +1,65 @@
from fabric.utils import GLib
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.base import BaseOSDContainer
from services import CapsLock
class CapsLockOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.capslock = CapsLock.get_initial()
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
self.icon = Image(icon_name="capslock-disabled-symbolic", icon_size=26)
self.label = Label()
self.update_icon(False)
self.update_label(False)
self.children = self.icon, self.label
def _connect_specific_signals(self):
self.capslock.connect("state_changed", self._on_caps_lock_state_changed)
GLib.timeout_add(100, self._initialize_state)
def _initialize_state(self):
"""Initialize the caps lock state after component setup."""
is_caps_on = self.capslock.is_on
self.update_icon(is_caps_on)
self.update_label(is_caps_on)
return False
def _on_caps_lock_state_changed(self, _, is_on: bool):
"""Handle CapsLock state changes."""
if not self.is_hovered():
self.update_icon(is_on)
self.update_label(is_on)
self.show_capslock_osd()
def show_capslock_osd(self):
"""Trigger the OSD to show the CapsLock container."""
if self.osd:
self.osd.show_capslock_osd()
else:
self.update()
def update_icon(self, is_on: bool):
self.icon.set_from_icon_name(
"capslock-enabled-symbolic" if is_on else "capslock-disabled-symbolic",
26,
)
if is_on:
self.icon.style_classes = "capslock-on"
else:
self.icon.style_classes = "capslock-off"
def update_label(self, is_on: bool):
self.label.set_text("CapsLock ON" if is_on else "CapsLock OFF")
if is_on:
self.label.style_classes = "capslock-on"
else:
self.label.style_classes = "capslock-off"
@@ -0,0 +1,52 @@
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.base import BaseOSDContainer
from services import KeyboardLayout
class KeyboardLayoutOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.icon = Image(icon_name="input-keyboard-symbolic", icon_size=26)
self.label = Label()
self.keyboard_layout = KeyboardLayout.get_initial()
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
# Get initial layout from service
layout = self.keyboard_layout.current_layout
self.label.set_text(layout)
self.children = self.icon, self.label
def _connect_specific_signals(self):
# Connect to layout change signal from service
self.keyboard_layout.connect("layout_changed", self._on_layout_changed)
def _on_layout_changed(self, service, layout: str):
"""Handle layout changes from the service."""
if not self.is_hovered():
current_text = self.label.get_text()
if current_text != layout:
self.label.set_text(layout)
self.show_kb_layout_osd()
def show_kb_layout_osd(self):
"""Trigger the OSD to show the keyboard layout container."""
if self.osd:
self.osd.show_kb_layout_osd()
else:
self.update()
def update(self, *_):
"""Override to update display before showing OSD."""
# Update the display with current layout
layout = self.keyboard_layout.current_layout
self.label.set_text(layout)
# Call parent's update to show the OSD
super().update()
+116
View File
@@ -0,0 +1,116 @@
from fabric.utils import GLib
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.base import BaseOSDContainer
from services import Audio
class MicrophoneOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.audio = Audio(controller_name="fabric-osd-microphone")
self._last_muted = None
self._connected_mics = set()
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
self.icon = Image(
icon_name="microphone-sensitivity-muted-symbolic", icon_size=26
)
self.label = Label()
self.update_icon(True) # Start with muted state
self.update_label(True)
self.children = self.icon, self.label
def _connect_specific_signals(self):
# Connect to audio service changed signal
self.audio.connect("changed", self._on_audio_changed)
# Connect to microphones list changes
self.audio.connect("notify::microphones", self._on_microphones_ready)
# Connect to default microphone changes
self.audio.connect("notify::microphone", self._on_default_microphone_changed)
# Initial connection to all existing microphones
self._on_microphones_ready()
# Defer initialization to allow services to initialize
GLib.timeout_add(100, self._initialize_state)
def _initialize_state(self):
"""Initialize the microphone mute state after component setup."""
mic = self.audio.microphone
if mic:
is_muted = mic.muted
self._last_muted = is_muted
self.update_icon(is_muted)
self.update_label(is_muted)
return False
def _on_microphones_ready(self, *_):
"""Called when audio microphones list changes."""
for mic in self.audio.microphones:
if mic not in self._connected_mics:
mic.connect("notify::is-muted", self._on_mute_changed)
self._connected_mics.add(mic)
def _on_default_microphone_changed(self, *_):
"""Handle default microphone changes."""
mic = self.audio.microphone
if mic:
self._on_mute_changed(mic)
def _on_audio_changed(self, *_):
"""Handle general audio service changes."""
mic = self.audio.microphone
if mic:
self._on_mute_changed(mic)
def _on_mute_changed(self, microphone, *_):
"""Handle microphone mute changes for any microphone."""
is_muted = microphone.muted
# Only update and show if mute state actually changed
if self._last_muted is None or is_muted != self._last_muted:
self._last_muted = is_muted
self.update_icon(is_muted)
self.update_label(is_muted)
self.show_microphone_osd()
def update_icon(self, is_muted: bool):
"""Update icon based on mute state."""
icon_name = (
"microphone-sensitivity-muted-symbolic"
if is_muted
else "microphone-sensitivity-high-symbolic"
)
self.icon.set_from_icon_name(icon_name, 26)
# Add style classes for styling
self.icon.style_classes = "mic-muted" if is_muted else "mic-unmuted"
def update_label(self, is_muted: bool):
"""Update label based on mute state."""
self.label.set_text("Microphone MUTED" if is_muted else "Microphone ON")
self.label.style_classes = "mic-muted" if is_muted else "mic-unmuted"
def show_microphone_osd(self):
"""Trigger the OSD to show."""
if self.osd:
self.osd.show_microphone_osd()
else:
self.update()
def update(self, *_):
"""Override to update display before showing OSD."""
mic = self.audio.microphone
if mic:
self._last_muted = mic.muted
self.update_icon(mic.muted)
self.update_label(mic.muted)
super().update()
+159
View File
@@ -0,0 +1,159 @@
from fabric.utils import GLib
from fabric.widgets.image import Image
from fabric.widgets.label import Label
from fabric.widgets.wayland import WaylandWindow as Window
from modules.osd.components.base import BaseOSDContainer
from services import NetworkClient
class NetworkOSDContainer(BaseOSDContainer):
def __init__(self, window: Window, **kwargs):
super().__init__(window, **kwargs)
self.network = NetworkClient()
self._initialized = False # Track if initial setup is complete
self._setup_specific_components()
self._connect_specific_signals()
def _setup_specific_components(self):
self.icon = Image(icon_name="network-wired-symbolic", icon_size=26)
self.label = Label()
# Defer initialization to allow services to initialize
GLib.timeout_add(100, self._initialize_state)
self.children = self.icon, self.label
def _connect_specific_signals(self):
# Connect to WiFi device signals
self.network.connect("wifi_device_added", self._on_wifi_device_added)
self.network.connect("wifi_device_removed", self._on_wifi_device_removed)
# Connect to Ethernet device signals
self.network.connect("ethernet_device_added", self._on_ethernet_device_added)
self.network.connect(
"ethernet_device_removed", self._on_ethernet_device_removed
)
# Connect to network state changes
self.network.connect("notify::state", self._on_network_state_changed)
def _initialize_state(self):
"""Initialize the network state after component setup."""
self._update_network_display()
# Mark as initialized after initial state is set
GLib.timeout_add(500, self._mark_initialized)
return False
def _mark_initialized(self):
"""Mark the component as fully initialized."""
self._initialized = True
return False
def _on_wifi_device_added(self, *args):
"""Handle WiFi device added."""
if self.network.wifi_device:
# Connect to WiFi-specific signals
self.network.wifi_device.connect(
"notify::active-access-point", self._on_wifi_connection_changed
)
# Only show OSD if we're already initialized (not first setup)
if self._initialized:
self._on_wifi_connection_changed()
def _on_wifi_device_removed(self, *args):
"""Handle WiFi device removed."""
if not self._initialized:
return
self.update_icon("network-wired-disconnected-symbolic")
self.update_label("WiFi Disconnected")
self.show_network_osd()
def _on_ethernet_device_added(self, *args):
"""Handle Ethernet device added."""
if self.network.ethernet_device:
# Connect to Ethernet-specific signals
self.network.ethernet_device.connect("changed", self._on_ethernet_changed)
# Only show OSD if we're already initialized (not first setup)
if self._initialized:
self._on_ethernet_changed()
def _on_ethernet_device_removed(self, *args):
"""Handle Ethernet device removed."""
if not self._initialized:
return
self.update_icon("network-wired-disconnected-symbolic")
self.update_label("Ethernet Disconnected")
self.show_network_osd()
def _on_wifi_connection_changed(self, *args):
"""Handle WiFi connection changes."""
if not self._initialized:
return
if not self.is_hovered():
self._update_network_display()
self.show_network_osd()
def _on_ethernet_changed(self, *args):
"""Handle Ethernet state changes."""
if not self._initialized:
return
if not self.is_hovered():
self._update_network_display()
self.show_network_osd()
def _on_network_state_changed(self, *args):
"""Handle network state changes."""
if not self._initialized:
return
if not self.is_hovered():
self._update_network_display()
self.show_network_osd()
def _update_network_display(self):
"""Update display based on current network state."""
wifi = self.network.wifi_device
ethernet = self.network.ethernet_device
# Priority: WiFi active > Ethernet active > Disconnected
if wifi and wifi.active_access_point:
# WiFi is connected
ssid = wifi.active_access_point.ssid
icon = wifi.active_access_point.icon
self.update_icon(icon)
self.update_label(f"WiFi: {ssid}")
elif ethernet and ethernet.internet == "activated":
# Ethernet is connected
self.update_icon("network-wired-symbolic")
self.update_label("Wired Connection")
elif ethernet and ethernet.internet == "activating":
# Ethernet is connecting
self.update_icon("network-wired-acquiring-symbolic")
self.update_label("Connecting...")
else:
# No active connection
self.update_icon("network-wired-disconnected-symbolic")
self.update_label("Disconnected")
def update_icon(self, icon_name: str):
"""Update the network icon."""
self.icon.set_from_icon_name(icon_name, 26)
def update_label(self, text: str):
"""Update the network label."""
self.label.set_text(text)
def show_network_osd(self):
"""Trigger the OSD to show."""
if self.osd:
self.osd.show_network_osd()
else:
self.update()
def update(self, *_):
"""Override to update display before showing OSD."""
self._update_network_display()
super().update()
+255
View File
@@ -0,0 +1,255 @@
from fabric.widgets.box import Box
from fabric.widgets.wayland import WaylandWindow as Window
import config.data as data
from modules.osd.components import (
AudioOSDContainer,
BatteryOSDContainer,
BrightnessOSDContainer,
CapsLockOSDContainer,
KeyboardLayoutOSDContainer,
MicrophoneOSDContainer,
NetworkOSDContainer,
)
from services import has_config_changed, on_config_change
class OSD(Box):
def __init__(self, window: Window, **kwargs):
super().__init__(orientation="h", name="osd", **kwargs)
self.window = window
self._load_config()
# Container dictionary for easy access
self.containers = {}
self.current_container = None
self._create_containers()
self._setup_initial_container()
self._connect_signals()
on_config_change(self._on_config_change)
def _create_containers(self):
if self._audio_enabled:
container = AudioOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["audio"] = container
if self._brightness_enabled:
container = BrightnessOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["brightness"] = container
if self._capslock_enabled:
container = CapsLockOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["capslock"] = container
if getattr(self, "_kb_layout_enabled", False):
container = KeyboardLayoutOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["kb_layout"] = container
if getattr(self, "_network_enabled", False):
container = NetworkOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["network"] = container
if getattr(self, "_microphone_enabled", False):
container = MicrophoneOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["microphone"] = container
if getattr(self, "_battery_enabled", False):
container = BatteryOSDContainer(orientation="h", window=self.window)
container.osd = self
container.COOLDOWN_MS = self._cooldown_ms
self.containers["battery"] = container
def _setup_initial_container(self):
self.current_container = None
self.children = []
def _connect_signals(self):
# All OSD containers (audio, brightness, capslock, keyboard_layout,
# network, microphone) handle their signal connections internally
# and call their respective show_*_osd() methods when needed.
# No external signal connections are needed here.
pass
def _load_config(self):
config = data.DATA()
self._osd_enabled = config.get("osd")
self._audio_enabled = config.get("osd_audio")
self._brightness_enabled = config.get("osd_brightness")
self._capslock_enabled = config.get("osd_capslock")
self._kb_layout_enabled = config.get("osd_kb_layout")
self._network_enabled = config.get("osd_network")
self._microphone_enabled = config.get("osd_microphone")
self._battery_enabled = config.get("osd_battery")
self._cooldown_ms = config.get("osd_cooldown_ms")
def _on_config_change(self, new_config, old_config):
paths = [
"osd",
"osd_audio",
"osd_brightness",
"osd_capslock",
"osd_kb_layout",
"osd_network",
"osd_microphone",
"osd_battery",
"osd_cooldown_ms",
"osd_position",
]
if any(has_config_changed(old_config, new_config, p) for p in paths):
old_osd_enabled = self._osd_enabled
old_audio_enabled = self._audio_enabled
old_brightness_enabled = self._brightness_enabled
old_capslock_enabled = self._capslock_enabled
old_kb_layout_enabled = getattr(self, "_kb_layout_enabled", False)
old_network_enabled = getattr(self, "_network_enabled", False)
old_microphone_enabled = getattr(self, "_microphone_enabled", False)
old_battery_enabled = getattr(self, "_battery_enabled", False)
old_osd_position = getattr(self.window, "_current_osd_position", None)
self._load_config()
# Get current OSD position from config
config = data.DATA()
current_osd_position = config.get("osd_position") or "bottom"
# Handle OSD position change by updating window properties
if (
old_osd_position is not None
and old_osd_position != current_osd_position
):
self.window._update_osd_position(current_osd_position)
if old_osd_enabled != self._osd_enabled:
self.window.set_visible(self._osd_enabled)
if not self._osd_enabled:
self.window.hide()
return
if (
old_audio_enabled != self._audio_enabled
or old_brightness_enabled != self._brightness_enabled
or old_capslock_enabled != self._capslock_enabled
or old_kb_layout_enabled != self._kb_layout_enabled
or old_network_enabled != self._network_enabled
or old_microphone_enabled != self._microphone_enabled
or old_battery_enabled != self._battery_enabled
):
# Clean up old containers
for container in self.containers.values():
container.cleanup_all_handlers()
self.containers.clear()
self._create_containers()
self._setup_initial_container()
self._connect_signals()
def _show_osd(self, container_type: str, enabled_flag: bool):
container = self.containers.get(container_type)
if not self._osd_enabled or not enabled_flag or not container:
return
if self.current_container != container_type:
# Clean up previous container if it exists
if self.current_container:
prev_container = self.containers.get(self.current_container)
if prev_container:
prev_container.cleanup_all_handlers()
prev_container.window.hide()
self.current_container = container_type
self.children = container
container.update()
def show_audio_osd(self):
self._show_osd("audio", self._audio_enabled)
def show_brightness_osd(self):
self._show_osd("brightness", self._brightness_enabled)
def show_capslock_osd(self):
self._show_osd("capslock", self._capslock_enabled)
def show_kb_layout_osd(self):
self._show_osd("kb_layout", getattr(self, "_kb_layout_enabled", False))
def show_network_osd(self):
self._show_osd("network", getattr(self, "_network_enabled", False))
def show_microphone_osd(self):
self._show_osd("microphone", self._microphone_enabled)
def show_battery_osd(self):
self._show_osd("battery", getattr(self, "_battery_enabled", False))
def toggle(self):
if not self._osd_enabled:
return
if self.current_container:
current_container = self.containers.get(self.current_container)
if current_container:
current_container.update()
class OSDWindow(Window):
def __init__(self, **kwargs):
# Load position config
config = data.DATA()
position = config.get("osd_position") or "bottom"
# Set margin based on position
if position == "top":
margin = "40px 0px 0px 0px"
anchor = "top"
else: # bottom (default)
margin = "0px 0px 40px 0px"
anchor = "bottom"
super().__init__(
name="osd-window",
title="fabric-osd",
anchor=anchor,
margin=margin,
child=OSD(window=self),
visible=False,
all_visible=False,
**kwargs,
)
# Store current position for change detection
self._current_osd_position = position
self.build()
def _update_osd_position(self, position):
"""Update OSD window position based on config change"""
# Set margin based on position
if position == "top":
margin = "40px 0px 0px 0px"
anchor = "top"
else: # bottom (default)
margin = "0px 0px 40px 0px"
anchor = "bottom"
# Update window properties
self.set_anchor(anchor)
self.set_margin(margin)
self._current_osd_position = position