Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/UniGetUI.Avalonia/Infrastructure/HeadlessDaemonHost.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using UniGetUI.Core.Classes;
using UniGetUI.Interface;
using UniGetUI.PackageEngine;
using UniGetUI.PackageEngine.Classes.Packages.Classes;
Expand All @@ -11,6 +12,8 @@ public static async Task<int> 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),
Expand Down
95 changes: 93 additions & 2 deletions src/UniGetUI.Avalonia/ViewModels/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

/// <summary>
/// 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.
/// </summary>
/// <param name="releaseWebViews">
/// True when the window was hidden (not merely minimized).
/// </param>
public void SuspendForBackground(bool releaseWebViews)
{
var page = CurrentPageContent as Control;
bool hidden = releaseWebViews;

if (page is SettingsBasePage) return;
Comment thread
Thenewmanator15 marked this conversation as resolved.
Resolved

if (page is not null && (ReferenceEquals(page, HelpPage) || ReferenceEquals(page, ReleaseNotesPage)))
{
if (!hidden) return;

_suspendedForBackground = true;
CurrentPageContent = null;
Comment thread
Thenewmanator15 marked this conversation as resolved.
Resolved
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;

/// <summary>
/// Called when the main window comes back on screen; undoes <see cref="SuspendForBackground"/>.
/// </summary>
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
{
Expand Down Expand Up @@ -1050,7 +1130,12 @@ public async Task<bool> 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;
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions src/UniGetUI.Avalonia/Views/MainWindow.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(); });
Expand Down Expand Up @@ -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)
Expand Down
79 changes: 79 additions & 0 deletions src/UniGetUI.Core.Classes.Tests/IdleMemoryTrimmerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
namespace UniGetUI.Core.Classes.Tests;

public sealed class IdleMemoryTrimmerTests : IDisposable
{
private readonly Func<bool> _originalIsAppInBackground = IdleMemoryTrimmer.IsAppInBackground;
private readonly TimeSpan _originalQuietPeriod = IdleMemoryTrimmer.QuietPeriod;

public void Dispose()
{
IdleMemoryTrimmer.IsAppInBackground = _originalIsAppInBackground;
IdleMemoryTrimmer.QuietPeriod = _originalQuietPeriod;
}

private static async Task<bool> 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<byte[]>();
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));
}
}
103 changes: 103 additions & 0 deletions src/UniGetUI.Core.Classes/IdleMemoryTrimmer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using System.Runtime;
using System.Runtime.InteropServices;
using UniGetUI.Core.Logging;

namespace UniGetUI.Core.Classes;

/// <summary>
/// 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 <see cref="Request"/> when it finishes. Once no further
/// request has arrived for <see cref="QuietPeriod"/>, 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.
/// </summary>
public static partial class IdleMemoryTrimmer
{
/// <summary>
/// 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.
/// </summary>
public static Func<bool> IsAppInBackground { get; set; } = static () => false;

/// <summary>How long the app must stay quiet after the last request before trimming.</summary>
public static TimeSpan QuietPeriod { get; set; } = TimeSpan.FromSeconds(20);

private static long _lastRequest;

/// <summary>The number of trims performed since the process started.</summary>
public static int TrimCount => Volatile.Read(ref _trimCount);
private static int _trimCount;

/// <summary>
/// Asks for a trim once the app has been quiet for <see cref="QuietPeriod"/>. Cheap and safe
/// to call often, from any thread: a later request replaces the ones before it.
/// </summary>
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);
}
});
}

/// <summary>Collects and compacts the whole heap now, and releases what that frees.</summary>
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);
}
2 changes: 2 additions & 0 deletions src/UniGetUI.Core.Classes/UniGetUI.Core.Classes.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(SharedTargetFrameworks)</TargetFrameworks>
<!-- LibraryImport (IdleMemoryTrimmer) generates unsafe marshalling code. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using UniGetUI.Core.Classes;
using UniGetUI.Core.Logging;
using UniGetUI.Core.Tools;
using UniGetUI.PackageEngine.Interfaces;
Expand Down Expand Up @@ -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();
}

/// <summary>
Expand Down
Loading