Implement size limit for Litehtml image cache
authorAndrej Kacian <ticho@claws-mail.org>
Fri, 8 Feb 2019 18:42:54 +0000 (19:42 +0100)
committerAndrej Kacian <ticho@claws-mail.org>
Tue, 12 Feb 2019 18:38:10 +0000 (19:38 +0100)
src/plugins/litehtml_viewer/container_linux.cpp
src/plugins/litehtml_viewer/container_linux.h

index f24add4..e4d3c1d 100644 (file)
@@ -823,15 +823,48 @@ void container_linux::fill_ellipse( cairo_t* cr, int x, int y, int width, int he
 
 void container_linux::clear_images()
 {
-/*     for(images_map::iterator i = m_images.begin(); i != m_images.end(); i++)
-       {
-               if(i->second)
-               {
-                       delete i->second;
+       for(auto i = m_images.begin(); i != m_images.end(); ++i) {
+               image *img = &(*i);
+
+               if (img->second) {
+                       g_object_unref(img->second);
                }
        }
+
        m_images.clear();
-*/
+}
+
+void container_linux::clear_images(gint desired_size)
+{
+       gint size = 0;
+
+       /* First, tally up size of all the stored GdkPixbufs and
+        * deallocate those which make the total size be above
+        * the desired_size limit. We will remove their list
+        * elements later. */
+       for (auto i = m_images.rbegin(); i != m_images.rend(); ++i) {
+               image *img = &(*i);
+               gint cursize;
+
+               if (img->second == NULL)
+                       continue;
+
+               cursize = gdk_pixbuf_get_byte_length(img->second);
+
+               if (size + cursize > desired_size) {
+                       g_object_unref(img->second);
+                       img->second = NULL;
+               } else {
+                       size += cursize;
+               }
+       }
+
+       /* Remove elements whose GdkPixbuf pointers point to NULL. */
+       m_images.remove_if([&](image _img) -> bool {
+                       if (_img.second == NULL)
+                               return true;
+                       return false;
+                       });
 }
 
 const litehtml::tchar_t* container_linux::get_default_font_name() const
index 8c6eb6d..8298437 100644 (file)
@@ -86,6 +86,10 @@ public:
 
        void                                                            clear_images();
 
+       /* Trim down images cache to less than desired_size [bytes],
+        * starting from oldest stored. */
+       void                                                            clear_images(gint desired_size);
+
 protected:
        virtual void                                            draw_ellipse(cairo_t* cr, int x, int y, int width, int height, const litehtml::web_color& color, int line_width);
        virtual void                                            fill_ellipse(cairo_t* cr, int x, int y, int width, int height, const litehtml::web_color& color);