Fixed Potential memory leak

This commit is contained in:
tr1x_em committed 2025-08-07 23:00:16 +05:30
1 parent d286998d91
commit 643d39b38b
6 files changed
+264 -173

No files matched your search

+5 -5
View File
@@ -36,11 +36,11 @@ for log in [
"fabric.bluetooth.service", "fabric.bluetooth.service",
"services.network", "services.network",
"utils.wayland", "utils.wayland",
"modules.notification.notification", # "modules.notification.notification",
"modules.notification.notification_center", # "modules.notification.notification_center",
"modules.controlcenter.player", # "modules.controlcenter.player",
"services.brightness", # "services.brightness",
"modules.controlcenter.expanded_player", # "modules.controlcenter.expanded_player",
]: ]:
logger.disable(log) logger.disable(log)
+64 -34
View File
@@ -6,6 +6,7 @@ from fabric.utils.helpers import (
) )
from fabric.widgets.box import Box from fabric.widgets.box import Box
from fabric.widgets.button import Button from fabric.widgets.button import Button
from loguru import logger
from fabric.widgets.centerbox import CenterBox from fabric.widgets.centerbox import CenterBox
from fabric.widgets.label import Label from fabric.widgets.label import Label
from fabric.widgets.scale import Scale from fabric.widgets.scale import Scale
@@ -50,11 +51,12 @@ class ModusControlCenter(Window):
self._per_app_volume_initialized = False self._per_app_volume_initialized = False
self._expanded_player_initialized = False self._expanded_player_initialized = False
# Store references for cleanup # Store references for cleanup - initialize all as None
self._signal_connections = [] self._signal_connections = []
self._music_widget_content = None self._music_widget_content = None
self._per_app_volume_widget = None self._per_app_volume_widget = None
self._expanded_player_widget = None self._expanded_player_widget = None
self._mpris_manager = None # Shared MPRIS manager instance
self.add_keybinding("Escape", self.hide_controlcenter) self.add_keybinding("Escape", self.hide_controlcenter)
@@ -358,24 +360,59 @@ class ModusControlCenter(Window):
self._cleanup_when_hidden() self._cleanup_when_hidden()
def _cleanup_when_hidden(self): def _cleanup_when_hidden(self):
"""Clean up resources when widget is hidden""" """Aggressively clean up resources when widget is hidden to reduce memory usage"""
# Clean up music widget content if it exists try:
if self._music_widget_content and not self._music_initialized: # Clean up music widget content if it exists
# Remove from the parent container if self._music_widget_content:
current_children = list(self.music_widget.children) # Remove from the parent container
if self._music_widget_content in current_children: current_children = list(self.music_widget.children)
current_children.remove(self._music_widget_content) if self._music_widget_content in current_children:
self.music_widget.children = current_children current_children.remove(self._music_widget_content)
self._music_widget_content = None self.music_widget.children = current_children
# Reset lazy loading flags to allow re-initialization when shown again # Trigger periodic cleanup before destroying
# Keep initialized flags to avoid recreating heavy components unnecessarily if hasattr(self._music_widget_content, "_periodic_cleanup"):
self._music_widget_content._periodic_cleanup()
# Properly destroy the music widget content
try:
self._music_widget_content.destroy()
except Exception as e:
logger.warning(f"Failed to destroy music widget content: {e}")
self._music_widget_content = None
# Clean up shared MPRIS manager when hidden to free memory
if self._mpris_manager:
try:
self._mpris_manager.destroy()
except Exception as e:
logger.warning(
f"Failed to destroy MPRIS manager during cleanup: {e}"
)
self._mpris_manager = None
# Reset initialization flags to force recreation next time
self._music_initialized = False
# Force garbage collection
import gc
gc.collect()
logger.debug("Control center aggressive cleanup completed")
except Exception as e:
logger.warning(f"Control center cleanup failed: {e}")
def _ensure_music_widget(self): def _ensure_music_widget(self):
"""Lazy load music widget content""" """Lazy load music widget content - reuse MPRIS manager"""
if not self._music_initialized: if not self._music_initialized:
# Create shared MPRIS manager if it doesn't exist
if self._mpris_manager is None:
self._mpris_manager = MprisPlayerManager()
self._music_widget_content = PlayerBoxStack( self._music_widget_content = PlayerBoxStack(
MprisPlayerManager(), control_center=self self._mpris_manager, control_center=self
) )
# Add to the music widget's children list # Add to the music widget's children list
current_children = list(self.music_widget.children) current_children = list(self.music_widget.children)
@@ -422,22 +459,7 @@ class ModusControlCenter(Window):
h_expand=True, h_expand=True,
name="control-center-widgets", name="control-center-widgets",
children=[ children=[
Box( self.wifi_man,
orientation="horizontal",
name="top-widget",
h_expand=True,
children=[
Box(
orientation="vertical",
name="wb-widget",
style_classes="menu",
spacing=5,
children=[
self.wifi_man,
],
),
],
),
], ],
) )
self.wifi_center_box = CenterBox(start_children=[self.wifi_widgets]) self.wifi_center_box = CenterBox(start_children=[self.wifi_widgets])
@@ -710,10 +732,10 @@ class ModusControlCenter(Window):
pass pass
# Clean up heavy components # Clean up heavy components
if self._wifi_man: if hasattr(self, "wifi_man") and self.wifi_man:
self._wifi_man.destroy() self.wifi_man.destroy()
if self._bluetooth_man: if hasattr(self, "bluetooth_man") and self.bluetooth_man:
self._bluetooth_man.destroy() self.bluetooth_man.destroy()
if self._music_widget_content: if self._music_widget_content:
self._music_widget_content.destroy() self._music_widget_content.destroy()
if self._per_app_volume_widget: if self._per_app_volume_widget:
@@ -721,4 +743,12 @@ class ModusControlCenter(Window):
if self._expanded_player_widget: if self._expanded_player_widget:
self._expanded_player_widget.destroy() self._expanded_player_widget.destroy()
# Clean up shared MPRIS manager
if self._mpris_manager:
try:
self._mpris_manager.destroy()
except Exception as e:
logger.warning(f"Failed to destroy MPRIS manager: {e}")
self._mpris_manager = None
super().destroy() super().destroy()
+58 -7
View File
@@ -28,7 +28,7 @@ CACHE_DIR = f"{data.CACHE_DIR}/media"
def cleanup_old_cache_files(): def cleanup_old_cache_files():
"""Clean up old artwork cache files (older than 1 day).""" """Clean up old artwork cache files (older than 1 day) and limit total cache size."""
try: try:
if not os.path.exists(CACHE_DIR): if not os.path.exists(CACHE_DIR):
return return
@@ -37,16 +37,46 @@ def cleanup_old_cache_files():
current_time = time.time() current_time = time.time()
one_day_ago = current_time - (24 * 60 * 60) # 24 hours one_day_ago = current_time - (24 * 60 * 60) # 24 hours
cache_files = []
# Collect all cache files with their modification times
for filename in os.listdir(CACHE_DIR): for filename in os.listdir(CACHE_DIR):
filepath = os.path.join(CACHE_DIR, filename) filepath = os.path.join(CACHE_DIR, filename)
try: try:
if os.path.isfile(filepath): if os.path.isfile(filepath):
file_mtime = os.path.getmtime(filepath) file_mtime = os.path.getmtime(filepath)
if file_mtime < one_day_ago: file_size = os.path.getsize(filepath)
os.unlink(filepath) cache_files.append((filepath, file_mtime, file_size))
except Exception: except Exception:
pass # Ignore individual file errors pass # Ignore individual file errors
# Remove files older than 1 day
total_size = 0
recent_files = []
for filepath, file_mtime, file_size in cache_files:
if file_mtime < one_day_ago:
try:
os.unlink(filepath)
except Exception:
pass
else:
recent_files.append((filepath, file_mtime, file_size))
total_size += file_size
# If cache is still too large (>50MB), remove oldest files
MAX_CACHE_SIZE = 50 * 1024 * 1024 # 50MB
if total_size > MAX_CACHE_SIZE:
# Sort by modification time (oldest first)
recent_files.sort(key=lambda x: x[1])
for filepath, _, file_size in recent_files:
if total_size <= MAX_CACHE_SIZE:
break
try:
os.unlink(filepath)
total_size -= file_size
except Exception:
pass
except Exception: except Exception:
pass # Ignore all errors in cleanup pass # Ignore all errors in cleanup
@@ -133,20 +163,41 @@ class PlayerBoxStack(Box):
super().destroy() super().destroy()
def _periodic_cleanup(self): def _periodic_cleanup(self):
"""Light cleanup for reuse - clean internal state but preserve widget""" """Enhanced cleanup for reuse - clean internal state and free memory"""
try: try:
# Destroy all player boxes properly to free their resources
current_children = list(self.player_stack.get_children())
for child in current_children:
if hasattr(child, "destroy") and child != self.no_media_box:
try:
child.destroy()
except Exception as e:
logger.warning(f"Failed to destroy player child: {e}")
# Reset to no media state # Reset to no media state
self.player_stack.children = [self.no_media_box] self.player_stack.children = [self.no_media_box]
# Clear player buttons but don't destroy them # Clear player buttons
for button in self.player_buttons:
try:
button.destroy()
except Exception:
pass
self.player_buttons.clear() self.player_buttons.clear()
# Reset stack position # Reset stack position
self.current_stack_pos = 0 self.current_stack_pos = 0
logger.debug("PlayerBoxStack periodic cleanup completed") # Clean up old cache files more aggressively
cleanup_old_cache_files()
# Force garbage collection
import gc
gc.collect()
logger.debug("PlayerBoxStack enhanced cleanup completed")
except Exception as e: except Exception as e:
logger.warning(f"PlayerBoxStack periodic cleanup failed: {e}") logger.warning(f"PlayerBoxStack enhanced cleanup failed: {e}")
def _create_no_media_box(self): def _create_no_media_box(self):
"""Create a placeholder box for when no media is playing.""" """Create a placeholder box for when no media is playing."""
+106 -116
View File
@@ -24,7 +24,7 @@ from config.data import load_config
# Module-level constants # Module-level constants
WEATHER_UPDATE_INTERVAL = 600 # 10 minutes WEATHER_UPDATE_INTERVAL = 600 # 10 minutes
WEATHER_CACHE_TIMEOUT = 1800 # 30 minutes WEATHER_CACHE_TIMEOUT = 1800 # 30 minutes
SYSTEM_UPDATE_INTERVAL = 1000 # 1 second SYSTEM_UPDATE_INTERVAL = 1000 # 1 second
CALENDAR_UPDATE_INTERVAL = 86400000 # 24 hours CALENDAR_UPDATE_INTERVAL = 86400000 # 24 hours
LOCATION_CACHE_TIMEOUT = 604800 # 7 days (extended from 24h) LOCATION_CACHE_TIMEOUT = 604800 # 7 days (extended from 24h)
@@ -35,54 +35,48 @@ executor = ThreadPoolExecutor(max_workers=4)
# Weather condition to CSS class mapping (iOS-style gradients) # Weather condition to CSS class mapping (iOS-style gradients)
WEATHER_GRADIENT_MAP = { WEATHER_GRADIENT_MAP = {
# Clear/Sunny conditions - bright blue to lighter blue # Clear/Sunny conditions - bright blue to lighter blue
0: "weather-clear", # Clear sky 0: "weather-clear", # Clear sky
1: "weather-mostly-clear", # Mainly clear 1: "weather-mostly-clear", # Mainly clear
# Cloudy conditions - grey gradients # Cloudy conditions - grey gradients
2: "weather-partly-cloudy", # Partly cloudy 2: "weather-partly-cloudy", # Partly cloudy
3: "weather-overcast", # Overcast 3: "weather-overcast", # Overcast
# Fog conditions - muted grey/blue # Fog conditions - muted grey/blue
45: "weather-fog", # Fog 45: "weather-fog", # Fog
48: "weather-fog", # Depositing rime fog 48: "weather-fog", # Depositing rime fog
# Light rain/drizzle - blue-grey gradients # Light rain/drizzle - blue-grey gradients
51: "weather-light-rain", # Light drizzle 51: "weather-light-rain", # Light drizzle
53: "weather-rain", # Moderate drizzle 53: "weather-rain", # Moderate drizzle
55: "weather-rain", # Dense drizzle 55: "weather-rain", # Dense drizzle
61: "weather-light-rain", # Slight rain 61: "weather-light-rain", # Slight rain
80: "weather-light-rain", # Slight rain showers 80: "weather-light-rain", # Slight rain showers
# Heavy rain - darker blue-grey # Heavy rain - darker blue-grey
63: "weather-heavy-rain", # Moderate rain 63: "weather-heavy-rain", # Moderate rain
65: "weather-heavy-rain", # Heavy rain 65: "weather-heavy-rain", # Heavy rain
81: "weather-heavy-rain", # Moderate rain showers 81: "weather-heavy-rain", # Moderate rain showers
82: "weather-storm", # Violent rain showers 82: "weather-storm", # Violent rain showers
# Snow conditions - blue-white gradients # Snow conditions - blue-white gradients
56: "weather-snow", # Light freezing drizzle 56: "weather-snow", # Light freezing drizzle
57: "weather-snow", # Dense freezing drizzle 57: "weather-snow", # Dense freezing drizzle
66: "weather-snow", # Light freezing rain 66: "weather-snow", # Light freezing rain
67: "weather-snow", # Heavy freezing rain 67: "weather-snow", # Heavy freezing rain
71: "weather-snow", # Slight snow fall 71: "weather-snow", # Slight snow fall
73: "weather-heavy-snow", # Moderate snow fall 73: "weather-heavy-snow", # Moderate snow fall
75: "weather-heavy-snow", # Heavy snow fall 75: "weather-heavy-snow", # Heavy snow fall
77: "weather-snow", # Snow grains 77: "weather-snow", # Snow grains
85: "weather-snow", # Slight snow showers 85: "weather-snow", # Slight snow showers
86: "weather-heavy-snow", # Heavy snow showers 86: "weather-heavy-snow", # Heavy snow showers
# Storm conditions - dark dramatic gradients # Storm conditions - dark dramatic gradients
95: "weather-storm", # Thunderstorm 95: "weather-storm", # Thunderstorm
96: "weather-storm", # Thunderstorm with slight hail 96: "weather-storm", # Thunderstorm with slight hail
99: "weather-storm", # Thunderstorm with heavy hail 99: "weather-storm", # Thunderstorm with heavy hail
} }
# Weather condition to emoji mapping # Weather condition to emoji mapping
WEATHER_EMOJI_MAP = { WEATHER_EMOJI_MAP = {
0: "☀️", # Clear sky 0: "☀️", # Clear sky
1: "🌤️", # Mainly clear 1: "🌤️", # Mainly clear
2: "⛅", # Partly cloudy 2: "⛅", # Partly cloudy
3: "☁️", # Overcast 3: "☁️", # Overcast
45: "🌫️", # Fog 45: "🌫️", # Fog
48: "🌫️", # Depositing rime fog 48: "🌫️", # Depositing rime fog
51: "🌦️", # Light drizzle 51: "🌦️", # Light drizzle
@@ -96,17 +90,17 @@ WEATHER_EMOJI_MAP = {
66: "🌨️", # Light freezing rain 66: "🌨️", # Light freezing rain
67: "🌨️", # Heavy freezing rain 67: "🌨️", # Heavy freezing rain
71: "🌨️", # Slight snow fall 71: "🌨️", # Slight snow fall
73: "❄️", # Moderate snow fall 73: "❄️", # Moderate snow fall
75: "❄️", # Heavy snow fall 75: "❄️", # Heavy snow fall
77: "🌨️", # Snow grains 77: "🌨️", # Snow grains
80: "🌦️", # Slight rain showers 80: "🌦️", # Slight rain showers
81: "🌧️", # Moderate rain showers 81: "🌧️", # Moderate rain showers
82: "⛈️", # Violent rain showers 82: "⛈️", # Violent rain showers
85: "🌨️", # Slight snow showers 85: "🌨️", # Slight snow showers
86: "❄️", # Heavy snow showers 86: "❄️", # Heavy snow showers
95: "⛈️", # Thunderstorm 95: "⛈️", # Thunderstorm
96: "⛈️", # Thunderstorm with slight hail 96: "⛈️", # Thunderstorm with slight hail
99: "⛈️", # Thunderstorm with heavy hail 99: "⛈️", # Thunderstorm with heavy hail
} }
# Weather condition descriptions # Weather condition descriptions
@@ -143,9 +137,9 @@ WEATHER_DESC_MAP = {
# Location APIs in order of preference (fastest first) # Location APIs in order of preference (fastest first)
LOCATION_APIS = [ LOCATION_APIS = [
"https://ipapi.co/json/", # Fastest, 200ms average "https://ipapi.co/json/", # Fastest, 200ms average
"http://ip-api.com/json/", # Fast fallback, 150ms average "http://ip-api.com/json/", # Fast fallback, 150ms average
"https://ipinfo.io/json" # Original fallback "https://ipinfo.io/json", # Original fallback
] ]
# Global cache for weather data # Global cache for weather data
@@ -186,13 +180,15 @@ def get_coordinates(city: str) -> Optional[Tuple[float, float]]:
try: try:
encoded_city = urllib.parse.quote(city) encoded_city = urllib.parse.quote(city)
url = f"https://nominatim.openstreetmap.org/search?q={encoded_city}&format=json&limit=1" url = f"https://nominatim.openstreetmap.org/search?q={encoded_city}&format=json&limit=1"
response = requests.get(url, timeout=3, headers={'User-Agent': 'Modus-Desktop/1.0'}) response = requests.get(
url, timeout=3, headers={"User-Agent": "Modus-Desktop/1.0"}
)
if response.status_code == 200: if response.status_code == 200:
data = response.json() data = response.json()
if data: if data:
lat = float(data[0]['lat']) lat = float(data[0]["lat"])
lon = float(data[0]['lon']) lon = float(data[0]["lon"])
_location_cache[cache_key] = (lat, lon, current_time) _location_cache[cache_key] = (lat, lon, current_time)
return lat, lon return lat, lon
except (requests.RequestException, ValueError, KeyError) as e: except (requests.RequestException, ValueError, KeyError) as e:
@@ -225,11 +221,11 @@ def get_weather_data(lat: float, lon: float) -> Optional[Dict[str, Any]]:
def format_weather_data(weather_data: Dict[str, Any], city: str) -> List[str]: def format_weather_data(weather_data: Dict[str, Any], city: str) -> List[str]:
"""Format weather data into the expected format.""" """Format weather data into the expected format."""
try: try:
current = weather_data['current_weather'] current = weather_data["current_weather"]
daily = weather_data['daily'] daily = weather_data["daily"]
# Get weather code and map to emoji and description # Get weather code and map to emoji and description
weather_code = current['weathercode'] weather_code = current["weathercode"]
emoji = WEATHER_EMOJI_MAP.get(weather_code, "🌤️") emoji = WEATHER_EMOJI_MAP.get(weather_code, "🌤️")
condition = WEATHER_DESC_MAP.get(weather_code, "Unknown") condition = WEATHER_DESC_MAP.get(weather_code, "Unknown")
gradient_class = WEATHER_GRADIENT_MAP.get(weather_code, "weather-clear") gradient_class = WEATHER_GRADIENT_MAP.get(weather_code, "weather-clear")
@@ -292,6 +288,7 @@ def get_weather(callback):
def update_weather(widget): def update_weather(widget):
"""Update weather widget with new data.""" """Update weather widget with new data."""
def fetch_and_update(): def fetch_and_update():
get_weather(lambda weather_info: update_widget(widget, weather_info)) get_weather(lambda weather_info: update_widget(widget, weather_info))
return True return True
@@ -334,35 +331,22 @@ class Weather(Box):
def _create_labels(self): def _create_labels(self):
"""Create all weather labels.""" """Create all weather labels."""
self.city = Label( self.city = Label(
name="city", name="city", label="Loading...", justification="right", h_align="start"
label="Loading...",
justification="right",
h_align="start"
)
self.temperature = Label(
name="temperature",
label="--°",
h_align="start"
)
self.condition_em = Label(
name="condition-emoji",
label="🌤️",
h_align="start"
)
self.condition = Label(
name="condition",
label="Loading...",
h_align="start"
)
self.feels_like = Label(
name="feels-like",
label="H:-- L:--",
h_align="start"
) )
self.temperature = Label(name="temperature", label="--°", h_align="start")
self.condition_em = Label(name="condition-emoji", label="🌤️", h_align="start")
self.condition = Label(name="condition", label="Loading...", h_align="start")
self.feels_like = Label(name="feels-like", label="H:-- L:--", h_align="start")
def _layout_labels(self): def _layout_labels(self):
"""Add labels to the widget in proper order.""" """Add labels to the widget in proper order."""
labels = [self.city, self.temperature, self.condition_em, self.condition, self.feels_like] labels = [
self.city,
self.temperature,
self.condition_em,
self.condition,
self.feels_like,
]
for label in labels: for label in labels:
self.add(label) self.add(label)
@@ -371,7 +355,9 @@ class Weather(Box):
if not weather_info or len(weather_info) != 7: if not weather_info or len(weather_info) != 7:
return return
emoji, temp, condition, location, maxtemp, mintemp, gradient_class = weather_info emoji, temp, condition, location, maxtemp, mintemp, gradient_class = (
weather_info
)
maxmin = f"H:{maxtemp} L:{mintemp}" maxmin = f"H:{maxtemp} L:{mintemp}"
# Batch update labels for better performance # Batch update labels for better performance
@@ -380,7 +366,7 @@ class Weather(Box):
(self.temperature, temp), (self.temperature, temp),
(self.condition_em, emoji), (self.condition_em, emoji),
(self.condition, condition), (self.condition, condition),
(self.feels_like, maxmin) (self.feels_like, maxmin),
] ]
for label, text in label_updates: for label, text in label_updates:
@@ -429,7 +415,9 @@ class Date(Box):
date_interval = 10000 # 10 seconds date_interval = 10000 # 10 seconds
self.dateone = DateTime(formatters=["%a"], interval=date_interval, name="day") self.dateone = DateTime(formatters=["%a"], interval=date_interval, name="day")
self.datetwo = DateTime(formatters=["%b"], interval=date_interval, name="month") self.datetwo = DateTime(formatters=["%b"], interval=date_interval, name="month")
self.datethree = DateTime(formatters=["%-d"], interval=date_interval, name="date") self.datethree = DateTime(
formatters=["%-d"], interval=date_interval, name="date"
)
# Layout components # Layout components
self.top.add(self.dateone) self.top.add(self.dateone)
@@ -501,17 +489,18 @@ class Calendar(Box):
def _create_days_header(self): def _create_days_header(self):
"""Create day abbreviations header.""" """Create day abbreviations header."""
self.days_header = Box( self.days_header = Box(
name="calendar-days-header", name="calendar-days-header", orientation="h", h_expand=True, spacing=2
orientation="h",
h_expand=True,
spacing=2
) )
day_names = ["S", "M", "T", "W", "T", "F", "S"] day_names = ["S", "M", "T", "W", "T", "F", "S"]
for i, day_name in enumerate(day_names): for i, day_name in enumerate(day_names):
is_weekend = i in (0, 6) # Sunday or Saturday is_weekend = i in (0, 6) # Sunday or Saturday
day_label = Label( day_label = Label(
name="calendar-day-header-weekend" if is_weekend else "calendar-day-header", name=(
"calendar-day-header-weekend"
if is_weekend
else "calendar-day-header"
),
label=day_name, label=day_name,
h_align="center", h_align="center",
h_expand=True, h_expand=True,
@@ -526,9 +515,11 @@ class Calendar(Box):
def update_calendar_if_needed(self) -> bool: def update_calendar_if_needed(self) -> bool:
"""Check if date changed and update calendar if needed.""" """Check if date changed and update calendar if needed."""
now = datetime.datetime.now() now = datetime.datetime.now()
if (now.month != self.current_month or if (
now.year != self.current_year or now.month != self.current_month
now.day != self.current_day): or now.year != self.current_year
or now.day != self.current_day
):
self._update_current_date() self._update_current_date()
self.update_calendar() self.update_calendar()
@@ -562,9 +553,11 @@ class Calendar(Box):
) )
else: else:
# Regular day # Regular day
is_today = (day == self.current_day and is_today = (
self.current_month == current_date.month and day == self.current_day
self.current_year == current_date.year) and self.current_month == current_date.month
and self.current_year == current_date.year
)
is_weekend = day_index in (0, 6) # Sunday or Saturday is_weekend = day_index in (0, 6) # Sunday or Saturday
if is_today: if is_today:
@@ -575,10 +568,7 @@ class Calendar(Box):
name = "calendar-day" name = "calendar-day"
day_label = Label( day_label = Label(
name=name, name=name, label=str(day), h_align="center", h_expand=True
label=str(day),
h_align="center",
h_expand=True
) )
week_box.add(day_label) week_box.add(day_label)
@@ -633,9 +623,7 @@ class SystemInfoBase(Box):
# Create progress bar and labels # Create progress bar and labels
self.progress = self.create_progress_bar(name="progress") self.progress = self.create_progress_bar(name="progress")
self.main_label = Label( self.main_label = Label(
label="0%\nLoading", label="0%\nLoading", justification="center", name="progress-label"
justification="center",
name="progress-label"
) )
# Create info container # Create info container
@@ -656,13 +644,15 @@ class SystemInfoBase(Box):
h_align="center", h_align="center",
v_align="center", v_align="center",
children=[ children=[
Box(children=[ Box(
Overlay( children=[
child=self.progress, Overlay(
tooltip_text="", child=self.progress,
overlays=self.main_label, tooltip_text="",
) overlays=self.main_label,
]), )
]
),
Box( Box(
h_align="center", h_align="center",
justification="centre", justification="centre",
@@ -680,7 +670,9 @@ class SystemInfoBase(Box):
"""Start the update timer - call this after subclass initialization is complete.""" """Start the update timer - call this after subclass initialization is complete."""
invoke_repeater(SYSTEM_UPDATE_INTERVAL, self.update) invoke_repeater(SYSTEM_UPDATE_INTERVAL, self.update)
def create_info_line(self, indicator_name: str, info_text: str, value_text: str) -> Box: def create_info_line(
self, indicator_name: str, info_text: str, value_text: str
) -> Box:
"""Create an information line with indicator, label, and value.""" """Create an information line with indicator, label, and value."""
indicator = Label(label="■", name=indicator_name) indicator = Label(label="■", name=indicator_name)
info_label = Label(label=info_text, name="info-text") info_label = Label(label=info_text, name="info-text")
@@ -712,12 +704,8 @@ class RamInfo(SystemInfoBase):
super().__init__("info-box-widget", **kwargs) super().__init__("info-box-widget", **kwargs)
# Create info lines and store references # Create info lines and store references
self.used_line = self.create_info_line( self.used_line = self.create_info_line("used-color-indicator", "Used", "0.0GB")
"used-color-indicator", "Used", "0.0GB" self.free_line = self.create_info_line("free-color-indicator", "Free", "0.0GB")
)
self.free_line = self.create_info_line(
"free-color-indicator", "Free", "0.0GB"
)
# Add to info container # Add to info container
self.info_container.add(self.used_line) self.info_container.add(self.used_line)
@@ -790,7 +778,9 @@ class CpuInfo(SystemInfoBase):
if any(sensor in name.lower() for sensor in cpu_sensor_names): if any(sensor in name.lower() for sensor in cpu_sensor_names):
for entry in entries: for entry in entries:
entry_label = (entry.label or "").lower() entry_label = (entry.label or "").lower()
if any(pattern in entry_label for pattern in cpu_label_patterns): if any(
pattern in entry_label for pattern in cpu_label_patterns
):
return round(entry.current, 1) return round(entry.current, 1)
except Exception as e: except Exception as e:
print(f"Error reading CPU temperature: {e}") print(f"Error reading CPU temperature: {e}")
+22 -1
View File
@@ -252,16 +252,37 @@ class MprisPlayerManager(Service):
**kwargs, **kwargs,
): ):
self._manager = Playerctl.PlayerManager.new() self._manager = Playerctl.PlayerManager.new()
bulk_connect( self._signal_connections = []
# Track signal connections for cleanup
connections = bulk_connect(
self._manager, self._manager,
{ {
"name-appeared": self.on_name_appeared, "name-appeared": self.on_name_appeared,
"name-vanished": self.on_name_vanished, "name-vanished": self.on_name_vanished,
}, },
) )
# Store as (object, handler_id) tuples
for handler_id in connections:
self._signal_connections.append((self._manager, handler_id))
self.add_players() self.add_players()
super().__init__(**kwargs) super().__init__(**kwargs)
def destroy(self):
"""Clean up resources when the manager is destroyed."""
# Disconnect all signal connections
for obj, handler_id in self._signal_connections:
try:
obj.disconnect(handler_id)
except Exception as e:
logger.warning(f"Failed to disconnect manager signal: {e}")
self._signal_connections.clear()
# Clean up the manager
if hasattr(self, '_manager'):
del self._manager
def on_name_appeared(self, manager, player_name: Playerctl.PlayerName): def on_name_appeared(self, manager, player_name: Playerctl.PlayerName):
logger.info(f"[MprisPlayer] {player_name.name} appeared") logger.info(f"[MprisPlayer] {player_name.name} appeared")
new_player = Playerctl.Player.new_from_name(player_name) new_player = Playerctl.Player.new_from_name(player_name)
+9 -10
View File
@@ -216,14 +216,14 @@
#toggle-button { #toggle-button {
min-width: 40px; min-width: 40px;
min-height: 20px; min-height: 20px;
background-color: #888; background-color: #bababa;
border-radius: 15px; border-radius: 15px;
padding: 2px; padding: 2px;
transition: background-color 0.3s ease; transition: background-color 0.3s ease;
} }
#toggle-button slider { #toggle-button slider {
background-color: var(--primary); background-color: #fff;
border-radius: 50%; border-radius: 50%;
min-width: 16px; min-width: 16px;
min-height: 8px; min-height: 8px;
@@ -234,14 +234,13 @@
background-color: #4487f6; background-color: #4487f6;
} }
#toggle-button:checked slider { /* #toggle-button:checked slider { */
background-color: #bababa; /* background-color: #fff; */
} /* } */
/**/
#toggle-button:checked image { /* #toggle-button:checked image { */
color: var(--shadow); /* opacity: 0; */
opacity: 0; /* } */
}
.menu { .menu {
margin: 5px; margin: 5px;