From 15b8a98a6c4af20558abaa82e676042245f19c72 Mon Sep 17 00:00:00 2001 From: Alon Levy Date: Sun, 29 Jan 2012 23:29:50 +0200 Subject: [PATCH 4/6] add a font cache, fix repeated reload leading to EMFILE --- sdltools.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ 1 files changed, 41 insertions(+), 0 deletions(-) diff --git a/sdltools.cpp b/sdltools.cpp index 0806981..b47d4bc 100644 --- a/sdltools.cpp +++ b/sdltools.cpp @@ -11,6 +11,9 @@ published by the Free Software Foundation. */ #include #include +#include +#include + #include #include @@ -246,8 +249,46 @@ TTF_Font *init_font(const char *resource_path, const char *font_file, int size) } */ +/* + * Font cache. Avoid reopening a font file. Avoid leaking fonts on reload + * (EMFILE after many hits of the key 'r'). + * + * NB: Assume for now the font files themselves do not change + */ + +using std::map; +using std::pair; +using std::string; + +class FontCache { +private: + typedef pair key_type; + typedef map cache_type; + typedef pair pair_type; + cache_type m_cache; + TTF_Font *load_font(const char *font_path, int size); +public: + TTF_Font *get_font(const char *font_path, int size) + { + cache_type::iterator it; + key_type key = key_type(font_path, size); + if (m_cache.count(key) == 0) { + m_cache.insert(pair_type(key, load_font(font_path, size))); + it = m_cache.find(key); + } else { + it = m_cache.find(key); + } + return it->second; + } +} font_cache; + TTF_Font *load_font(const char *font_path, int size) { + return font_cache.get_font(font_path, size); +} + +TTF_Font *FontCache::load_font(const char *font_path, int size) +{ TTF_Font *font; font = TTF_OpenFont(font_path, size); // Point size -- 1.7.9.1