Flow.Launcher/Flow.Launcher.Infrastructure/Image/ImageCache.cs

81 lines
2.2 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
2014-12-18 11:22:47 +00:00
using System.Linq;
2024-05-29 22:57:26 +00:00
using System.Threading.Tasks;
using System.Windows.Media;
2024-05-29 22:57:26 +00:00
using BitFaster.Caching.Lfu;
2014-12-18 11:22:47 +00:00
2020-08-05 09:57:23 +00:00
namespace Flow.Launcher.Infrastructure.Image
2014-12-18 11:22:47 +00:00
{
public class ImageCache
2014-12-18 11:22:47 +00:00
{
2024-05-30 05:48:56 +00:00
private const int MaxCached = 150;
2024-05-29 22:57:26 +00:00
private ConcurrentLfu<(string, bool), ImageSource> CacheManager { get; set; } = new(MaxCached);
2021-05-23 14:54:52 +00:00
2024-05-29 22:57:26 +00:00
public void Initialize(IEnumerable<(string, bool)> usage)
{
2024-05-29 22:57:26 +00:00
foreach (var key in usage)
{
2024-05-29 22:57:26 +00:00
CacheManager.AddOrUpdate(key, null);
}
}
public ImageSource this[string path, bool isFullImage = false]
2014-12-18 11:22:47 +00:00
{
get
2014-12-18 11:22:47 +00:00
{
2024-05-29 22:57:26 +00:00
return CacheManager.TryGet((path, isFullImage), out var value) ? value : null;
2014-12-18 11:22:47 +00:00
}
set
{
2024-05-29 22:57:26 +00:00
CacheManager.AddOrUpdate((path, isFullImage), value);
}
}
2014-12-18 11:22:47 +00:00
2024-05-29 22:57:26 +00:00
public async ValueTask<ImageSource> GetOrAddAsync(string key,
Func<(string, bool), Task<ImageSource>> valueFactory,
bool isFullImage = false)
{
return await CacheManager.GetOrAddAsync((key, isFullImage), valueFactory);
}
public bool ContainsKey(string key, bool isFullImage)
{
2024-05-29 22:57:26 +00:00
return CacheManager.TryGet((key, isFullImage), out _);
2014-12-18 11:22:47 +00:00
}
2022-12-29 03:43:40 +00:00
public bool TryGetValue(string key, bool isFullImage, out ImageSource image)
{
2024-05-29 22:57:26 +00:00
if (CacheManager.TryGet((key, isFullImage), out var value))
2022-12-29 03:43:40 +00:00
{
2024-05-29 22:57:26 +00:00
image = value;
return image != null;
2022-12-29 03:43:40 +00:00
}
image = null;
return false;
2022-12-29 03:43:40 +00:00
}
public int CacheSize()
{
2024-05-29 22:57:26 +00:00
return CacheManager.Count;
}
/// <summary>
/// return the number of unique images in the cache (by reference not by checking images content)
/// </summary>
public int UniqueImagesInCache()
{
2024-05-29 22:57:26 +00:00
return CacheManager.Select(x => x.Value)
.Distinct()
.Count();
}
2024-05-29 22:57:26 +00:00
public IEnumerable<KeyValuePair<(string, bool), ImageSource>> EnumerateEntries()
{
2024-05-29 22:57:26 +00:00
return CacheManager;
}
2014-12-18 11:22:47 +00:00
}
}