From 1e25513c2401af8fc6ff0d96d3154eb88416eb48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Wed, 14 Oct 2026 19:24:06 +0300 Subject: [PATCH 1/2] Fix: Use the icon theme's native sizes for small file icons on Linux Breeze and most freedesktop themes draw small icons for fixed pixel grids (16/22/32/48) while the layout requested 20px and 24px, so every folder and mime icon was a 22px SVG resampled by a non-integer factor. The icon theme provider now reports the nearest declared Places/MimeTypes size and the layout helper adopts it for icon requests up to 64px. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01BTZhMsNyJ6k4VC68CNb5WU --- .../Helpers/Layout/LayoutSizeKindHelper.cs | 19 +++++++ .../Icons/IIconThemeProvider.cs | 5 ++ .../Icons/IconThemeIndex.cs | 7 ++- .../Icons/LinuxIconThemeProvider.cs | 51 +++++++++++++++++++ .../Icons/IconThemeTests.cs | 47 +++++++++++++++++ 5 files changed, 128 insertions(+), 1 deletion(-) diff --git a/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs b/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs index f75cc6d7776a..69b3466c49e9 100644 --- a/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs +++ b/src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs @@ -1,6 +1,10 @@ // Copyright (c) Files Community // Licensed under the MIT License. +#if !WINDOWS +using Files.Platform.Abstractions.Icons; +#endif + namespace Files.App.Helpers { public static class LayoutSizeKindHelper @@ -16,6 +20,21 @@ public static uint GetIconSize(FolderLayoutModes folderLayoutMode) { if (folderLayoutMode == FolderLayoutModes.GridView) return (uint)Math.Max(1, GetGridViewItemWidth(LayoutSettingsService.GridViewSize) - 24); + +#if WINDOWS + return GetRequestedIconSize(folderLayoutMode); +#else + // Icon themes draw small sizes for their own pixel grid (Breeze: 16/22/32), so the layout adopts the nearest one. + return IconThemeProvider?.GetNativeSize(GetRequestedIconSize(folderLayoutMode)) ?? GetRequestedIconSize(folderLayoutMode); +#endif + } + +#if !WINDOWS + private static IIconThemeProvider? IconThemeProvider { get; } = Ioc.Default.GetService(); +#endif + + private static uint GetRequestedIconSize(FolderLayoutModes folderLayoutMode) + { return folderLayoutMode switch { // Details diff --git a/src/Files.Platform.Abstractions/Icons/IIconThemeProvider.cs b/src/Files.Platform.Abstractions/Icons/IIconThemeProvider.cs index 376de078e8a6..2e0ea9e73c16 100644 --- a/src/Files.Platform.Abstractions/Icons/IIconThemeProvider.cs +++ b/src/Files.Platform.Abstractions/Icons/IIconThemeProvider.cs @@ -42,5 +42,10 @@ public interface IIconThemeProvider /// Resolves candidates in lookup order, including alternate sizes and inherited themes, so callers can skip images that fail to decode. /// Task> ResolveIconCandidatesAsync(IReadOnlyList iconNames, uint size, int scale = 1, CancellationToken cancellationToken = default); + + /// + /// Gets the size closest to that the current theme draws at its own pixel grid, or when the theme has no fixed sizes. + /// + uint GetNativeSize(uint size, int scale = 1); } } diff --git a/src/Files.Platform.Linux/Icons/IconThemeIndex.cs b/src/Files.Platform.Linux/Icons/IconThemeIndex.cs index 3de200f1b413..c5aa1fa6cf9b 100644 --- a/src/Files.Platform.Linux/Icons/IconThemeIndex.cs +++ b/src/Files.Platform.Linux/Icons/IconThemeIndex.cs @@ -27,6 +27,11 @@ public enum IconDirectoryType /// public sealed record IconDirectory(string Path, int Size, int Scale, IconDirectoryType Type, int MinSize, int MaxSize, int Threshold) { + /// + /// Gets the icon context (Places, MimeTypes, ...) the directory declares, if any. + /// + public string? Context { get; init; } + /// /// Determines whether the directory can serve an icon of the given size and scale. /// @@ -130,7 +135,7 @@ public static IconThemeIndex Parse(string content) var min = TryInt(s, "MinSize", out var mn) ? mn : size; var max = TryInt(s, "MaxSize", out var mx) ? mx : size; var threshold = TryInt(s, "Threshold", out var th) ? th : 2; - dirs.Add(new IconDirectory(name, size, scale, type, min, max, threshold)); + dirs.Add(new IconDirectory(name, size, scale, type, min, max, threshold) { Context = s.GetValueOrDefault("Context") }); } return new IconThemeIndex { Inherits = inherits, Directories = dirs }; diff --git a/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs b/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs index 2a47aa1b9b10..94b831dcf23a 100644 --- a/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs +++ b/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs @@ -93,6 +93,7 @@ public sealed class LinuxIconThemeProvider : IIconThemeProvider private readonly Lazy _themeName; private readonly ConcurrentDictionary _themes = new(StringComparer.Ordinal); private readonly ConcurrentDictionary<(string Name, int Size, int Scale), IconLookupResult?> _cache = new(); + private readonly ConcurrentDictionary<(uint Size, int Scale), uint> _nativeSizes = new(); /// /// Initializes a new instance using the process environment. @@ -159,6 +160,56 @@ public Task> ResolveIconCandidatesAsync(IReadOnl }, cancellationToken); } + // Small artwork is drawn for its pixel grid; resampling 22px Breeze folders to 20px blurs every stroke. + private const uint MaxNativeSnapSize = 64; + + // The contexts file browsers draw from. Breeze has actions/24 but no places/24, so other contexts cannot vote. + private static readonly string[] NativeSizeContexts = ["Places", "MimeTypes"]; + + /// + public uint GetNativeSize(uint size, int scale = 1) + { + if (size == 0 || size > MaxNativeSnapSize) + return size; + + return _nativeSizes.GetOrAdd((size, Math.Max(1, scale)), key => FindNativeSize(key.Size, key.Scale)); + } + + private uint FindNativeSize(uint size, int scale) + { + var directories = new List(); + var visited = new HashSet(StringComparer.Ordinal); + CollectDirectories(CurrentThemeName, visited, directories); + + var candidates = directories.Where(d => d.Scale == scale && d.Type != IconDirectoryType.Scalable).ToList(); + var contextual = candidates.Where(d => d.Context is not null && NativeSizeContexts.Contains(d.Context, StringComparer.OrdinalIgnoreCase)).ToList(); + if (contextual.Count > 0) + candidates = contextual; + + if (candidates.Count == 0) + return size; + + // Nearest declared size; a tie prefers the larger one so icons never shrink below the layout's request. + var best = candidates + .Select(d => (uint)d.Size) + .Distinct() + .OrderBy(s => Math.Abs((long)s - size)) + .ThenByDescending(s => s) + .First(); + + return best; + } + + private void CollectDirectories(string theme, HashSet visited, List directories) + { + if (!visited.Add(theme) || GetTheme(theme) is not { } index) + return; + + directories.AddRange(index.Directories); + foreach (var parent in index.Inherits) + CollectDirectories(parent, visited, directories); + } + private IconLookupResult? Resolve(string iconName, int size, int scale) { if (string.IsNullOrEmpty(iconName)) diff --git a/tests/Files.Platform.Tests/Icons/IconThemeTests.cs b/tests/Files.Platform.Tests/Icons/IconThemeTests.cs index 6652530ef584..279e1ead1174 100644 --- a/tests/Files.Platform.Tests/Icons/IconThemeTests.cs +++ b/tests/Files.Platform.Tests/Icons/IconThemeTests.cs @@ -92,6 +92,53 @@ public void Index_ParsesDirectoriesAndInherits() Assert.AreEqual(2, index.Directories[1].Scale); } + [TestMethod] + public void Index_ParsesContext() + { + var index = IconThemeIndex.Parse("[Icon Theme]\nDirectories=places/22,actions/24\n\n[places/22]\nSize=22\nContext=Places\nType=Fixed\n\n[actions/24]\nSize=24\nType=Fixed\n"); + + Assert.AreEqual("Places", index.Directories[0].Context); + Assert.IsNull(index.Directories[1].Context); + } + + [TestMethod] + public void NativeSize_PicksNearestDeclaredSizeAcrossInheritance() + { + var provider = CreateProvider(); + + // Child declares 16 and 48, Parent 32, hicolor 64; scalable directories do not count. + Assert.AreEqual(16u, provider.GetNativeSize(20)); + Assert.AreEqual(32u, provider.GetNativeSize(24)); // tie between 16 and 32 prefers the larger size + Assert.AreEqual(48u, provider.GetNativeSize(40)); + Assert.AreEqual(64u, provider.GetNativeSize(64)); + Assert.AreEqual(96u, provider.GetNativeSize(96)); // large artwork scales smoothly + Assert.AreEqual(0u, provider.GetNativeSize(0)); + Assert.AreEqual(20u, provider.GetNativeSize(20, 2)); // no @2x directories + } + + [TestMethod] + public void NativeSize_OnlyCountsPlacesAndMimeTypesWhenDeclared() + { + Directory.CreateDirectory(Path.Combine(_icons, "Ctx")); + File.WriteAllText(Path.Combine(_icons, "Ctx", "index.theme"), + "[Icon Theme]\nName=Ctx\nDirectories=places/22,mimetypes/16,actions/24,apps/20\n\n[places/22]\nSize=22\nContext=Places\nType=Fixed\n\n[mimetypes/16]\nSize=16\nContext=MimeTypes\nType=Fixed\n\n[actions/24]\nSize=24\nContext=Actions\nType=Fixed\n\n[apps/20]\nSize=20\nContext=Applications\nType=Fixed\n"); + var provider = CreateProvider("Ctx"); + + Assert.AreEqual(22u, provider.GetNativeSize(20)); + Assert.AreEqual(22u, provider.GetNativeSize(24)); + Assert.AreEqual(16u, provider.GetNativeSize(16)); + } + + [TestMethod] + public void NativeSize_KeepsRequestWithoutFixedDirectories() + { + Directory.CreateDirectory(Path.Combine(_icons, "Vector")); + File.WriteAllText(Path.Combine(_icons, "Vector", "index.theme"), "[Icon Theme]\nName=Vector\nDirectories=scalable/places\n\n[scalable/places]\nSize=48\nType=Scalable\nMinSize=8\nMaxSize=512\n"); + var provider = CreateProvider("Vector"); + + Assert.AreEqual(20u, provider.GetNativeSize(20)); + } + [TestMethod] public async Task Resolve_PicksExactSizeDirectory() { From f6185ff0861c8f456afd827a25d196698c8b4f8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kov=C3=A1cs=20B=C3=A1lint=20Hunor?= Date: Wed, 14 Oct 2026 19:50:34 +0300 Subject: [PATCH 2/2] Fix: Recolour themed icons for the app theme and rank scalable directories by range Breeze's 16/22px places and mimetypes icons paint with currentColor through a current-color-scheme stylesheet that the host is expected to replace; without that, breeze-dark icons are white on the light theme. SvgRasterizer now substitutes a Breeze-style palette chosen from the app theme, like KIconLoader does. The lookup also ranks a Scalable directory by its MinSize..MaxSize range instead of ahead of every fixed size, so 20px no longer resolves to Breeze's places/96 artwork. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01BTZhMsNyJ6k4VC68CNb5WU --- .../Helpers/MenuFlyout/LinuxAppIcons.cs | 2 +- .../Desktop/Services/LinuxIconHelper.cs | 48 ++++++++++++++----- .../Storage/Helpers/DriveHelpers.Linux.cs | 2 +- .../Icons/IconColorScheme.cs | 42 ++++++++++++++++ .../Icons/LinuxIconThemeProvider.cs | 5 +- .../Icons/SvgRasterizer.cs | 29 +++++++---- .../Icons/IconThemeTests.cs | 18 +++++++ .../Icons/SvgRasterizerTests.cs | 22 +++++++++ 8 files changed, 143 insertions(+), 25 deletions(-) create mode 100644 src/Files.Platform.Linux/Icons/IconColorScheme.cs diff --git a/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs b/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs index 6d5543cf42ee..ab1aed0f5acc 100644 --- a/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs +++ b/src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs @@ -34,7 +34,7 @@ internal static class LinuxAppIcons if (result is { } found) { if (found.IsSvg) - bytes = await Task.Run(() => SvgRasterizer.RenderToPng(found.Path, (int)size)); + bytes = await Task.Run(() => SvgRasterizer.RenderToPng(found.Path, (int)size, Files.App.Utils.Storage.LinuxIconHelper.CurrentColorScheme)); else if (!found.Path.EndsWith(".xpm", StringComparison.OrdinalIgnoreCase)) bytes = await File.ReadAllBytesAsync(found.Path); } diff --git a/src/Files.App/Platforms/Desktop/Services/LinuxIconHelper.cs b/src/Files.App/Platforms/Desktop/Services/LinuxIconHelper.cs index e436466cee94..7edce704d6dc 100644 --- a/src/Files.App/Platforms/Desktop/Services/LinuxIconHelper.cs +++ b/src/Files.App/Platforms/Desktop/Services/LinuxIconHelper.cs @@ -8,6 +8,7 @@ using Files.Platform.Linux.Icons; using Files.Platform.Linux.Mime; using Microsoft.Extensions.Logging; +using Microsoft.UI.Xaml; using SkiaSharp; using System.Collections.Concurrent; using System.Globalization; @@ -21,7 +22,7 @@ namespace Files.App.Utils.Storage /// internal static class LinuxIconHelper { - private static readonly ConcurrentDictionary<(string Name, uint Size), byte[]?> _themeCache = new(); + private static readonly ConcurrentDictionary<(string Name, uint Size, IconColorScheme Scheme), byte[]?> _themeCache = new(); private static readonly ConcurrentDictionary _mimeIconNames = new(StringComparer.Ordinal); private const long MimeIconNamesTtlMs = 5000; @@ -30,6 +31,24 @@ internal static class LinuxIconHelper private static IMimeTypeService Mime => Ioc.Default.GetRequiredService(); private static IUserDirectories Directories => Ioc.Default.GetRequiredService(); + /// + /// The palette for themed monochrome icons, following the application theme like KIconLoader follows the KDE scheme. + /// + internal static IconColorScheme CurrentColorScheme + { + get + { + var mode = Ioc.Default.GetService()?.AppThemeMode ?? ElementTheme.Default; + var isDark = mode switch + { + ElementTheme.Dark => true, + ElementTheme.Light => false, + _ => Files.Platform.Linux.Theme.LinuxColorScheme.IsDark, + }; + return IconColorScheme.ForTheme(isDark); + } + } + public static async Task GetIconAsync(string? path, uint size, bool isFolder, IconOptions options, CancellationToken cancellationToken = default) { try @@ -63,13 +82,14 @@ internal static class LinuxIconHelper return null; var names = await GetIconNamesAsync(path, isFolder); - var key = (names[0], size); + var scheme = CurrentColorScheme; + var key = (names[0], size, scheme); if (_themeCache.TryGetValue(key, out var cached)) return cached; - var bytes = await LoadThemeIconAsync(names, size); + var bytes = await LoadThemeIconAsync(names, size, scheme); if (bytes is null && isFolder) - bytes = await Task.Run(() => LoadIconFile(Path.Combine(AppContext.BaseDirectory, "Assets", "FolderIcon.png"), size)); + bytes = await Task.Run(() => LoadIconFile(Path.Combine(AppContext.BaseDirectory, "Assets", "FolderIcon.png"), size, scheme)); _themeCache[key] = bytes; return bytes; } @@ -90,11 +110,12 @@ internal static class LinuxIconHelper if (string.IsNullOrEmpty(path) || new FileInfo(path).LinkTarget is null) return null; - var key = ("emblem-symbolic-link", size); + var scheme = CurrentColorScheme; + var key = ("emblem-symbolic-link", size, scheme); if (_themeCache.TryGetValue(key, out var cached)) return cached; - var bytes = await LoadThemeIconAsync(["emblem-symbolic-link", "emblem-link", "emblem-symbolic-link-symbolic"], size); + var bytes = await LoadThemeIconAsync(["emblem-symbolic-link", "emblem-link", "emblem-symbolic-link-symbolic"], size, scheme); _themeCache[key] = bytes; return bytes; } @@ -113,16 +134,17 @@ internal static class LinuxIconHelper { var icon = await Task.Run(() => DesktopEntryDisplay.TryRead(path, CultureInfo.CurrentUICulture)?.Icon); + var scheme = CurrentColorScheme; if (DesktopEntryDisplay.IsSafeIconName(icon)) - return await LoadThemeIconAsync([icon!], size); + return await LoadThemeIconAsync([icon!], size, scheme); if (DesktopEntryDisplay.IsAllowedIconPath(icon, Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), out var iconPath)) - return await Task.Run(() => LoadIconFile(iconPath, size)); + return await Task.Run(() => LoadIconFile(iconPath, size, scheme)); return null; } - private static byte[]? LoadIconFile(string iconPath, uint size) + private static byte[]? LoadIconFile(string iconPath, uint size, IconColorScheme? scheme) { try { @@ -134,7 +156,7 @@ internal static class LinuxIconHelper return null; if (iconPath.EndsWith(".svg", StringComparison.OrdinalIgnoreCase)) - return SvgRasterizer.RenderToPng(data, (int)size); + return SvgRasterizer.RenderToPng(data, (int)size, scheme); // PNG signature if (data.Length <= 8 || data[0] != 0x89 || data[1] != (byte)'P' || data[2] != (byte)'N' || data[3] != (byte)'G') @@ -195,13 +217,13 @@ private static async Task> GetIconNamesAsync(string? path, return null; } - private static async Task LoadThemeIconAsync(IReadOnlyList names, uint size) + private static async Task LoadThemeIconAsync(IReadOnlyList names, uint size, IconColorScheme? scheme) { var result = await Theme.ResolveIconAsync(names, size); if (result is null) return null; - var bytes = await Task.Run(() => LoadIconFile(result.Value.Path, size)); + var bytes = await Task.Run(() => LoadIconFile(result.Value.Path, size, scheme)); if (bytes is not null) return bytes; @@ -210,7 +232,7 @@ private static async Task> GetIconNamesAsync(string? path, if (candidate.Path == result.Value.Path) continue; - bytes = await Task.Run(() => LoadIconFile(candidate.Path, size)); + bytes = await Task.Run(() => LoadIconFile(candidate.Path, size, scheme)); if (bytes is not null) return bytes; } diff --git a/src/Files.App/Utils/Storage/Helpers/DriveHelpers.Linux.cs b/src/Files.App/Utils/Storage/Helpers/DriveHelpers.Linux.cs index 16112cd1f591..b879384a5e72 100644 --- a/src/Files.App/Utils/Storage/Helpers/DriveHelpers.Linux.cs +++ b/src/Files.App/Utils/Storage/Helpers/DriveHelpers.Linux.cs @@ -581,7 +581,7 @@ private static string DecodeUdevName(string name) { if (found.IsSvg) { - var png = await Task.Run(() => Files.Platform.Linux.Icons.SvgRasterizer.RenderToPng(found.Path, (int)size)); + var png = await Task.Run(() => Files.Platform.Linux.Icons.SvgRasterizer.RenderToPng(found.Path, (int)size, LinuxIconHelper.CurrentColorScheme)); if (png is not null) return png; } diff --git a/src/Files.Platform.Linux/Icons/IconColorScheme.cs b/src/Files.Platform.Linux/Icons/IconColorScheme.cs new file mode 100644 index 000000000000..fb6d0a858678 --- /dev/null +++ b/src/Files.Platform.Linux/Icons/IconColorScheme.cs @@ -0,0 +1,42 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +namespace Files.Platform.Linux.Icons +{ + /// + /// The palette substituted into themed SVG icons that paint with currentColor through the + /// current-color-scheme stylesheet (Breeze and derivatives), as KIconLoader does for KDE applications. + /// + public sealed record IconColorScheme( + string Text, + string Background, + string Highlight, + string HighlightedText, + string PositiveText, + string NeutralText, + string NegativeText, + string ActiveText, + string Complement, + string Contrast) + { + /// Breeze Light colours. + public static IconColorScheme Light { get; } = new("#232629", "#fcfcfc", "#3daee9", "#fcfcfc", "#27ae60", "#f67400", "#da4453", "#3daee9", "#31363b", "#fcfcfc"); + + /// Breeze Dark colours. + public static IconColorScheme Dark { get; } = new("#fcfcfc", "#232629", "#3daee9", "#fcfcfc", "#27ae60", "#f67400", "#da4453", "#3daee9", "#fcfcfc", "#232629"); + + /// + /// Gets the scheme matching the application theme. + /// + public static IconColorScheme ForTheme(bool isDark) => isDark ? Dark : Light; + + /// + /// Builds the stylesheet KIconLoader injects, covering every ColorScheme-* class Breeze icons use. + /// + public string ToStyleSheet() => + $".ColorScheme-Text {{ color:{Text}; }} .ColorScheme-Background {{ color:{Background}; }} .ColorScheme-Highlight {{ color:{Highlight}; }} " + + $".ColorScheme-HighlightedText {{ color:{HighlightedText}; }} .ColorScheme-PositiveText {{ color:{PositiveText}; }} .ColorScheme-NeutralText {{ color:{NeutralText}; }} " + + $".ColorScheme-NegativeText {{ color:{NegativeText}; }} .ColorScheme-ActiveText {{ color:{ActiveText}; }} .ColorScheme-Complement {{ color:{Complement}; }} " + + $".ColorScheme-Contrast {{ color:{Contrast}; }} .ColorScheme-Accent {{ color:{Highlight}; }}"; + } +} diff --git a/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs b/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs index 94b831dcf23a..1703a4acb9b7 100644 --- a/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs +++ b/src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs @@ -270,8 +270,9 @@ private IEnumerable FindInTheme(string theme, string name, int if (!visited.Add(theme) || GetTheme(theme) is not { } index) yield break; - // Without an exact match, scalable artwork beats resampling a raster frame - foreach (var directory in index.Directories.OrderBy(d => d.Matches(size, scale) ? 0 : d.Type == IconDirectoryType.Scalable ? 1 : 2).ThenBy(d => d.Distance(size, scale))) + // Matching directories first, then the nearest by distance. A scalable directory only matches inside its + // MinSize..MaxSize range: Breeze declares places/96 as Scalable 96..256, and serving 20px from it blurs every edge. + foreach (var directory in index.Directories.OrderBy(d => d.Matches(size, scale) ? 0 : 1).ThenBy(d => d.Distance(size, scale))) { foreach (var baseDir in _options.IconDirectories) { diff --git a/src/Files.Platform.Linux/Icons/SvgRasterizer.cs b/src/Files.Platform.Linux/Icons/SvgRasterizer.cs index adeb4f3a9521..f3a80be7972d 100644 --- a/src/Files.Platform.Linux/Icons/SvgRasterizer.cs +++ b/src/Files.Platform.Linux/Icons/SvgRasterizer.cs @@ -1,4 +1,4 @@ -// Copyright (c) Files Community +// Copyright (c) Files Community // Licensed under the MIT License. using SkiaSharp; @@ -16,15 +16,16 @@ namespace Files.Platform.Linux.Icons /// public static class SvgRasterizer { - private static readonly ConcurrentDictionary<(string Path, int Size), byte[]?> _cache = new(); + private static readonly ConcurrentDictionary<(string Path, int Size, IconColorScheme? Scheme), byte[]?> _cache = new(); /// /// Renders the SVG at into a square PNG of , or returns on failure. + /// recolours icons that paint through the current-color-scheme stylesheet. /// - public static byte[]? RenderToPng(string path, int pixelSize) + public static byte[]? RenderToPng(string path, int pixelSize, IconColorScheme? scheme = null) { pixelSize = Math.Clamp(pixelSize, 8, 1024); - return _cache.GetOrAdd((path, pixelSize), key => Render(key.Path, key.Size)); + return _cache.GetOrAdd((path, pixelSize, scheme), key => Render(key.Path, key.Size, key.Scheme)); } private const long MaxSvgBytes = 4L * 1024 * 1024; @@ -38,25 +39,37 @@ public static class SvgRasterizer /// public static string NormalizeTransforms(string svg) => TransformAttribute.Replace(svg, match => AdjacentNumbers.Replace(match.Value, ",")); + // Breeze ships "" and + // expects the host to replace it with its palette; the shipped colour only suits the theme's own variant. + private static readonly Regex ColorSchemeStyle = new(@"]*\bid=[""']current-color-scheme[""'][^>]*>[^<]*", RegexOptions.NonBacktracking | RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1)); + + /// + /// Replaces the icon's current-color-scheme stylesheet with , as KIconLoader does. + /// + public static string ApplyColorScheme(string svg, IconColorScheme? scheme) + => scheme is null ? svg : ColorSchemeStyle.Replace(svg, ""); + /// /// Renders SVG content the caller already read (not cached), so the file is never opened a second time. /// - public static byte[]? RenderToPng(byte[] svgData, int pixelSize) + public static byte[]? RenderToPng(byte[] svgData, int pixelSize, IconColorScheme? scheme = null) { pixelSize = Math.Clamp(pixelSize, 8, 1024); if (svgData.Length > MaxSvgBytes) return null; - return Render(svg => svg.FromSvg(NormalizeTransforms(System.Text.Encoding.UTF8.GetString(svgData))), pixelSize); + return Render(svg => svg.FromSvg(Prepare(System.Text.Encoding.UTF8.GetString(svgData), scheme)), pixelSize); } - private static byte[]? Render(string path, int pixelSize) + private static string Prepare(string svg, IconColorScheme? scheme) => NormalizeTransforms(ApplyColorScheme(svg, scheme)); + + private static byte[]? Render(string path, int pixelSize, IconColorScheme? scheme) { var fileInfo = new FileInfo(path); if (!fileInfo.Exists || fileInfo.Length > MaxSvgBytes) return null; - return Render(svg => svg.FromSvg(NormalizeTransforms(File.ReadAllText(path))), pixelSize); + return Render(svg => svg.FromSvg(Prepare(File.ReadAllText(path), scheme)), pixelSize); } private static byte[]? Render(Func load, int pixelSize) diff --git a/tests/Files.Platform.Tests/Icons/IconThemeTests.cs b/tests/Files.Platform.Tests/Icons/IconThemeTests.cs index 279e1ead1174..3f01ad729808 100644 --- a/tests/Files.Platform.Tests/Icons/IconThemeTests.cs +++ b/tests/Files.Platform.Tests/Icons/IconThemeTests.cs @@ -159,6 +159,24 @@ public async Task Resolve_PicksClosestSizeWhenNoExactMatch() Assert.AreEqual(Path.Combine(_icons, "Child", "48x48/places", "folder.png"), (await provider.ResolveIconAsync("folder", 40))!.Value.Path); } + [TestMethod] + public async Task Resolve_IgnoresScalableArtworkOutsideItsRange() + { + // Breeze declares places/96 as Scalable 96..256 next to fixed 16/22/32 pixel-grid artwork. + Directory.CreateDirectory(Path.Combine(_icons, "Big")); + File.WriteAllText(Path.Combine(_icons, "Big", "index.theme"), + "[Icon Theme]\nName=Big\nDirectories=places/16,places/22,places/96\n\n[places/16]\nSize=16\nType=Fixed\n\n[places/22]\nSize=22\nType=Fixed\n\n[places/96]\nSize=96\nType=Scalable\nMinSize=96\nMaxSize=256\n"); + Touch("Big", "places/16", "folder.svg"); + Touch("Big", "places/22", "folder.svg"); + Touch("Big", "places/96", "folder.svg"); + var provider = CreateProvider("Big"); + + Assert.AreEqual(Path.Combine(_icons, "Big", "places/22", "folder.svg"), (await provider.ResolveIconAsync("folder", 20))!.Value.Path); + Assert.AreEqual(Path.Combine(_icons, "Big", "places/22", "folder.svg"), (await provider.ResolveIconAsync("folder", 24))!.Value.Path); + Assert.AreEqual(Path.Combine(_icons, "Big", "places/96", "folder.svg"), (await provider.ResolveIconAsync("folder", 128))!.Value.Path); + Assert.AreEqual(Path.Combine(_icons, "Big", "places/96", "folder.svg"), (await provider.ResolveIconAsync("folder", 64))!.Value.Path, "Above every fixed size the scalable artwork is nearest."); + } + [TestMethod] public async Task Resolve_PrefersScalableArtworkAtLargeAndHiDpiSizes() { diff --git a/tests/Files.Platform.Tests/Icons/SvgRasterizerTests.cs b/tests/Files.Platform.Tests/Icons/SvgRasterizerTests.cs index ebc4c3834ecd..95c937be894a 100644 --- a/tests/Files.Platform.Tests/Icons/SvgRasterizerTests.cs +++ b/tests/Files.Platform.Tests/Icons/SvgRasterizerTests.cs @@ -32,6 +32,28 @@ public void RendersSvgToPng() } } + [TestMethod] + public void AppliesColorSchemeToThemedIcons() + { + const string svg = ""; + var data = Encoding.UTF8.GetBytes(svg); + + Assert.AreEqual(new SKColor(0xfc, 0xfc, 0xfc), CenterColor(SvgRasterizer.RenderToPng(data, 16)!), "The shipped colour stays without a scheme."); + Assert.AreEqual(new SKColor(0x23, 0x26, 0x29), CenterColor(SvgRasterizer.RenderToPng(data, 16, IconColorScheme.Light)!)); + Assert.AreEqual(new SKColor(0xfc, 0xfc, 0xfc), CenterColor(SvgRasterizer.RenderToPng(data, 16, IconColorScheme.Dark)!)); + + var plain = ""; + Assert.AreEqual(plain, SvgRasterizer.ApplyColorScheme(plain, IconColorScheme.Light), "Only the current-color-scheme stylesheet is replaced."); + Assert.IsTrue(SvgRasterizer.ApplyColorScheme(svg, IconColorScheme.Dark).Contains(".ColorScheme-Highlight { color:#3daee9; }", StringComparison.Ordinal)); + } + + private static SKColor CenterColor(byte[] png) + { + using var bitmap = SKBitmap.Decode(png); + var color = bitmap.GetPixel(bitmap.Width / 2, bitmap.Height / 2); + return new SKColor(color.Red, color.Green, color.Blue); + } + [TestMethod] public void ReturnsNullForInvalidSvg() {