From 7f83ece6a0c07d0fbc1902502050563b5a8c09e4 Mon Sep 17 00:00:00 2001 From: Liza Carvelli Date: Wed, 1 Nov 2023 10:09:37 +0100 Subject: [PATCH] Add IconCache --- IconCache.cs | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 IconCache.cs diff --git a/IconCache.cs b/IconCache.cs new file mode 100644 index 0000000..96f28e2 --- /dev/null +++ b/IconCache.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using Dalamud.Interface.Internal; +using Dalamud.Plugin.Services; + +namespace LLib; + +public sealed class IconCache : IDisposable +{ + private readonly ITextureProvider _textureProvider; + private readonly Dictionary _textureWraps = new(); + + public IconCache(ITextureProvider textureProvider) + { + _textureProvider = textureProvider; + } + + public IDalamudTextureWrap? GetIcon(uint iconId) + { + if (_textureWraps.TryGetValue(iconId, out TextureContainer? container)) + return container.Texture; + + var iconTex = _textureProvider.GetIcon(iconId); + if (iconTex != null) + { + if (iconTex.ImGuiHandle != nint.Zero) + { + _textureWraps[iconId] = new TextureContainer { Texture = iconTex }; + return iconTex; + } + + iconTex.Dispose(); + } + + _textureWraps[iconId] = new TextureContainer { Texture = null }; + return null; + } + + public void Dispose() + { + foreach (TextureContainer container in _textureWraps.Values) + container.Dispose(); + + _textureWraps.Clear(); + } + + private sealed class TextureContainer : IDisposable + { + public required IDalamudTextureWrap? Texture { get; init; } + + public void Dispose() => Texture?.Dispose(); + } +}