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

100 lines
2.8 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
2014-12-18 11:22:47 +00:00
using System.Linq;
using System.Threading;
using System.Windows.Media;
using FastCache;
using FastCache.Services;
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 ImageUsage
{
public int usage;
public ImageSource imageSource;
public ImageUsage(int usage, ImageSource image)
{
this.usage = usage;
imageSource = image;
}
}
public class ImageCache
2014-12-18 11:22:47 +00:00
{
private const int MaxCached = 150;
2021-05-23 14:54:52 +00:00
2023-04-24 14:58:32 +00:00
public void Initialize(Dictionary<(string, bool), int> usage)
{
foreach (var key in usage.Keys)
{
Cached<ImageUsage>.Save(key, new ImageUsage(usage[key], null), TimeSpan.MaxValue, MaxCached);
}
}
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
{
if (!Cached<ImageUsage>.TryGet((path, isFullImage), out var value))
{
return null;
}
value.Value.usage++;
return value.Value.imageSource;
2014-12-18 11:22:47 +00:00
}
set
{
if (Cached<ImageUsage>.TryGet((path, isFullImage), out var cached))
{
cached.Value.imageSource = value;
cached.Value.usage++;
}
Cached<ImageUsage>.Save((path, isFullImage), new ImageUsage(0, value), TimeSpan.MaxValue,
MaxCached);
}
}
2014-12-18 11:22:47 +00:00
public bool ContainsKey(string key, bool isFullImage)
{
return Cached<ImageUsage>.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)
{
if (Cached<ImageUsage>.TryGet((key, isFullImage), out var value))
2022-12-29 03:43:40 +00:00
{
image = value.Value.imageSource;
value.Value.usage++;
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()
{
return CacheManager.TotalCount<(string, bool), ImageUsage>();
}
/// <summary>
/// return the number of unique images in the cache (by reference not by checking images content)
/// </summary>
public int UniqueImagesInCache()
{
return CacheManager.EnumerateEntries<(string, bool), ImageUsage>().Select(x => x.Value.imageSource)
.Distinct()
.Count();
}
public IEnumerable<Cached<(string, bool), ImageUsage>> EnumerateEntries()
{
return CacheManager.EnumerateEntries<(string, bool), ImageUsage>();
}
2014-12-18 11:22:47 +00:00
}
}