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
+343 -252

No files matched your search

+64 -34
View File
@@ -6,6 +6,7 @@ from fabric.utils.helpers import (
)
from fabric.widgets.box import Box
from fabric.widgets.button import Button
from loguru import logger
from fabric.widgets.centerbox import CenterBox
from fabric.widgets.label import Label
from fabric.widgets.scale import Scale
@@ -50,11 +51,12 @@ class ModusControlCenter(Window):
self._per_app_volume_initialized = False
self._expanded_player_initialized = False
# Store references for cleanup
# Store references for cleanup - initialize all as None
self._signal_connections = []
self._music_widget_content = None
self._per_app_volume_widget = None
self._expanded_player_widget = None
self._mpris_manager = None # Shared MPRIS manager instance
self.add_keybinding("Escape", self.hide_controlcenter)
@@ -358,24 +360,59 @@ class ModusControlCenter(Window):
self._cleanup_when_hidden()
def _cleanup_when_hidden(self):
"""Clean up resources when widget is hidden"""
# Clean up music widget content if it exists
if self._music_widget_content and not self._music_initialized:
# Remove from the parent container
current_children = list(self.music_widget.children)
if self._music_widget_content in current_children:
current_children.remove(self._music_widget_content)
self.music_widget.children = current_children
self._music_widget_content = None
"""Aggressively clean up resources when widget is hidden to reduce memory usage"""
try:
# Clean up music widget content if it exists
if self._music_widget_content:
# Remove from the parent container
current_children = list(self.music_widget.children)
if self._music_widget_content in current_children:
current_children.remove(self._music_widget_content)
self.music_widget.children = current_children
# Reset lazy loading flags to allow re-initialization when shown again
# Keep initialized flags to avoid recreating heavy components unnecessarily
# Trigger periodic cleanup before destroying
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):
"""Lazy load music widget content"""
"""Lazy load music widget content - reuse MPRIS manager"""
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(
MprisPlayerManager(), control_center=self
self._mpris_manager, control_center=self
)
# Add to the music widget's children list
current_children = list(self.music_widget.children)
@@ -422,22 +459,7 @@ class ModusControlCenter(Window):
h_expand=True,
name="control-center-widgets",
children=[
Box(
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_man,
],
)
self.wifi_center_box = CenterBox(start_children=[self.wifi_widgets])
@@ -710,10 +732,10 @@ class ModusControlCenter(Window):
pass
# Clean up heavy components
if self._wifi_man:
self._wifi_man.destroy()
if self._bluetooth_man:
self._bluetooth_man.destroy()
if hasattr(self, "wifi_man") and self.wifi_man:
self.wifi_man.destroy()
if hasattr(self, "bluetooth_man") and self.bluetooth_man:
self.bluetooth_man.destroy()
if self._music_widget_content:
self._music_widget_content.destroy()
if self._per_app_volume_widget:
@@ -721,4 +743,12 @@ class ModusControlCenter(Window):
if self._expanded_player_widget:
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()
+58 -7
View File
@@ -28,7 +28,7 @@ CACHE_DIR = f"{data.CACHE_DIR}/media"
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:
if not os.path.exists(CACHE_DIR):
return
@@ -37,16 +37,46 @@ def cleanup_old_cache_files():
current_time = time.time()
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):
filepath = os.path.join(CACHE_DIR, filename)
try:
if os.path.isfile(filepath):
file_mtime = os.path.getmtime(filepath)
if file_mtime < one_day_ago:
os.unlink(filepath)
file_size = os.path.getsize(filepath)
cache_files.append((filepath, file_mtime, file_size))
except Exception:
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:
pass # Ignore all errors in cleanup
@@ -133,20 +163,41 @@ class PlayerBoxStack(Box):
super().destroy()
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:
# 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
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()
# Reset stack position
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:
logger.warning(f"PlayerBoxStack periodic cleanup failed: {e}")
logger.warning(f"PlayerBoxStack enhanced cleanup failed: {e}")
def _create_no_media_box(self):
"""Create a placeholder box for when no media is playing."""