Skip to content
Merged
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
49 changes: 45 additions & 4 deletions PdVm.Runtime/PdVmWinFormsApplication.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ internal PdVmWinFormsApplicationSession(
_onDispose = onDispose;
}

public bool HasMainForm => _mainForm is not null;
public bool HasMainForm => Volatile.Read(ref _mainForm) is not null;

public void RunMessageLoop()
{
EnsureUiThread();
var form = _mainForm ?? throw new InvalidOperationException(
var form = Volatile.Read(ref _mainForm) ?? throw new InvalidOperationException(
"the RSS program did not register a main form with EventLoop::Show");
var formType = Type.GetType(
"System.Windows.Forms.Form, System.Windows.Forms",
Expand All @@ -95,7 +95,8 @@ internal void RegisterMainForm(object form)
{
ArgumentNullException.ThrowIfNull(form);
EnsureUiThread();
if (_mainForm is not null && !ReferenceEquals(_mainForm, form))
var existing = Volatile.Read(ref _mainForm);
if (existing is not null && !ReferenceEquals(existing, form))
{
throw new InvalidOperationException("a Windows Forms program can register only one main form");
}
Expand All @@ -104,7 +105,47 @@ internal void RegisterMainForm(object form)
BindingFlags.Public | BindingFlags.Instance)?.GetValue(form) ??
throw new InvalidOperationException(
$"{form.GetType().FullName} does not expose a window handle");
_mainForm = form;
Volatile.Write(ref _mainForm, form);
}

/// <summary>
/// Closes this session's main form so that <see cref="RunMessageLoop"/> returns.
/// Unlike <c>Application.Exit</c>, which tears down every message loop in the process,
/// this only ends the loop owned by this session and may be called from any thread.
/// </summary>
public bool CloseMainForm()
{
var form = Volatile.Read(ref _mainForm);
if (form is null)
{
return false;
}

var beginInvoke = form.GetType().GetMethod(
"BeginInvoke",
BindingFlags.Public | BindingFlags.Instance,
binder: null,
types: [typeof(Delegate)],
modifiers: null);
if (beginInvoke is null)
{
return false;
}

// Route through the same close path as EventLoop::Close so that a bound
// FormClosing callback does not veto the shutdown.
Action action = () => PdVmWinFormsEventLoop.Close(form);
try
{
_ = beginInvoke.Invoke(form, [action]);
return true;
}
catch (TargetInvocationException exception)
when (exception.InnerException is InvalidOperationException or ObjectDisposedException)
{
// The window handle is already gone, so the loop has nothing left to close.
return false;
}
}

internal PdVmScriptCallback<PdVmUnit, PdVmUnit> CreateUnitCallback(
Expand Down
3 changes: 2 additions & 1 deletion PdVm.Tests/PdVmDotNetHostTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PdVm.Tests;

[Collection(WinFormsCollection.Name)]
public sealed class PdVmDotNetHostTests
{
[Fact]
Expand Down Expand Up @@ -67,7 +68,7 @@ public void ConstructsWindowsFormOnStaThreadWithoutCompileTimeWindowsDependency(
{
try
{
Assert.True(PdVmDotNetHost.InitializeWindowsFormsApplication());
Assert.True(WinFormsTestSupport.Initialize());
var host = new PdVmDotNetHost(allowDynamicSystemCalls: true);
Assert.True(host.CanResolveType("System.Windows.Forms.Form"));
var handle = ReturnValue(host.Call(
Expand Down
3 changes: 2 additions & 1 deletion PdVm.Tests/PdVmMinesweeperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

namespace PdVm.Tests;

[Collection(WinFormsCollection.Name)]
public sealed class PdVmMinesweeperTests
{
[Fact]
Expand Down Expand Up @@ -65,7 +66,7 @@ pub fn test_cell(index: int) -> [int] {
{
try
{
PdVmDotNetHost.InitializeWindowsFormsApplication();
_ = WinFormsTestSupport.Initialize();
using var program = Assert.IsAssignableFrom<IPdVmCallableProgram>(
PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(outputPath))));
var host = PdVmDefaultHost.CreateConsoleHost();
Expand Down
21 changes: 5 additions & 16 deletions PdVm.Tests/PdVmTypedDotNetInteropTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace PdVm.Tests;

[Collection(WinFormsCollection.Name)]
public sealed class PdVmTypedDotNetInteropTests
{
[Fact]
Expand Down Expand Up @@ -377,7 +378,7 @@ public void WinFormsButtonClickInvokesRssCallbackOnTheOwningStaThread()
{
try
{
_ = PdVmDotNetHost.InitializeWindowsFormsApplication();
_ = WinFormsTestSupport.Initialize();
using var program = Assert.IsAssignableFrom<IPdVmCallableProgram>(
PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output))));
var host = PdVmDefaultHost.CreateConsoleHost();
Expand All @@ -386,7 +387,7 @@ public void WinFormsButtonClickInvokesRssCallbackOnTheOwningStaThread()
using var application = PdVmWinFormsApplication.Attach(program, host);
_ = PdVmExecution.Run(program, host);
using var watchdog = new System.Threading.Timer(
_ => ExitWindowsFormsApplication(),
_ => application.CloseMainForm(),
null,
TimeSpan.FromSeconds(3),
Timeout.InfiniteTimeSpan);
Expand Down Expand Up @@ -1170,7 +1171,7 @@ public void WinFormsTimerInvokesRssCallableOnTheOwningStaThread()
{
try
{
_ = PdVmDotNetHost.InitializeWindowsFormsApplication();
_ = WinFormsTestSupport.Initialize();
using var program = Assert.IsAssignableFrom<IPdVmCallableProgram>(
PdVmAssemblyLoader.CreateProgram(Assembly.Load(File.ReadAllBytes(output))));
var host = PdVmDefaultHost.CreateConsoleHost();
Expand All @@ -1179,7 +1180,7 @@ public void WinFormsTimerInvokesRssCallableOnTheOwningStaThread()
using var application = PdVmWinFormsApplication.Attach(program, host);
_ = PdVmExecution.Run(program, host);
using var watchdog = new System.Threading.Timer(
_ => ExitWindowsFormsApplication(),
_ => application.CloseMainForm(),
null,
TimeSpan.FromSeconds(3),
Timeout.InfiniteTimeSpan);
Expand Down Expand Up @@ -1254,18 +1255,6 @@ private static PdVmProgramMetadata GetProgramMetadata(IPdVmProgram program)
return Assert.IsType<PdVmProgramMetadata>(metadataField.GetValue(program));
}

private static void ExitWindowsFormsApplication() =>
Type.GetType(
"System.Windows.Forms.Application, System.Windows.Forms",
throwOnError: true)!
.GetMethod(
"Exit",
BindingFlags.Public | BindingFlags.Static,
binder: null,
types: Type.EmptyTypes,
modifiers: null)!
.Invoke(null, null);

private static async Task WaitUntilAsync(Func<bool> condition)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
Expand Down
165 changes: 165 additions & 0 deletions PdVm.Tests/WinFormsTestSupport.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
using System.Reflection;
using PdVm.Runtime;

namespace PdVm.Tests;

/// <summary>
/// Windows Forms keeps process-wide state: visual styles and DPI awareness can only be
/// configured before the first window handle exists, and <c>Application.Exit</c> terminates
/// every message loop in the process. Tests that create forms therefore join one
/// non-parallel collection and share a single initialization.
/// </summary>
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class WinFormsCollection
{
public const string Name = "windows-forms";
}

/// <summary>
/// Process-wide Windows Forms setup shared by the UI tests.
/// </summary>
internal static class WinFormsTestSupport
{
private static readonly object Gate = new();
private static bool _initialized;
private static bool _available;
private static Exception? _failure;

/// <summary>
/// Initializes Windows Forms once per process and reports whether it is usable.
/// The first call also pumps a throwaway message loop so that one-time toolkit
/// initialization (assembly load, GDI+/font/theme setup, first window creation)
/// does not land inside a test's own deadline.
/// </summary>
public static bool Initialize()
{
lock (Gate)
{
if (!_initialized)
{
_initialized = true;
try
{
_available = PdVmDotNetHost.InitializeWindowsFormsApplication();
if (_available)
{
PumpThrowawayMessageLoop();
}
}
catch (Exception exception)
{
_failure = exception;
}
}

if (_failure is not null)
{
throw new InvalidOperationException("Windows Forms initialization failed", _failure);
}

return _available;
}
}

/// <summary>
/// Closes a form on its own UI thread without touching other message loops in the process.
/// </summary>
public static bool CloseForm(object form)
{
ArgumentNullException.ThrowIfNull(form);
var close = form.GetType().GetMethod(
"Close",
BindingFlags.Public | BindingFlags.Instance,
binder: null,
types: Type.EmptyTypes,
modifiers: null);
if (close is null)
{
return false;
}

var beginInvoke = form.GetType().GetMethod(
"BeginInvoke",
BindingFlags.Public | BindingFlags.Instance,
binder: null,
types: [typeof(Delegate)],
modifiers: null);
if (beginInvoke is null)
{
return false;
}

Action action = () => close.Invoke(form, null);
try
{
_ = beginInvoke.Invoke(form, [action]);
return true;
}
catch (TargetInvocationException exception)
when (exception.InnerException is InvalidOperationException or ObjectDisposedException)
{
// The window handle is already gone; the owning loop has nothing left to close.
return false;
}
}

private static void PumpThrowawayMessageLoop()
{
if (!OperatingSystem.IsWindows())
{
return;
}

Exception? failure = null;
var thread = new Thread(() =>
{
try
{
RunThrowawayMessageLoop();
}
catch (Exception exception)
{
failure = exception;
}
})
{
IsBackground = true,
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
if (!thread.Join(TimeSpan.FromSeconds(30)))
{
throw new InvalidOperationException("the Windows Forms warm-up message loop did not exit");
}

if (failure is not null)
{
throw new InvalidOperationException("the Windows Forms warm-up message loop failed", failure);
}
}

private static void RunThrowawayMessageLoop()
{
var formType = Type.GetType(
"System.Windows.Forms.Form, System.Windows.Forms",
throwOnError: true)!;
var application = Type.GetType(
"System.Windows.Forms.Application, System.Windows.Forms",
throwOnError: true)!;
var form = Activator.CreateInstance(formType)!;
formType.GetProperty("ShowInTaskbar")?.SetValue(form, false);
using var timer = new System.Threading.Timer(
_ => CloseForm(form),
null,
TimeSpan.FromMilliseconds(100),
Timeout.InfiniteTimeSpan);
var run = application.GetMethod(
"Run",
BindingFlags.Public | BindingFlags.Static,
binder: null,
types: [formType],
modifiers: null)!;
_ = run.Invoke(null, [form]);
(form as IDisposable)?.Dispose();
}
}
Loading