From 16441f2f0c7efdf087986226884587dadd37d359 Mon Sep 17 00:00:00 2001 From: Thenewmanator15 Date: Sat, 14 Nov 2026 23:14:30 +0000 Subject: [PATCH 1/5] Pause the open page's work while the window is off screen Pages only stopped their periodic work in OnLeave, which only navigation calls. So whichever page was open when the window was hidden to the tray (or minimized) kept running in the background for the rest of the session: the Software Catalog rescanned the installed and upgradable lists and stat'ed the catalog file every two seconds on the UI thread, Manager Health kept refreshing, the log pages kept the full log in memory, and Help / Release Notes kept a WebView2 process cluster alive. The main window now suspends the current page (OnLeave) when it goes off screen and resumes it (OnEnter) when it comes back. When the window is hidden rather than minimized, the WebView2 pages are also released and rebuilt on show. Settings pages are left alone: they do no background work and their OnLeave would reset them to the settings home page. --- .../ViewModels/MainWindowViewModel.cs | 58 ++++++++++++++++++- .../Views/MainWindow.axaml.cs | 15 ++++- 2 files changed, 71 insertions(+), 2 deletions(-) diff --git a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs index 83ca1b5709..ea86223d41 100644 --- a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs @@ -928,6 +928,57 @@ 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; + + /// + /// 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. + /// + /// + /// True when the window was hidden (not merely minimized): the WebView2 pages are then + /// dropped as well, and rebuilt when the window is shown again. + /// + public void SuspendForBackground(bool releaseWebViews) + { + var page = CurrentPageContent as Control; + + // Settings pages do no background work, and their OnLeave resets them to the settings + // home page, which would lose the user's place on every minimize. + if (page is SettingsBasePage) return; + + if (!_suspendedForBackground) + { + _suspendedForBackground = true; + (page as IEnterLeaveListener)?.OnLeave(); + } + + if (releaseWebViews && page is not null + && (ReferenceEquals(page, HelpPage) || ReferenceEquals(page, ReleaseNotesPage))) + { + CurrentPageContent = null; + ReleaseWebViewPage(page); + } + } + + /// + /// 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) + CurrentPageContent = GetPageForType(_currentPage); + (CurrentPageContent as IEnterLeaveListener)?.OnEnter(); + } + private Control GetPageForType(PageType type) => type switch { @@ -1050,7 +1101,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; diff --git a/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs b/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs index 2c81ed634c..76beac7cde 100644 --- a/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs +++ b/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs @@ -2411,7 +2411,20 @@ private void SetFocusedCaretVisible(bool visible) } private void UpdateOnScreenState() - => _isOnScreen = IsVisible && WindowState != WindowState.Minimized; + { + bool wasOnScreen = _isOnScreen; + _isOnScreen = IsVisible && WindowState != WindowState.Minimized; + 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(); + } public void ShowRuntimeNotification(string title, string message, RuntimeNotificationLevel level, string? launchAction = null) => ShowBanner(title, message, level, launchAction); From 5864a87ae5ddec572569273bd206990470be8690 Mon Sep 17 00:00:00 2001 From: Thenewmanator15 Date: Sun, 15 Nov 2026 00:32:12 +0000 Subject: [PATCH 2/5] Hand memory back to the OS once the app is idle in the background The garbage collector only runs when the app allocates. A UniGetUI sitting in the tray (or running headless) allocates almost nothing between update checks, so whatever a check left behind stayed in the heap as garbage until the next one, and the heap stayed at its high-water mark the whole time. A memory snapshot of an idle headless session showed the largest heap region full of dead data, such as the complete PyPI file listings pip's update check had parsed minutes earlier. IdleMemoryTrimmer runs one compacting collection once the app has been quiet for 20 seconds, and only while it is in the background (window hidden or minimized, or a headless session), so the user never pays for the pause. Package loaders request it when a load finishes, and the main window when it goes off screen. Measured on Linux with update checks every minute: the managed heap of a headless session returns to ~4 MB after each check, where it previously sat at 60-150 MB, and private memory holds at 41-53 MB where the same build without this kept climbing past 260 MB. --- .../Infrastructure/HeadlessDaemonHost.cs | 3 + .../ViewModels/MainWindowViewModel.cs | 4 + .../Views/MainWindow.axaml.cs | 2 + .../IdleMemoryTrimmerTests.cs | 79 +++++++++++++++++++ .../IdleMemoryTrimmer.cs | 77 ++++++++++++++++++ .../AbstractPackageLoader.cs | 4 + 6 files changed, 169 insertions(+) create mode 100644 src/UniGetUI.Core.Classes.Tests/IdleMemoryTrimmerTests.cs create mode 100644 src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs 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 ea86223d41..3441870251 100644 --- a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs @@ -16,6 +16,7 @@ using UniGetUI.Avalonia.Views.Pages.LogPages; using UniGetUI.Avalonia.Views.Pages.SettingsPages; using UniGetUI.Core.Data; +using UniGetUI.Core.Classes; using UniGetUI.Core.Logging; using UniGetUI.Core.SettingsEngine; using UniGetUI.Core.Tools; @@ -964,6 +965,9 @@ public void SuspendForBackground(bool releaseWebViews) CurrentPageContent = null; ReleaseWebViewPage(page); } + + // Whatever the window was showing is now garbage worth handing back. + IdleMemoryTrimmer.Request(); } /// diff --git a/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs b/src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs index 76beac7cde..db9bf610a2 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; @@ -257,6 +258,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 => { UpdateOnScreenState(); _ = SaveGeometryAsync(); }); 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..41323ea2e0 --- /dev/null +++ b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs @@ -0,0 +1,77 @@ +using System.Runtime; +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 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; + 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)" + ); + } +} 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(); } /// From 9062dea3915d4e32f785817b4c4dc6af5be0ee2b Mon Sep 17 00:00:00 2001 From: Thenewmanator15 Date: Sun, 15 Nov 2026 00:57:00 +0000 Subject: [PATCH 3/5] Return freed native memory to the system when trimming on Linux Memory freed by native code goes back to glibc's allocator, which keeps it for reuse rather than returning it to the system, so a long-running session crept up over many update checks even with the managed heap flat. The idle trim now also calls malloc_trim on Linux, and quietly stops trying on C libraries that do not have it (musl). Measured on a headless session checking for updates every minute: private memory settles at 20-22 MB, where it previously ranged over 41-53 MB and drifted upwards. --- .../IdleMemoryTrimmer.cs | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs index 41323ea2e0..9ce65dc5e7 100644 --- a/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs +++ b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs @@ -1,4 +1,5 @@ using System.Runtime; +using System.Runtime.InteropServices; using UniGetUI.Core.Logging; namespace UniGetUI.Core.Classes; @@ -68,10 +69,35 @@ public static void TrimNow() 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; + } + } + + [DllImport("libc")] + private static extern int malloc_trim(nuint pad); } From ea7b4ff396a50b85e95507c0d4787f618c6205cd Mon Sep 17 00:00:00 2001 From: TheNEwmanator15 <3686761+Thenewmanator15@users.noreply.github.com> Date: Mon, 16 Nov 2026 01:04:05 +0000 Subject: [PATCH 4/5] Fix formatting so the CI format gate passes The PR check fails on any whitespace or code-style diff; this is the part of the formatting fix that belongs to the commits on this branch. --- src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs index 3441870251..34e55f78ae 100644 --- a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs @@ -15,8 +15,8 @@ using UniGetUI.Avalonia.Views.Pages; using UniGetUI.Avalonia.Views.Pages.LogPages; using UniGetUI.Avalonia.Views.Pages.SettingsPages; -using UniGetUI.Core.Data; using UniGetUI.Core.Classes; +using UniGetUI.Core.Data; using UniGetUI.Core.Logging; using UniGetUI.Core.SettingsEngine; using UniGetUI.Core.Tools; From 39f04bc7c1fc099d7da56170427314885b58b41e Mon Sep 17 00:00:00 2001 From: TheNEwmanator15 <3686761+Thenewmanator15@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:58:08 +0000 Subject: [PATCH 5/5] Keep the user's place when the window is only minimized Review feedback on pausing the open page: - Help lost its place on minimize and restore: resuming called OnEnter, and HelpPage.OnEnter navigates back to the address the page was opened with, discarding any link followed since. Help and Release Notes do no periodic work, so they no longer get OnLeave/OnEnter at all. They are still dropped when the window is hidden to the tray, 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 now only happens when the window is hidden, not when it is minimized. - ShowHelp(url) while the Help page was released (window hidden, Help still the current page) dropped the address: NavigateToAsync returns early for the same page and there was no page to navigate. The address is now kept and applied when the page is rebuilt. - malloc_trim is declared with LibraryImport instead of DllImport, as the other libc imports in the repository are. UniGetUI.Core.Classes allows unsafe blocks for the generated marshalling code. --- .../ViewModels/MainWindowViewModel.cs | 55 +++++++++++++++---- .../IdleMemoryTrimmer.cs | 6 +- .../UniGetUI.Core.Classes.csproj | 2 + 3 files changed, 48 insertions(+), 15 deletions(-) diff --git a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs index 34e55f78ae..bee3807a1c 100644 --- a/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs +++ b/src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs @@ -933,6 +933,10 @@ private void ReleaseWebViewPage(Control? leftPage) // 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 @@ -940,36 +944,47 @@ private void ReleaseWebViewPage(Control? leftPage) /// 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): the WebView2 pages are then - /// dropped as well, and rebuilt when the window is shown again. + /// True when the window was hidden (not merely minimized). /// public void SuspendForBackground(bool releaseWebViews) { var page = CurrentPageContent as Control; + bool hidden = releaseWebViews; - // Settings pages do no background work, and their OnLeave resets them to the settings - // home page, which would lose the user's place on every minimize. if (page is SettingsBasePage) return; - if (!_suspendedForBackground) + if (page is not null && (ReferenceEquals(page, HelpPage) || ReferenceEquals(page, ReleaseNotesPage))) { - _suspendedForBackground = true; - (page as IEnterLeaveListener)?.OnLeave(); - } + if (!hidden) return; - if (releaseWebViews && page is not null - && (ReferenceEquals(page, HelpPage) || ReferenceEquals(page, ReleaseNotesPage))) - { + _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 . /// @@ -979,7 +994,17 @@ public void ResumeFromBackground() _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(); } @@ -1271,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.Core.Classes/IdleMemoryTrimmer.cs b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs index 9ce65dc5e7..855050c34f 100644 --- a/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs +++ b/src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs @@ -17,7 +17,7 @@ namespace UniGetUI.Core.Classes; /// 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 class IdleMemoryTrimmer +public static partial class IdleMemoryTrimmer { /// /// Whether nobody is looking at the app right now. The front-end sets it: a window that is @@ -98,6 +98,6 @@ private static void TrimNativeHeap() } } - [DllImport("libc")] - private static extern int malloc_trim(nuint pad); + [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