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
Let users replace Filee's surface, text and status colours with a theme.json next to settings.json
Kayzeld6535467bbcc
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex c4dac75b..69aee0c4 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -67,7 +67,9 @@ Bump `AppSettings.CurrentSchemaVersion` and add a step to `SettingsMigrations` w- `LocalizationService` loads `Assets/i18n/<lang>.json` into `Application.Resources`; XAML uses`{DynamicResource key}`, so switching language updates the UI live.- `ThemeService` writes the accent colour, corner radii, fonts and Fluent's `SystemAccentColor*` into- application resources. Light/dark surface colours are theme dictionaries in `Styles/Soft.axaml`.+ application resources. Light/dark surface colours are theme dictionaries in `Styles/Soft.axaml`; a user's+ `theme.json` (`CustomTheme`, see [CUSTOM-THEMES.md](CUSTOM-THEMES.md)) overrides them with theme dictionaries in+ application resources, which are searched first.## Command line and watch foldersdiff --git a/docs/CUSTOM-THEMES.md b/docs/CUSTOM-THEMES.mdnew file mode 100644index 00000000..6deed09a--- /dev/null+++ b/docs/CUSTOM-THEMES.md@@ -0,0 +1,35 @@+# Custom themes++Filee's own colours can be replaced with a `theme.json` file in the folder that holds `settings.json`:++- Windows: `%APPDATA%\Filee\theme.json`+- Linux: `~/.config/Filee/theme.json`+- macOS: `~/Library/Application Support/Filee/theme.json`+- With `FILEE_DATA_DIR` set: `theme.json` in that folder++```jsonc+{+ "dark": {+ "page": "#101820", // window background+ "surface": "#18222C", // cards and donut slices+ "surfaceAlt": "#22303C", // badges, small buttons, preview boxes+ "border": "#1CFFFFFF", // card and control outlines+ "text": "#E8E4D8",+ "textSecondary": "#A8B0B8", // hints and captions+ "danger": "#F09595",+ "success": "#5DCAA5",+ "warning": "#EF9F27"+ },+ "light": {+ "page": "#F4F6F8"+ }+}+```++- `dark` and `light` are both optional, and so is every colour in them. Anything left out keeps Filee's colour.+- Colours are `#RRGGBB` or `#AARRGGBB`. Unknown names and other values are ignored and written to the log.+- The accent colour, corner radius and light/dark choice stay in **Settings > Theme**.+- Filee reads the file when it starts and whenever a setting is saved. Restart Filee, or change any setting, after+ editing it. Deleting the file brings the built-in colours back.++Keep `text` and `textSecondary` readable on `page`, `surface` and `surfaceAlt`: they are drawn on all three.diff --git a/src/Filee.App/App.axaml.cs b/src/Filee.App/App.axaml.csindex e7c8ef68..c402e21a 100644--- a/src/Filee.App/App.axaml.cs+++ b/src/Filee.App/App.axaml.cs@@ -224,7 +224,8 @@ public partial class App : Applicationif (loc.NeedsUpdate(settings.Language))loc.SetLanguage(settings.Language);- AppHost.Get<ThemeService>().Apply(settings.Theme, loc.Language);+ var custom = CustomTheme.Load(AppHost.Get<UserDataStore>().Directory, AppHost.Get<ILogger<App>>());+ AppHost.Get<ThemeService>().Apply(settings.Theme, loc.Language, custom);AppHost.Get<TriggerService>().Apply(settings);AppHost.Get<ConverterCatalog>().Priority = settings.EnginePriority;if (ownCopiesChanged || routesChanged)diff --git a/src/Filee.App/Services/ThemeService.cs b/src/Filee.App/Services/ThemeService.csindex 47f0ef41..1830a641 100644--- a/src/Filee.App/Services/ThemeService.cs+++ b/src/Filee.App/Services/ThemeService.cs@@ -1,7 +1,9 @@-// Applies ThemeSettings (light/dark, accent colour, corner radius, font order, reduced motion) at runtime by-// writing resources into Application.Resources. All styles reference these with DynamicResource.+// Applies ThemeSettings (light/dark, accent colour, corner radius, font order, reduced motion) and the user's+// theme.json colours at runtime by writing resources into Application.Resources. All styles reference these with+// DynamicResource.using Avalonia;+using Avalonia.Controls;using Avalonia.Media;using Avalonia.Styling;using Filee.Core.Platform;@@ -24,7 +26,21 @@ public sealed class ThemeService(IPlatformServices platform)private const string SystemFallbacks ="Segoe UI, Nirmala UI, Malgun Gothic, Microsoft YaHei, PingFang SC, Apple SD Gothic Neo, Kohinoor Devanagari, sans-serif";- public void Apply(ThemeSettings theme, string language)+ /// <summary>theme.json colour names → the brushes in Styles/Soft.axaml they replace.</summary>+ private static readonly IReadOnlyDictionary<string, string> CustomBrushKeys = new Dictionary<string, string>+ {+ ["page"] = "PageBrush",+ ["surface"] = "SurfaceBrush",+ ["surfaceAlt"] = "SurfaceAltBrush",+ ["border"] = "SubtleBorderBrush",+ ["text"] = "TextPrimaryBrush",+ ["textSecondary"] = "TextSecondaryBrush",+ ["danger"] = "DangerBrush",+ ["success"] = "SuccessBrush",+ ["warning"] = "WarningBrush",+ };++ public void Apply(ThemeSettings theme, string language, CustomTheme? custom = null){var app = Application.Current ?? throw new InvalidOperationException("No application.");var res = app.Resources;@@ -66,9 +82,27 @@ public sealed class ThemeService(IPlatformServices platform): $"{Korean}, {Chinese}";res["AppFontFamily"] = FontFamily.Parse($"{Latin}, {Devanagari}, {cjk}, {SystemFallbacks}");+ // Application.Resources is searched before the styles, so these theme dictionaries win over Soft.axaml's.+ ApplyCustom(res, ThemeVariant.Light, custom?.Light);+ ApplyCustom(res, ThemeVariant.Dark, custom?.Dark);+Motion.Configure(theme.ReduceMotion, () => platform.PrefersReducedMotion);}+ /// <summary>Replaces (or, with no colours, removes) the user's colours for one variant.</summary>+ private static void ApplyCustom(IResourceDictionary res, ThemeVariant variant, IReadOnlyDictionary<string, string>? colors)+ {+ var dictionary = new ResourceDictionary();+ foreach (var (name, value) in colors ?? new Dictionary<string, string>())+ if (CustomBrushKeys.TryGetValue(name, out var key) && Color.TryParse(value, out var color))+ dictionary[key] = new SolidColorBrush(color);++ if (dictionary.Count == 0)+ res.ThemeDictionaries.Remove(variant);+ else+ res.ThemeDictionaries[variant] = dictionary;+ }+/// <summary>Lightens (amount > 0) or darkens (amount < 0) a colour.</summary>public static Color Shade(Color c, double amount){diff --git a/src/Filee.Core/Settings/CustomTheme.cs b/src/Filee.Core/Settings/CustomTheme.csnew file mode 100644index 00000000..65a02383--- /dev/null+++ b/src/Filee.Core/Settings/CustomTheme.cs@@ -0,0 +1,81 @@+// A user colour theme: theme.json next to settings.json overrides the surface, text and status colours of the light+// and/or dark variant. It is a separate file (not part of settings.json) so a theme can be shared and replaced on+// its own; the accent colour stays in ThemeSettings, where the Theme page edits it.++using System.Text.Json;+using System.Text.RegularExpressions;+using Microsoft.Extensions.Logging;+using Microsoft.Extensions.Logging.Abstractions;++namespace Filee.Core.Settings;++/// <summary>Colours from <c>theme.json</c>, by variant. Missing keys keep Filee's own colours.</summary>+public sealed partial class CustomTheme+{+ /// <summary>File name inside the data directory (<see cref="UserDataStore.Directory"/>).</summary>+ public const string FileName = "theme.json";++ /// <summary>Colour names a theme may set.</summary>+ public static readonly IReadOnlyList<string> Keys =+ ["page", "surface", "surfaceAlt", "border", "text", "textSecondary", "danger", "success", "warning"];++ /// <summary>Colours for the light variant, as name → <c>#RRGGBB</c> or <c>#AARRGGBB</c>.</summary>+ public Dictionary<string, string> Light { get; set; } = [];++ /// <summary>Colours for the dark variant, as name → <c>#RRGGBB</c> or <c>#AARRGGBB</c>.</summary>+ public Dictionary<string, string> Dark { get; set; } = [];++ /// <summary>True when neither variant sets a colour.</summary>+ public bool IsEmpty => Light.Count == 0 && Dark.Count == 0;++ /// <summary>+ /// Reads <c>theme.json</c> from <paramref name="directory"/>. Unknown names and values that are not hex colours+ /// are dropped (and logged); a missing, empty or unreadable file gives null, so Filee's own colours apply.+ /// The file is the user's: unlike settings.json it is never renamed or rewritten.+ /// </summary>+ public static CustomTheme? Load(string directory, ILogger? log = null)+ {+ log ??= NullLogger.Instance;+ var path = Path.Combine(directory, FileName);+ if (!File.Exists(path))+ return null;++ CustomTheme? theme;+ try+ {+ using var stream = File.OpenRead(path);+ theme = JsonSerializer.Deserialize(stream, FileeJsonContext.Default.CustomTheme);+ }+ catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)+ {+ log.LogWarning(ex, "Custom theme {Path} could not be read; using the built-in colours", path);+ return null;+ }+ if (theme is null)+ return null;++ theme.Light = Clean(theme.Light, "light", path, log);+ theme.Dark = Clean(theme.Dark, "dark", path, log);+ return theme.IsEmpty ? null : theme;+ }++ private static Dictionary<string, string> Clean(Dictionary<string, string>? colors, string variant, string path, ILogger log)+ {+ var clean = new Dictionary<string, string>();+ foreach (var (name, value) in colors ?? [])+ {+ // Names are matched case-insensitively and stored in their canonical spelling.+ var key = Keys.FirstOrDefault(k => string.Equals(k, name, StringComparison.OrdinalIgnoreCase));+ if (key is null)+ log.LogWarning("Custom theme {Path}: unknown colour {Variant}.{Name} ignored", path, variant, name);+ else if (value is null || !HexColor().IsMatch(value))+ log.LogWarning("Custom theme {Path}: {Variant}.{Name} is not #RRGGBB or #AARRGGBB, ignored", path, variant, name);+ else+ clean[key] = value;+ }+ return clean;+ }++ [GeneratedRegex("^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$")]+ private static partial Regex HexColor();+}diff --git a/src/Filee.Core/Settings/FileeJsonContext.cs b/src/Filee.Core/Settings/FileeJsonContext.csindex 5258396b..bb4e4b6b 100644--- a/src/Filee.Core/Settings/FileeJsonContext.cs+++ b/src/Filee.Core/Settings/FileeJsonContext.cs@@ -19,6 +19,7 @@ namespace Filee.Core.Settings;[JsonSerializable(typeof(List<ToolbarProfile>))][JsonSerializable(typeof(PresetBundle))][JsonSerializable(typeof(List<HistoryEntry>))]+[JsonSerializable(typeof(CustomTheme))]internal sealed partial class FileeJsonContext : JsonSerializerContext;/// <summary>File format used to import / export presets and profiles.</summary>diff --git a/tests/Filee.App.Tests/RenderTests.cs b/tests/Filee.App.Tests/RenderTests.csindex 853e56eb..1f5c4178 100644--- a/tests/Filee.App.Tests/RenderTests.cs+++ b/tests/Filee.App.Tests/RenderTests.cs@@ -601,6 +601,61 @@ public class RenderTestsAppHost.Get<ThemeService>().Apply(new ThemeSettings(), "en");}+ [AvaloniaFact]+ public void Custom_theme_colours_replace_the_built_in_ones_and_go_away_with_the_file()+ {+ TestServices.EnsureInitialized("en");+ var service = AppHost.Get<ThemeService>();+ var dark = new ThemeSettings { Mode = ThemeMode.Dark };+ var custom = new CustomTheme+ {+ Dark = { ["page"] = "#101820", ["surface"] = "#18222C", ["surfaceAlt"] = "#22303C", ["text"] = "#E8E4D8" },+ };+ try+ {+ service.Apply(dark, "en", custom);+ var vm = new MainWindowViewModel(AppHost.Services, AppHost.Get<Filee.Core.Localization.ILocalizer>(), AppHost.Get<UpdateService>());+ vm.Navigate("theme");+ var window = new MainWindow { DataContext = vm, Width = 1080, Height = 820 };+ window.Show();+ Pump();++ Assert.Equal(Avalonia.Media.Color.Parse("#101820"), Assert.IsAssignableFrom<Avalonia.Media.ISolidColorBrush>(window.Background).Color);+ Assert.Equal(Avalonia.Media.Color.Parse("#E8E4D8"), BrushColor(window, "TextPrimaryBrush"));+ // Colours the file does not set, and the other variant, keep Filee's own.+ Assert.Equal(Avalonia.Media.Color.Parse("#AEACA4"), BrushColor(window, "TextSecondaryBrush"));+ Assert.Equal(Avalonia.Media.Color.Parse("#F6F5F1"), BrushColor(window, "PageBrush", Avalonia.Styling.ThemeVariant.Light));+ Save(window, "page-theme-custom.png");++ // Applying without a theme file (deleted, or emptied) restores the built-in colours on the open window.+ service.Apply(dark, "en");+ Pump();+ Assert.Equal(Avalonia.Media.Color.Parse("#1B1B19"), Assert.IsAssignableFrom<Avalonia.Media.ISolidColorBrush>(window.Background).Color);+ window.Close();++ service.Apply(dark, "en", custom);+ var radial = AppHost.Get<RadialViewModel>();+ radial.Load([@"C:\photos\a.jpg"], clickMode: true);+ var donut = new RadialWindow { DataContext = radial };+ donut.Show();+ donut.DonutControl.SetExternalHighlight(1);+ Pump();+ Assert.Equal(Avalonia.Media.Color.Parse("#18222C"), Assert.IsAssignableFrom<Avalonia.Media.ISolidColorBrush>(donut.DonutControl.SliceBrush).Color);+ Save(donut, "donut-custom-theme.png");+ donut.Close();+ }+ finally+ {+ service.Apply(new ThemeSettings(), "en");+ }+ }++ private static Avalonia.Media.Color BrushColor(Window window, string key, Avalonia.Styling.ThemeVariant? variant = null)+ {+ Assert.True(window.TryFindResource(key, variant ?? window.ActualThemeVariant, out var value), key);+ return Assert.IsAssignableFrom<Avalonia.Media.ISolidColorBrush>(value).Color;+ }+[AvaloniaFact]public void Preset_popup_renders(){diff --git a/tests/Filee.Core.Tests/CustomThemeTests.cs b/tests/Filee.Core.Tests/CustomThemeTests.csnew file mode 100644index 00000000..41e4c215--- /dev/null+++ b/tests/Filee.Core.Tests/CustomThemeTests.cs@@ -0,0 +1,68 @@+// theme.json: reading, dropping what Filee cannot use, and leaving the user's file alone.++using Filee.Core.Settings;++namespace Filee.Core.Tests;++public class CustomThemeTests+{+ [Fact]+ public void No_file_means_no_custom_theme()+ {+ using var dir = new TempDir();+ Assert.Null(CustomTheme.Load(dir.Path));+ }++ [Fact]+ public void Reads_both_variants_with_comments_and_any_name_casing()+ {+ using var dir = new TempDir();+ dir.File(CustomTheme.FileName, """+ {+ // Night+ "dark": { "page": "#101820", "TEXT": "#E8E4D8", "border": "#33FFFFFF" },+ "light": { "surfaceAlt": "#EEF1F4", },+ }+ """);++ var theme = CustomTheme.Load(dir.Path)!;++ Assert.Equal("#101820", theme.Dark["page"]);+ Assert.Equal("#E8E4D8", theme.Dark["text"]);+ Assert.Equal("#33FFFFFF", theme.Dark["border"]);+ Assert.Equal("#EEF1F4", Assert.Single(theme.Light).Value);+ }++ [Fact]+ public void Unknown_names_and_bad_colours_are_dropped()+ {+ using var dir = new TempDir();+ dir.File(CustomTheme.FileName, """+ { "dark": { "page": "#101820", "toolbarGlow": "#FFFFFF", "text": "white", "danger": "#F00" } }+ """);++ var theme = CustomTheme.Load(dir.Path)!;++ Assert.Equal("page", Assert.Single(theme.Dark).Key);+ Assert.Empty(theme.Light);+ }++ [Theory]+ [InlineData("{ not json")]+ [InlineData("""{ "dark": { "page": "red" } }""")]+ [InlineData("{}")]+ public void A_file_with_nothing_usable_keeps_the_built_in_colours_and_is_not_touched(string content)+ {+ using var dir = new TempDir();+ var path = dir.File(CustomTheme.FileName, content);++ Assert.Null(CustomTheme.Load(dir.Path));+ Assert.Equal(content, File.ReadAllText(path));+ }++ [Fact]+ public void Every_name_is_unique()+ {+ Assert.Equal(CustomTheme.Keys.Count, CustomTheme.Keys.Distinct(StringComparer.OrdinalIgnoreCase).Count());+ }+}