IconUtils: add cache to avoid redundant I/O

This commit is contained in:
Le Tan 2018-05-18 20:58:10 +08:00
parent 52546e4664
commit 18ee02d920
2 changed files with 20 additions and 3 deletions

View File

@ -1,6 +1,5 @@
#include "viconutils.h" #include "viconutils.h"
#include <QDebug>
#include <QRegExp> #include <QRegExp>
#include <QByteArray> #include <QByteArray>
#include <QPixmap> #include <QPixmap>
@ -8,13 +7,20 @@
#include "vutils.h" #include "vutils.h"
QHash<QString, QIcon> VIconUtils::m_cache;
VIconUtils::VIconUtils() VIconUtils::VIconUtils()
{ {
} }
QIcon VIconUtils::icon(const QString &p_file, const QString &p_fg, bool p_addDisabled) QIcon VIconUtils::icon(const QString &p_file, const QString &p_fg, bool p_addDisabled)
{ {
const QString key = cacheKey(p_file, p_fg, p_addDisabled);
auto it = m_cache.find(key);
if (it != m_cache.end()) {
return it.value();
}
QFileInfo fi(p_file); QFileInfo fi(p_file);
bool isSvg = fi.suffix().toLower() == "svg"; bool isSvg = fi.suffix().toLower() == "svg";
if (p_fg.isEmpty() || !isSvg) { if (p_fg.isEmpty() || !isSvg) {
@ -48,5 +54,8 @@ QIcon VIconUtils::icon(const QString &p_file, const QString &p_fg, bool p_addDis
icon.addPixmap(disabledPixmap, QIcon::Disabled); icon.addPixmap(disabledPixmap, QIcon::Disabled);
} }
// Add to cache.
m_cache.insert(key, icon);
return icon; return icon;
} }

View File

@ -3,12 +3,12 @@
#include <QString> #include <QString>
#include <QIcon> #include <QIcon>
#include <QHash>
#include "vpalette.h" #include "vpalette.h"
extern VPalette *g_palette; extern VPalette *g_palette;
class VIconUtils class VIconUtils
{ {
public: public:
@ -94,6 +94,14 @@ public:
private: private:
VIconUtils(); VIconUtils();
static QString cacheKey(const QString &p_file, const QString &p_fg, bool p_addDisabled)
{
return p_file + "_" + p_fg + "_" + (p_addDisabled ? "1" : "0");
}
// file_fg_addDisabled as key.
static QHash<QString, QIcon> m_cache;
}; };
#endif // VICONUTILS_H #endif // VICONUTILS_H