diff --git a/src/UniGetUI.Avalonia/Infrastructure/HeadlessDaemonHost.cs b/src/UniGetUI.Avalonia/Infrastructure/HeadlessDaemonHost.cs index 922c21e4f8..bbdd22e523 100644 --- a/src/UniGetUI.Avalonia/Infrastructure/HeadlessDaemonHost.cs +++ b/src/UniGetUI.Avalonia/Infrastructure/HeadlessDaemonHost.cs @@ -1,3 +1,4 @@ +using UniGetUI.Core.Classes; using UniGetUI.Interface; using UniGetUI.PackageEngine; using UniGetUI.PackageEngine.Classes.Packages.Classes; @@ -11,6 +12,8 @@ public static async Task RunAsync() return await HeadlessIpcHost.RunAsync(async () => { ProcessEnvironmentConfigurator.PrepareForCurrentPlatform(); + // Nobody is ever looking at a headless session. + IdleMemoryTrimmer.IsAppInBackground = static () => true; PEInterface.LoadLoaders(); await Task.WhenAll( Task.Run(ElevatorLoader.LoadAsync), diff --git a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs index 83ca1b5709..bee3807a1c 100644 --- a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs @@ -15,6 +15,7 @@ using UniGetUI.Avalonia.Views.Pages; using UniGetUI.Avalonia.Views.Pages.LogPages; using UniGetUI.Avalonia.Views.Pages.SettingsPages; +using UniGetUI.Core.Classes; using UniGetUI.Core.Data; using UniGetUI.Core.Logging; using UniGetUI.Core.SettingsEngine; @@ -928,6 +929,85 @@ private void ReleaseWebViewPage(Control? leftPage) else if (ReferenceEquals(leftPage, ReleaseNotesPage)) { ReleaseNotesPage?.Dispose(); ReleaseNotesPage = null; } } + // True while the window is off screen (hidden to the tray or minimized) and the current page + // has been told to stop its periodic work through OnLeave. + private bool _suspendedForBackground; + + // A Help address asked for while the Help page was released (window hidden to the tray); + // applied when the page is rebuilt. + private string? _pendingHelpAttachment; + + /// + /// Called when the main window goes off screen. Pages only stop their periodic work in + /// OnLeave, which navigation calls, so without this the page that was open when the window + /// was hidden to the tray kept running in the background indefinitely: the Software Catalog + /// rescans the installed and upgradable lists every two seconds, Manager Health keeps + /// refreshing, the log pages keep the whole log in memory, and Help / Release Notes keep a + /// WebView2 process cluster alive. + /// + /// What is done depends on how far away the window went, so that minimizing never costs the + /// user their place: + /// - Settings pages are never touched: their OnLeave resets them to the settings home page. + /// - Help and Release Notes do no periodic work, and Help's OnEnter goes back to the address + /// it was opened with, discarding any link followed since. They get no OnLeave/OnEnter; + /// they are only dropped when the window is hidden, and rebuilt when it is shown again. + /// - The log pages clear the log in OnLeave and reload it in OnEnter, which loses the scroll + /// position. That only happens when the window is hidden, not when it is minimized. + /// - Every other page is suspended in both cases. + /// + /// + /// True when the window was hidden (not merely minimized). + /// + public void SuspendForBackground(bool releaseWebViews) + { + var page = CurrentPageContent as Control; + bool hidden = releaseWebViews; + + if (page is SettingsBasePage) return; + + if (page is not null && (ReferenceEquals(page, HelpPage) || ReferenceEquals(page, ReleaseNotesPage))) + { + if (!hidden) return; + + _suspendedForBackground = true; + CurrentPageContent = null; + ReleaseWebViewPage(page); + } + else if (!_suspendedForBackground && (hidden || !IsLogPage(page))) + { + _suspendedForBackground = true; + (page as IEnterLeaveListener)?.OnLeave(); + } + + // Whatever the window was showing is now garbage worth handing back. + IdleMemoryTrimmer.Request(); + } + + private static bool IsLogPage(Control? page) => page is BaseLogPage or global::UniGetUI.Avalonia.Views.Pages.LogPages.OperationHistoryPage; + + /// + /// Called when the main window comes back on screen; undoes . + /// + public void ResumeFromBackground() + { + if (!_suspendedForBackground) return; + _suspendedForBackground = false; + + if (CurrentPageContent is null && _currentPage is not PageType.Null) + { + // A released Help or Release Notes page: a new one loads its own start address. + CurrentPageContent = GetPageForType(_currentPage); + if (_pendingHelpAttachment is { } attachment) + { + _pendingHelpAttachment = null; + HelpPage?.NavigateTo(attachment); + } + return; + } + + (CurrentPageContent as IEnterLeaveListener)?.OnEnter(); + } + private Control GetPageForType(PageType type) => type switch { @@ -1050,7 +1130,12 @@ public async Task NavigateToAsync( if (oldPage is ISearchBoxPage oldSPage) oldSPage.QueryBackup = GlobalSearchText; - (oldPage as IEnterLeaveListener)?.OnLeave(); + // A page suspended while the window was off screen has already left; navigating + // (e.g. from a tray or toast action) ends the suspension instead of leaving it twice. + if (_suspendedForBackground) + _suspendedForBackground = false; + else + (oldPage as IEnterLeaveListener)?.OnLeave(); CurrentPageContent = newPage; _oldPage = _currentPage; @@ -1211,7 +1296,13 @@ private async Task ShowHelpAsync(string uriAttachment) { if (!await NavigateToAsync(PageType.Help)) return; - HelpPage?.NavigateTo(uriAttachment); + + // Help is already the current page but was released while the window is hidden: there + // is no page to navigate yet, so keep the address for when it is rebuilt. + if (HelpPage is null) + _pendingHelpAttachment = uriAttachment; + else + HelpPage.NavigateTo(uriAttachment); } public async Task LoadCloudBundleAsync(string content) diff --git a/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs b/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs index 06e48198c4..c51d3d3eda 100644 --- a/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs +++ b/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs @@ -21,6 +21,7 @@ using UniGetUI.Avalonia.Views.Controls; using UniGetUI.Avalonia.Views.DialogPages; using UniGetUI.Avalonia.Views.Pages; +using UniGetUI.Core.Classes; using UniGetUI.Core.Logging; using UniGetUI.Core.SettingsEngine; using UniGetUI.Core.Tools; @@ -259,6 +260,7 @@ public MainWindow() Resized += (_, _) => _ = SaveGeometryAsync(); ModalLayer.SizeChanged += (_, _) => UpdateModalSurfaceSize(); PositionChanged += (_, _) => _ = SaveGeometryAsync(); + IdleMemoryTrimmer.IsAppInBackground = static () => !_isOnScreen; Activated += (_, _) => SetFocusedCaretVisible(true); Deactivated += (_, _) => SetFocusedCaretVisible(false); this.GetObservable(WindowStateProperty).SubscribeValue(state => { SyncShowWindowState(state); UpdateOnScreenState(); _ = SaveGeometryAsync(); }); @@ -2503,8 +2505,19 @@ private void SetFocusedCaretVisible(bool visible) private void UpdateOnScreenState() { + bool wasOnScreen = _isOnScreen; _isOnScreen = IsVisible && WindowState != WindowState.Minimized; BackgroundEfficiencyMode.Refresh(); + if (DataContext is not MainWindowViewModel viewModel) + return; + + // Stop the open page's periodic work while nobody can see it (see SuspendForBackground). + // Suspending again is harmless, and lets a minimized window that is then hidden to the + // tray release its web views too. + if (!_isOnScreen) + viewModel.SuspendForBackground(releaseWebViews: !IsVisible); + else if (!wasOnScreen) + viewModel.ResumeFromBackground(); } private void SyncShowWindowState(WindowState state) diff --git a/src/UniGetUI.Core.Classes.Tests/IdleMemoryTrimmerTests.cs b/src/UniGetUI.Core.Classes.Tests/IdleMemoryTrimmerTests.cs new file mode 100644 index 0000000000..373903ebcc --- /dev/null +++ b/src/UniGetUI.Core.Classes.Tests/IdleMemoryTrimmerTests.cs @@ -0,0 +1,79 @@ +namespace UniGetUI.Core.Classes.Tests; + +public sealed class IdleMemoryTrimmerTests : IDisposable +{ + private readonly Func _originalIsAppInBackground = IdleMemoryTrimmer.IsAppInBackground; + private readonly TimeSpan _originalQuietPeriod = IdleMemoryTrimmer.QuietPeriod; + + public void Dispose() + { + IdleMemoryTrimmer.IsAppInBackground = _originalIsAppInBackground; + IdleMemoryTrimmer.QuietPeriod = _originalQuietPeriod; + } + + private static async Task WaitForTrimCountAsync(int expected, int timeoutMs) + { + var watch = System.Diagnostics.Stopwatch.StartNew(); + while (watch.ElapsedMilliseconds < timeoutMs) + { + if (IdleMemoryTrimmer.TrimCount >= expected) + return true; + await Task.Delay(20); + } + return IdleMemoryTrimmer.TrimCount >= expected; + } + + [Fact] + public async Task TrimsOnceTheAppHasBeenQuietInTheBackground() + { + IdleMemoryTrimmer.IsAppInBackground = static () => true; + IdleMemoryTrimmer.QuietPeriod = TimeSpan.FromMilliseconds(50); + int before = IdleMemoryTrimmer.TrimCount; + + IdleMemoryTrimmer.Request(); + + Assert.True(await WaitForTrimCountAsync(before + 1, 5000)); + } + + [Fact] + public async Task DoesNotTrimWhileTheAppIsInTheForeground() + { + IdleMemoryTrimmer.IsAppInBackground = static () => false; + IdleMemoryTrimmer.QuietPeriod = TimeSpan.FromMilliseconds(50); + int before = IdleMemoryTrimmer.TrimCount; + + IdleMemoryTrimmer.Request(); + await Task.Delay(500); + + Assert.Equal(before, IdleMemoryTrimmer.TrimCount); + } + + [Fact] + public async Task ABurstOfRequestsTrimsOnlyOnce() + { + IdleMemoryTrimmer.IsAppInBackground = static () => true; + IdleMemoryTrimmer.QuietPeriod = TimeSpan.FromMilliseconds(300); + int before = IdleMemoryTrimmer.TrimCount; + + for (int i = 0; i < 25; i++) + IdleMemoryTrimmer.Request(); + + Assert.True(await WaitForTrimCountAsync(before + 1, 5000)); + await Task.Delay(700); + Assert.Equal(before + 1, IdleMemoryTrimmer.TrimCount); + } + + [Fact] + public void TrimNowReleasesUnreachableMemory() + { + var garbage = new List(); + for (int i = 0; i < 64; i++) + garbage.Add(new byte[1024 * 1024]); + long withGarbage = GC.GetTotalMemory(forceFullCollection: false); + garbage.Clear(); + + IdleMemoryTrimmer.TrimNow(); + + Assert.True(GC.GetTotalMemory(forceFullCollection: false) < withGarbage - (32L * 1024 * 1024)); + } +} diff --git a/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs new file mode 100644 index 0000000000..855050c34f --- /dev/null +++ b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs @@ -0,0 +1,103 @@ +using System.Runtime; +using System.Runtime.InteropServices; +using UniGetUI.Core.Logging; + +namespace UniGetUI.Core.Classes; + +/// +/// Hands memory back to the operating system once the app has gone quiet in the background. +/// +/// The garbage collector only runs when the app allocates. A UniGetUI sitting in the tray +/// allocates almost nothing between update checks, so everything a check left behind (command +/// output, parsed package indexes, package lists it replaced) stayed in the heap as garbage +/// until the next check, and the heap stayed at its high-water mark the whole time. +/// +/// Work that leaves such garbage calls when it finishes. Once no further +/// request has arrived for , and only while the app is in the +/// background, one compacting collection runs and the freed memory is released. Nothing happens +/// while the user is looking at the window, where a blocking collection would only cost a pause. +/// +public static partial class IdleMemoryTrimmer +{ + /// + /// Whether nobody is looking at the app right now. The front-end sets it: a window that is + /// hidden or minimized, or a headless session. Defaults to "no", which disables trimming. + /// + public static Func IsAppInBackground { get; set; } = static () => false; + + /// How long the app must stay quiet after the last request before trimming. + public static TimeSpan QuietPeriod { get; set; } = TimeSpan.FromSeconds(20); + + private static long _lastRequest; + + /// The number of trims performed since the process started. + public static int TrimCount => Volatile.Read(ref _trimCount); + private static int _trimCount; + + /// + /// Asks for a trim once the app has been quiet for . Cheap and safe + /// to call often, from any thread: a later request replaces the ones before it. + /// + public static void Request() + { + long request = Interlocked.Increment(ref _lastRequest); + TimeSpan delay = QuietPeriod; + _ = Task.Run(async () => + { + try + { + await Task.Delay(delay).ConfigureAwait(false); + if (request != Interlocked.Read(ref _lastRequest) || !IsAppInBackground()) + return; + + TrimNow(); + } + catch (Exception ex) + { + Logger.Warn("Could not trim memory while idle"); + Logger.Warn(ex); + } + }); + } + + /// Collects and compacts the whole heap now, and releases what that frees. + public static void TrimNow() + { + long before = GC.GetTotalMemory(forceFullCollection: false); + long committedBefore = GC.GetGCMemoryInfo().TotalCommittedBytes; + GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; + GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, blocking: true, compacting: true); + long after = GC.GetTotalMemory(forceFullCollection: false); + long committedAfter = GC.GetGCMemoryInfo().TotalCommittedBytes; + TrimNativeHeap(); + Interlocked.Increment(ref _trimCount); + Logger.Debug( + $"Trimmed memory while idle: managed heap {before / 1048576.0:F1} MB -> {after / 1048576.0:F1} MB" + + $" (committed {committedBefore / 1048576.0:F1} MB -> {committedAfter / 1048576.0:F1} MB)" + ); + } + + // On Linux, memory freed by native code (the runtime itself, TLS, compression, child + // process plumbing) goes back to glibc's allocator, which keeps it for reuse rather than + // returning it to the system, so the process creeps up over many update checks. + // malloc_trim hands those free pages back. Other C libraries (musl) do not have it. + private static bool _nativeTrimUnavailable; + + private static void TrimNativeHeap() + { + if (!OperatingSystem.IsLinux() || _nativeTrimUnavailable) + return; + + try + { + _ = malloc_trim(0); + } + catch (Exception ex) when (ex is EntryPointNotFoundException or DllNotFoundException) + { + _nativeTrimUnavailable = true; + } + } + + [LibraryImport("libc")] + private static partial int malloc_trim(nuint pad); +} diff --git a/src/UniGetUI.Core.Classes/UniGetUI.Core.Classes.csproj b/src/UniGetUI.Core.Classes/UniGetUI.Core.Classes.csproj index b66c05a73b..c9fd4b986f 100644 --- a/src/UniGetUI.Core.Classes/UniGetUI.Core.Classes.csproj +++ b/src/UniGetUI.Core.Classes/UniGetUI.Core.Classes.csproj @@ -1,6 +1,8 @@ $(SharedTargetFrameworks) + + true diff --git a/src/UniGetUI.PackageEngine.PackageLoader/AbstractPackageLoader.cs b/src/UniGetUI.PackageEngine.PackageLoader/AbstractPackageLoader.cs index f16869804e..93da2548f3 100644 --- a/src/UniGetUI.PackageEngine.PackageLoader/AbstractPackageLoader.cs +++ b/src/UniGetUI.PackageEngine.PackageLoader/AbstractPackageLoader.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using UniGetUI.Core.Classes; using UniGetUI.Core.Logging; using UniGetUI.Core.Tools; using UniGetUI.PackageEngine.Interfaces; @@ -179,6 +180,9 @@ protected void InvokeStartedLoadingEvent() protected void InvokeFinishedLoadingEvent() { FinishedLoading?.Invoke(this, EventArgs.Empty); + + // A load leaves the managers' output and the list it replaced behind as garbage. + IdleMemoryTrimmer.Request(); } ///