using System.Drawing; using System.Text.RegularExpressions; using Pastel; namespace Yuanshen.Common.Console; public static class ConsoleTheme { public static readonly Color GradientFrom = Color.FromArgb(0x7B, 0x2F, 0xF7); public static readonly Color GradientTo = Color.FromArgb(0xE0, 0x40, 0xFB); public static readonly Color Accent = Color.FromArgb(0xC7, 0x7D, 0xFF); public static readonly Color Muted = Color.FromArgb(0x6B, 0x5E, 0x7A); public static readonly Color Text = Color.FromArgb(0xEC, 0xE4, 0xF5); private static bool _enabled; public static void Enable() { if (_enabled) return; _enabled = true; try { System.Console.OutputEncoding = System.Text.Encoding.UTF8; } catch { } ConsoleExtensions.Enable(); } public static Color Lerp(Color from, Color to, double t) { t = Math.Clamp(t, 0d, 1d); return Color.FromArgb( (int)(from.R + (to.R - from.R) * t), (int)(from.G + (to.G - from.G) * t), (int)(from.B + (to.B - from.B) * t)); } public static string Gradient(string text) => Gradient(text, GradientFrom, GradientTo); public static string Gradient(string text, Color from, Color to) { if (string.IsNullOrEmpty(text)) return text; System.Text.StringBuilder builder = new(text.Length * 12); int steps = Math.Max(text.Length - 1, 1); for (int i = 0; i < text.Length; i++) { char symbol = text[i]; if (symbol == ' ') { builder.Append(symbol); continue; } builder.Append(symbol.ToString().Pastel(Lerp(from, to, (double)i / steps))); } return builder.ToString(); } public static int Width { get { try { return System.Console.WindowWidth > 20 ? System.Console.WindowWidth : 100; } catch { return 100; } } } public static string Center(string plain, string rendered) { int pad = Math.Max((Width - plain.Length) / 2, 0); return new string(' ', pad) + rendered; } public static string Center(string rendered) => Center(Strip(rendered), rendered); public static string Strip(string text) => AnsiPattern.Replace(text, string.Empty); private static readonly Regex AnsiPattern = new((char)27 + @"\[[0-9;]*m", RegexOptions.Compiled); }