Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Release the main window in the tray and give memory back when idle

KnifeLemona524a699dba0
diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.cs
index 9ad8ebec..7ec9e56f 100644
--- a/src/Filee.App/App.axaml.cs
+++ b/src/Filee.App/App.axaml.cs
@@ -111,6 +111,7 @@ public partial class App : Application
desktop.Exit += (_, _) =>
{
+ AppHost.Get<MemoryTrimmer>().Dispose();
AppHost.Get<TriggerService>().Dispose();
AppHost.Get<TrayService>().Dispose();
AppHost.Get<WatchFolderService>().DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(5));
diff --git a/src/Filee.App/Services/AppHost.cs b/src/Filee.App/Services/AppHost.cs
index 5b03168f..8575f197 100644
--- a/src/Filee.App/Services/AppHost.cs
+++ b/src/Filee.App/Services/AppHost.cs
@@ -65,8 +65,8 @@ public static class AppHost
services.AddSingleton<RadialController>();
services.AddSingleton<TrayService>();
services.AddSingleton<UpdateService>();
+ services.AddSingleton<MemoryTrimmer>();
services.AddSingleton<WindowService>();
- services.AddSingleton<MainWindowViewModel>();
_services = services.BuildServiceProvider();
return _services;
diff --git a/src/Filee.App/Services/MemoryTrimmer.cs b/src/Filee.App/Services/MemoryTrimmer.cs
new file mode 100644
index 00000000..635e7663
--- /dev/null
+++ b/src/Filee.App/Services/MemoryTrimmer.cs
@@ -0,0 +1,115 @@
+// Gives memory back while Filee waits in the tray (issue #119): a while after the last conversion finished, and after
+// the main window was released. Large images grow the managed heap and the engines' caches, and the garbage collector
+// keeps that memory committed for the next allocation, so Filee stayed hundreds of MB above its idle size.
+
+using System.Diagnostics;
+using System.Runtime;
+using Filee.Core.Conversion;
+using Filee.Engines.Infrastructure;
+using Filee.Platform.Windows;
+using Microsoft.Extensions.Logging;
+
+namespace Filee.App.Services;
+
+public sealed class MemoryTrimmer : IDisposable
+{
+ /// <summary>How long no conversion may have run before memory is trimmed.</summary>
+ public static readonly TimeSpan IdleDelay = TimeSpan.FromSeconds(30);
+
+ private readonly Func<bool> _busy;
+ private readonly Action _trim;
+ private readonly TimeSpan _delay;
+ private readonly Timer _timer;
+ private readonly Lock _lock = new();
+ private bool _requested;
+ private bool _disposed;
+ private int _trims;
+
+ public MemoryTrimmer(JobQueue queue, ILogger<MemoryTrimmer> log)
+ : this(() => queue.IsBusy, () => Trim(log), IdleDelay)
+ {
+ queue.JobFinished += (_, _) => Request();
+ }
+
+ internal MemoryTrimmer(Func<bool> busy, Action trim, TimeSpan delay)
+ {
+ _busy = busy;
+ _trim = trim;
+ _delay = delay;
+ _timer = new Timer(_ => OnQuiet());
+ }
+
+ /// <summary>How often memory was trimmed.</summary>
+ internal int Trims => Volatile.Read(ref _trims);
+
+ /// <summary>
+ /// Memory was freed (a job finished, the main window closed): trim once <see cref="IdleDelay"/> has passed without
+ /// another request and no conversion runs. A request meanwhile moves the time on; nothing happens without one.
+ /// </summary>
+ public void Request()
+ {
+ lock (_lock)
+ {
+ if (_disposed)
+ return;
+ _requested = true;
+ _timer.Change(_delay, Timeout.InfiniteTimeSpan);
+ }
+ }
+
+ private void OnQuiet()
+ {
+ lock (_lock)
+ {
+ if (!_requested || _disposed)
+ return;
+ if (_busy())
+ {
+ // A conversion started meanwhile: never during one. Look again later (its end requests too).
+ _timer.Change(_delay, Timeout.InfiniteTimeSpan);
+ return;
+ }
+ _requested = false;
+ }
+ _trim();
+ Interlocked.Increment(ref _trims);
+ }
+
+ /// <summary>Drops the engines' caches, collects and compacts every heap, then trims the working set (Windows).</summary>
+ internal static void Trim(ILogger log)
+ {
+ try
+ {
+ var watch = Stopwatch.StartNew();
+ var before = PrivateMegabytes();
+ EngineCaches.Release();
+ GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
+ // Aggressive also decommits the free memory the collector would keep for later (about 5 MB more here).
+ GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, blocking: true, compacting: true);
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ ProcessMemory.TrimWorkingSet();
+ log.LogInformation("Trimmed memory: private {Before} MB → {After} MB (managed heap {Heap} MB) in {Elapsed} ms",
+ before, PrivateMegabytes(), GC.GetTotalMemory(false) / (1024 * 1024), watch.ElapsedMilliseconds);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ log.LogWarning(ex, "Could not trim memory");
+ }
+ }
+
+ private static long PrivateMegabytes()
+ {
+ using var process = Process.GetCurrentProcess();
+ return process.PrivateMemorySize64 / (1024 * 1024);
+ }
+
+ public void Dispose()
+ {
+ lock (_lock)
+ {
+ _disposed = true;
+ _timer.Dispose();
+ }
+ }
+}
diff --git a/src/Filee.App/Services/Motion.cs b/src/Filee.App/Services/Motion.cs
index 5b19cb77..db141a98 100644
--- a/src/Filee.App/Services/Motion.cs
+++ b/src/Filee.App/Services/Motion.cs
@@ -66,7 +66,10 @@ public static class Motion
public static void Track(Window window)
{
lock (Windows)
+ {
+ Windows.RemoveAll(w => !w.TryGetTarget(out _)); // the main window is a new one each time it opens
Windows.Add(new WeakReference<Window>(window));
+ }
Apply(window);
}
diff --git a/src/Filee.App/Services/WindowService.cs b/src/Filee.App/Services/WindowService.cs
index 1c23eec7..9548a42c 100644
--- a/src/Filee.App/Services/WindowService.cs
+++ b/src/Filee.App/Services/WindowService.cs
@@ -14,9 +14,10 @@ using Microsoft.Extensions.DependencyInjection;
namespace Filee.App.Services;
-public sealed class WindowService(ILocalizer loc, IServiceProvider services)
+public sealed class WindowService(ILocalizer loc, IServiceProvider services, MemoryTrimmer trimmer)
{
private MainWindow? _main;
+ private MainWindowPlacement? _mainPlacement;
private ToastWindow? _toast;
private EngineSetupWindow? _engineSetup;
private UpdateNoticeWindow? _updateNotice;
@@ -25,14 +26,32 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)
public MainWindow? Main => _main;
- /// <summary>Shows (or brings to front) the main window, optionally on a page.</summary>
+ /// <summary>
+ /// Shows (or brings to front) the main window, optionally on a page. Going to the tray closes it
+ /// (<see cref="MainWindow.HideToTray"/>): a new one opens where and on the page the last one was.
+ /// </summary>
public void ShowMain(string? page = null)
{
Motion.Refresh();
if (_main is null)
{
- _main = new MainWindow { DataContext = services.GetRequiredService<MainWindowViewModel>() };
- _main.Closed += (_, _) => _main = null;
+ var model = ActivatorUtilities.CreateInstance<MainWindowViewModel>(services);
+ var main = new MainWindow { DataContext = model };
+ if (_mainPlacement is { } placement)
+ {
+ placement.ApplyTo(main);
+ if (page is null)
+ model.Navigate(placement.Page);
+ }
+ main.Closing += (_, _) => _mainPlacement = MainWindowPlacement.Of(main, model, _mainPlacement);
+ main.Closed += (_, _) =>
+ {
+ if (_main == main)
+ _main = null;
+ model.Dispose();
+ trimmer.Request();
+ };
+ _main = main;
}
if (page is not null && _main.DataContext is MainWindowViewModel vm)
vm.Navigate(page);
@@ -248,4 +267,34 @@ public sealed class WindowService(ILocalizer loc, IServiceProvider services)
private static Window? MainWindowOrNull() =>
(Application.Current?.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.MainWindow;
+
+ /// <summary>Where the main window was and which page it showed, for the next one.</summary>
+ private sealed record MainWindowPlacement(PixelPoint? Position, Size? Size, bool Maximized, string Page)
+ {
+ /// <summary>The window's placement. Maximized or minimized, it keeps the position and size it had before.</summary>
+ public static MainWindowPlacement Of(MainWindow window, MainWindowViewModel vm, MainWindowPlacement? last) =>
+ window.WindowState switch
+ {
+ WindowState.Normal => new(window.Position, window.ClientSize, false, vm.SelectedItem.Key),
+ WindowState.Maximized => (last ?? new(null, null, false, "")) with { Maximized = true, Page = vm.SelectedItem.Key },
+ _ => (last ?? new(null, null, false, "")) with { Page = vm.SelectedItem.Key },
+ };
+
+ public void ApplyTo(MainWindow window)
+ {
+ // Only on a screen that is still there (a monitor may have been unplugged since).
+ if (Position is { } position && window.Screens.ScreenFromPoint(position) is not null)
+ {
+ window.WindowStartupLocation = WindowStartupLocation.Manual;
+ window.Position = position;
+ }
+ if (Size is { } size)
+ {
+ window.Width = size.Width;
+ window.Height = size.Height;
+ }
+ if (Maximized)
+ window.WindowState = WindowState.Maximized;
+ }
+ }
}
diff --git a/src/Filee.App/ViewModels/MainWindowViewModel.cs b/src/Filee.App/ViewModels/MainWindowViewModel.cs
index c64dcc4f..f5c2befd 100644
--- a/src/Filee.App/ViewModels/MainWindowViewModel.cs
+++ b/src/Filee.App/ViewModels/MainWindowViewModel.cs
@@ -26,10 +26,15 @@ public sealed partial class NavItem(string key, string titleKey, string iconKey,
public void Refresh(ILocalizer loc) => Title = loc[TitleKey];
}
-public sealed partial class MainWindowViewModel : ObservableObject
+/// <summary>
+/// One per main window (<see cref="WindowService.ShowMain"/>); disposed with it, which drops its subscriptions on the
+/// long-lived services and the current page.
+/// </summary>
+public sealed partial class MainWindowViewModel : ObservableObject, IDisposable
{
private readonly IServiceProvider _services;
private readonly ILocalizer _loc;
+ private bool _disposed;
/// <summary>The repository, for the GitHub button above the version.</summary>
public string RepositoryUrl => UpdateService.RepositoryUrl;
@@ -39,11 +44,7 @@ public sealed partial class MainWindowViewModel : ObservableObject
_services = services;
_loc = loc;
Updates = updates;
- updates.PropertyChanged += (_, e) =>
- {
- if (UpdateTexts.Affects(e.PropertyName))
- RefreshVersionTexts();
- };
+ updates.PropertyChanged += OnUpdatesChanged;
RefreshVersionTexts();
Items =
[
@@ -59,13 +60,7 @@ public sealed partial class MainWindowViewModel : ObservableObject
];
foreach (var item in Items)
item.Refresh(loc);
- loc.LanguageChanged += (_, _) =>
- {
- foreach (var item in Items)
- item.Refresh(loc);
- RefreshVersionTexts();
- CurrentPage = CreatePage(SelectedItem); // rebuild so code-generated labels update too
- };
+ loc.LanguageChanged += OnLanguageChanged;
_selectedItem = Items[0];
_currentPage = CreatePage(Items[0]);
}
@@ -93,6 +88,20 @@ public sealed partial class MainWindowViewModel : ObservableObject
[RelayCommand]
private Task DownloadUpdate() => Updates.UpdateAsync();
+ private void OnUpdatesChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
+ {
+ if (UpdateTexts.Affects(e.PropertyName))
+ RefreshVersionTexts();
+ }
+
+ private void OnLanguageChanged(object? sender, EventArgs e)
+ {
+ foreach (var item in Items)
+ item.Refresh(_loc);
+ RefreshVersionTexts();
+ CurrentPage = CreatePage(SelectedItem); // rebuild so code-generated labels update too
+ }
+
private void RefreshVersionTexts()
{
VersionText = _loc.Format("about.version", UpdateService.CurrentVersion);
@@ -117,4 +126,14 @@ public sealed partial class MainWindowViewModel : ObservableObject
private ObservableObject CreatePage(NavItem item) =>
(ObservableObject)ActivatorUtilities.CreateInstance(_services, item.PageType);
+
+ public void Dispose()
+ {
+ if (_disposed)
+ return;
+ _disposed = true;
+ Updates.PropertyChanged -= OnUpdatesChanged;
+ _loc.LanguageChanged -= OnLanguageChanged;
+ (CurrentPage as IDisposable)?.Dispose();
+ }
}
diff --git a/src/Filee.App/Views/MainWindow.axaml.cs b/src/Filee.App/Views/MainWindow.axaml.cs
index eeed08a7..e21e9f49 100644
--- a/src/Filee.App/Views/MainWindow.axaml.cs
+++ b/src/Filee.App/Views/MainWindow.axaml.cs
@@ -1,5 +1,6 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
+using Avalonia.Threading;
using Filee.App.Services;
using Filee.App.ViewModels;
using Filee.Core.Localization;
@@ -8,6 +9,9 @@ namespace Filee.App.Views;
public partial class MainWindow : Window
{
+ private bool _releasePosted;
+ private bool _releasing;
+
public MainWindow()
{
InitializeComponent();
@@ -27,10 +31,31 @@ public partial class MainWindow : Window
protected override void OnClosing(WindowClosingEventArgs e)
{
base.OnClosing(e);
- if (e.CloseReason is WindowCloseReason.WindowClosing)
+ if (e.CloseReason is WindowCloseReason.WindowClosing && !_releasing)
{
e.Cancel = true;
- Hide();
+ HideToTray();
}
}
+
+ /// <summary>
+ /// Leaves Filee in the tray: hides the window at once, then closes it for real, so its pages, visuals and images
+ /// don't stay in memory until the next time (issue #119). <see cref="WindowService.ShowMain"/> opens a new one.
+ /// </summary>
+ internal void HideToTray()
+ {
+ Hide();
+ if (_releasePosted)
+ return;
+ _releasePosted = true;
+ // Posted: a window can't close inside its own Closing handler.
+ Dispatcher.UIThread.Post(() =>
+ {
+ _releasePosted = false;
+ if (IsVisible)
+ return; // shown again meanwhile
+ _releasing = true;
+ Close();
+ });
+ }
}
diff --git a/src/Filee.Core/Conversion/JobQueue.cs b/src/Filee.Core/Conversion/JobQueue.cs
index 590f3337..010dbe55 100644
--- a/src/Filee.Core/Conversion/JobQueue.cs
+++ b/src/Filee.Core/Conversion/JobQueue.cs
@@ -22,6 +22,7 @@ public sealed class JobQueue : IAsyncDisposable
private readonly ConcurrentDictionary<string, SemaphoreSlim> _engineGates = new();
private readonly HashSet<string> _reservedOutputs = new(StringComparer.OrdinalIgnoreCase);
private readonly Task _worker;
+ private int _busy;
/// <param name="catalog">Converters and their priority.</param>
/// <param name="pdfMerger">Used by "Merge into one PDF" presets.</param>
@@ -45,10 +46,14 @@ public sealed class JobQueue : IAsyncDisposable
/// <summary>Raised (on a background thread) once when a job reaches a final state.</summary>
public event EventHandler<ConversionJob>? JobFinished;
+ /// <summary>True while a job waits in the queue or runs (the app frees memory only when this is false).</summary>
+ public bool IsBusy => Volatile.Read(ref _busy) > 0;
+
/// <summary>Adds a job to the queue and returns it immediately.</summary>
public ConversionJob Enqueue(IReadOnlyList<string> sources, Preset preset, string presetDisplayName)
{
var job = new ConversionJob(sources, preset, presetDisplayName);
+ Interlocked.Increment(ref _busy); // until the worker is done with it
_channel.Writer.TryWrite(job);
JobUpdated?.Invoke(this, job);
return job;
@@ -56,6 +61,19 @@ public sealed class JobQueue : IAsyncDisposable
/// <summary>Runs a job to completion on the calling task. Used by tests and by <see cref="Enqueue"/>'s worker.</summary>
public async Task RunAsync(ConversionJob job)
+ {
+ Interlocked.Increment(ref _busy);
+ try
+ {
+ await RunJobAsync(job);
+ }
+ finally
+ {
+ Interlocked.Decrement(ref _busy);
+ }
+ }
+
+ private async Task RunJobAsync(ConversionJob job)
{
job.State = JobState.Running;
Notify(job);
@@ -457,14 +475,21 @@ public sealed class JobQueue : IAsyncDisposable
{
await foreach (var job in _channel.Reader.ReadAllAsync())
{
- if (job.CancellationToken.IsCancellationRequested)
+ try
+ {
+ if (job.CancellationToken.IsCancellationRequested)
+ {
+ job.State = JobState.Cancelled;
+ Notify(job);
+ JobFinished?.Invoke(this, job);
+ continue;
+ }
+ await RunAsync(job);
+ }
+ finally
{
- job.State = JobState.Cancelled;
- Notify(job);
- JobFinished?.Invoke(this, job);
- continue;
+ Interlocked.Decrement(ref _busy);
}
- await RunAsync(job);
}
}
diff --git a/src/Filee.Engines/Cad/CadFonts.cs b/src/Filee.Engines/Cad/CadFonts.cs
index 81def30a..eeca4ada 100644
--- a/src/Filee.Engines/Cad/CadFonts.cs
+++ b/src/Filee.Engines/Cad/CadFonts.cs
@@ -62,6 +62,21 @@ internal static class CadFonts
[ThreadStatic]
private static Dictionary<SKTypeface, SKFont>? _measuringFonts;
+ // Bumped by ReleaseCache: each thread drops its measuring fonts the next time it measures (only it may touch them).
+ private static int _generation;
+ [ThreadStatic]
+ private static int _measuringGeneration;
+
+ /// <summary>Forgets the typefaces looked up so far (<see cref="Infrastructure.EngineCaches.Release"/>).</summary>
+ internal static void ReleaseCache()
+ {
+ Interlocked.Increment(ref _generation);
+ Families.Clear();
+ Fallbacks.Clear();
+ Defaults.Clear();
+ FontMetrics.Clear();
+ }
+
/// <summary>
/// The typeface for a text style: its TrueType family if installed (family name or font file), else the
/// default sans-serif typeface. Never null.
@@ -140,6 +155,14 @@ internal static class CadFonts
/// </summary>
private static SKFont MeasuringFont(SKTypeface typeface)
{
+ var generation = Volatile.Read(ref _generation);
+ if (_measuringFonts is not null && _measuringGeneration != generation)
+ {
+ foreach (var old in _measuringFonts.Values)
+ old.Dispose();
+ _measuringFonts = null;
+ }
+ _measuringGeneration = generation;
_measuringFonts ??= [];
if (!_measuringFonts.TryGetValue(typeface, out var font))
_measuringFonts[typeface] = font = CreateFont(typeface, MeasureSize);
diff --git a/src/Filee.Engines/Hwp/RhwpFonts.cs b/src/Filee.Engines/Hwp/RhwpFonts.cs
index c3056c4c..ed191e19 100644
--- a/src/Filee.Engines/Hwp/RhwpFonts.cs
+++ b/src/Filee.Engines/Hwp/RhwpFonts.cs
@@ -55,6 +55,9 @@ internal static class RhwpFonts
private static readonly ConcurrentDictionary<string, InstalledFont?> Fonts = new(StringComparer.OrdinalIgnoreCase);
+ /// <summary>Forgets the fonts looked up so far (<see cref="Infrastructure.EngineCaches.Release"/>).</summary>
+ internal static void ReleaseCache() => Fonts.Clear();
+
/// <summary>Replacements by (slot, face): the language, coverage and CFF2 rules above.</summary>
internal static Dictionary<(string Slot, string Face), string> Plan(
IReadOnlyList<(string Slot, string Face)> slots, string text, Func<string, InstalledFont?> lookup)
diff --git a/src/Filee.Engines/Infrastructure/EngineCaches.cs b/src/Filee.Engines/Infrastructure/EngineCaches.cs
new file mode 100644
index 00000000..f73fca9d
--- /dev/null
+++ b/src/Filee.Engines/Infrastructure/EngineCaches.cs
@@ -0,0 +1,23 @@
+// Caches engines keep between conversions (typefaces looked up for HWP and CAD text, Skia's glyph and resource
+// caches). The app releases them while no conversion runs, so a Filee waiting in the tray gives the memory back.
+
+using Filee.Engines.Cad;
+using Filee.Engines.Hwp;
+using SkiaSharp;
+
+namespace Filee.Engines.Infrastructure;
+
+public static class EngineCaches
+{
+ /// <summary>
+ /// Drops what the engines cache between conversions. Call only while no conversion runs: the next one looks
+ /// everything up again.
+ /// </summary>
+ public static void Release()
+ {
+ RhwpFonts.ReleaseCache();
+ CadFonts.ReleaseCache();
+ // Skia's caches are shared with the UI's renderer and guarded by Skia itself; they refill on demand.
+ SKGraphics.PurgeAllCaches();
+ }
+}
diff --git a/src/Filee.Platform.Windows/NativeMethods.cs b/src/Filee.Platform.Windows/NativeMethods.cs
index b4521c18..d78133ca 100644
--- a/src/Filee.Platform.Windows/NativeMethods.cs
+++ b/src/Filee.Platform.Windows/NativeMethods.cs
@@ -48,6 +48,13 @@ internal static partial class NativeMethods
[LibraryImport("user32.dll")]
public static partial int GetSystemMetrics(int index);
+ [LibraryImport("kernel32.dll")]
+ public static partial nint GetCurrentProcess();
+
+ [LibraryImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ public static partial bool SetProcessWorkingSetSize(nint process, nint minimumSize, nint maximumSize);
+
[LibraryImport("user32.dll", EntryPoint = "SystemParametersInfoW")]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool SystemParametersInfo(uint action, uint param, [MarshalAs(UnmanagedType.Bool)] out bool value, uint winIni);
diff --git a/src/Filee.Platform.Windows/ProcessMemory.cs b/src/Filee.Platform.Windows/ProcessMemory.cs
new file mode 100644
index 00000000..c693aa1e
--- /dev/null
+++ b/src/Filee.Platform.Windows/ProcessMemory.cs
@@ -0,0 +1,14 @@
+// Hands the pages of this process back to Windows once it is idle in the tray, so Task Manager shows what Filee
+// really needs instead of what the last conversion touched.
+
+namespace Filee.Platform.Windows;
+
+public static class ProcessMemory
+{
+ /// <summary>
+ /// Removes as many pages as possible from the working set (they come back on use). No-op off Windows; false when
+ /// Windows refused.
+ /// </summary>
+ public static bool TrimWorkingSet() =>
+ !OperatingSystem.IsWindows() || NativeMethods.SetProcessWorkingSetSize(NativeMethods.GetCurrentProcess(), -1, -1);
+}
diff --git a/tests/Filee.App.Tests/MainWindowReleaseTests.cs b/tests/Filee.App.Tests/MainWindowReleaseTests.cs
new file mode 100644
index 00000000..51126fab
--- /dev/null
+++ b/tests/Filee.App.Tests/MainWindowReleaseTests.cs
@@ -0,0 +1,103 @@
+// Going to the tray releases the main window (issue #119): the next "Open" builds a new one, where and on the page the
+// last one was, and nothing keeps the old window, its view model or its page alive.
+
+using System.Runtime.CompilerServices;
+using Avalonia;
+using Avalonia.Headless;
+using Avalonia.Headless.XUnit;
+using Avalonia.Threading;
+using Filee.App.Services;
+using Filee.App.ViewModels;
+using Filee.App.Views;
+
+namespace Filee.App.Tests;
+
+public class MainWindowReleaseTests
+{
+ private static void Pump()
+ {
+ for (var i = 0; i < 20; i++)
+ {
+ Dispatcher.UIThread.RunJobs();
+ AvaloniaHeadlessPlatform.ForceRenderTimerTick();
+ }
+ }
+
+ [AvaloniaFact]
+ public void Closing_to_the_tray_releases_the_window_and_open_builds_a_new_one_where_it_was()
+ {
+ TestServices.EnsureInitialized("en");
+ var windows = AppHost.Get<WindowService>();
+ var (window, model, page) = OpenMoveAndClose(windows);
+ Assert.Null(windows.Main);
+
+ windows.ShowMain();
+ Pump();
+ var second = windows.Main!;
+ Assert.True(second.IsVisible);
+ Assert.Equal("watch", ((MainWindowViewModel)second.DataContext!).SelectedItem.Key);
+ Assert.Equal(new PixelPoint(140, 90), second.Position);
+ Assert.Equal(new Size(900, 640), second.ClientSize);
+
+ // Nothing holds the closed window, its view model or its page any more.
+ for (var i = 0; i < 3; i++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ Pump();
+ }
+ Assert.False(window.TryGetTarget(out _), "window");
+ Assert.False(model.TryGetTarget(out _), "view model");
+ Assert.False(page.TryGetTarget(out _), "page");
+
+ second.Close();
+ Pump();
+ Assert.Null(windows.Main);
+ }
+
+ [AvaloniaFact]
+ public void A_window_shown_again_before_it_was_released_stays_open()
+ {
+ TestServices.EnsureInitialized("en");
+ var windows = AppHost.Get<WindowService>();
+ windows.ShowMain();
+ Pump();
+ var main = windows.Main!;
+
+ main.Close();
+ windows.ShowMain(); // e.g. the tray's Open, handled before the posted release
+ Pump();
+ Assert.Same(main, windows.Main);
+ Assert.True(main.IsVisible);
+
+ main.Close();
+ Pump();
+ Assert.Null(windows.Main);
+ }
+
+ // Not inlined: nothing on the test's stack may hold the first window when it is collected.
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static (WeakReference<MainWindow>, WeakReference<MainWindowViewModel>, WeakReference<object>) OpenMoveAndClose(WindowService windows)
+ {
+ windows.ShowMain("watch");
+ Pump();
+ var main = windows.Main!;
+ main.Position = new PixelPoint(140, 90);
+ main.Width = 900;
+ main.Height = 640;
+ Pump();
+ var model = (MainWindowViewModel)main.DataContext!;
+ var page = model.CurrentPage;
+
+ main.Close(); // as the title bar's close button
+ Pump();
+ Assert.False(main.IsVisible);
+ main.Close(); // again, e.g. a test cleaning up: harmless
+ Pump();
+ // The old view model no longer follows the language (it would rebuild its page).
+ AppHost.Get<LocalizationService>().SetLanguage("ko");
+ Assert.Same(page, model.CurrentPage);
+ AppHost.Get<LocalizationService>().SetLanguage("en");
+ return (new(main), new(model), new(page));
+ }
+}
diff --git a/tests/Filee.App.Tests/MemoryTrimmerTests.cs b/tests/Filee.App.Tests/MemoryTrimmerTests.cs
new file mode 100644
index 00000000..8e2665e2
--- /dev/null
+++ b/tests/Filee.App.Tests/MemoryTrimmerTests.cs
@@ -0,0 +1,62 @@
+// Memory is given back once conversions are over: after a quiet spell, never while one runs, and not again without
+// a new reason.
+
+using Filee.App.Services;
+
+namespace Filee.App.Tests;
+
+public class MemoryTrimmerTests
+{
+ private static readonly TimeSpan Delay = TimeSpan.FromMilliseconds(100);
+
+ private static async Task Until(Func<bool> condition)
+ {
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
+ while (!condition() && DateTime.UtcNow < deadline)
+ await Task.Delay(10, TestContext.Current.CancellationToken);
+ }
+
+ [Fact]
+ public async Task Trims_once_after_a_quiet_spell_and_not_again_without_a_request()
+ {
+ using var trimmer = new MemoryTrimmer(() => false, () => { }, Delay);
+ await Task.Delay(Delay * 3, TestContext.Current.CancellationToken);
+ Assert.Equal(0, trimmer.Trims); // nothing happened yet
+
+ trimmer.Request();
+ trimmer.Request();
+ await Until(() => trimmer.Trims > 0);
+ await Task.Delay(Delay * 3, TestContext.Current.CancellationToken);
+ Assert.Equal(1, trimmer.Trims);
+ }
+
+ [Fact]
+ public async Task Never_trims_while_a_conversion_runs()
+ {
+ var busy = true;
+ var trimmedWhileBusy = false;
+ using var trimmer = new MemoryTrimmer(() => Volatile.Read(ref busy), () => trimmedWhileBusy |= Volatile.Read(ref busy), Delay);
+ trimmer.Request();
+ await Task.Delay(Delay * 5, TestContext.Current.CancellationToken);
+ Assert.Equal(0, trimmer.Trims);
+
+ Volatile.Write(ref busy, false);
+ await Until(() => trimmer.Trims > 0);
+ Assert.Equal(1, trimmer.Trims);
+ Assert.False(trimmedWhileBusy);
+ }
+
+ [Fact]
+ public async Task A_new_request_moves_the_trim_on()
+ {
+ using var trimmer = new MemoryTrimmer(() => false, () => { }, TimeSpan.FromSeconds(2));
+ for (var i = 0; i < 5; i++)
+ {
+ trimmer.Request();
+ await Task.Delay(100, TestContext.Current.CancellationToken);
+ }
+ Assert.Equal(0, trimmer.Trims); // a conversion finishing every 100 ms: still converting
+ await Until(() => trimmer.Trims > 0);
+ Assert.Equal(1, trimmer.Trims);
+ }
+}
diff --git a/tests/Filee.Core.Tests/JobQueueTests.cs b/tests/Filee.Core.Tests/JobQueueTests.cs
index 4c3d302d..b21b311c 100644
--- a/tests/Filee.Core.Tests/JobQueueTests.cs
+++ b/tests/Filee.Core.Tests/JobQueueTests.cs
@@ -28,6 +28,47 @@ public class JobQueueTests
Assert.Equal(1, job.Progress);
}
+ [Fact]
+ public async Task Is_busy_from_enqueueing_until_the_job_has_finished()
+ {
+ // The app frees memory only while the queue is idle: a waiting or running job must count.
+ using var dir = new TempDir();
+ var gate = new TaskCompletionSource();
+ await using var queue = new JobQueue(new ConverterCatalog([new GatedConverter(gate.Task, new ConversionEdge("jpg", "png"))]));
+ var busyWhenFinished = new TaskCompletionSource<bool>();
+ queue.JobFinished += (_, _) => busyWhenFinished.TrySetResult(queue.IsBusy);
+ Assert.False(queue.IsBusy);
+
+ queue.Enqueue([dir.File("a.jpg")], new Preset { TargetFormat = "png" }, "Test");
+ Assert.True(queue.IsBusy);
+ await Task.Delay(100, TestContext.Current.CancellationToken);
+ Assert.True(queue.IsBusy);
+
+ gate.SetResult();
+ Assert.True(await busyWhenFinished.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken));
+ var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
+ while (queue.IsBusy && DateTime.UtcNow < deadline)
+ await Task.Delay(10, TestContext.Current.CancellationToken);
+ Assert.False(queue.IsBusy);
+ }
+
+ /// <summary>Converts like <see cref="FakeConverter"/> once the gate opens.</summary>
+ private sealed class GatedConverter(Task gate, params ConversionEdge[] edges) : IConverter
+ {
+ private readonly FakeConverter _inner = new("gated", edges);
+ public string Id => "gated";
+ public string DisplayName => "gated";
+ public IReadOnlyList<ConversionEdge> Edges => edges;
+ public int MaxParallelism => 0;
+ public EngineStatus GetStatus() => EngineStatus.Available();
+
+ public async Task<IReadOnlyList<string>> ConvertAsync(ConversionStep step, IProgress<double>? progress, CancellationToken cancellationToken)
+ {
+ await gate;
+ return await _inner.ConvertAsync(step, progress, cancellationToken);
+ }
+ }
+
[Fact]
public async Task Rotate_needs_an_engine_that_turns_images_and_turns_once_on_a_longer_route()
{
diff --git a/tests/Filee.Engines.Tests/CadTests.cs b/tests/Filee.Engines.Tests/CadTests.cs
index 0578c57a..dd576d18 100644
--- a/tests/Filee.Engines.Tests/CadTests.cs
+++ b/tests/Filee.Engines.Tests/CadTests.cs
@@ -357,6 +357,15 @@ public class CadTests(EngineFixture fx) : IClassFixture<EngineFixture>
Assert.Contains(runs, r => r.Text.Contains('A') && r.Typeface.ContainsGlyph('A'));
}
+ [Fact]
+ public void Text_measures_the_same_after_the_idle_app_released_the_caches()
+ {
+ var before = CadFonts.Layout("도면 ABC", CadFonts.Resolve(null, false, false)).Select(r => (r.Text, r.Advance)).ToList();
+ Filee.Engines.Infrastructure.EngineCaches.Release();
+ var after = CadFonts.Layout("도면 ABC", CadFonts.Resolve(null, false, false)).Select(r => (r.Text, r.Advance)).ToList();
+ Assert.Equal(before, after);
+ }
+
// ───────────────────────── Helpers ─────────────────────────
private static IEnumerable<OpCodeName> Operators(CSequence sequence)