Code/UI/DmlrUiTheme.cs

Static theme store for the addon's UI. Holds one ThemeRecord (accent color, text color, surface opacity, menu hotkeys, stats HUD toggles) plus preset swatches, persists it to a cookie and dmlr-ui-theme-v3.json, sanitizes loaded values, and derives CSS strings (gradients, rgba borders, contrast text) for the menus.

File Access
🐞 Alpha() clamps to a 0.35 minimum and HexToRgba routes every alpha through it, so BorderSubtle (0.14), AccentSoft (0.18) and the 0.20 header tint all render at 0.35 opacity, far stronger than the values passed in.
using Sandbox;
using System;
using System.Globalization;

namespace DmlrAddon;

/// <summary>
/// BASE DE CODAGE 2 · Thème d'Interface s&amp;box Simplifié &amp; Incrusté (Blanc + Bleu par défaut).
/// 2 couleurs modifiables très simples :
///  - Couleur 1 (Accent · Bleu s&amp;box #3B82F6 par défaut) : boutons actifs, badges, barres et liserés
///  - Couleur 2 (Texte &amp; Décors · Blanc pur #FFFFFF par défaut) : textes incrustés, titres et repères
/// + Niveau d'incrustation (transparence du fond sombre) et option HUD Statistiques Haut-Droite.
/// </summary>
public static class DmlrUiTheme
{
	public sealed class ThemeRecord
	{
		public int SchemaVersion { get; set; } = 5;

		// Touche d'ouverture du Menu DMLR (F4 par défaut, modifiable si un serveur utilise déjà F4)
		public string MenuKey { get; set; } = "F4";

		// Touche secondaire de secours toujours active en parallèle (F7 par défaut)
		public string BackupKey { get; set; } = "F7";

		// HUD Statistiques Haut-Droite (Complet par défaut)
		public bool ShowStatsHud { get; set; } = true;
		public bool CompactStatsHud { get; set; } = false;

		// 2 Couleurs modifiables : Bleu s&box + Blanc pur par défaut
		public string AccentColor { get; set; } = "#3B82F6"; // Couleur 1 : Bleu s&box
		public string TextColor { get; set; } = "#FFFFFF";   // Couleur 2 : Blanc s&box

		// Niveau d'incrustation sur le jeu (léger / incrusté s&box / profond)
		public float SurfaceOpacity { get; set; } = 0.68f;
	}

	// Touches rapides proposées en 1 clic (sans conflit avec les touches ZQSD/WASD de s&box)
	public static readonly string[] QuickBindKeys =
	{
		"F4", "F6", "F7", "F8", "F9", "F10", "M", "K", "INSERT", "HOME"
	};

	// Ensemble des touches détectables par écoute directe ("Appuyer sur une touche...")
	public static readonly string[] AllBindableKeys =
	{
		"F2", "F3", "F4", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
		"M", "K", "L", "N", "P", "O", "I", "U", "Y", "T", "H", "J", "B",
		"INSERT", "HOME", "END", "PGUP", "PGDN", "DELETE"
	};

	public readonly record struct Swatch( string Name, string Hex );
	public readonly record struct DuoPreset( string Name, string Accent, string Text );

	public static readonly Swatch[] AccentSwatches =
	{
		new( "Bleu s&box", "#3B82F6" ),
		new( "Ciel",       "#38BDF8" ),
		new( "Bleu Roi",   "#2563EB" ),
		new( "Émeraude",   "#34D399" ),
		new( "Violet",     "#A855F7" ),
		new( "Or",         "#F5C451" ),
		new( "Rose",       "#F472B6" ),
		new( "Blanc",      "#FFFFFF" )
	};

	public static readonly Swatch[] TextSwatches =
	{
		new( "Blanc Pur",   "#FFFFFF" ),
		new( "Blanc s&box", "#F1F5FF" ),
		new( "Bleu Glace",  "#DBEAFE" ),
		new( "Bleu Clair",  "#93C5FD" ),
		new( "Or Doux",     "#FEF3C7" ),
		new( "Menthe",      "#D1FAE5" )
	};

