From cf50829e6ad4a623eb0d3a3757438da900e0a2c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Sat, 10 Oct 2026 08:34:28 +0300 Subject: [PATCH] Add experimental opt-in niri display scale detection Co-Authored-By: GPT-6.1-sol (OpenAI Codex) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_016FAtbHHLQSiJiYcw2vnKiq --- .github/README.md | 4 + docs/linux-port/appearance-transparency.md | 8 + .../investigations/pixelation-findings.md | 8 +- .../Contracts/IAppearanceSettingsService.cs | 1 + .../Settings/AppearanceSettingsService.cs | 6 + src/Files.App/Strings/en-US/Resources.resw | 6 + .../Settings/AppearanceViewModel.cs | 9 + .../Views/Settings/AppearancePage.xaml | 9 + .../Windowing/CompositorScaleSettings.cs | 41 ++++ .../Windowing/DisplayScaleResolver.cs | 116 +++++++++- .../Windowing/NiriScaleClient.cs | 141 +++++++++++ .../Windowing/CompositorScaleSettingsTests.cs | 110 +++++++++ .../Windowing/DisplayScaleResolverTests.cs | 218 ++++++++++++++++++ 13 files changed, 669 insertions(+), 8 deletions(-) create mode 100644 src/Files.Platform.Linux/Windowing/CompositorScaleSettings.cs create mode 100644 src/Files.Platform.Linux/Windowing/NiriScaleClient.cs create mode 100644 tests/Files.Platform.Tests/Windowing/CompositorScaleSettingsTests.cs diff --git a/.github/README.md b/.github/README.md index 05ed7097674d..92dfe283ddbc 100644 --- a/.github/README.md +++ b/.github/README.md @@ -119,6 +119,10 @@ curl -LO https://github.com/MemerGamer/LinuxFiles/releases/download/nightly/Linu - [Showcase](../docs/linux-port/SHOWCASE.md): screenshots and the feature checklist - [Packaging details](../docs/linux-port/packaging.md) and the [roadmap](../docs/linux-port/PLAN.md) +## Troubleshooting + +**Soft text or icons on niri / xwayland-satellite:** Enable **Detect display scale from the compositor (experimental)** in Settings > Appearance and restart Files to use niri's focused output scale when no Uno, Xft, GDK or Qt scale hint is present and both `NIRI_SOCKET` and `WAYLAND_DISPLAY` are set. Check stderr for `[display-scale]` to see whether IPC or CLI detection succeeded. Detection defaults off and may double-scale on some setups. `FILES_NIRI_SCALE=1` forces it on and `FILES_NIRI_SCALE=0` forces it off, overriding the saved preference. Launch with `UNO_DISPLAY_SCALE_OVERRIDE=1.25 files` to select a scale manually (replace `1.25` with your output scale). The scale is chosen at startup. See [display scale details](../docs/linux-port/appearance-transparency.md#display-scale-on-niri). + ## Reporting bugs - **Linux bugs and Linux feature requests:** open an issue in [this fork](https://github.com/MemerGamer/LinuxFiles/issues). diff --git a/docs/linux-port/appearance-transparency.md b/docs/linux-port/appearance-transparency.md index c151b8486647..f7c8ad5ee058 100644 --- a/docs/linux-port/appearance-transparency.md +++ b/docs/linux-port/appearance-transparency.md @@ -26,3 +26,11 @@ Settings > Appearance > Backdrop (`BackdropMode`) with Background opacity (`Back ## Not offered - **Native Wayland / org_kde_kwin_blur.** The Skia host is X11 only. - **Backdrop material (Mica/Acrylic).** Not implemented on Linux; the Backdrop material card is hidden. + +## Display scale on niri + +On niri with xwayland-satellite, Files can render at 1x when XWayland publishes no DPI, leaving text and icons soft after compositor scaling. Enable **Detect display scale from the compositor (experimental)** in Settings > Appearance to detect the output scale at startup as a last resort. The boolean `DetectCompositorDisplayScale` defaults to false and is read directly from the XDG user settings file before Uno/window creation, without DI. Missing, non-regular or malformed settings leave detection off. The saved preference is read only when niri detection is eligible and no environment override is set. **Restart required; some setups may double-scale.** Existing scale hints retain precedence: `UNO_DISPLAY_SCALE_OVERRIDE`, any `Xft.dpi` resource, `GDK_SCALE`/`GDK_DPI_SCALE`, or `QT_SCALE_FACTOR`/`QT_SCREEN_SCALE_FACTORS` take precedence, including an explicit 1x or malformed hint. Both `NIRI_SOCKET` and `WAYLAND_DISPLAY` must be set. + +The fallback queries the Unix socket named by `NIRI_SOCKET` for `Outputs` and `FocusedOutput`. The [niri IPC protocol](https://github.com/YaLTeR/niri/blob/main/niri-ipc/src/lib.rs) encodes these unit requests as JSON strings (`"Outputs"` and `"FocusedOutput"`), each terminated by a newline. It reads `logical.scale` from the focused output, or the first output if focus is unavailable. If socket detection fails, it resolves `niri` through the existing absolute-directory PATH lookup and runs `niri msg --json outputs` (and `focused-output`) without a shell. Socket detection and the CLI fallback each have a 500 ms budget, with up to another 500 ms to reap a terminated CLI process; replies are capped at 256 KiB. Errors, timeouts and invalid output scales leave the existing detection unchanged. Valid scales are clamped to 1–4, and the selected IPC/CLI source is logged once to stderr as `[display-scale]`. + +After the display/toolkit hints, `FILES_NIRI_SCALE=1` forces this fallback on and `FILES_NIRI_SCALE=0` forces it off, overriding the saved setting. Unset or other values use the setting. Neither value overrides display/toolkit hints. To choose a scale manually, launch with e.g. `UNO_DISPLAY_SCALE_OVERRIDE=1.25 files` (use your output's scale). Detection runs once before Uno starts; moving the window between outputs does not update the scale. A sandbox that cannot access the niri socket or executable may still need the manual override. diff --git a/docs/linux-port/investigations/pixelation-findings.md b/docs/linux-port/investigations/pixelation-findings.md index f0521d3659e3..0fdec046020c 100644 --- a/docs/linux-port/investigations/pixelation-findings.md +++ b/docs/linux-port/investigations/pixelation-findings.md @@ -1,6 +1,6 @@ # Pixelated / soft text and icons on Wayland (niri + xwayland-satellite, fractional scale) -Status: diagnosis only; no app change was justified by the measurements. Follows `ui-frameworks-wayland.md`. +Status: original headless diagnosis below; the missing-scale niri case is now addressed by the [startup IPC fallback](../appearance-transparency.md#display-scale-on-niri). Follows `ui-frameworks-wayland.md`. ## Method Headless only (`scripts/linux/headless-run.sh`, private Xvfb, sandbox HOME, `FILES_SANDBOX_DRIVES=scripts/linux/showcase-drives.txt`, 1600x1000), debug build of main (5 Oct). The scale is driven by `FILES_HEADLESS_XFT_DPI` (writes `Xft.dpi` to the private display): 96 = 1x, 144 = 1.5x, 192 = 2x. Uno reads `Xft.dpi` itself; `UNO_DISPLAY_SCALE_OVERRIDE=` (e.g. `1.5`, not a DPI) also works, `DisplayScaleResolver` falls back to `QT_SCALE_FACTOR`/`GDK_SCALE`. At 1.5x/2x the window is the same 1280x800 physical size, so fewer logical pixels fit (at 2x the sidebar collapses). Pixel crops were taken with ImageMagick (nearest-neighbour zoom). @@ -12,12 +12,12 @@ Headless only (`scripts/linux/headless-run.sh`, private Xvfb, sandbox HOME, `FIL - **DPI reporting is correct when `Xft.dpi` is an integer** (`DisplayScaleResolver` already converts fractional `Xft.dpi` and the Qt/GDK variables to an override). Icon caches (`IconCacheService`, `LinuxIconThemeProvider`) key on logical size, not scale; only a live scale change (moving between monitors) would serve stale-resolution bitmaps. Not observed, not fixed. ## Cause breakdown for the reported blur -1. **XWayland upscaling (dominant, not fixable in-app).** If the compositor/xwayland-satellite does not publish a fractional scale (no `Xft.dpi`, no `GDK_SCALE`), Uno renders at 1.0 and the compositor stretches the whole buffer by 1.5. Everything (text and icons) is then uniformly soft regardless of how well the app rasterises. Only a native Wayland host (fractional-scale-v1 + viewporter, see `ui-frameworks-wayland.md`) removes this. This could not be reproduced here: Xvfb has no compositor resampling. +1. **XWayland upscaling (dominant in the original report).** If the compositor/xwayland-satellite does not publish a fractional scale (no `Xft.dpi`, no `GDK_SCALE`), Uno renders at 1.0 and the compositor stretches the whole buffer by 1.5. Everything (text and icons) is then uniformly soft regardless of how well the app rasterises. The reporter subsequently confirmed that `UNO_DISPLAY_SCALE_OVERRIDE=1.25` renders crisply at the correct size on their niri + xwayland-satellite setup. The experimental opt-in startup IPC fallback supplies that missing scale when enabled in Settings > Appearance; native Wayland (fractional-scale-v1 + viewporter, see `ui-frameworks-wayland.md`) remains a separate host improvement. This could not be reproduced here: Xvfb has no compositor resampling. 2. **Hinting at 1x (small, upstream).** `Normal` hinting on Selawik gives the blocky look at 100%. Needs Uno to expose `SKFont.Hinting` (Slight/None); no supported switch. 3. **Icons/DPI plumbing (no defect found).** -## What a user can do today (no code change) +## Manual scale override Make the X11 side advertise the real scale so Uno renders at device resolution: launch with `UNO_DISPLAY_SCALE_OVERRIDE=1.5` (match the output scale) or export `Xft.dpi: 144` into the XWayland session. Whether xwayland-satellite then also rescales the surface (double scaling) depends on its version and was not verifiable without the real display; check on the real session. ## Not done -No code was changed because every app-side lever either already behaves correctly (icons, DPI) or is unreachable without patching Uno (hinting). Candidate follow-ups: ask/patch Uno for `SKFontHinting.Slight`; read the real output scale from niri IPC (`NIRI_SOCKET`) or the portal when `Xft.dpi` is absent (unverified without a real compositor); native Wayland host. +The original investigation made no code changes. The niri missing-scale fallback is now implemented; visual confirmation on the reporter's compositor and live scale changes between monitors remain unverified. Candidate follow-ups: ask/patch Uno for `SKFontHinting.Slight`; native Wayland host. diff --git a/src/Files.App/Data/Contracts/IAppearanceSettingsService.cs b/src/Files.App/Data/Contracts/IAppearanceSettingsService.cs index 7e27cc215318..6d1d4706dbd6 100644 --- a/src/Files.App/Data/Contracts/IAppearanceSettingsService.cs +++ b/src/Files.App/Data/Contracts/IAppearanceSettingsService.cs @@ -36,6 +36,7 @@ public interface IAppearanceSettingsService : IBaseSettingsService, INotifyPrope ColourSource ColourSource { get; set; } BackdropMode BackdropMode { get; set; } float BackgroundOpacity { get; set; } + bool DetectCompositorDisplayScale { get; set; } /// /// Gets or sets a value for the app theme background color. diff --git a/src/Files.App/Services/Settings/AppearanceSettingsService.cs b/src/Files.App/Services/Settings/AppearanceSettingsService.cs index 922165eeaa9c..a9f27039a961 100644 --- a/src/Files.App/Services/Settings/AppearanceSettingsService.cs +++ b/src/Files.App/Services/Settings/AppearanceSettingsService.cs @@ -57,6 +57,12 @@ public BackdropMode BackdropMode set => Set(value.ToString()); } + public bool DetectCompositorDisplayScale + { + get => Get(false); + set => Set(value); + } + public float BackgroundOpacity { get => AppearancePreferences.ClampOpacity(Get(0.85f), 0); diff --git a/src/Files.App/Strings/en-US/Resources.resw b/src/Files.App/Strings/en-US/Resources.resw index c74357cca8bc..0979eaef9860 100644 --- a/src/Files.App/Strings/en-US/Resources.resw +++ b/src/Files.App/Strings/en-US/Resources.resw @@ -5126,4 +5126,10 @@ High contrast keeps the window opaque. Your opacity choice is retained. + + Detect display scale from the compositor (experimental) + + + Requires a restart. Uses the niri output scale when no display or toolkit scale is configured. May double-scale on some setups. + diff --git a/src/Files.App/ViewModels/Settings/AppearanceViewModel.cs b/src/Files.App/ViewModels/Settings/AppearanceViewModel.cs index 242754cc8ced..e9c1f26428ca 100644 --- a/src/Files.App/ViewModels/Settings/AppearanceViewModel.cs +++ b/src/Files.App/ViewModels/Settings/AppearanceViewModel.cs @@ -48,6 +48,15 @@ public int SelectedBackdropMode OnPropertyChanged(nameof(IsBackgroundOpacityEnabled)); } } + public bool DetectCompositorDisplayScale + { + get => UserSettingsService.AppearanceSettingsService.DetectCompositorDisplayScale; + set + { + UserSettingsService.AppearanceSettingsService.DetectCompositorDisplayScale = value; + OnPropertyChanged(); + } + } public float BackgroundOpacity { get => UserSettingsService.AppearanceSettingsService.BackgroundOpacity; diff --git a/src/Files.App/Views/Settings/AppearancePage.xaml b/src/Files.App/Views/Settings/AppearancePage.xaml index 2a97e2eff0d2..1cb9f329895e 100644 --- a/src/Files.App/Views/Settings/AppearancePage.xaml +++ b/src/Files.App/Views/Settings/AppearancePage.xaml @@ -148,6 +148,15 @@ Value="{x:Bind ViewModel.BackgroundOpacity, Mode=TwoWay}" /> + + + + Reads the startup scale preference without constructing the app's settings services. + public static class CompositorScaleSettings + { + public const string SettingName = "DetectCompositorDisplayScale"; + private const int MaxSettingsLength = 1024 * 1024; + + public static bool Read(string settingsPath) + { + try + { + using var stream = PreviewFile.OpenRead(settingsPath); + var fileLength = stream.Length; + if (fileLength > MaxSettingsLength) + return false; + // Limit the actual read as well, in case a concurrent writer grows the file. + var buffer = new byte[(int)fileLength + 1]; + var length = stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false); + if (length == buffer.Length) + return false; + var offset = length >= 3 && buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF ? 3 : 0; + using var document = JsonDocument.Parse(buffer.AsMemory(offset, length - offset)); + return document.RootElement.ValueKind == JsonValueKind.Object && + document.RootElement.TryGetProperty(SettingName, out var value) && value.ValueKind == JsonValueKind.True; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException or NotSupportedException or ArgumentException) + { + return false; + } + } + } +} diff --git a/src/Files.Platform.Linux/Windowing/DisplayScaleResolver.cs b/src/Files.Platform.Linux/Windowing/DisplayScaleResolver.cs index 60dc603a1126..1ed1e5bbc977 100644 --- a/src/Files.Platform.Linux/Windowing/DisplayScaleResolver.cs +++ b/src/Files.Platform.Linux/Windowing/DisplayScaleResolver.cs @@ -4,21 +4,26 @@ using System; using System.Globalization; using System.Runtime.InteropServices; +using System.Text.Json; +using System.Threading; namespace Files.Platform.Linux.Windowing { /// /// Works out the display scale to hand to Uno. Uno's X11 host reads Xft.dpi (set by KDE and GNOME on X11) and honours - /// UNO_DISPLAY_SCALE_OVERRIDE; this fills the gap when Xft.dpi is absent (some XWayland sessions) from toolkit variables. + /// UNO_DISPLAY_SCALE_OVERRIDE; this fills the gap when Xft.dpi is absent (some XWayland sessions) from toolkit variables or niri IPC. /// public static class DisplayScaleResolver { public const string OverrideVariable = "UNO_DISPLAY_SCALE_OVERRIDE"; + private static int niriSourceLogged; + /// /// Returns the value to assign to , or null when Uno's own detection should be used. /// - public static string? Resolve(Func getEnv, string? xResources) + public static string? Resolve(Func getEnv, string? xResources, Func? readNiriScale = null, + bool detectCompositorDisplayScale = false, Func? readCompositorScaleSetting = null) { if (!string.IsNullOrWhiteSpace(getEnv(OverrideVariable))) return null; @@ -38,7 +43,100 @@ public static class DisplayScaleResolver double? scale = global is null && screen is null ? null : (global ?? 1.0) * (screen ?? 1.0); scale ??= ParseScale(getEnv("GDK_SCALE")); - return scale is { } s && s > 1.0 ? Math.Min(s, 4.0).ToString("0.##", CultureInfo.InvariantCulture) : null; + if (scale is { } s && s > 1.0) + return Math.Min(s, 4.0).ToString("0.##", CultureInfo.InvariantCulture); + + if (string.IsNullOrWhiteSpace(getEnv("NIRI_SOCKET")) || string.IsNullOrWhiteSpace(getEnv("WAYLAND_DISPLAY")) || + GetXftDpiText(xResources) is not null) + return null; + + foreach (var variable in new[] { OverrideVariable, "GDK_SCALE", "GDK_DPI_SCALE", "QT_SCALE_FACTOR", "QT_SCREEN_SCALE_FACTORS" }) + if (!string.IsNullOrEmpty(getEnv(variable))) + return null; + + try + { + if (!(getEnv("FILES_NIRI_SCALE") switch + { + "1" => true, + "0" => false, + _ => readCompositorScaleSetting?.Invoke() ?? detectCompositorDisplayScale, + })) + return null; + + return readNiriScale?.Invoke() is { } niri && double.IsFinite(niri) && niri > 0 + ? Math.Clamp(niri, 1.0, 4.0).ToString("0.###", CultureInfo.InvariantCulture) : null; + } + catch (Exception) + { + return null; + } + } + + /// + /// Reads niri's socket reply or CLI output, preferring the separately queried focused output. + /// + public static double? ParseNiriOutputs(string? outputsJson, string? focusedOutputJson = null) + { + if (string.IsNullOrWhiteSpace(outputsJson) || outputsJson.Length > NiriScaleClient.MaxResponseLength) + return null; + + try + { + using var document = JsonDocument.Parse(outputsJson); + var outputs = UnwrapNiriReply(document.RootElement, "Outputs"); + if (outputs.ValueKind != JsonValueKind.Object) + return null; + + var focusedName = ParseNiriFocusedName(focusedOutputJson); + JsonElement? first = null; + foreach (var output in outputs.EnumerateObject()) + { + first ??= output.Value; + if (output.Name == focusedName) + return ParseNiriOutputScale(output.Value); + } + return first is { } fallback ? ParseNiriOutputScale(fallback) : null; + } + catch (JsonException) + { + return null; + } + } + + private static JsonElement UnwrapNiriReply(JsonElement root, string response) + { + if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("Err", out _)) + return default; + if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("Ok", out var ok)) + return ok.ValueKind == JsonValueKind.Object && ok.TryGetProperty(response, out var result) ? result : default; + return root; + } + + private static string? ParseNiriFocusedName(string? json) + { + if (string.IsNullOrWhiteSpace(json) || json.Length > NiriScaleClient.MaxResponseLength) + return null; + try + { + using var document = JsonDocument.Parse(json); + var output = UnwrapNiriReply(document.RootElement, "FocusedOutput"); + return output.ValueKind == JsonValueKind.Object && output.TryGetProperty("name", out var name) && name.ValueKind == JsonValueKind.String + ? name.GetString() : null; + } + catch (JsonException) + { + return null; + } + } + + private static double? ParseNiriOutputScale(JsonElement output) + { + if (output.ValueKind != JsonValueKind.Object || !output.TryGetProperty("logical", out var logical) || + logical.ValueKind != JsonValueKind.Object || !logical.TryGetProperty("scale", out var value) || + value.ValueKind != JsonValueKind.Number || !value.TryGetDouble(out var scale) || !double.IsFinite(scale) || scale <= 0) + return null; + return Math.Clamp(scale, 1.0, 4.0); } /// @@ -133,9 +231,12 @@ public static void ApplyToProcess() return; string? resolved; + string? niriSource = null; try { - resolved = Resolve(Environment.GetEnvironmentVariable, ReadXResources()); + resolved = Resolve(Environment.GetEnvironmentVariable, ReadXResources(), + () => NiriScaleClient.ReadScale(out niriSource), + readCompositorScaleSetting: () => CompositorScaleSettings.Read(new LinuxAppDataPaths().UserSettingsFilePath)); } catch (Exception) { @@ -144,7 +245,14 @@ public static void ApplyToProcess() } if (resolved is not null) + { Environment.SetEnvironmentVariable(OverrideVariable, resolved); + if (niriSource is not null && Interlocked.Exchange(ref niriSourceLogged, 1) == 0) + { + try { Console.Error.WriteLine($"[display-scale] Using niri {niriSource}: {resolved}"); } + catch (System.IO.IOException) { } + } + } } private static string? ReadXResources() diff --git a/src/Files.Platform.Linux/Windowing/NiriScaleClient.cs b/src/Files.Platform.Linux/Windowing/NiriScaleClient.cs new file mode 100644 index 000000000000..c800fce5ee54 --- /dev/null +++ b/src/Files.Platform.Linux/Windowing/NiriScaleClient.cs @@ -0,0 +1,141 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Linux.Launching; +using System; +using System.Diagnostics; +using System.IO; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Files.Platform.Linux.Windowing +{ + internal static class NiriScaleClient + { + internal const int MaxResponseLength = 256 * 1024; + private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(500); + + internal static double? ReadScale(out string? source) + { + source = null; + var socketPath = Environment.GetEnvironmentVariable("NIRI_SOCKET"); + using (var timeout = new CancellationTokenSource(Timeout)) + { + var outputs = TrySocketRequest(socketPath, "Outputs", timeout.Token); + if (outputs is not null) + { + var focused = TrySocketRequest(socketPath, "FocusedOutput", timeout.Token); + if (DisplayScaleResolver.ParseNiriOutputs(outputs, focused) is { } scale) + { + source = "IPC"; + return scale; + } + } + } + + try + { + var binary = new PathExecutableLocator().Locate("niri"); + if (binary is null) + return null; + using var timeout = new CancellationTokenSource(Timeout); + var outputs = TryCommand(binary, "outputs", timeout.Token); + if (outputs is null) + return null; + var focused = TryCommand(binary, "focused-output", timeout.Token); + source = "CLI"; + return DisplayScaleResolver.ParseNiriOutputs(outputs, focused); + } + catch (Exception) + { + return null; + } + } + + private static string? TrySocketRequest(string? path, string request, CancellationToken cancellationToken) + { + try + { + return SocketRequestAsync(path, request, cancellationToken).GetAwaiter().GetResult(); + } + catch (Exception) + { + return null; + } + } + + private static async Task SocketRequestAsync(string? path, string request, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(path)) + return null; + using var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); + await socket.ConnectAsync(new UnixDomainSocketEndPoint(path), cancellationToken).ConfigureAwait(false); + using var stream = new NetworkStream(socket); + // Unit variants in niri's serde protocol are JSON strings, followed by a newline. + await stream.WriteAsync(Encoding.UTF8.GetBytes($"\"{request}\"\n"), cancellationToken).ConfigureAwait(false); + using var reader = new StreamReader(stream, new UTF8Encoding(false, true)); + return await ReadBoundedAsync(reader, true, cancellationToken).ConfigureAwait(false); + } + + private static string? TryCommand(string binary, string command, CancellationToken cancellationToken) + { + try + { + cancellationToken.ThrowIfCancellationRequested(); + var info = new ProcessStartInfo(binary) + { + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + foreach (var argument in new[] { "msg", "--json", command }) + info.ArgumentList.Add(argument); + using var process = TracedProcess.Start(info); + if (process is null) + return null; + try + { + process.StandardInput.Close(); + var output = ReadBoundedAsync(process.StandardOutput, false, cancellationToken); + var error = ReadBoundedAsync(process.StandardError, false, cancellationToken); + Task.WhenAll(process.WaitForExitAsync(cancellationToken), output, error).GetAwaiter().GetResult(); + return process.ExitCode == 0 ? output.Result : null; + } + finally + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + process.WaitForExit((int)Timeout.TotalMilliseconds); + } + } + } + catch (Exception) + { + return null; + } + } + + private static async Task ReadBoundedAsync(StreamReader reader, bool singleLine, CancellationToken cancellationToken) + { + var buffer = new char[4096]; + var result = new StringBuilder(); + int count; + while ((count = await reader.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false)) > 0) + { + var newline = singleLine ? Array.IndexOf(buffer, '\n', 0, count) : -1; + var length = newline >= 0 ? newline : count; + if (result.Length + length > MaxResponseLength) + throw new IOException("niri response exceeds the size limit."); + result.Append(buffer, 0, length); + if (newline >= 0) + return result.ToString(); + } + return result.ToString(); + } + } +} diff --git a/tests/Files.Platform.Tests/Windowing/CompositorScaleSettingsTests.cs b/tests/Files.Platform.Tests/Windowing/CompositorScaleSettingsTests.cs new file mode 100644 index 000000000000..72a1ea5982b4 --- /dev/null +++ b/tests/Files.Platform.Tests/Windowing/CompositorScaleSettingsTests.cs @@ -0,0 +1,110 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Platform.Linux; +using Files.Platform.Linux.Windowing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; +using System.IO; +using System.Diagnostics; +using System.Threading.Tasks; + +namespace Files.Platform.Tests.Windowing +{ + [TestClass] + public sealed class CompositorScaleSettingsTests + { + [TestMethod] + [DataRow("{}", false)] + [DataRow("\uFEFF{\"DetectCompositorDisplayScale\":true}", true)] + [DataRow("{\"DetectCompositorDisplayScale\":true}", true)] + [DataRow("{\"DetectCompositorDisplayScale\":false}", false)] + [DataRow("{\"DetectCompositorDisplayScale\":\"true\"}", false)] + [DataRow("{\"DetectCompositorDisplayScale\":1}", false)] + [DataRow("null", false)] + [DataRow("[]", false)] + [DataRow("{", false)] + public void Read_OnlyAcceptsPersistedBooleanTrue(string json, bool expected) + { + var root = Path.Combine(Path.GetTempPath(), "files-scale-" + Guid.NewGuid().ToString("N")); + var paths = new LinuxAppDataPaths(key => key == "XDG_CONFIG_HOME" ? root : null, root); + try + { + Directory.CreateDirectory(paths.SettingsDirectory); + Assert.IsFalse(CompositorScaleSettings.Read(paths.UserSettingsFilePath)); + File.WriteAllText(paths.UserSettingsFilePath, json); + Assert.AreEqual(expected, CompositorScaleSettings.Read(paths.UserSettingsFilePath)); + } + finally + { + Directory.Delete(root, true); + } + } + + [TestMethod] + public void Read_DirectoryDefaultsOff() + { + Assert.IsFalse(CompositorScaleSettings.Read(Path.GetTempPath())); + } + + [TestMethod] + public void Read_FifoDefaultsOffWithoutBlocking() + { + if (!OperatingSystem.IsLinux() || !File.Exists("/usr/bin/mkfifo")) + Assert.Inconclusive("Linux and mkfifo are required."); + + var path = Path.Combine(Path.GetTempPath(), "files-scale-fifo-" + Guid.NewGuid().ToString("N")); + Task? read = null; + try + { + var info = new ProcessStartInfo("/usr/bin/mkfifo") { UseShellExecute = false }; + info.ArgumentList.Add(path); + using (var process = Process.Start(info)!) + { + try + { + Assert.IsTrue(process.WaitForExit(1000)); + Assert.AreEqual(0, process.ExitCode); + } + finally + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(500); + } + } + } + read = Task.Run(() => CompositorScaleSettings.Read(path)); + Assert.IsTrue(read.Wait(1000), "Reading a FIFO must not wait for a writer."); + Assert.IsFalse(read.Result); + } + finally + { + if (read is not null && !read.IsCompleted) + { + // Unblock a regressed reader so the test doesn't leave a waiting thread. + using var unblock = File.Open(path, FileMode.Open, FileAccess.ReadWrite); + read.Wait(1000); + } + File.Delete(path); + } + } + + + [TestMethod] + public void Read_OversizedFileDefaultsOff() + { + var path = Path.GetTempFileName(); + try + { + File.WriteAllText(path, new string(' ', 1024 * 1024 + 1)); + Assert.IsFalse(CompositorScaleSettings.Read(path)); + } + finally + { + File.Delete(path); + } + } + } +} diff --git a/tests/Files.Platform.Tests/Windowing/DisplayScaleResolverTests.cs b/tests/Files.Platform.Tests/Windowing/DisplayScaleResolverTests.cs index 1e9a01a5e2e0..06a6380d8f53 100644 --- a/tests/Files.Platform.Tests/Windowing/DisplayScaleResolverTests.cs +++ b/tests/Files.Platform.Tests/Windowing/DisplayScaleResolverTests.cs @@ -3,6 +3,7 @@ using Files.Platform.Linux.Windowing; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System; using System.Collections.Generic; namespace Files.Platform.Tests.Windowing @@ -10,6 +11,15 @@ namespace Files.Platform.Tests.Windowing [TestClass] public sealed class DisplayScaleResolverTests { + private const string NiriOutputsFixture = """ + {"DP-1":{"name":"DP-1","logical":{"scale":1.25,"x":0,"y":0}}, + "HDMI-A-1":{"name":"HDMI-A-1","logical":{"scale":2,"x":1920,"y":0}}} + """; + + private const string NiriFocusedFixture = """ + {"name":"HDMI-A-1","logical":{"scale":2}} + """; + private static string? Resolve(string? xResources, params (string Key, string Value)[] env) { var map = new Dictionary(); @@ -107,5 +117,213 @@ public void XftDpi_ToleratesWhitespaceBeforeColon() Assert.IsNull(Resolve("Xft.dpi : 144\n", ("GDK_SCALE", "2"))); Assert.AreEqual(1.5, DisplayScaleResolver.GetEffectiveScale(_ => null, " Xft.dpi\t:\t144\r\n")); } + + + [TestMethod] + public void NiriOutputs_CliAndSocketFixtures_PreferFocusedOutput() + { + Assert.AreEqual(2.0, DisplayScaleResolver.ParseNiriOutputs(NiriOutputsFixture, NiriFocusedFixture)); + Assert.AreEqual(2.0, DisplayScaleResolver.ParseNiriOutputs( + "{\"Ok\":{\"Outputs\":" + NiriOutputsFixture + "}}", + "{\"Ok\":{\"FocusedOutput\":" + NiriFocusedFixture + "}}")); + } + + [TestMethod] + public void NiriOutputs_UnknownFocus_UsesFirstOutput() + { + foreach (var focus in new string?[] { null, "null", "{}", "garbage", "{\"name\":\"missing\"}", "{\"Ok\":{\"FocusedOutput\":null}}" }) + Assert.AreEqual(1.25, DisplayScaleResolver.ParseNiriOutputs(NiriOutputsFixture, focus), focus); + } + + [TestMethod] + public void NiriOutputs_MissingFirstScale_CanStillUseFocusedOutput() + { + const string outputs = """{"DP-1":{"logical":null},"HDMI-A-1":{"logical":{"scale":2}}}"""; + Assert.IsNull(DisplayScaleResolver.ParseNiriOutputs(outputs)); + Assert.AreEqual(2.0, DisplayScaleResolver.ParseNiriOutputs(outputs, NiriFocusedFixture)); + } + + [TestMethod] + [DataRow("garbage")] + [DataRow("[]")] + [DataRow("null")] + [DataRow("{}")] + [DataRow("{\"Err\":\"failed\"}")] + [DataRow("{\"Ok\":{\"Outputs\":[]}}")] + [DataRow("{\"Ok\":{\"Version\":\"26.04\"}}")] + [DataRow("{\"DP-1\":{}}")] + [DataRow("{\"DP-1\":{\"logical\":null}}")] + [DataRow("{\"DP-1\":{\"logical\":{}}}")] + [DataRow("{\"DP-1\":{\"logical\":{\"scale\":\"1.25\"}}}")] + [DataRow("{\"DP-1\":{\"logical\":{\"scale\":0}}}")] + [DataRow("{\"DP-1\":{\"logical\":{\"scale\":-1}}}")] + [DataRow("{\"DP-1\":{\"logical\":{\"scale\":1e999}}}")] + public void NiriOutputs_MalformedFixtures_ReturnNull(string json) + { + Assert.IsNull(DisplayScaleResolver.ParseNiriOutputs(json)); + } + + [TestMethod] + [DataRow(0.5, 1.0)] + [DataRow(1.25, 1.25)] + [DataRow(8.0, 4.0)] + public void NiriOutputs_ClampsScale(double input, double expected) + { + var json = "{\"DP-1\":{\"logical\":{\"scale\":" + input.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}}}"; + Assert.AreEqual(expected, DisplayScaleResolver.ParseNiriOutputs(json)); + } + + [TestMethod] + [DataRow(null, false, false)] + [DataRow(null, true, true)] + [DataRow("1", false, true)] + [DataRow("1", true, true)] + [DataRow("0", false, false)] + [DataRow("0", true, false)] + [DataRow("invalid", false, false)] + [DataRow("invalid", true, true)] + public void NiriFallback_EnvironmentOverridesOptInSetting(string? value, bool setting, bool enabled) + { + var env = NiriEnvironment(); + env.Remove("FILES_NIRI_SCALE"); + if (value is not null) env["FILES_NIRI_SCALE"] = value; + var calls = 0; + var result = DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => { calls++; return 1.25; }, setting); + Assert.AreEqual(enabled ? "1.25" : null, result); + Assert.AreEqual(enabled ? 1 : 0, calls); + } + + [TestMethod] + public void NiriFallback_ReadsSettingOnlyWhenNeeded() + { + var env = NiriEnvironment(); + var calls = 0; + bool ReadSetting() { calls++; return true; } + string? Resolve() => DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => 1.25, + readCompositorScaleSetting: ReadSetting); + + Assert.AreEqual("1.25", Resolve()); + env["FILES_NIRI_SCALE"] = "0"; + Assert.IsNull(Resolve()); + env.Remove("FILES_NIRI_SCALE"); + env["GDK_SCALE"] = "1"; + Assert.IsNull(Resolve()); + env.Remove("GDK_SCALE"); + env.Remove("WAYLAND_DISPLAY"); + Assert.IsNull(Resolve()); + Assert.AreEqual(0, calls); + env["WAYLAND_DISPLAY"] = "wayland-test"; + Assert.AreEqual("1.25", Resolve()); + Assert.AreEqual(1, calls); + Assert.IsNull(DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => 1.25, + readCompositorScaleSetting: () => throw new System.IO.IOException())); + } + + + [TestMethod] + public void NiriFallback_DefaultIsOff() + { + var env = NiriEnvironment(); + env.Remove("FILES_NIRI_SCALE"); + var calls = 0; + Assert.IsNull(DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => { calls++; return 2; })); + Assert.AreEqual(0, calls); + } + + [TestMethod] + [DataRow("UNO_DISPLAY_SCALE_OVERRIDE", "1.5", null)] + [DataRow("GDK_SCALE", "2", "2")] + [DataRow("GDK_SCALE", "1", null)] + [DataRow("QT_SCALE_FACTOR", "1.5", "1.5")] + [DataRow("QT_SCREEN_SCALE_FACTORS", "DP-1=1.25", "1.25")] + public void NiriFallback_DisplayHintsBeatForcedOnAndSetting(string variable, string value, string? expected) + { + var env = NiriEnvironment(); + env[variable] = value; + var calls = 0; + double? ReadScale() { calls++; return 2; } + Assert.AreEqual(expected, DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, ReadScale, true)); + Assert.IsNull(DisplayScaleResolver.Resolve(NiriEnvironment().GetValueOrDefault, "Xft.dpi: 144", ReadScale, true)); + Assert.AreEqual(0, calls); + } + + private static Dictionary NiriEnvironment() => new() + { + ["NIRI_SOCKET"] = "/tmp/files-test-niri.sock", + ["FILES_NIRI_SCALE"] = "1", + ["WAYLAND_DISPLAY"] = "wayland-test", + }; + + [TestMethod] + public void NiriOutputs_OversizedFixture_ReturnsNull() + { + Assert.IsNull(DisplayScaleResolver.ParseNiriOutputs(new string(' ', 256 * 1024) + NiriOutputsFixture)); + } + + [TestMethod] + public void NiriOutputs_MalformedFocusedScale_DoesNotUseAnotherOutput() + { + const string outputs = """{"DP-1":{"logical":{"scale":1.25}},"HDMI-A-1":{"logical":{}}}"""; + Assert.IsNull(DisplayScaleResolver.ParseNiriOutputs(outputs, NiriFocusedFixture)); + } + + [TestMethod] + public void NiriFallback_OnlyQueriesWithoutOtherScaleHints() + { + var env = NiriEnvironment(); + var calls = 0; + double? ReadScale() { calls++; return DisplayScaleResolver.ParseNiriOutputs(NiriOutputsFixture); } + Assert.AreEqual("1.25", DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, ReadScale)); + Assert.AreEqual(1, calls); + + foreach (var variable in new[] { "UNO_DISPLAY_SCALE_OVERRIDE", "GDK_SCALE", "GDK_DPI_SCALE", "QT_SCALE_FACTOR", "QT_SCREEN_SCALE_FACTORS" }) + { + foreach (var value in new[] { "1", "2", "garbage", " " }) + { + env[variable] = value; + DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, ReadScale); + Assert.AreEqual(1, calls, variable + "=" + value); + } + env.Remove(variable); + } + + foreach (var dpi in new[] { "96", "144", "120.0", "garbage", "" }) + { + DisplayScaleResolver.Resolve(env.GetValueOrDefault, "Xft.dpi: " + dpi, ReadScale); + Assert.AreEqual(1, calls, dpi); + } + } + + [TestMethod] + public void NiriFallback_RequiresSessionAndHonoursOptOut() + { + foreach (var variable in new[] { "NIRI_SOCKET", "WAYLAND_DISPLAY", "FILES_NIRI_SCALE" }) + { + var env = NiriEnvironment(); + if (variable == "FILES_NIRI_SCALE") + env[variable] = "0"; + else + env.Remove(variable); + var calls = 0; + Assert.IsNull(DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => { calls++; return 2; })); + Assert.AreEqual(0, calls, variable); + } + var disabled = NiriEnvironment(); + disabled["FILES_NIRI_SCALE"] = "0"; + disabled["GDK_SCALE"] = "2"; + Assert.AreEqual("2", DisplayScaleResolver.Resolve(disabled.GetValueOrDefault, null)); + } + + [TestMethod] + public void NiriFallback_ErrorsAndInvalidScales_LeaveUnoDetection() + { + var env = NiriEnvironment(); + Assert.IsNull(DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => throw new TimeoutException())); + foreach (var scale in new double?[] { null, double.NaN, double.PositiveInfinity, -1, 0 }) + Assert.IsNull(DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => scale)); + Assert.AreEqual("1", DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => 0.5)); + Assert.AreEqual("4", DisplayScaleResolver.Resolve(env.GetValueOrDefault, null, () => 8)); + } + } }