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.
C# audio-converteravaloniabatch-conversionconvertercsharpdocument-converterdocx-to-pdfdotnetdrag-and-dropfile-conversionfile-converterheic-converterhwphwpximage-converterlinuxmacospdf-convertervideo-converterwindows
Transparent windows: log how they are drawn, take away backdrops Filee never asked for
KnifeLemon90d4e42724af
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 8855c26b..9b66b1df 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -194,6 +194,18 @@ can't be received through Avalonia; for a browser drag Filee reads the address aregisters too (see "Files dragged from a web browser"). A click-mode donut opened for a later launch or the service forgives one loss offocus within a second of opening (`ActivationGrace`): Filee becoming the active app can take focus away from it.+The donut, the toast and the notices are transparent windows. On Windows Filee keeps Avalonia's rendering defaults+(ANGLE on Direct3D 11 composed through WinUI composition, then DirectComposition, then the window's redirection+surface; software rendering when Direct3D 11 fails): each of them keeps per-pixel transparency. The log says what was+picked (`Rendering: AngleEgl with WinUIComposition`), lists the graphics adapters, carries Avalonia's own errors from+starting the GPU paths (`AvaloniaLogForwarder`), and describes each kind of transparent window the first time it+shows (`TransparentWindows`). A system backdrop (Acrylic, Mica) or an accent blur on such a window turns its+transparent area into a blurred rectangle (issue #269). Filee sets neither, so one found there came from another+program: each time the window shows, a backdrop is set back to none and the accent (which can't be read back) is+turned off. For a report that still shows the wrong thing, the `FILEE_RENDERING` environment variable picks another+way to draw (`WindowsRendering`): `dcomp` (skip WinUI composition), `redirection` (Direct3D into the redirection+surface) or `software` (no GPU); unset or `auto` keeps the defaults. Filee reads it at start.+## Explorer integrationSettings → General → "Show “Convert with Filee” in the Explorer context menu" (`AppSettings.ContextMenuEnabled`) isdiff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex d41bbee3..b6724eba 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -109,6 +109,12 @@ public partial class App : Application};triggers.Start();log.LogInformation("Filee {Version} started", UpdateService.CurrentVersion);+ // Which way the transparent windows (donut, toast) are drawn, for reports of one that isn't see-through (#269).+ if (OperatingSystem.IsWindows())+ {+ log.LogInformation("{Rendering}", WindowsRendering.Describe(Environment.GetEnvironmentVariable(WindowsRendering.Variable)));+ TransparentWindows.Watch(log);+ }// macOS: ask for Accessibility with the system's own alert when the user opened Filee (not at sign-in) and// a drag gesture is on. The home page keeps a reminder until it is given. Asked once the main window is up:// asked earlier, the alert ends up behind it.diff --git a/src/Filee.App/Program.cs b/src/Filee.App/Program.csindex c1aaf098..b1b45e58 100644--- a/src/Filee.App/Program.cs+++ b/src/Filee.App/Program.cs@@ -277,12 +277,18 @@ internal static class Programvar builder = AppBuilder.Configure<App>().UsePlatformDetect();if (OperatingSystem.IsMacOS())builder = builder.With(new MacOSPlatformOptions { ShowInDock = PreloadedStore?.Settings.ShowInDock ?? true });- return builder+ if (OperatingSystem.IsWindows())+ builder = builder.With(WindowsRendering.Options(+ WindowsRendering.Normalize(Environment.GetEnvironmentVariable(WindowsRendering.Variable)),+ adapters => Log.LogInformation("Graphics adapters: {Adapters}", adapters)));+ builder = builder.ConfigureFonts(fonts => fonts.AddFontCollection(new FileeFontCollection()))#if DEBUG.WithDeveloperTools()#endif.LogToTrace();+ AvaloniaLogForwarder.Install(Log);+ return builder;}}diff --git a/src/Filee.App/Services/AvaloniaLogForwarder.cs b/src/Filee.App/Services/AvaloniaLogForwarder.csnew file mode 100644index 00000000..89f711cd--- /dev/null+++ b/src/Filee.App/Services/AvaloniaLogForwarder.cs@@ -0,0 +1,64 @@+// Avalonia writes why a graphics path failed to start (ANGLE, WinUI composition, DirectComposition) to its own log,+// which only reaches a debugger. These few areas go to Filee's log as well, so a report of a window drawn the wrong way+// shows the reason. Everything still goes to the sink that was there before.++using Avalonia.Logging;+using Microsoft.Extensions.Logging;++namespace Filee.App.Services;++internal sealed class AvaloniaLogForwarder(ILogSink? inner, Microsoft.Extensions.Logging.ILogger log) : ILogSink+{+ /// <summary>A failing render loop can repeat its error every frame: the log gets the first few lines.</summary>+ internal const int MaxLines = 20;++ private int _lines;++ /// <summary>Wraps Avalonia's current sink (set it up after <c>LogToTrace</c>).</summary>+ public static void Install(Microsoft.Extensions.Logging.ILogger log) =>+ Logger.Sink = new AvaloniaLogForwarder(Logger.Sink, log);++ /// <summary>Graphics start-up areas at Warning and above; Win32Platform only for errors (it warns about clipboard formats).</summary>+ public static bool Forwards(LogEventLevel level, string area) => area switch+ {+ "OpenGL" or "WinUIComposition" or "Vulkan" => level >= LogEventLevel.Warning,+ LogArea.Win32Platform => level >= LogEventLevel.Error,+ _ => false,+ };++ public bool IsEnabled(LogEventLevel level, string area) =>+ Forwards(level, area) || inner?.IsEnabled(level, area) == true;++ public void Log(LogEventLevel level, string area, object? source, string messageTemplate) =>+ Log(level, area, source, messageTemplate, []);++ public void Log(LogEventLevel level, string area, object? source, string messageTemplate, params object?[] propertyValues)+ {+ if (inner?.IsEnabled(level, area) == true)+ inner.Log(level, area, source, messageTemplate, propertyValues);+ if (!Forwards(level, area) || Interlocked.Increment(ref _lines) > MaxLines)+ return;+ log.Log(level >= LogEventLevel.Error ? LogLevel.Error : LogLevel.Warning, "Avalonia [{Area}]: {Message}",+ area, Format(messageTemplate, propertyValues));+ }++ /// <summary>Fills "{0}" or "{Name}" holes in order, as Avalonia's templates use either.</summary>+ public static string Format(string template, IReadOnlyList<object?> values)+ {+ var text = new System.Text.StringBuilder();+ var next = 0;+ for (var i = 0; i < template.Length; i++)+ {+ var end = template[i] == '{' ? template.IndexOf('}', i + 1) : -1;+ if (end < 0)+ {+ text.Append(template[i]);+ continue;+ }+ text.Append(next < values.Count ? values[next] : template[i..(end + 1)]);+ next++;+ i = end;+ }+ return text.ToString();+ }+}diff --git a/src/Filee.App/Services/TransparentWindows.cs b/src/Filee.App/Services/TransparentWindows.csnew file mode 100644index 00000000..ad3b2f2f--- /dev/null+++ b/src/Filee.App/Services/TransparentWindows.cs@@ -0,0 +1,54 @@+// Windows: looks at every transparent window (the donut, the toast, the notices) as it shows. The first time each kind+// shows, the log gets the transparency Avalonia reports next to the one asked for, and what the desktop compositor+// puts behind it. A system backdrop on such a window turns its transparent area into a blurred, tinted rectangle, the+// look of issue #269, and so does an accent blur. Filee never sets either, so one found there came from another program+// (tools that restyle every window do this): a backdrop is logged and set back to none; the accent, which can't be read+// back, is turned off each time. Such tools react to a window showing from their own process, so the window is looked+// at again a moment later.++using System.Runtime.Versioning;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Threading;+using Filee.Platform.Windows;+using Microsoft.Extensions.Logging;++namespace Filee.App.Services;++internal static class TransparentWindows+{+ private static readonly TimeSpan LookAgainAfter = TimeSpan.FromMilliseconds(600);+ private static readonly HashSet<string> Described = new(StringComparer.Ordinal);+ private static readonly HashSet<string> Warned = new(StringComparer.Ordinal);++ [SupportedOSPlatform("windows")]+ public static void Watch(ILogger log) =>+ Visual.IsVisibleProperty.Changed.AddClassHandler<Window>((window, e) =>+ {+ if (!e.GetNewValue<bool>() || !window.TransparencyLevelHint.Contains(WindowTransparencyLevel.Transparent))+ return;+ // After the native window has been shown and styled.+ Dispatcher.UIThread.Post(() => Check(window, log), DispatcherPriority.Background);+ DispatcherTimer.RunOnce(() => Check(window, log), LookAgainAfter);+ });++ [SupportedOSPlatform("windows")]+ private static void Check(Window window, ILogger log)+ {+ if (!window.IsVisible || window.TryGetPlatformHandle() is not { Handle: var hwnd and not 0 })+ return;+ var kind = window.GetType().Name;+ WindowBackdrop.ResetAccent(hwnd);+ var state = WindowBackdrop.Read(hwnd);+ if (Described.Add(kind))+ log.LogInformation("{Window}: transparency {Actual} (asked {Asked}), {State}, transparency effects {Effects}",+ kind, window.ActualTransparencyLevel, string.Join(", ", window.TransparencyLevelHint), state,+ WindowBackdrop.TransparencyEffects() switch { true => "on", false => "off", null => "unknown" });+ if (!state.HasForeignMaterial)+ return;+ var cleared = WindowBackdrop.ClearForeign(hwnd);+ if (Warned.Add(kind))+ log.LogWarning("{Window} got a backdrop Filee didn't ask for ({State}), probably from a program that restyles " ++ "windows; {Result}", kind, state, cleared ? "set it back to none" : "could not set it back to none");+ }+}diff --git a/src/Filee.App/Services/WindowsRendering.cs b/src/Filee.App/Services/WindowsRendering.csnew file mode 100644index 00000000..3d7e4429--- /dev/null+++ b/src/Filee.App/Services/WindowsRendering.cs@@ -0,0 +1,129 @@+// How Avalonia draws Filee's windows on Windows. The donut, the toast and the notices are transparent windows; a report+// of one standing on a dark rectangle (issue #269) needs to say which way they were drawn, so the log gets it once per+// start, with the graphics adapters, and FILEE_RENDERING picks another way without a new build.+//+// Avalonia's defaults: ANGLE (OpenGL ES on Direct3D 11) composed through WinUI composition, else DirectComposition, else+// drawn into the window's redirection surface; software rendering when Direct3D 11 can't start. Every one of these+// keeps per-pixel transparency (a redirection surface through DwmEnableBlurBehindWindow with an empty region), so+// Filee keeps the defaults and only changes them when the variable asks.++using System.Runtime.InteropServices;+using Avalonia;+using Avalonia.Platform;++namespace Filee.App.Services;++internal static class WindowsRendering+{+ public const string Variable = "FILEE_RENDERING";++ /// <summary>FILEE_RENDERING's values besides "auto" (or unset): Avalonia's defaults.</summary>+ public static readonly IReadOnlyList<string> Choices = ["dcomp", "redirection", "software"];++ /// <summary>The variable's value in lower case, or null for unset, empty and "auto".</summary>+ public static string? Normalize(string? value)+ {+ var choice = value?.Trim().ToLowerInvariant();+ return string.IsNullOrEmpty(choice) || choice == "auto" ? null : choice;+ }++ /// <summary>+ /// Avalonia's Windows options for <paramref name="choice"/> (from <see cref="Normalize"/>): "dcomp" skips WinUI+ /// composition, "redirection" draws with Direct3D into the redirection surface, "software" without the GPU. Unknown+ /// values keep the defaults. <paramref name="adapters"/> hears which graphics adapters Direct3D found and which one+ /// it uses (the first, as without the callback). Not on ARM64: there the callback would turn off Avalonia's own+ /// choice of adapter.+ /// </summary>+ public static Win32PlatformOptions Options(string? choice, Action<string>? adapters)+ {+ var options = new Win32PlatformOptions();+ switch (choice)+ {+ case "dcomp":+ options.CompositionMode = [Win32CompositionMode.DirectComposition, Win32CompositionMode.RedirectionSurface];+ break;+ case "redirection":+ options.CompositionMode = [Win32CompositionMode.RedirectionSurface];+ break;+ case "software":+ options.RenderingMode = [Win32RenderingMode.Software];+ break;+ }+ if (adapters is not null && RuntimeInformation.ProcessArchitecture != Architecture.Arm64)+ options.GraphicsAdapterSelectionCallback = list =>+ {+ adapters(DescribeAdapters(list.Select(a => a.Description).ToList(), 0));+ return 0;+ };+ return options;+ }++ /// <summary>"[0] intel(r) uhd graphics (used), [1] nvidia geforce rtx 4060 laptop gpu".</summary>+ public static string DescribeAdapters(IReadOnlyList<string?> names, int used) =>+ names.Count == 0+ ? "none"+ : string.Join(", ", names.Select((name, i) => $"[{i}] {name ?? "(no name)"}{(i == used ? " (used)" : "")}"));++ /// <summary>+ /// "Rendering: AngleEgl with WinUIComposition (FILEE_RENDERING not set)", from what Avalonia registered at start.+ /// </summary>+ public static string Describe(string? variable)+ {+ var locate = Locator();+ if (locate is null)+ return $"Rendering: unknown, Avalonia's services can't be read ({Asked(variable)})";+ var graphics = locate(typeof(IPlatformGraphics));+ var factoryType = Type.GetType("Avalonia.Win32.IWindowsSurfaceFactory, Avalonia.Win32", throwOnError: false);+ var factory = factoryType is null ? null : locate(factoryType);+ return $"Rendering: {RenderingName(graphics?.GetType().Name)} with " ++ $"{CompositionName(graphics is null ? null : factory?.GetType().Name, factoryType is not null)} ({Asked(variable)})";+ }++ private static string Asked(string? variable) => Normalize(variable) switch+ {+ null => $"{Variable} not set",+ var choice when Choices.Contains(choice) => $"{Variable}={choice}",+ var choice => $"{Variable}={choice} is unknown and ignored",+ };++ /// <summary>+ /// Avalonia's service locator, and the surface factory a composition mode registers in it, are left out of its+ /// reference assemblies: both are reached by name. Null when that no longer works.+ /// </summary>+ private static Func<Type, object?>? Locator()+ {+ try+ {+ var current = typeof(AvaloniaObject).Assembly.GetType("Avalonia.AvaloniaLocator")+ ?.GetProperty("Current")?.GetValue(null);+ var getService = current?.GetType().GetMethod("GetService", [typeof(Type)]);+ return getService is null ? null : type => getService.Invoke(current, [type]);+ }+ catch (Exception ex) when (ex is System.Reflection.TargetInvocationException or MemberAccessException)+ {+ return null;+ }+ }++ /// <summary>Avalonia's rendering mode for the type name of its platform graphics (null: software).</summary>+ public static string RenderingName(string? graphicsType) => graphicsType switch+ {+ null => "Software",+ "D3D11AngleWin32PlatformGraphics" => "AngleEgl",+ "D3D9AngleWin32PlatformGraphics" => "AngleEgl (Direct3D 9)",+ "WglPlatformOpenGlInterface" => "Wgl",+ _ when graphicsType.Contains("Vulkan", StringComparison.Ordinal) => "Vulkan",+ _ => graphicsType,+ };++ /// <summary>Avalonia's composition mode for the type name of its window surface factory (null: none registered).</summary>+ public static string CompositionName(string? factoryType, bool lookedUp = true) => factoryType switch+ {+ _ when !lookedUp => "an unknown composition mode",+ null => "RedirectionSurface",+ "WinUiCompositorConnection" => "WinUIComposition",+ "DirectCompositionConnection" => "DirectComposition",+ "DxgiConnection" => "LowLatencyDxgiSwapChain",+ _ => factoryType,+ };+}diff --git a/src/Filee.Platform.Windows/WindowBackdrop.cs b/src/Filee.Platform.Windows/WindowBackdrop.csnew file mode 100644index 00000000..8e60976b--- /dev/null+++ b/src/Filee.Platform.Windows/WindowBackdrop.cs@@ -0,0 +1,133 @@+// What the desktop compositor (DWM) shows behind a transparent Filee window. Filee never asks it for a material (Mica,+// Acrylic), so the transparent pixels around the donut show the windows behind it. Programs that restyle every+// window can still put one there: the donut then stands on a blurred, tinted rectangle (issue #269). Read says what the+// window got; ClearForeign takes such a material away again. The older way to the same look, the undocumented accent+// policy, can't be read back: ResetAccent turns it off without looking, which changes nothing on a window without one.++using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using Microsoft.Win32;++namespace Filee.Platform.Windows;++/// <param name="Redirected">The window draws into a redirection surface (no DirectComposition / WinUI tree).</param>+/// <param name="Layered">WS_EX_LAYERED: Avalonia never sets it, so something else did.</param>+/// <param name="SystemBackdrop">DWMWA_SYSTEMBACKDROP_TYPE (Windows 11 22H2+), -1 when it can't be read.</param>+public readonly record struct WindowBackdropState(bool Redirected, bool Layered, int SystemBackdrop)+{+ // DWM_SYSTEMBACKDROP_TYPE: 0 auto, 1 none, 2 Mica, 3 Acrylic, 4 Mica Alt.+ public const int BackdropNone = 1;++ /// <summary>A backdrop material Filee didn't ask for.</summary>+ public bool HasForeignMaterial => SystemBackdrop > BackdropNone;++ public override string ToString() =>+ $"{(Redirected ? "redirection surface" : "composition surface")}{(Layered ? ", layered" : "")}, " ++ $"system backdrop {BackdropName(SystemBackdrop)}";++ public static string BackdropName(int type) => type switch+ {+ -1 => "unknown",+ 0 => "auto",+ 1 => "none",+ 2 => "Mica",+ 3 => "Acrylic",+ 4 => "Mica Alt",+ _ => type.ToString(System.Globalization.CultureInfo.InvariantCulture),+ };+}++public static partial class WindowBackdrop+{+ private const int GWL_EXSTYLE = -20;+ private const long WS_EX_LAYERED = 0x00080000, WS_EX_NOREDIRECTIONBITMAP = 0x00200000;+ private const int DWMWA_SYSTEMBACKDROP_TYPE = 38;+ private const int WCA_ACCENT_POLICY = 19;++ [SupportedOSPlatform("windows")]+ public static WindowBackdropState Read(nint hwnd)+ {+ var exStyle = (long)GetWindowLongPtr(hwnd, GWL_EXSTYLE);+ return new WindowBackdropState(+ Redirected: (exStyle & WS_EX_NOREDIRECTIONBITMAP) == 0,+ Layered: (exStyle & WS_EX_LAYERED) != 0,+ SystemBackdrop: ReadSystemBackdrop(hwnd));+ }++ /// <summary>+ /// Sets the backdrop back to none. True when Windows took the change. Only for windows Filee never gives a material.+ /// </summary>+ [SupportedOSPlatform("windows")]+ public static unsafe bool ClearForeign(nint hwnd)+ {+ var none = WindowBackdropState.BackdropNone;+ return DwmSetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &none, sizeof(int)) == 0;+ }++ /// <summary>Turns off an accent blur or acrylic (ACCENT_DISABLED). True when Windows took it.</summary>+ [SupportedOSPlatform("windows")]+ public static unsafe bool ResetAccent(nint hwnd)+ {+ var policy = new AccentPolicy();+ var data = new CompositionAttributeData { Attribute = WCA_ACCENT_POLICY, Data = &policy, Size = sizeof(AccentPolicy) };+ try+ {+ return SetWindowCompositionAttribute(hwnd, ref data);+ }+ catch (EntryPointNotFoundException)+ {+ return false;+ }+ }++ /// <summary>Settings → Personalization → Colors → Transparency effects; null when it can't be read.</summary>+ [SupportedOSPlatform("windows")]+ public static bool? TransparencyEffects()+ {+ try+ {+ using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize");+ return key?.GetValue("EnableTransparency") is int value ? value != 0 : null;+ }+ catch (Exception ex) when (ex is System.Security.SecurityException or UnauthorizedAccessException or IOException)+ {+ return null;+ }+ }++ private static unsafe int ReadSystemBackdrop(nint hwnd)+ {+ int type;+ return DwmGetWindowAttribute(hwnd, DWMWA_SYSTEMBACKDROP_TYPE, &type, sizeof(int)) == 0 ? type : -1;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct AccentPolicy+ {+ public int State;+ public int Flags;+ public int GradientColor;+ public int AnimationId;+ }++ [StructLayout(LayoutKind.Sequential)]+ private unsafe struct CompositionAttributeData+ {+ public int Attribute;+ public void* Data;+ public nint Size;+ }++ [LibraryImport("user32.dll", EntryPoint = "GetWindowLongPtrW")]+ private static partial nint GetWindowLongPtr(nint hwnd, int index);++ [LibraryImport("dwmapi.dll")]+ private static unsafe partial int DwmGetWindowAttribute(nint hwnd, int attribute, void* value, int size);++ [LibraryImport("dwmapi.dll")]+ private static unsafe partial int DwmSetWindowAttribute(nint hwnd, int attribute, void* value, int size);++ [LibraryImport("user32.dll")]+ [return: MarshalAs(UnmanagedType.Bool)]+ private static partial bool SetWindowCompositionAttribute(nint hwnd, ref CompositionAttributeData data);+}diff --git a/tests/Filee.App.Tests/WindowsRenderingTests.cs b/tests/Filee.App.Tests/WindowsRenderingTests.csnew file mode 100644index 00000000..01cfdeff--- /dev/null+++ b/tests/Filee.App.Tests/WindowsRenderingTests.cs@@ -0,0 +1,227 @@+// How Filee draws its transparent windows on Windows (issue #269): the FILEE_RENDERING escape hatch, the log line+// describing what Avalonia picked, Avalonia's own graphics errors in Filee's log, and backdrops Filee never asked for.++using System.Runtime.InteropServices;+using Avalonia;+using Avalonia.Headless.XUnit;+using Avalonia.Logging;+using Avalonia.Platform;+using Filee.App.Services;+using Filee.Platform.Windows;+using Microsoft.Extensions.Logging;++namespace Filee.App.Tests;++public class WindowsRenderingTests+{+ [Theory]+ [InlineData(null, null)]+ [InlineData("", null)]+ [InlineData(" ", null)]+ [InlineData(" Auto ", null)]+ [InlineData(" DComp ", "dcomp")]+ [InlineData("SOFTWARE", "software")]+ [InlineData("vulkan", "vulkan")]+ public void Normalize_trims_lowers_and_reads_auto_as_unset(string? value, string? expected) =>+ Assert.Equal(expected, WindowsRendering.Normalize(value));++ [Theory]+ [InlineData(null)]+ [InlineData("vulkan")]+ public void Unset_and_unknown_values_keep_Avalonias_defaults(string? choice)+ {+ var defaults = new Win32PlatformOptions();+ var options = WindowsRendering.Options(choice, adapters: null);+ Assert.Equal(defaults.RenderingMode, options.RenderingMode);+ Assert.Equal(defaults.CompositionMode, options.CompositionMode);+ Assert.Null(options.GraphicsAdapterSelectionCallback);+ }++ [Fact]+ public void Defaults_keep_transparency_in_every_fallback()+ {+ // The reason Filee doesn't reorder them: WinUI composition, DirectComposition and the redirection surface all+ // keep per-pixel alpha; the low-latency swap chain (which doesn't) isn't in the list.+ var defaults = new Win32PlatformOptions();+ Assert.DoesNotContain(Win32CompositionMode.LowLatencyDxgiSwapChain, defaults.CompositionMode);+ Assert.Equal(Win32CompositionMode.RedirectionSurface, defaults.CompositionMode[^1]);+ Assert.Equal(Win32RenderingMode.Software, defaults.RenderingMode[^1]);+ }++ [Fact]+ public void Dcomp_skips_WinUI_composition()+ {+ var options = WindowsRendering.Options("dcomp", adapters: null);+ Assert.Equal([Win32CompositionMode.DirectComposition, Win32CompositionMode.RedirectionSurface], options.CompositionMode);+ Assert.Equal(new Win32PlatformOptions().RenderingMode, options.RenderingMode);+ }++ [Fact]+ public void Redirection_draws_with_the_GPU_into_the_redirection_surface()+ {+ var options = WindowsRendering.Options("redirection", adapters: null);+ Assert.Equal([Win32CompositionMode.RedirectionSurface], options.CompositionMode);+ Assert.Equal(new Win32PlatformOptions().RenderingMode, options.RenderingMode);+ }++ [Fact]+ public void Software_leaves_the_GPU_out()+ {+ var options = WindowsRendering.Options("software", adapters: null);+ Assert.Equal([Win32RenderingMode.Software], options.RenderingMode);+ }++ [Fact]+ public void Every_documented_choice_changes_something()+ {+ var defaults = new Win32PlatformOptions();+ foreach (var choice in WindowsRendering.Choices)+ {+ var options = WindowsRendering.Options(choice, adapters: null);+ Assert.False(options.RenderingMode.SequenceEqual(defaults.RenderingMode)+ && options.CompositionMode.SequenceEqual(defaults.CompositionMode), choice);+ }+ }++ [Fact]+ public void The_adapter_callback_reports_the_list_and_keeps_the_first_adapter()+ {+ var reported = new List<string>();+ var options = WindowsRendering.Options(null, reported.Add);+ if (RuntimeInformation.ProcessArchitecture == Architecture.Arm64)+ {+ // Avalonia picks around Adreno GPUs itself there; a callback would turn that off.+ Assert.Null(options.GraphicsAdapterSelectionCallback);+ return;+ }+ var chosen = options.GraphicsAdapterSelectionCallback!(+ [+ new PlatformGraphicsDeviceAdapterDescription { Description = "intel(r) uhd graphics" },+ new PlatformGraphicsDeviceAdapterDescription { Description = "nvidia geforce rtx 4060 laptop gpu" },+ ]);+ Assert.Equal(0, chosen);+ Assert.Equal(["[0] intel(r) uhd graphics (used), [1] nvidia geforce rtx 4060 laptop gpu"], reported);+ }++ [Fact]+ public void Adapters_without_names_still_read()+ {+ Assert.Equal("none", WindowsRendering.DescribeAdapters([], 0));+ Assert.Equal("[0] (no name) (used)", WindowsRendering.DescribeAdapters([null], 0));+ }++ [Theory]+ [InlineData(null, "Software")]+ [InlineData("D3D11AngleWin32PlatformGraphics", "AngleEgl")]+ [InlineData("WglPlatformOpenGlInterface", "Wgl")]+ [InlineData("VulkanPlatformGraphics", "Vulkan")]+ [InlineData("SomethingNew", "SomethingNew")]+ public void Rendering_names_follow_Avalonias_options(string? type, string expected) =>+ Assert.Equal(expected, WindowsRendering.RenderingName(type));++ [Theory]+ [InlineData(null, "RedirectionSurface")]+ [InlineData("WinUiCompositorConnection", "WinUIComposition")]+ [InlineData("DirectCompositionConnection", "DirectComposition")]+ [InlineData("DxgiConnection", "LowLatencyDxgiSwapChain")]+ public void Composition_names_follow_Avalonias_options(string? type, string expected) =>+ Assert.Equal(expected, WindowsRendering.CompositionName(type));++ [Fact]+ public void A_composition_mode_that_cant_be_looked_up_is_not_called_a_redirection_surface() =>+ Assert.Equal("an unknown composition mode", WindowsRendering.CompositionName(null, lookedUp: false));++ [AvaloniaFact]+ public void The_log_line_says_what_was_asked()+ {+ Assert.StartsWith("Rendering: ", WindowsRendering.Describe(null));+ Assert.EndsWith("(FILEE_RENDERING not set)", WindowsRendering.Describe(null));+ Assert.EndsWith("(FILEE_RENDERING=software)", WindowsRendering.Describe(" Software"));+ Assert.EndsWith("(FILEE_RENDERING=opengl is unknown and ignored)", WindowsRendering.Describe("opengl"));+ }+}++public class AvaloniaLogForwarderTests+{+ private sealed class ListSink : ILogSink+ {+ public List<string> Messages { get; } = [];++ public bool IsEnabled(LogEventLevel level, string area) => level >= LogEventLevel.Warning;++ public void Log(LogEventLevel level, string area, object? source, string messageTemplate) => Messages.Add(messageTemplate);++ public void Log(LogEventLevel level, string area, object? source, string messageTemplate, params object?[] propertyValues) =>+ Messages.Add(messageTemplate);+ }++ [Theory]+ [InlineData(LogEventLevel.Error, "OpenGL", true)]+ [InlineData(LogEventLevel.Warning, "WinUIComposition", true)]+ [InlineData(LogEventLevel.Information, "OpenGL", false)]+ [InlineData(LogEventLevel.Error, LogArea.Win32Platform, true)]+ [InlineData(LogEventLevel.Warning, LogArea.Win32Platform, false)]+ [InlineData(LogEventLevel.Error, LogArea.Binding, false)]+ public void Only_graphics_start_up_problems_are_forwarded(LogEventLevel level, string area, bool forwarded) =>+ Assert.Equal(forwarded, AvaloniaLogForwarder.Forwards(level, area));++ [Theory]+ [InlineData("Unable to load ANGLE: {0}", "Unable to load ANGLE: boom")]+ [InlineData("Unsupported data format {Format}", "Unsupported data format boom")]+ [InlineData("No holes", "No holes")]+ public void Templates_get_their_values(string template, string expected) =>+ Assert.Equal(expected, AvaloniaLogForwarder.Format(template, ["boom"]));++ [Fact]+ public void Holes_without_a_value_stay_as_they_are() =>+ Assert.Equal("a {0} b {1}", AvaloniaLogForwarder.Format("a {0} b {1}", []));++ [Fact]+ public void Forwards_to_the_log_and_still_to_the_sink_before_it()+ {+ var inner = new ListSink();+ var log = new ListLogger();+ var sink = new AvaloniaLogForwarder(inner, log);++ sink.Log(LogEventLevel.Error, "OpenGL", null, "Unable to initialize ANGLE-based rendering with DirectX11 : {0}", "E_FAIL");+ sink.Log(LogEventLevel.Warning, LogArea.Binding, null, "A binding failed");++ Assert.Equal(2, inner.Messages.Count);+ var line = Assert.Single(log.Lines);+ Assert.Equal(LogLevel.Error, line.Level);+ Assert.Equal("Avalonia [OpenGL]: Unable to initialize ANGLE-based rendering with DirectX11 : E_FAIL", line.Message);+ Assert.True(sink.IsEnabled(LogEventLevel.Warning, "WinUIComposition"));+ Assert.False(sink.IsEnabled(LogEventLevel.Information, "OpenGL"));+ }++ [Fact]+ public void A_repeating_error_fills_only_a_few_lines()+ {+ var log = new ListLogger();+ var sink = new AvaloniaLogForwarder(null, log);+ for (var i = 0; i < AvaloniaLogForwarder.MaxLines * 3; i++)+ sink.Log(LogEventLevel.Error, LogArea.Win32Platform, null, "Failed to wait for vblank");+ Assert.Equal(AvaloniaLogForwarder.MaxLines, log.Lines.Count);+ }+}++public class WindowBackdropStateTests+{+ [Theory]+ [InlineData(-1, false)]+ [InlineData(0, false)]+ [InlineData(1, false)]+ [InlineData(2, true)]+ [InlineData(3, true)]+ [InlineData(4, true)]+ public void Only_a_material_counts_as_foreign(int backdrop, bool foreign) =>+ Assert.Equal(foreign, new WindowBackdropState(Redirected: false, Layered: false, backdrop).HasForeignMaterial);++ [Fact]+ public void Reads_as_a_log_line()+ {+ Assert.Equal("composition surface, system backdrop auto", new WindowBackdropState(false, false, 0).ToString());+ Assert.Equal("redirection surface, layered, system backdrop Acrylic", new WindowBackdropState(true, true, 3).ToString());+ Assert.Equal("composition surface, system backdrop unknown", new WindowBackdropState(false, false, -1).ToString());+ }+}