Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/Files.App/Helpers/Layout/LayoutSizeKindHelper.cs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<IIconThemeProvider>();
#endif

private static uint GetRequestedIconSize(FolderLayoutModes folderLayoutMode)
{
return folderLayoutMode switch
{
// Details
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Helpers/MenuFlyout/LinuxAppIcons.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
48 changes: 35 additions & 13 deletions src/Files.App/Platforms/Desktop/Services/LinuxIconHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -21,7 +22,7 @@ namespace Files.App.Utils.Storage
/// </summary>
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<string, (string[] Names, long At)> _mimeIconNames = new(StringComparer.Ordinal);
private const long MimeIconNamesTtlMs = 5000;

Expand All @@ -30,6 +31,24 @@ internal static class LinuxIconHelper
private static IMimeTypeService Mime => Ioc.Default.GetRequiredService<IMimeTypeService>();
private static IUserDirectories Directories => Ioc.Default.GetRequiredService<IUserDirectories>();

/// <summary>
/// The palette for themed monochrome icons, following the application theme like KIconLoader follows the KDE scheme.
/// </summary>
internal static IconColorScheme CurrentColorScheme
{
get
{
var mode = Ioc.Default.GetService<IAppThemeModeService>()?.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<byte[]?> GetIconAsync(string? path, uint size, bool isFolder, IconOptions options, CancellationToken cancellationToken = default)
{
try
Expand Down Expand Up @@ -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;
}
Expand All @@ -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;
}
Expand All @@ -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
{
Expand All @@ -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')
Expand Down Expand Up @@ -195,13 +217,13 @@ private static async Task<IReadOnlyList<string>> GetIconNamesAsync(string? path,
return null;
}

private static async Task<byte[]?> LoadThemeIconAsync(IReadOnlyList<string> names, uint size)
private static async Task<byte[]?> LoadThemeIconAsync(IReadOnlyList<string> 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;

Expand All @@ -210,7 +232,7 @@ private static async Task<IReadOnlyList<string>> 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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Files.App/Utils/Storage/Helpers/DriveHelpers.Linux.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
5 changes: 5 additions & 0 deletions src/Files.Platform.Abstractions/Icons/IIconThemeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// </summary>
Task<IReadOnlyList<IconLookupResult>> ResolveIconCandidatesAsync(IReadOnlyList<string> iconNames, uint size, int scale = 1, CancellationToken cancellationToken = default);

/// <summary>
/// Gets the size closest to <paramref name="size"/> that the current theme draws at its own pixel grid, or <paramref name="size"/> when the theme has no fixed sizes.
/// </summary>
uint GetNativeSize(uint size, int scale = 1);
}
}
42 changes: 42 additions & 0 deletions src/Files.Platform.Linux/Icons/IconColorScheme.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Copyright (c) Files Community
// Licensed under the MIT License.

namespace Files.Platform.Linux.Icons
{
/// <summary>
/// The palette substituted into themed SVG icons that paint with <c>currentColor</c> through the
/// <c>current-color-scheme</c> stylesheet (Breeze and derivatives), as KIconLoader does for KDE applications.
/// </summary>
public sealed record IconColorScheme(
string Text,
string Background,
string Highlight,
string HighlightedText,
string PositiveText,
string NeutralText,
string NegativeText,
string ActiveText,
string Complement,
string Contrast)
{
/// <summary>Breeze Light colours.</summary>
public static IconColorScheme Light { get; } = new("#232629", "#fcfcfc", "#3daee9", "#fcfcfc", "#27ae60", "#f67400", "#da4453", "#3daee9", "#31363b", "#fcfcfc");

/// <summary>Breeze Dark colours.</summary>
public static IconColorScheme Dark { get; } = new("#fcfcfc", "#232629", "#3daee9", "#fcfcfc", "#27ae60", "#f67400", "#da4453", "#3daee9", "#fcfcfc", "#232629");

/// <summary>
/// Gets the scheme matching the application theme.
/// </summary>
public static IconColorScheme ForTheme(bool isDark) => isDark ? Dark : Light;

/// <summary>
/// Builds the stylesheet KIconLoader injects, covering every <c>ColorScheme-*</c> class Breeze icons use.
/// </summary>
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}; }}";
}
}
7 changes: 6 additions & 1 deletion src/Files.Platform.Linux/Icons/IconThemeIndex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,11 @@ public enum IconDirectoryType
/// </summary>
public sealed record IconDirectory(string Path, int Size, int Scale, IconDirectoryType Type, int MinSize, int MaxSize, int Threshold)
{
/// <summary>
/// Gets the icon context (Places, MimeTypes, ...) the directory declares, if any.
/// </summary>
public string? Context { get; init; }

/// <summary>
/// Determines whether the directory can serve an icon of the given size and scale.
/// </summary>
Expand Down Expand Up @@ -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 };
Expand Down
56 changes: 54 additions & 2 deletions src/Files.Platform.Linux/Icons/LinuxIconThemeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ public sealed class LinuxIconThemeProvider : IIconThemeProvider
private readonly Lazy<string> _themeName;
private readonly ConcurrentDictionary<string, IconThemeIndex?> _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();

/// <summary>
/// Initializes a new instance using the process environment.
Expand Down Expand Up @@ -159,6 +160,56 @@ public Task<IReadOnlyList<IconLookupResult>> 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"];

/// <inheritdoc/>
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<IconDirectory>();
var visited = new HashSet<string>(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<string> visited, List<IconDirectory> 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))
Expand Down Expand Up @@ -219,8 +270,9 @@ private IEnumerable<IconLookupResult> 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)
{
Expand Down
Loading
Loading