| | | 1 | | using System; |
| | | 2 | | using System.Collections.Concurrent; |
| | | 3 | | using System.Windows; |
| | | 4 | | using System.Windows.Interop; |
| | | 5 | | using System.Windows.Media; |
| | | 6 | | using System.Windows.Media.Imaging; |
| | | 7 | | using SwitchBlade.Contracts; |
| | | 8 | | |
| | | 9 | | namespace SwitchBlade.Services |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Extracts and caches application icons from executable files. |
| | | 13 | | /// Icons are cached by full executable path to handle different versions of same-named executables. |
| | | 14 | | /// </summary> |
| | | 15 | | public class IconService : IIconService |
| | | 16 | | { |
| | 13 | 17 | | private readonly ConcurrentDictionary<string, ImageSource?> _iconCache = new(StringComparer.OrdinalIgnoreCase); |
| | | 18 | | private readonly ISettingsService _settingsService; |
| | | 19 | | private readonly IIconExtractor _iconExtractor; |
| | | 20 | | |
| | 6 | 21 | | public int CacheCount => _iconCache.Count; |
| | | 22 | | |
| | | 23 | | // Default to a safe limit if settings unavailable (though they should be) |
| | | 24 | | private const int FallbackMaxCacheSize = 200; |
| | | 25 | | |
| | 13 | 26 | | public IconService(ISettingsService settingsService, IIconExtractor? iconExtractor = null) |
| | 13 | 27 | | { |
| | 13 | 28 | | _settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); |
| | 12 | 29 | | _iconExtractor = iconExtractor ?? new IconExtractor(); |
| | 12 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Gets the icon for the specified executable path. |
| | | 34 | | /// Uses a cache to avoid repeated extractions. |
| | | 35 | | /// </summary> |
| | | 36 | | public ImageSource? GetIcon(string? executablePath) |
| | 14 | 37 | | { |
| | 14 | 38 | | if (string.IsNullOrEmpty(executablePath)) |
| | 2 | 39 | | return null; |
| | | 40 | | |
| | | 41 | | // Check cache size limit before adding new items |
| | 12 | 42 | | int limit = _settingsService.Settings?.IconCacheSize ?? FallbackMaxCacheSize; |
| | | 43 | | |
| | | 44 | | // If cache is full and this is a new item, clear it to prevent unbounded growth |
| | 12 | 45 | | if (_iconCache.Count >= limit && !_iconCache.ContainsKey(executablePath)) |
| | 1 | 46 | | { |
| | 1 | 47 | | _iconCache.Clear(); |
| | 1 | 48 | | Core.Logger.Log($"Icon cache limit ({limit}) reached. Cleared cache."); |
| | 1 | 49 | | } |
| | | 50 | | |
| | 21 | 51 | | return _iconCache.GetOrAdd(executablePath, path => _iconExtractor.ExtractIcon(path)); |
| | 14 | 52 | | } |
| | | 53 | | |
| | | 54 | | /// <summary> |
| | | 55 | | /// Clears the icon cache to free memory. |
| | | 56 | | /// </summary> |
| | | 57 | | public void ClearCache() |
| | 1 | 58 | | { |
| | 1 | 59 | | _iconCache.Clear(); |
| | 1 | 60 | | } |
| | | 61 | | } |
| | | 62 | | } |