借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
6.23 KiB
XCoder
using System;
using Avalonia;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Styling;
using Avalonia.Threading;

namespace NewLife.XCoder.Services;

/// <summary>系统外观适配:跟随系统强调色,并在高对比度模式下强化对比</summary>
/// <remarks>
/// 强调色与高对比度都由系统设置决定,不新增主题数量:强调色只覆盖 <c>Accent</c> 系列令牌,
/// 高对比度只覆盖底色、文字与描边令牌,落在应用资源的最上层,取消设置后自动回落到主题令牌。
/// 品牌渐变(<c>Hero*</c>)与控制台令牌保持不变,避免浅色强调色破坏白字对比。
/// </remarks>
public static class SystemAppearance
{
    private const String DarkSurface = "#0E1520";

    private static IPlatformSettings? _settings;

    /// <summary>当前是否处于高对比度模式</summary>
    public static Boolean HighContrast { get; private set; }

    /// <summary>当前生效的强调色;为空表示沿用主题默认色</summary>
    public static Color? AccentColor { get; private set; }

    /// <summary>订阅系统外观变化;启动时调用一次</summary>
    public static void Initialize()
    {
        var app = Application.Current;
        if (app == null) return;

        _settings = app.PlatformSettings;
        if (_settings != null) _settings.ColorValuesChanged += (s, e) => Refresh();

        // 强调色明暗与高对比度取值都跟深色/浅色相关,主题变化后重新推导
        ThemeService.Changed += _ => Refresh();
        app.ActualThemeVariantChanged += (s, e) => Refresh();

        Refresh();
    }

    /// <summary>按当前系统设置重新应用(界面线程)</summary>
    public static void Refresh()
    {
        if (!Dispatcher.UIThread.CheckAccess())
        {
            Dispatcher.UIThread.Post(Refresh);
            return;
        }

        var dark = Application.Current?.ActualThemeVariant == ThemeVariant.Dark;
        Apply(_settings?.GetColorValues(), dark);
    }

    /// <summary>按系统颜色设置刷新强调色与高对比度覆盖</summary>
    /// <param name="values">平台颜色设置</param>
    /// <param name="dark">深色主题下取更亮的强调色</param>
    public static void Apply(PlatformColorValues? values, Boolean dark)
    {
        var resources = Avalonia.Application.Current?.Resources;
        if (resources == null) return;

        // 强调色:系统未提供(如部分 Linux 桌面)时沿用主题默认色
        AccentColor = values != null && values.AccentColor1.A > 0 ? values.AccentColor1 : null;
        if (AccentColor is { } accent)
        {
            var palette = BuildAccent(accent, dark);
            resources["Accent"] = new SolidColorBrush(palette.Accent);
            resources["AccentHover"] = new SolidColorBrush(palette.Hover);
            resources["AccentSoft"] = new SolidColorBrush(palette.Soft);
        }
        else
        {
            resources.Remove("Accent");
            resources.Remove("AccentHover");
            resources.Remove("AccentSoft");
        }

        HighContrast = values?.ContrastPreference == ColorContrastPreference.High;
        if (HighContrast)
        {
            foreach (var item in HighContrastTokens(dark)) resources[item.Key] = new SolidColorBrush(item.Value);
        }
        else
        {
            foreach (var key in HighContrastKeys) resources.Remove(key);
        }
    }

    /// <summary>按强调色推导强调色、悬停色与浅底色</summary>
    /// <param name="accent">系统强调色</param>
    /// <param name="dark">是否深色主题</param>
    /// <returns>三档强调色</returns>
    public static (Color Accent, Color Hover, Color Soft) BuildAccent(Color accent, Boolean dark)
    {
        var baseColor = accent;
        // 过亮/过暗的强调色直接使用会看不清,先往可用区间拉一把
        if (dark && Luminance(baseColor) < 0.35) baseColor = Blend(baseColor, Colors.White, 0.3);
        if (!dark && Luminance(baseColor) > 0.7) baseColor = Blend(baseColor, Colors.Black, 0.35);

        var hover = dark ? Blend(baseColor, Colors.White, 0.18) : Blend(baseColor, Colors.Black, 0.14);
        var soft = dark ? Blend(baseColor, Color.Parse(DarkSurface), 0.82) : Blend(baseColor, Colors.White, 0.88);
        return (baseColor, hover, soft);
    }

    private static readonly String[] HighContrastKeys =
    [
        "BgPage", "BgSurface", "BgSurface2", "BgSidebar", "BgSubtle", "BgSidebarActive", "BgHover", "BgPressed",
        "BorderDefault", "BorderStrong", "TextPrimary", "TextSecondary", "TextTertiary",
    ];

    private static (String Key, Color Value)[] HighContrastTokens(Boolean dark)
    {
        if (dark)
        {
            var white = Colors.White;
            var black = Colors.Black;
            return
            [
                ("BgPage", black), ("BgSurface", black), ("BgSurface2", Color.Parse("#0A0A0A")),
                ("BgSidebar", black), ("BgSubtle", Color.Parse("#1F1F1F")), ("BgSidebarActive", Color.Parse("#1F1F1F")),
                ("BgHover", Color.Parse("#1F1F1F")), ("BgPressed", Color.Parse("#333333")),
                ("BorderDefault", white), ("BorderStrong", white),
                ("TextPrimary", white), ("TextSecondary", white), ("TextTertiary", Color.Parse("#E6E6E6")),
            ];
        }

        var light = Colors.Black;
        var surface = Colors.White;
        return
        [
            ("BgPage", surface), ("BgSurface", surface), ("BgSurface2", surface),
            ("BgSidebar", surface), ("BgSubtle", Color.Parse("#E6E6E6")), ("BgSidebarActive", Color.Parse("#E6E6E6")),
            ("BgHover", Color.Parse("#E6E6E6")), ("BgPressed", Color.Parse("#CCCCCC")),
            ("BorderDefault", light), ("BorderStrong", light),
            ("TextPrimary", light), ("TextSecondary", light), ("TextTertiary", Color.Parse("#1A1A1A")),
        ];
    }

    private static Double Luminance(Color color) => (0.2126 * color.R + 0.7152 * color.G + 0.0722 * color.B) / 255;

    private static Color Blend(Color from, Color to, Double ratio)
    {
        var t = Math.Clamp(ratio, 0, 1);
        Byte Mix(Byte a, Byte b) => (Byte)Math.Round(a + (b - a) * t);

        return Color.FromArgb(from.A, Mix(from.R, to.R), Mix(from.G, to.G), Mix(from.B, to.B));
    }
}