XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFESystem

【Rust】XFE系统,基于Rust和汇编

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Runtime.CompilerServices;
using Cosmos.Build.API.Attributes;
using Cosmos.Kernel.System.Graphics;

namespace XFESystem.Kernel;

/// <summary>
/// Fix Cosmos 3.0.88's constant Console color getters without modifying its package.
/// The build applies these project overrides after the upstream default plugs.
/// </summary>
[Plug(typeof(global::System.Console))]
public static class ConsoleColorPlug
{
    [PlugMember]
    public static ConsoleColor get_ForegroundColor() => ConsoleColorState.Foreground;

    [PlugMember]
    public static ConsoleColor get_BackgroundColor() => ConsoleColorState.Background;

    [PlugMember]
    public static void set_ForegroundColor(ConsoleColor value) => ConsoleColorState.SetForeground(value);

    [PlugMember]
    public static void set_BackgroundColor(ConsoleColor value) => ConsoleColorState.SetBackground(value);

    [PlugMember]
    public static void ResetColor() => ConsoleColorState.Reset();
}

public static class ConsoleColorState
{
    public static ConsoleColor Foreground { get; private set; } = ConsoleColor.White;
    public static ConsoleColor Background { get; private set; } = ConsoleColor.Black;

    public static void SetForeground(ConsoleColor value)
    {
        Validate(value);
        SetForegroundNative(CurrentConsole, value);
        Foreground = value;
    }

    public static void SetBackground(ConsoleColor value)
    {
        Validate(value);
        SetBackgroundNative(CurrentConsole, value);
        Background = value;
    }

    public static void Reset()
    {
        ResetNative(CurrentConsole);
        Foreground = ConsoleColor.White;
        Background = ConsoleColor.Black;
    }

    private static void Validate(ConsoleColor value)
    {
        if ((uint)value > 15) throw new ArgumentOutOfRangeException(nameof(value));
    }

    private static KernelConsole CurrentConsole => KernelConsole.Default
        ?? throw new InvalidOperationException("The guest console is not initialized.");

    [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "SetForegroundColor")]
    private static extern void SetForegroundNative(KernelConsole console, ConsoleColor value);
    [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "SetBackgroundColor")]
    private static extern void SetBackgroundNative(KernelConsole console, ConsoleColor value);
    [UnsafeAccessor(UnsafeAccessorKind.Method, Name = "ResetColors")]
    private static extern void ResetNative(KernelConsole console);
}