1- using System . Collections . Concurrent ;
21using System . Collections . ObjectModel ;
32using System . ComponentModel ;
43using System . Net . Http ;
4+ using Avalonia ;
55using Avalonia . Collections ;
66using Avalonia . Media . Imaging ;
77using Avalonia . Threading ;
@@ -27,8 +27,66 @@ public sealed class PackageWrapper : INotifyPropertyChanged, IDisposable
2727 {
2828 Timeout = TimeSpan . FromSeconds ( 8 ) ,
2929 } ;
30- private static readonly ConcurrentDictionary < long , Bitmap ? > _iconCache = new ( ) ;
31- private static readonly SemaphoreSlim _iconLoadSemaphore = new ( 4 , 4 ) ;
30+ private static readonly SemaphoreSlim _iconLoadSemaphore = new ( 8 , 8 ) ;
31+
32+ // Cap decoded icon size; the list shows icons at ≤64px (128 covers 2x DPI).
33+ private const int MaxIconSide = 128 ;
34+
35+ // Bounded LRU by package hash. Evicted entries aren't disposed: a visible row may still
36+ // reference the bitmap, so dropping it here only makes it GC-eligible.
37+ private const int MaxIconCacheEntries = 512 ;
38+ private static readonly object _iconCacheLock = new ( ) ;
39+ private static readonly Dictionary < long , LinkedListNode < ( long Hash , Bitmap ? Bitmap ) > > _iconCache = new ( ) ;
40+ private static readonly LinkedList < ( long Hash , Bitmap ? Bitmap ) > _iconCacheOrder = new ( ) ;
41+
42+ private static bool TryGetCachedIcon ( long hash , out Bitmap ? bitmap )
43+ {
44+ lock ( _iconCacheLock )
45+ {
46+ if ( _iconCache . TryGetValue ( hash , out var node ) )
47+ {
48+ _iconCacheOrder . Remove ( node ) ;
49+ _iconCacheOrder . AddFirst ( node ) ;
50+ bitmap = node . Value . Bitmap ;
51+ return true ;
52+ }
53+ }
54+ bitmap = null ;
55+ return false ;
56+ }
57+
58+ private static void CacheIcon ( long hash , Bitmap ? bitmap )
59+ {
60+ lock ( _iconCacheLock )
61+ {
62+ if ( _iconCache . TryGetValue ( hash , out var existing ) )
63+ {
64+ existing . Value = ( hash , bitmap ) ;
65+ _iconCacheOrder . Remove ( existing ) ;
66+ _iconCacheOrder . AddFirst ( existing ) ;
67+ return ;
68+ }
69+
70+ var node = new LinkedListNode < ( long , Bitmap ? ) > ( ( hash , bitmap ) ) ;
71+ _iconCache [ hash ] = node ;
72+ _iconCacheOrder . AddFirst ( node ) ;
73+
74+ while ( _iconCache . Count > MaxIconCacheEntries && _iconCacheOrder . Last is { } last )
75+ {
76+ _iconCacheOrder . RemoveLast ( ) ;
77+ _iconCache . Remove ( last . Value . Hash ) ;
78+ }
79+ }
80+ }
81+
82+ public static void ClearIconCache ( )
83+ {
84+ lock ( _iconCacheLock )
85+ {
86+ _iconCache . Clear ( ) ;
87+ _iconCacheOrder . Clear ( ) ;
88+ }
89+ }
3290
3391 public IPackage Package { get ; }
3492 public PackageWrapper Self => this ;
@@ -73,6 +131,8 @@ public bool IsChecked
73131 public string InstallerHostChangeTooltip { get ; private set ; } = "" ;
74132
75133 private CancellationTokenSource ? _installerHostCheckCts ;
134+ // Cancels this row's queued/in-flight icon load on disposal so it stops rooting the wrapper.
135+ private readonly CancellationTokenSource _lifetimeCts = new ( ) ;
76136
77137 public string SourceIconPath => IconTypeToSvgPath ( Package . Source . IconId ) ;
78138
@@ -102,12 +162,20 @@ public PackageWrapper(IPackage package, PackagesPageViewModel page)
102162 Package . PropertyChanged += Package_PropertyChanged ;
103163 UpdateDisplayState ( ) ;
104164
105- if ( ! Settings . Get ( Settings . K . DisableIconsOnPackageLists ) )
106- _ = LoadIconAsync ( ) ;
107-
165+ // Icons load lazily per visible row (see EnsureIconLoaded), not eagerly for every result.
108166 MaybeStartInstallerHostCheck ( ) ;
109167 }
110168
169+ private int _iconLoadStarted ;
170+
171+ /// <summary>Loads this row's icon at most once; called when the row becomes visible.</summary>
172+ public void EnsureIconLoaded ( )
173+ {
174+ if ( Settings . Get ( Settings . K . DisableIconsOnPackageLists ) ) return ;
175+ if ( Interlocked . Exchange ( ref _iconLoadStarted , 1 ) != 0 ) return ;
176+ _ = LoadIconAsync ( ) ;
177+ }
178+
111179 /// <summary>
112180 /// For upgradable WinGet packages, asynchronously fetches the installer URL host for
113181 /// both the installed and the new version, and flags the row when the hosts differ.
@@ -183,8 +251,9 @@ await Dispatcher.UIThread.InvokeAsync(() =>
183251
184252 private async Task LoadIconAsync ( )
185253 {
254+ CancellationToken token = _lifetimeCts . Token ;
186255 long hash = Package . GetHash ( ) ;
187- if ( _iconCache . TryGetValue ( hash , out Bitmap ? cached ) )
256+ if ( TryGetCachedIcon ( hash , out Bitmap ? cached ) )
188257 {
189258 if ( cached is not null )
190259 IconBitmap = cached ;
@@ -193,12 +262,12 @@ private async Task LoadIconAsync()
193262
194263 try
195264 {
196- await _iconLoadSemaphore . WaitAsync ( ) . ConfigureAwait ( false ) ;
265+ await _iconLoadSemaphore . WaitAsync ( token ) . ConfigureAwait ( false ) ;
197266 Bitmap bitmap ;
198267 try
199268 {
200- var uri = await Task . Run ( Package . GetIconUrlIfAny ) . ConfigureAwait ( false ) ;
201- if ( uri is null ) { _iconCache [ hash ] = null ; return ; }
269+ var uri = await Task . Run ( Package . GetIconUrlIfAny , token ) . ConfigureAwait ( false ) ;
270+ if ( uri is null ) { CacheIcon ( hash , null ) ; return ; }
202271
203272 Bitmap ? decoded ;
204273 if ( uri . IsFile )
@@ -207,30 +276,35 @@ private async Task LoadIconAsync()
207276 {
208277 // Avalonia's Bitmap (Skia) can't decode SVG/AVIF/ICO/TIFF — the
209278 // icon cache may produce those. Reject upfront so we don't throw.
210- _iconCache [ hash ] = null ;
279+ CacheIcon ( hash , null ) ;
211280 return ;
212281 }
213- decoded = await Task . Run ( ( ) => TryDecodeIcon ( uri . LocalPath ) ) . ConfigureAwait ( false ) ;
282+ decoded = await Task . Run ( ( ) => TryDecodeIcon ( uri . LocalPath ) , token ) . ConfigureAwait ( false ) ;
214283 }
215284 else if ( uri . Scheme is "http" or "https" )
216285 {
217- var bytes = await _iconHttpClient . GetByteArrayAsync ( uri ) . ConfigureAwait ( false ) ;
286+ var bytes = await _iconHttpClient . GetByteArrayAsync ( uri , token ) . ConfigureAwait ( false ) ;
218287 decoded = TryDecodeIcon ( bytes , uri . Host ) ;
219288 }
220- else { _iconCache [ hash ] = null ; return ; }
289+ else { CacheIcon ( hash , null ) ; return ; }
221290
222- if ( decoded is null ) { _iconCache [ hash ] = null ; return ; }
291+ if ( decoded is null ) { CacheIcon ( hash , null ) ; return ; }
223292 bitmap = decoded ;
224- _iconCache [ hash ] = bitmap ;
293+ CacheIcon ( hash , bitmap ) ;
225294 }
226295 finally
227296 {
228297 _iconLoadSemaphore . Release ( ) ;
229298 }
230299
231- await Dispatcher . UIThread . InvokeAsync ( ( ) => IconBitmap = bitmap ) ;
300+ if ( token . IsCancellationRequested ) return ;
301+ await Dispatcher . UIThread . InvokeAsync ( ( ) =>
302+ {
303+ if ( ! token . IsCancellationRequested ) IconBitmap = bitmap ;
304+ } ) ;
232305 }
233- catch { _iconCache [ hash ] = null ; }
306+ catch ( OperationCanceledException ) { /* row discarded before its icon finished loading */ }
307+ catch { CacheIcon ( hash , null ) ; }
234308 }
235309
236310 // Icons come from a shared on-disk cache that can hold empty or partial entries after an
@@ -239,18 +313,41 @@ private async Task LoadIconAsync()
239313 {
240314 var info = new FileInfo ( filePath ) ;
241315 if ( ! info . Exists || info . Length == 0 ) return null ;
242- return TryDecodeIcon ( ( ) => new Bitmap ( filePath ) , filePath ) ;
316+ return TryDecodeIcon ( ( ) => { using var fs = File . OpenRead ( filePath ) ; return DecodeDownscaled ( fs ) ; } , filePath ) ;
243317 }
244318
245319 private static Bitmap ? TryDecodeIcon ( byte [ ] bytes , string source )
246- => bytes . Length == 0 ? null : TryDecodeIcon ( ( ) => new Bitmap ( new MemoryStream ( bytes ) ) , source ) ;
320+ => bytes . Length == 0 ? null : TryDecodeIcon ( ( ) => { using var ms = new MemoryStream ( bytes ) ; return DecodeDownscaled ( ms ) ; } , source ) ;
247321
248322 private static Bitmap ? TryDecodeIcon ( Func < Bitmap > decode , string source )
249323 {
250324 try { return decode ( ) ; }
251325 catch ( Exception ex ) { Logger . Debug ( $ "Discarding undecodable icon '{ source } ': { ex . Message } ") ; return null ; }
252326 }
253327
328+ // Downscales oversized icons to MaxIconSide; small icons pass through (never upscaled).
329+ private static Bitmap DecodeDownscaled ( Stream stream )
330+ {
331+ var bitmap = new Bitmap ( stream ) ;
332+ PixelSize size = bitmap . PixelSize ;
333+ if ( size . Width <= MaxIconSide && size . Height <= MaxIconSide )
334+ return bitmap ;
335+
336+ double scale = ( double ) MaxIconSide / Math . Max ( size . Width , size . Height ) ;
337+ var target = new PixelSize (
338+ Math . Max ( 1 , ( int ) Math . Round ( size . Width * scale ) ) ,
339+ Math . Max ( 1 , ( int ) Math . Round ( size . Height * scale ) ) ) ;
340+
341+ try
342+ {
343+ return bitmap . CreateScaledBitmap ( target , BitmapInterpolationMode . HighQuality ) ;
344+ }
345+ finally
346+ {
347+ bitmap . Dispose ( ) ;
348+ }
349+ }
350+
254351 private static bool IsSkiaDecodableExtension ( string path )
255352 {
256353 string ext = Path . GetExtension ( path ) ;
@@ -314,6 +411,7 @@ public void Dispose()
314411 _installerHostCheckCts ? . Cancel ( ) ;
315412 _installerHostCheckCts ? . Dispose ( ) ;
316413 _installerHostCheckCts = null ;
414+ _lifetimeCts . Cancel ( ) ; // not disposed: a background load may still hold the token
317415 }
318416}
319417
0 commit comments