[gnome-music/wip/mschraal/texturecache-memory-size-improvements: 9/9] texturecache: Drop cache on low memory




commit 07457089fbb1715624c417301d495472344fec48
Author: Marinus Schraal <mschraal gnome org>
Date:   Wed Apr 20 23:23:57 2022 +0200

    texturecache: Drop cache on low memory

 gnomemusic/texturecache.py | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
---
diff --git a/gnomemusic/texturecache.py b/gnomemusic/texturecache.py
index ec8d540cc..24fb13686 100644
--- a/gnomemusic/texturecache.py
+++ b/gnomemusic/texturecache.py
@@ -27,7 +27,7 @@ from enum import IntEnum
 from typing import Dict, Optional, Tuple, Union
 import time, typing
 
-from gi.repository import GLib, GObject, Gdk
+from gi.repository import GLib, GObject, Gdk, Gio
 
 from gnomemusic.asyncqueue import AsyncQueue
 from gnomemusic.musiclogger import MusicLogger
@@ -63,14 +63,17 @@ class TextureCache(GObject.GObject):
         "texture": (GObject.SignalFlags.RUN_FIRST, None, (object, ))
     }
 
+    _MAX_CACHE_SIZE = 800
+
     _async_queue = AsyncQueue("TextureCache")
     _cleanup_id = 0
     _log = MusicLogger()
+    _memory_monitor = Gio.MemoryMonitor.dup_default()
     # Music has two main cycling views (AlbumsView and ArtistsView),
     # both have around 200 cycling items each when fully used. For
     # the cache to be useful it needs to be larger than the given
     # numbers combined.
-    _size = 800
+    _size = _MAX_CACHE_SIZE
     _textures: Dict[str, Tuple[
         TextureCache.LoadingState, float, Optional[Gdk.Texture]]] = {}
 
@@ -85,6 +88,8 @@ class TextureCache(GObject.GObject):
         if TextureCache._cleanup_id == 0:
             TextureCache._cleanup_id = GLib.timeout_add_seconds(
                 10, TextureCache._cache_cleanup)
+            TextureCache._memory_monitor.connect(
+                "low-memory-warning", TextureCache._low_memory_warning)
 
     def clear_pending_lookup_callback(self) -> None:
         """Disconnect ongoing lookup callback
@@ -114,6 +119,15 @@ class TextureCache(GObject.GObject):
             "finished", self._on_art_loading_finished, uri)
         self._async_queue.queue(self._art_loader, uri)
 
+    @classmethod
+    def _low_memory_warning(
+            cls, mm: Gio.MemoryMonitor,
+            level: Gio.MemoryMonitorWarningLevel) -> None:
+        if level < Gio.MemoryMonitorWarningLevel.LOW:
+            TextureCache._size = TextureCache._MAX_CACHE_SIZE
+        else:
+            TextureCache._size = 0
+
     @classmethod
     def _cache_cleanup(cls) -> None:
         """Sorts the available cache entries by recency and evicts


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]