using Brutal.Logging;
namespace Brutal.SdlApi;
///
/// The exception type an SDL callback (event watch/filter, log output function, …) failed with,
/// captured at the native boundary and rethrown from managed code at the next event pump. Derives
/// from so callers can catch the whole SDL failure family uniformly; the
/// original callback exception is preserved as .
///
public sealed class SdlCallbackException : SdlException
{
/// Initializes a new with the given message.
/// A description of the callback in which the exception occurred.
public SdlCallbackException(string message)
: base(message) { }
/// Initializes a new with a message and inner exception.
/// A description of the callback in which the exception occurred.
/// The original exception thrown inside the callback.
public SdlCallbackException(string message, Exception innerException)
: base(message, innerException) { }
}
///
/// Collects exceptions thrown inside SDL callbacks and rethrows them from managed code.
///
///
/// SDL invokes managed callbacks (event watches, event filters, log output functions, …) from
/// native code. An exception thrown out of such a callback cannot legally unwind across the native
/// stack frame that called it. Doing so is undefined behaviour. Instead, the callback wrappers in
/// this binding catch every exception and hand it to this aggregator with , which
/// also logs it immediately so it is never silently lost. The pending exceptions are rethrown from
/// managed code at the next pump point (,
/// , , …) via
/// . To bound memory when a pump point is never reached, only the first
/// exceptions are kept; further ones are counted and reported but not
/// stored.
///
internal sealed class ExceptionAggregator
{
/// The maximum number of pending exceptions retained; beyond this only a count is kept.
public const int MaxRetained = 16;
private readonly List _exceptions = [];
private int _dropped;
private readonly Lock _lock = new();
///
/// Records an exception raised inside a native-to-managed callback so it can be rethrown from
/// managed code at the next . The exception is logged immediately at
/// error level (so it is visible even if no pump point ever drains the aggregator) and retained
/// up to entries; further exceptions increment a dropped counter.
///
/// A description of the callback in which the exception occurred.
/// The exception that was caught, preserved as the inner exception.
public void Push(string message, Exception? innerException = null)
{
var wrapped = innerException is null
? new SdlCallbackException(message)
: new SdlCallbackException(message, innerException);
// Store before logging so a faulting logger cannot drop the exception.
lock (_lock)
{
if (_exceptions.Count < MaxRetained)
_exceptions.Add(wrapped);
else
_dropped++;
}
try
{
Sdl.TraceLog.Error(wrapped);
}
catch
{
// A logging fault must not cross the native boundary.
}
}
///
/// Rethrows any exceptions captured since the last check, then clears the pending set. Does
/// nothing when nothing is pending. A single pending exception (with none dropped) is rethrown
/// directly; otherwise the pending exceptions are wrapped in an
/// whose message notes how many further exceptions were dropped.
///
/// Exactly one callback exception was pending.
/// More than one callback exception was pending, or some were dropped.
public void CheckExceptions()
{
Exception exception;
lock (_lock)
{
if (_exceptions.Count == 0)
return;
var dropped = _dropped;
if (_exceptions.Count == 1 && dropped == 0)
{
exception = _exceptions[0];
}
else
{
var message =
$"{_exceptions.Count} SDL callback exception(s) occurred."
+ (
dropped > 0
? $" A further {dropped} were dropped (only the first {MaxRetained} are retained)."
: ""
);
exception = new AggregateException(message, _exceptions.ToArray());
}
_exceptions.Clear();
_dropped = 0;
}
throw exception;
}
///
/// Discards all pending exceptions without throwing. Used during
/// teardown, where the parked exceptions refer to a session that is ending.
///
public void Clear()
{
lock (_lock)
{
_exceptions.Clear();
_dropped = 0;
}
}
}
///
/// Provides access to the SDL3 library.
///
public static unsafe partial class Sdl
{
///
/// The name the generated P/Invoke surface imports against. The static
/// constructor registers a that normalizes
/// this name to the platform-specific SDL3 shared library.
///
internal const string Dll = "SDL3";
///
/// The logging category for the per-call trace logs the generated P/Invoke surface emits.
///
internal static readonly LogCategory TraceLog = LogCategory.Make("Sdl");
///
/// Captures exceptions thrown inside SDL callbacks (event watches/filters, log output) so they
/// can be rethrown safely from managed code at the next event pump instead of unwinding across
/// the native boundary.
///
internal static readonly ExceptionAggregator ExceptionAggregator = new();
}