DTLib/DTLib/Console/ColoredConsole.cs
2024-10-20 12:32:30 +05:00

90 lines
3.0 KiB
C#

namespace DTLib.Console;
public static class ColoredConsole
{
public static int Width => System.Console.WindowWidth;
public static int Height => System.Console.WindowHeight;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Fg(ConsoleColor color) => System.Console.ForegroundColor = color;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Bg(ConsoleColor color) => System.Console.BackgroundColor = color;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void ResetColor() => System.Console.ResetColor();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Clear()
{
ResetColor();
System.Console.Clear();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write(char c) => System.Console.Write(c);
public static void Write(string msg, ConsoleColor? fg = null, ConsoleColor? bg = null)
{
if(fg != null) Fg(fg.Value);
if(bg != null) Bg(bg.Value);
#if NETSTANDARD2_0
var chars = msg.ToCharArray();
#else
var chars = msg.AsSpan();
#endif
for (int i = 0; i < chars.Length; ++i)
{
Write(chars[i]);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteLine() => Write('\n');
public static void WriteLine(string msg, ConsoleColor? fg = null, ConsoleColor? bg = null)
{
Write(msg, fg, bg);
WriteLine();
}
public static string? ReadLine(string query, ConsoleColor? fg = null, ConsoleColor? bg = null)
{
Write(query, fg, bg);
Write(':');
Write(' ');
return System.Console.ReadLine();
}
public static void WriteHLine(char c, ConsoleColor? fg = null, ConsoleColor? bg = null)
{
WriteLine(c.Multiply(Width - 1), fg, bg);
}
public static void WriteTitle(string title, char spacing = '-',
string left_framing = "[", string right_framing = "]",
ConsoleColor? fg = null, ConsoleColor? bg = null)
{
int both_spacing_length = Width - title.Length - left_framing.Length - right_framing.Length - 1;
int left_spacing_length = both_spacing_length / 2;
int right_spacing_length = left_spacing_length + both_spacing_length % 2;
var b = new StringBuilder();
if(left_spacing_length > 0)
b.Append(spacing.Multiply(left_spacing_length));
b.Append(left_framing);
b.Append(title);
b.Append(right_framing);
if(right_spacing_length > 0)
b.Append(spacing.Multiply(right_spacing_length));
WriteLine(b.ToString(), fg, bg);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteCentred(string title, ConsoleColor? fg = null, ConsoleColor? bg = null)
{
WriteTitle(title, ' ', "", "", fg, bg);
}
}