	public static readonly DuoPreset[] Presets =
	{
		new( "s&box Bleu + Blanc",  "#3B82F6", "#FFFFFF" ),
		new( "s&box Ciel + Blanc",  "#38BDF8", "#F1F5FF" ),
		new( "s&box Blanc + Bleu",  "#FFFFFF", "#93C5FD" ),
		new( "Émeraude + Blanc",    "#34D399", "#FFFFFF" ),
		new( "Or + Blanc",          "#F5C451", "#FEF3C7" ),
		new( "Violet + Blanc",      "#A855F7", "#F1F5FF" )
	};

	private const string StorePath = "dmlr-ui-theme-v3.json";
	private const string GlobalCookieKey = "dmlr.global.ui.v4";
	private static bool _loaded;

	public static ThemeRecord Current { get; private set; } = new();
	public static int Revision { get; private set; }
	public static string MenuKeyLabel => SanitizeKey( Current.MenuKey, "F4" );
	public static string BackupKeyLabel => SanitizeKey( Current.BackupKey, "F7" );

	// État global unique partagé (immunisé contre les conflits scène Éditeur / Play et les doubles déclenchements F4)
	public static bool MenuOpen { get; private set; }
	private static float _lastToggleRealTime = -10f;

	public static void OpenMenu()
	{
		if ( MenuOpen ) return;
		MenuOpen = true;
		_lastToggleRealTime = RealTime.Now;
		Revision++;
	}

	public static void CloseMenu()
	{
		if ( !MenuOpen ) return;
		MenuOpen = false;
		_lastToggleRealTime = RealTime.Now;
		Revision++;
	}

	public static void ToggleMenu()
	{
		// Anti-double-toggle (ex: F4 déclenchant à la fois l'action Input et une commande console)
		float now = RealTime.Now;
		if ( now - _lastToggleRealTime < 0.20f )
			return;

		_lastToggleRealTime = now;
		MenuOpen = !MenuOpen;
		Revision++;
	}

	public static void EnsureLoaded()
	{
		if ( _loaded ) return;
		_loaded = true;
		try
		{
			ThemeRecord loaded = null;
			if ( Game.Cookies is not null )
			{
				loaded = Game.Cookies.Get<ThemeRecord>( GlobalCookieKey, null );
			}
			if ( loaded is null && FileSystem.Data.FileExists( StorePath ) )
			{
				loaded = FileSystem.Data.ReadJson<ThemeRecord>( StorePath );
			}
			if ( loaded is not null )
			{
				if ( loaded.SchemaVersion < 5 )
				{
					loaded.SchemaVersion = 5;
					loaded.ShowStatsHud = true;
					loaded.CompactStatsHud = false;
				}
				Current = Sanitize( loaded );
				Save();
			}
		}
		catch ( Exception e )
		{
			Log.Warning( $"[DMLR Theme] Load fallback: {e.Message}" );
		}
		Revision++;
	}

	public static void SetMenuKey( string newKey )
	{
		string clean = SanitizeKey( newKey, "F4" );
		Mutate( t => t.MenuKey = clean, $"Touche Menu DMLR mémorisée partout : [{clean}] (Secours : [{BackupKeyLabel}])." );
	}

	public static void Mutate( Action<ThemeRecord> change, string status = "" )
	{
		EnsureLoaded();
		change( Current );
		Current = Sanitize( Current );
		Save();
		if ( !string.IsNullOrEmpty( status ) ) DmlrCoreDatabase.SetStatus( status );
		Revision++;
	}

	public static void ApplyPreset( DuoPreset p )
	{
		Mutate( t =>
		{
			t.AccentColor = p.Accent;
			t.TextColor = p.Text;
		}, $"Couleurs appliquées : {p.Name}." );
	}

	public static void ResetTheme()
	{
		Current = new ThemeRecord();
		Save();
		DmlrCoreDatabase.SetStatus( "Couleurs s&box Bleu + Blanc réinitialisées." );
		Revision++;
	}

	private static void Save()
	{
		try
		{
			Game.Cookies?.Set( GlobalCookieKey, Current );
			FileSystem.Data.WriteJson( StorePath, Current );
		}
		catch ( Exception e ) { Log.Warning( $"[DMLR Theme] Save error: {e.Message}" ); }
	}

	// ── Jetons visuels s&box incrustés & cohérents ──
	public static string Accent => SanitizeHex( Current.AccentColor, "#3B82F6" );
	public static string Text => SanitizeHex( Current.TextColor, "#FFFFFF" );

