diff --git a/src/UniGetUI.Avalonia/Infrastructure/MemoryTrimmer.cs b/src/UniGetUI.Avalonia/Infrastructure/MemoryTrimmer.cs new file mode 100644 index 0000000000..04499a21b0 --- /dev/null +++ b/src/UniGetUI.Avalonia/Infrastructure/MemoryTrimmer.cs @@ -0,0 +1,82 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Avalonia.Threading; +using UniGetUI.Core.Logging; + +namespace UniGetUI.Avalonia.Infrastructure; + +// Collects and returns the working set to the OS once loading has settled — neither .NET nor the +// native allocator hand freed memory back on their own. Debounced so it never runs mid-load. +// Windows-only, best-effort. +internal static class MemoryTrimmer +{ + private static readonly TimeSpan SettleDelay = TimeSpan.FromSeconds(3); + private static DispatcherTimer? _timer; + + public static void RequestTrimAfterIdle() + { + if (!OperatingSystem.IsWindows()) return; + if (!Dispatcher.UIThread.CheckAccess()) + { + Dispatcher.UIThread.Post(RequestTrimAfterIdle); + return; + } + + _timer ??= CreateTimer(); + _timer.Stop(); + _timer.Start(); + } + + public static void CancelPending() + { + if (!OperatingSystem.IsWindows()) return; + if (!Dispatcher.UIThread.CheckAccess()) + { + Dispatcher.UIThread.Post(CancelPending); + return; + } + + _timer?.Stop(); + } + + private static DispatcherTimer CreateTimer() + { + var timer = new DispatcherTimer { Interval = SettleDelay }; + timer.Tick += (_, _) => + { + timer.Stop(); + Trim(); + }; + return timer; + } + + private static void Trim() => _ = Task.Run(() => + { + try + { + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + GC.WaitForPendingFinalizers(); + GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, blocking: true); + NativeMethods.SetProcessWorkingSetSize(NativeMethods.GetCurrentProcess(), -1, -1); + } + catch (Exception ex) + { + Logger.Warn($"Post-load working-set trim failed: {ex.Message}"); + } + }); + + private static class NativeMethods + { + [DllImport("kernel32.dll")] + public static extern nint GetCurrentProcess(); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static extern bool SetProcessWorkingSetSize( + nint hProcess, + nint dwMinimumWorkingSetSize, + nint dwMaximumWorkingSetSize + ); + } +} diff --git a/src/UniGetUI.Avalonia/Models/PackageCollections.cs b/src/UniGetUI.Avalonia/Models/PackageCollections.cs index b008c68bcd..b2220f5d61 100644 --- a/src/UniGetUI.Avalonia/Models/PackageCollections.cs +++ b/src/UniGetUI.Avalonia/Models/PackageCollections.cs @@ -1,7 +1,7 @@ -using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.ComponentModel; using System.Net.Http; +using Avalonia; using Avalonia.Collections; using Avalonia.Media.Imaging; using Avalonia.Threading; @@ -27,8 +27,66 @@ public sealed class PackageWrapper : INotifyPropertyChanged, IDisposable { Timeout = TimeSpan.FromSeconds(8), }; - private static readonly ConcurrentDictionary _iconCache = new(); - private static readonly SemaphoreSlim _iconLoadSemaphore = new(4, 4); + private static readonly SemaphoreSlim _iconLoadSemaphore = new(8, 8); + + // Cap decoded icon size; the list shows icons at ≤64px (128 covers 2x DPI). + private const int MaxIconSide = 128; + + // Bounded LRU by package hash. Evicted entries aren't disposed: a visible row may still + // reference the bitmap, so dropping it here only makes it GC-eligible. + private const int MaxIconCacheEntries = 512; + private static readonly object _iconCacheLock = new(); + private static readonly Dictionary> _iconCache = new(); + private static readonly LinkedList<(long Hash, Bitmap? Bitmap)> _iconCacheOrder = new(); + + private static bool TryGetCachedIcon(long hash, out Bitmap? bitmap) + { + lock (_iconCacheLock) + { + if (_iconCache.TryGetValue(hash, out var node)) + { + _iconCacheOrder.Remove(node); + _iconCacheOrder.AddFirst(node); + bitmap = node.Value.Bitmap; + return true; + } + } + bitmap = null; + return false; + } + + private static void CacheIcon(long hash, Bitmap? bitmap) + { + lock (_iconCacheLock) + { + if (_iconCache.TryGetValue(hash, out var existing)) + { + existing.Value = (hash, bitmap); + _iconCacheOrder.Remove(existing); + _iconCacheOrder.AddFirst(existing); + return; + } + + var node = new LinkedListNode<(long, Bitmap?)>((hash, bitmap)); + _iconCache[hash] = node; + _iconCacheOrder.AddFirst(node); + + while (_iconCache.Count > MaxIconCacheEntries && _iconCacheOrder.Last is { } last) + { + _iconCacheOrder.RemoveLast(); + _iconCache.Remove(last.Value.Hash); + } + } + } + + public static void ClearIconCache() + { + lock (_iconCacheLock) + { + _iconCache.Clear(); + _iconCacheOrder.Clear(); + } + } public IPackage Package { get; } public PackageWrapper Self => this; @@ -73,6 +131,8 @@ public bool IsChecked public string InstallerHostChangeTooltip { get; private set; } = ""; private CancellationTokenSource? _installerHostCheckCts; + // Cancels this row's queued/in-flight icon load on disposal so it stops rooting the wrapper. + private readonly CancellationTokenSource _lifetimeCts = new(); public string SourceIconPath => IconTypeToSvgPath(Package.Source.IconId); @@ -102,12 +162,20 @@ public PackageWrapper(IPackage package, PackagesPageViewModel page) Package.PropertyChanged += Package_PropertyChanged; UpdateDisplayState(); - if (!Settings.Get(Settings.K.DisableIconsOnPackageLists)) - _ = LoadIconAsync(); - + // Icons load lazily per visible row (see EnsureIconLoaded), not eagerly for every result. MaybeStartInstallerHostCheck(); } + private int _iconLoadStarted; + + /// Loads this row's icon at most once; called when the row becomes visible. + public void EnsureIconLoaded() + { + if (Settings.Get(Settings.K.DisableIconsOnPackageLists)) return; + if (Interlocked.Exchange(ref _iconLoadStarted, 1) != 0) return; + _ = LoadIconAsync(); + } + /// /// For upgradable WinGet packages, asynchronously fetches the installer URL host for /// both the installed and the new version, and flags the row when the hosts differ. @@ -183,8 +251,9 @@ await Dispatcher.UIThread.InvokeAsync(() => private async Task LoadIconAsync() { + CancellationToken token = _lifetimeCts.Token; long hash = Package.GetHash(); - if (_iconCache.TryGetValue(hash, out Bitmap? cached)) + if (TryGetCachedIcon(hash, out Bitmap? cached)) { if (cached is not null) IconBitmap = cached; @@ -193,12 +262,12 @@ private async Task LoadIconAsync() try { - await _iconLoadSemaphore.WaitAsync().ConfigureAwait(false); + await _iconLoadSemaphore.WaitAsync(token).ConfigureAwait(false); Bitmap bitmap; try { - var uri = await Task.Run(Package.GetIconUrlIfAny).ConfigureAwait(false); - if (uri is null) { _iconCache[hash] = null; return; } + var uri = await Task.Run(Package.GetIconUrlIfAny, token).ConfigureAwait(false); + if (uri is null) { CacheIcon(hash, null); return; } Bitmap? decoded; if (uri.IsFile) @@ -207,30 +276,35 @@ private async Task LoadIconAsync() { // Avalonia's Bitmap (Skia) can't decode SVG/AVIF/ICO/TIFF — the // icon cache may produce those. Reject upfront so we don't throw. - _iconCache[hash] = null; + CacheIcon(hash, null); return; } - decoded = await Task.Run(() => TryDecodeIcon(uri.LocalPath)).ConfigureAwait(false); + decoded = await Task.Run(() => TryDecodeIcon(uri.LocalPath), token).ConfigureAwait(false); } else if (uri.Scheme is "http" or "https") { - var bytes = await _iconHttpClient.GetByteArrayAsync(uri).ConfigureAwait(false); + var bytes = await _iconHttpClient.GetByteArrayAsync(uri, token).ConfigureAwait(false); decoded = TryDecodeIcon(bytes, uri.Host); } - else { _iconCache[hash] = null; return; } + else { CacheIcon(hash, null); return; } - if (decoded is null) { _iconCache[hash] = null; return; } + if (decoded is null) { CacheIcon(hash, null); return; } bitmap = decoded; - _iconCache[hash] = bitmap; + CacheIcon(hash, bitmap); } finally { _iconLoadSemaphore.Release(); } - await Dispatcher.UIThread.InvokeAsync(() => IconBitmap = bitmap); + if (token.IsCancellationRequested) return; + await Dispatcher.UIThread.InvokeAsync(() => + { + if (!token.IsCancellationRequested) IconBitmap = bitmap; + }); } - catch { _iconCache[hash] = null; } + catch (OperationCanceledException) { /* row discarded before its icon finished loading */ } + catch { CacheIcon(hash, null); } } // Icons come from a shared on-disk cache that can hold empty or partial entries after an @@ -239,11 +313,11 @@ private async Task LoadIconAsync() { var info = new FileInfo(filePath); if (!info.Exists || info.Length == 0) return null; - return TryDecodeIcon(() => new Bitmap(filePath), filePath); + return TryDecodeIcon(() => { using var fs = File.OpenRead(filePath); return DecodeDownscaled(fs); }, filePath); } private static Bitmap? TryDecodeIcon(byte[] bytes, string source) - => bytes.Length == 0 ? null : TryDecodeIcon(() => new Bitmap(new MemoryStream(bytes)), source); + => bytes.Length == 0 ? null : TryDecodeIcon(() => { using var ms = new MemoryStream(bytes); return DecodeDownscaled(ms); }, source); private static Bitmap? TryDecodeIcon(Func decode, string source) { @@ -251,6 +325,29 @@ private async Task LoadIconAsync() catch (Exception ex) { Logger.Debug($"Discarding undecodable icon '{source}': {ex.Message}"); return null; } } + // Downscales oversized icons to MaxIconSide; small icons pass through (never upscaled). + private static Bitmap DecodeDownscaled(Stream stream) + { + var bitmap = new Bitmap(stream); + PixelSize size = bitmap.PixelSize; + if (size.Width <= MaxIconSide && size.Height <= MaxIconSide) + return bitmap; + + double scale = (double)MaxIconSide / Math.Max(size.Width, size.Height); + var target = new PixelSize( + Math.Max(1, (int)Math.Round(size.Width * scale)), + Math.Max(1, (int)Math.Round(size.Height * scale))); + + try + { + return bitmap.CreateScaledBitmap(target, BitmapInterpolationMode.HighQuality); + } + finally + { + bitmap.Dispose(); + } + } + private static bool IsSkiaDecodableExtension(string path) { string ext = Path.GetExtension(path); @@ -314,6 +411,7 @@ public void Dispose() _installerHostCheckCts?.Cancel(); _installerHostCheckCts?.Dispose(); _installerHostCheckCts = null; + _lifetimeCts.Cancel(); // not disposed: a background load may still hold the token } } diff --git a/src/UniGetUI.Avalonia/UniGetUI.Avalonia.csproj b/src/UniGetUI.Avalonia/UniGetUI.Avalonia.csproj index b4ca7fdb92..b0875d7cc2 100644 --- a/src/UniGetUI.Avalonia/UniGetUI.Avalonia.csproj +++ b/src/UniGetUI.Avalonia/UniGetUI.Avalonia.csproj @@ -34,6 +34,11 @@ false + + + + + $(NoWarn);MVVMTK0045;AVLN3001 @@ -229,6 +234,7 @@ + diff --git a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs index 6adf890334..3c998b23c6 100644 --- a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs @@ -199,9 +199,16 @@ public MainWindowViewModel() if (loader is null) continue; var pt = pageType; loader.FinishedLoading += (_, _) => + { Dispatcher.UIThread.Post(() => Sidebar.SetNavItemLoading(pt, false)); + // Return the load's memory to the OS once it settles. + Infrastructure.MemoryTrimmer.RequestTrimAfterIdle(); + }; loader.StartedLoading += (_, _) => + { Dispatcher.UIThread.Post(() => Sidebar.SetNavItemLoading(pt, true)); + Infrastructure.MemoryTrimmer.CancelPending(); + }; Sidebar.SetNavItemLoading(pt, loader.IsLoading); } diff --git a/src/UniGetUI.Avalonia/ViewModels/Pages/SettingsPages/Interface_PViewModel.cs b/src/UniGetUI.Avalonia/ViewModels/Pages/SettingsPages/Interface_PViewModel.cs index c85d3d372a..bc74d87248 100644 --- a/src/UniGetUI.Avalonia/ViewModels/Pages/SettingsPages/Interface_PViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/Pages/SettingsPages/Interface_PViewModel.cs @@ -34,6 +34,7 @@ private async Task ResetIconCache(Visual? _) { try { Directory.Delete(CoreData.UniGetUICacheDirectory_Icons, true); } catch (Exception ex) { Logger.Error(ex); } + global::UniGetUI.PackageEngine.PackageClasses.PackageWrapper.ClearIconCache(); RestartRequired?.Invoke(this, EventArgs.Empty); await LoadIconCacheSize(); } diff --git a/src/UniGetUI.Avalonia/Views/Controls/PackageIconLoader.cs b/src/UniGetUI.Avalonia/Views/Controls/PackageIconLoader.cs new file mode 100644 index 0000000000..706b3cb8f7 --- /dev/null +++ b/src/UniGetUI.Avalonia/Views/Controls/PackageIconLoader.cs @@ -0,0 +1,50 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using UniGetUI.PackageEngine.PackageClasses; + +namespace UniGetUI.Avalonia.Views.Controls; + +// Calls PackageWrapper.EnsureIconLoaded when the icon element attaches or is rebound, so only +// realized (visible) rows in the virtualized list load their icons. +public static class PackageIconLoader +{ + public static readonly AttachedProperty TrackProperty = + AvaloniaProperty.RegisterAttached("Track", typeof(PackageIconLoader)); + + public static void SetTrack(Control control, bool value) => control.SetValue(TrackProperty, value); + public static bool GetTrack(Control control) => control.GetValue(TrackProperty); + + static PackageIconLoader() + { + TrackProperty.Changed.AddClassHandler((control, e) => + { + if (e.GetNewValue()) + { + control.AttachedToVisualTree += OnAttached; + control.DataContextChanged += OnDataContextChanged; + if (control.IsLoaded) TryLoad(control); + } + else + { + control.AttachedToVisualTree -= OnAttached; + control.DataContextChanged -= OnDataContextChanged; + } + }); + } + + private static void OnAttached(object? sender, VisualTreeAttachmentEventArgs e) + => TryLoad((Control)sender!); + + private static void OnDataContextChanged(object? sender, EventArgs e) + { + var control = (Control)sender!; + // A recycled container also fires this while detached; only load when realized. + if (control.IsLoaded) TryLoad(control); + } + + private static void TryLoad(Control control) + { + if (control.DataContext is PackageWrapper wrapper) wrapper.EnsureIconLoaded(); + } +} diff --git a/src/UniGetUI.Avalonia/Views/SoftwarePages/AbstractPackagesPage.axaml b/src/UniGetUI.Avalonia/Views/SoftwarePages/AbstractPackagesPage.axaml index 81f3562520..27ae1d3aae 100644 --- a/src/UniGetUI.Avalonia/Views/SoftwarePages/AbstractPackagesPage.axaml +++ b/src/UniGetUI.Avalonia/Views/SoftwarePages/AbstractPackagesPage.axaml @@ -525,7 +525,8 @@ - + + VerticalAlignment="Center" HorizontalAlignment="Center" + controls:PackageIconLoader.Track="True"> + VerticalAlignment="Center" HorizontalAlignment="Center" + controls:PackageIconLoader.Track="True"> FindPackages_UnSafe(string query) Manager.Status.ExecutableCallArgs + " search \"" + query - + "\" --accept-source-agreements " + + "\" --count " + + MAX_SEARCH_RESULTS + + " --accept-source-agreements " + WinGet.GetProxyArgument(), RedirectStandardOutput = true, RedirectStandardError = true, diff --git a/src/UniGetUI.PackageEngine.PackageLoader/DiscoverablePackagesLoader.cs b/src/UniGetUI.PackageEngine.PackageLoader/DiscoverablePackagesLoader.cs index 2a5d2e69ef..4ad94f68e8 100644 --- a/src/UniGetUI.PackageEngine.PackageLoader/DiscoverablePackagesLoader.cs +++ b/src/UniGetUI.PackageEngine.PackageLoader/DiscoverablePackagesLoader.cs @@ -8,6 +8,10 @@ public class DiscoverablePackagesLoader : AbstractPackageLoader { public static DiscoverablePackagesLoader Instance = null!; + // Cap results per manager; a broad query across every enabled manager otherwise wraps, + // tags and renders thousands of packages, freezing the UI and spiking RAM. + private const int MAX_RESULTS_PER_MANAGER = 100; + private string QUERY_TEXT = string.Empty; private volatile bool _pendingReload; @@ -70,7 +74,10 @@ protected override IReadOnlyList LoadPackagesFromManager(IPackageManag return []; } - return manager.FindPackages(text); + IReadOnlyList found = manager.FindPackages(text); + return found.Count > MAX_RESULTS_PER_MANAGER + ? found.Take(MAX_RESULTS_PER_MANAGER).ToArray() + : found; } protected override Task WhenAddingPackage(IPackage package) diff --git a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs index 9ae3929d1b..31ec77f1d6 100644 --- a/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs +++ b/src/UniGetUI.PackageEngine.PackageManagerClasses/Manager/Classes/ManagerLogger.cs @@ -9,10 +9,12 @@ public class ManagerLogger : IManagerLogger { private readonly IPackageManager Manager; + // Keep only recent operations; retained unbounded, each holds its full output and grows forever. + private const int MAX_RETAINED_OPERATIONS = 100; private readonly List operations = []; public IReadOnlyList Operations { - get => (IReadOnlyList)operations; + get { lock (operations) return operations.ToArray(); } } public ManagerLogger(IPackageManager manager) @@ -20,6 +22,16 @@ public ManagerLogger(IPackageManager manager) Manager = manager; } + private void Register(TaskLogger operation) + { + lock (operations) + { + operations.Add(operation); + if (operations.Count > MAX_RETAINED_OPERATIONS) + operations.RemoveRange(0, operations.Count - MAX_RETAINED_OPERATIONS); + } + } + public IProcessTaskLogger CreateNew(LoggableTaskType type, Process process) { if (process.StartInfo is null) @@ -35,20 +47,31 @@ public IProcessTaskLogger CreateNew(LoggableTaskType type, Process process) process.StartInfo.FileName, process.StartInfo.Arguments ); - operations.Add(operation); + Register(operation); return operation; } public INativeTaskLogger CreateNew(LoggableTaskType type) { NativeTaskLogger operation = new(Manager, type); - operations.Add(operation); + Register(operation); return operation; } } public abstract class TaskLogger : ITaskLogger { + // Cap retained output per stream (chunk-trimmed to keep appending O(1)); a search can emit thousands of lines. + protected const int MaxRetainedLines = 1000; + private const int TrimSlack = 256; + + protected static void AppendCapped(List target, string line) + { + target.Add(line); + if (target.Count > MaxRetainedLines + TrimSlack) + target.RemoveRange(0, target.Count - MaxRetainedLines); + } + protected DateTime StartTime; protected DateTime? EndTime; protected bool isComplete; @@ -167,7 +190,7 @@ public void AddToStdOut(IReadOnlyList lines) { if (line != "") { - StdOut.Add(line); + AppendCapped(StdOut, line); } } } @@ -193,7 +216,7 @@ public void AddToStdErr(IReadOnlyList lines) { if (line != "") { - StdErr.Add(line); + AppendCapped(StdErr, line); } } } @@ -325,7 +348,7 @@ public void Log(IReadOnlyList lines) { if (line != "") { - Info.Add(line); + AppendCapped(Info, line); } } } @@ -351,7 +374,7 @@ public void Error(IReadOnlyList lines) { if (line != "") { - Errors.Add(line); + AppendCapped(Errors, line); } } }