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.

Keep the cursor moving while Filee converts or quits (#511, #528)

cre8ive-marketingb3a34e86f292
diff --git a/src/Filee.App/Services/Triggers/QueuedGlobalHook.cs b/src/Filee.App/Services/Triggers/QueuedGlobalHook.cs
new file mode 100644
index 00000000..fafceb32
--- /dev/null
+++ b/src/Filee.App/Services/Triggers/QueuedGlobalHook.cs
@@ -0,0 +1,64 @@
+// SharpHook's EventLoopGlobalHook, except that the native callback never throws (#528). Its Dispose closes the event
+// queue before it stops the native hook, and its queue thread disposes the queue once drained; an input event in
+// between (or after a failed stop) threw on the OS hook thread and ended Filee. Here the hook stops first, and an
+// event that finds the queue closed is dropped: the hook is going away anyway.
+
+using System.Collections.Concurrent;
+using SharpHook;
+using SharpHook.Data;
+using SharpHook.Providers;
+
+namespace Filee.App.Services.Triggers;
+
+internal sealed class QueuedGlobalHook(IGlobalHookProvider? provider = null) : GlobalHookBase(provider)
+{
+ private readonly BlockingCollection<UioHookEvent> _events = [];
+ private int _loopStarted;
+
+ protected override void BeforeRun()
+ {
+ if (Interlocked.Exchange(ref _loopStarted, 1) == 0)
+ new Thread(RunEventLoop) { IsBackground = true, Name = "Filee input events" }.Start();
+ }
+
+ // The OS hook thread: Windows holds the cursor until this returns, so it only queues.
+ protected override void HandleHookEvent(ref UioHookEvent e)
+ {
+ if (!ShouldDispatchEvent(ref e))
+ return;
+ if (e.Type == EventType.HookDisabled)
+ {
+ DispatchEvent(ref e);
+ return;
+ }
+ try
+ {
+ _events.TryAdd(e);
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or ObjectDisposedException)
+ {
+ // Closed: the hook is being disposed.
+ }
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ try
+ {
+ base.Dispose(disposing); // stops the native hook first
+ }
+ finally
+ {
+ _events.CompleteAdding();
+ }
+ }
+
+ private void RunEventLoop()
+ {
+ foreach (var queued in _events.GetConsumingEnumerable())
+ {
+ var e = queued;
+ DispatchEvent(ref e);
+ }
+ }
+}
diff --git a/src/Filee.App/Services/Triggers/TriggerService.cs b/src/Filee.App/Services/Triggers/TriggerService.cs
index 24c1c8b9..29d1f46a 100644
--- a/src/Filee.App/Services/Triggers/TriggerService.cs
+++ b/src/Filee.App/Services/Triggers/TriggerService.cs
@@ -20,9 +20,9 @@ public sealed class TriggerService : IDisposable
private readonly ILogger<TriggerService> _log;
private readonly GestureDetector _detector = new();
private readonly string _ownProcess = Process.GetCurrentProcess().ProcessName;
- private EventLoopGlobalHook? _hook;
+ private QueuedGlobalHook? _hook;
private Thread? _hookThread;
- private readonly Func<EventLoopGlobalHook> _createHook;
+ private readonly Func<QueuedGlobalHook> _createHook;
private GnomePointerBridge? _gnomeBridge;
private GnomePointerInput? _gnomeInput;
private HashSet<string> _excluded = new(StringComparer.OrdinalIgnoreCase);
@@ -31,11 +31,11 @@ public sealed class TriggerService : IDisposable
private static readonly bool Trace = Environment.GetEnvironmentVariable("FILEE_TRACE_GESTURES") == "1";
public TriggerService(IPlatformServices platform, ILogger<TriggerService> log)
- : this(platform, log, () => new EventLoopGlobalHook(useBackgroundThreadForEventLoop: true))
+ : this(platform, log, () => new QueuedGlobalHook())
{
}
- internal TriggerService(IPlatformServices platform, ILogger<TriggerService> log, Func<EventLoopGlobalHook> createHook)
+ internal TriggerService(IPlatformServices platform, ILogger<TriggerService> log, Func<QueuedGlobalHook> createHook)
{
_platform = platform;
_log = log;
@@ -221,7 +221,8 @@ public sealed class TriggerService : IDisposable
NotifyStatus();
}
})
- { IsBackground = true, Name = "Filee global input" };
+ // Highest: Windows holds every mouse move until this thread has queued it (#511). It does nothing else.
+ { IsBackground = true, Name = "Filee global input", Priority = ThreadPriority.Highest };
_hookThread.Start();
}
catch (Exception ex)
diff --git a/src/Filee.Engines/Infrastructure/ProcessRunner.cs b/src/Filee.Engines/Infrastructure/ProcessRunner.cs
index d3671a80..7981e039 100644
--- a/src/Filee.Engines/Infrastructure/ProcessRunner.cs
+++ b/src/Filee.Engines/Infrastructure/ProcessRunner.cs
@@ -52,6 +52,7 @@ public static class ProcessRunner
if (!process.Start())
throw new InvalidOperationException($"Could not start {executable}.");
+ Lower(process);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
@@ -74,6 +75,22 @@ public static class ProcessRunner
return new ProcessResult(process.ExitCode, stdout.ToString(), stderr.ToString());
}
+ /// <summary>
+ /// Below normal priority, so a long conversion on every core leaves room for the desktop and Filee's own input
+ /// hook (#511); on an idle machine it is as fast. Programs it starts inherit it. A process that is already gone
+ /// or not ours to change stays as it is.
+ /// </summary>
+ internal static void Lower(Process process)
+ {
+ try
+ {
+ process.PriorityClass = ProcessPriorityClass.BelowNormal;
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException)
+ {
+ }
+ }
+
private static void TryKill(Process process)
{
try
diff --git a/src/Filee.Engines/Media/ClipPreview.cs b/src/Filee.Engines/Media/ClipPreview.cs
index 9d9f5d61..dcfef629 100644
--- a/src/Filee.Engines/Media/ClipPreview.cs
+++ b/src/Filee.Engines/Media/ClipPreview.cs
@@ -157,7 +157,7 @@ public static partial class ClipPreview
args.AddRange(["-to", ClipRange.Ffmpeg(end)]);
args.AddRange(["-i", Path.GetFullPath(path), "-map", "0:a:0", "-ac", "1", "-ar", PeakRate.ToString(CultureInfo.InvariantCulture),
"-c:a", "pcm_f32le", "-f", "f32le", samples]);
- var result = await FfmpegRunner.RunAsync(ffmpeg, args, null, cancellationToken, background: true);
+ var result = await FfmpegRunner.RunAsync(ffmpeg, args, null, cancellationToken);
if (result.ExitCode != 0 || !File.Exists(samples))
return []; // no sound
var bytes = await File.ReadAllBytesAsync(samples, cancellationToken);
diff --git a/src/Filee.Engines/Media/FfmpegRunner.cs b/src/Filee.Engines/Media/FfmpegRunner.cs
index eba84e03..219161da 100644
--- a/src/Filee.Engines/Media/FfmpegRunner.cs
+++ b/src/Filee.Engines/Media/FfmpegRunner.cs
@@ -30,13 +30,10 @@ internal static class FfmpegRunner
/// <param name="onPosition">Called with the output position in seconds whenever FFmpeg reports one.</param>
/// <param name="stallTimeout">How long FFmpeg may stay silent before it is killed; <see cref="DefaultStallTimeout"/> when null.</param>
/// <returns>Exit code and the last lines FFmpeg wrote to stderr (its error messages).</returns>
- /// <param name="background">
- /// Runs below normal priority: pictures and sound for a window (the clip window's timeline), which must not take
- /// the processor from the window itself.
- /// </param>
+ /// <remarks>Below normal priority, as every engine (<see cref="ProcessRunner.Lower"/>).</remarks>
public static async Task<ProcessResult> RunAsync(
string ffmpeg, IReadOnlyList<string> arguments, Action<double>? onPosition, CancellationToken cancellationToken,
- TimeSpan? stallTimeout = null, bool background = false)
+ TimeSpan? stallTimeout = null)
{
var psi = new ProcessStartInfo(ffmpeg)
{
@@ -79,8 +76,7 @@ internal static class FfmpegRunner
if (!process.Start())
throw new InvalidOperationException($"Could not start {ffmpeg}.");
- if (background)
- Lower(process);
+ ProcessRunner.Lower(process);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
@@ -115,18 +111,6 @@ internal static class FfmpegRunner
return new ProcessResult(process.ExitCode, "", stderr);
}
- /// <summary>Below normal priority; a process that is already gone or not ours to change stays as it is.</summary>
- internal static void Lower(Process process)
- {
- try
- {
- process.PriorityClass = ProcessPriorityClass.BelowNormal;
- }
- catch (Exception ex) when (ex is InvalidOperationException or System.ComponentModel.Win32Exception or NotSupportedException)
- {
- }
- }
-
/// <summary>
/// Runs a short query (<c>ffmpeg -version</c>, <c>-encoders</c>) synchronously. Both streams are read in the
/// background, so the time limit holds even when the program hangs with its output open (reading it to the end
diff --git a/src/Filee.Engines/Media/VideoFrames.cs b/src/Filee.Engines/Media/VideoFrames.cs
index 2bb60eb8..9b62c874 100644
--- a/src/Filee.Engines/Media/VideoFrames.cs
+++ b/src/Filee.Engines/Media/VideoFrames.cs
@@ -48,7 +48,7 @@ public static class VideoFrames
{
var (ffmpeg, _) = FfmpegConverter.Locate() ?? throw new InvalidOperationException("FFmpeg was not found.");
var arguments = MediaEncoding.FrameAt(Path.GetFullPath(path), Math.Max(0, seconds), output, maxHeight, null);
- var result = await FfmpegRunner.RunAsync(ffmpeg, arguments, null, cancellationToken, FrameStall, background: true);
+ var result = await FfmpegRunner.RunAsync(ffmpeg, arguments, null, cancellationToken, FrameStall);
return result.ExitCode == 0 && File.Exists(output) && new FileInfo(output).Length > 0;
}
diff --git a/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs b/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
index 2fbed49b..549c8249 100644
--- a/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
+++ b/tests/Filee.App.Tests/TriggerServiceLifecycleTests.cs
@@ -111,6 +111,33 @@ public sealed class TriggerServiceLifecycleTests
}
}
+ [Fact]
+ public void Input_after_the_event_queue_closed_never_throws_on_the_hook_thread()
+ {
+ // #528: a stop that fails leaves the native hook running with its queue closed. SharpHook's own event loop
+ // hook then threw on the OS hook thread for the next mouse move, which ended Filee.
+ var provider = new DelayedProvider();
+ var hook = new QueuedGlobalHook(provider);
+ var moves = 0;
+ hook.MouseMoved += (_, _) => Interlocked.Increment(ref moves);
+ var run = new Thread(() => hook.Run()) { IsBackground = true };
+ run.Start();
+ Assert.True(SpinWait.SpinUntil(() => provider.Runs == 1, 2000));
+ provider.PostMouse(EventType.MouseMoved, 1, 1, EventMask.None);
+ Assert.True(SpinWait.SpinUntil(() => Volatile.Read(ref moves) == 1, 2000));
+
+ provider.FailStop = true;
+ Assert.Throws<HookException>(hook.Dispose);
+ provider.PostMouse(EventType.MouseMoved, 2, 2, EventMask.None); // threw here before
+ provider.PostKey(EventType.KeyPressed, KeyCode.VcA);
+
+ provider.FailStop = false;
+ provider.StopRequested.Set();
+ provider.AllowExit.Set();
+ Assert.True(run.Join(2000));
+ Assert.Equal(1, Volatile.Read(ref moves));
+ }
+
private const EventMask Held = EventMask.LeftCtrl | EventMask.Button1;
[AvaloniaFact]
@@ -248,7 +275,7 @@ public sealed class TriggerServiceLifecycleTests
internal static TriggerService Create(DelayedProvider provider, Action key, bool wayland = false) =>
new(new NullPlatformServicesForHooks { PressCarriesPosition = !wayland }, NullLogger<TriggerService>.Instance, () =>
{
- var hook = new EventLoopGlobalHook(provider, useBackgroundThreadForEventLoop: true);
+ var hook = new QueuedGlobalHook(provider);
hook.KeyPressed += (_, _) => key();
return hook;
});