	// Fond sombre s&box subtilement teinté : HUD léger à droite vs Menu F4 bien distingué au centre
	public static string WindowBg => $"linear-gradient(180deg, rgba(13, 18, 30, {Alpha( Math.Clamp( Current.SurfaceOpacity + 0.14f, 0.62f, 0.96f ) )}), rgba(8, 11, 20, {Alpha( Math.Clamp( Current.SurfaceOpacity + 0.20f, 0.68f, 0.98f ) )}))";
	public static string HeaderBg => $"linear-gradient(90deg, {HexToRgba( Accent, 0.20f )}, rgba(15, 22, 36, 0.45))";
	public static string HudBg => $"linear-gradient(180deg, rgba(14, 18, 28, {Alpha( Math.Clamp( Current.SurfaceOpacity * 0.86f, 0.36f, 0.84f ) )}), rgba(9, 12, 19, {Alpha( Math.Clamp( Current.SurfaceOpacity * 0.92f, 0.40f, 0.88f ) )}))";
	public static string CardBg => $"rgba(255, 255, 255, 0.045)";
	public static string MenuCardBg => $"rgba(18, 25, 42, 0.62)";
	public static string BorderAccent => HexToRgba( Accent, 0.52f );
	public static string MenuBorderAccent => HexToRgba( Accent, 0.78f );
	public static string BorderSubtle => HexToRgba( Text, 0.14f );
	public static string AccentSoft => HexToRgba( Accent, 0.18f );
	public static string DuoBar => $"linear-gradient(to right, {Accent}, {Text})";

	// Contraste automatique noir/blanc sur les boutons actifs selon la luminosité de la couleur d'accent
	public static string OnAccentText => Luminance( Accent ) > 0.58f ? "#0B1020" : "#FFFFFF";

	private static string Alpha( float v ) => Math.Clamp( v, 0.35f, 0.95f ).ToString( "0.00", CultureInfo.InvariantCulture );

	public static string HexToRgba( string hex, float alpha )
	{
		ParseRgb( hex, out int r, out int g, out int b );
		return $"rgba({r}, {g}, {b}, {Alpha( alpha )})";
	}

	private static float Luminance( string hex )
	{
		ParseRgb( hex, out int r, out int g, out int b );
		return (0.299f * r + 0.587f * g + 0.114f * b) / 255f;
	}

	private static void ParseRgb( string hex, out int r, out int g, out int b )
	{
		hex = SanitizeHex( hex, "#3B82F6" );
		r = int.Parse( hex.Substring( 1, 2 ), NumberStyles.HexNumber );
		g = int.Parse( hex.Substring( 3, 2 ), NumberStyles.HexNumber );
		b = int.Parse( hex.Substring( 5, 2 ), NumberStyles.HexNumber );
	}

	private static string SanitizeHex( string hex, string fallback )
	{
		if ( string.IsNullOrWhiteSpace( hex ) ) return fallback;
		hex = hex.Trim();
		if ( hex.Length != 7 || hex[0] != '#' ) return fallback;
		for ( int i = 1; i < 7; i++ )
		{
			char ch = hex[i];
			bool ok = (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
			if ( !ok ) return fallback;
		}
		return hex;
	}

	public static string SanitizeKey( string key, string fallback )
	{
		if ( string.IsNullOrWhiteSpace( key ) ) return fallback;
		key = key.Trim().ToUpperInvariant();
		if ( key is "ESCAPE" or "ESC" or "MOUSE1" or "MOUSE2" or "W" or "A" or "S" or "D" or "Z" or "Q" or "SPACE" or "ENTER" or "TAB" )
			return fallback;
		return key.Length <= 12 ? key : fallback;
	}

	private static ThemeRecord Sanitize( ThemeRecord t )
	{
		t.MenuKey = SanitizeKey( t.MenuKey, "F4" );
		t.BackupKey = SanitizeKey( t.BackupKey, "F7" );
		t.SurfaceOpacity = Math.Clamp( float.IsFinite( t.SurfaceOpacity ) ? t.SurfaceOpacity : 0.68f, 0.42f, 0.90f );
		t.AccentColor = SanitizeHex( t.AccentColor, "#3B82F6" );
		t.TextColor = SanitizeHex( t.TextColor, "#FFFFFF" );
		return t;
	}
}