mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-28 22:18:25 +01:00
first
This commit is contained in:
parent
bd62d51ec9
commit
b578433e37
5 changed files with 784842 additions and 0 deletions
|
|
@ -0,0 +1,53 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Defines how a terminal action should be parsed
|
||||
/// </summary>
|
||||
public enum ArgParseMode
|
||||
{
|
||||
/// <summary>
|
||||
/// Parse the command string args into individual tokens, considering whitespace and quotes
|
||||
/// </summary>
|
||||
Default,
|
||||
|
||||
/// <summary>
|
||||
/// Output the raw unparsed command arg string
|
||||
/// </summary>
|
||||
Unparsed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An attribute which is used to define methods that can be registered as callback through a TerminalInterface
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class TerminalActionAttribute : Attribute
|
||||
{
|
||||
/// <param name="commandName">The command name</param>
|
||||
/// <param name="description">A description of the command</param>
|
||||
/// <param name="parsingMode">The type of parsing which should be used on the command</param>
|
||||
public TerminalActionAttribute(
|
||||
string commandName,
|
||||
string description = "",
|
||||
ArgParseMode parsingMode = ArgParseMode.Default
|
||||
)
|
||||
{
|
||||
CommandName = commandName.ToLower();
|
||||
Description = description;
|
||||
ParsingMode = parsingMode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name of the command
|
||||
/// </summary>
|
||||
public string CommandName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// A description of the command
|
||||
/// </summary>
|
||||
public string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The parsing mode of the command
|
||||
/// </summary>
|
||||
public ArgParseMode ParsingMode { get; }
|
||||
}
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the arguments which a command takes
|
||||
/// </summary>
|
||||
public struct ArgDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the arg
|
||||
/// </summary>
|
||||
public string Name;
|
||||
|
||||
/// <summary>
|
||||
/// The type of the arg
|
||||
/// </summary>
|
||||
public Type Type;
|
||||
|
||||
/// <summary>
|
||||
/// Whether or not this arg has a default value
|
||||
/// </summary>
|
||||
public bool HasDefault;
|
||||
|
||||
/// <summary>
|
||||
/// ToString() helper
|
||||
/// </summary>
|
||||
public override string ToString()
|
||||
{
|
||||
return Name;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A struct which represents a command which can be called through the terminal interface
|
||||
/// </summary>
|
||||
public readonly struct Command
|
||||
{
|
||||
private readonly List<ArgDefinition> _argDefinitions;
|
||||
private readonly Delegate _callback;
|
||||
|
||||
/// <summary>
|
||||
/// A description of the command
|
||||
/// </summary>
|
||||
public string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The parsing mode which should be used for this command
|
||||
/// </summary>
|
||||
public ArgParseMode ParsingMode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor, which takes a callback function and uses its parameters to define argument definitions
|
||||
/// </summary>
|
||||
/// <param name="callback"></param>
|
||||
/// <param name="description"></param>
|
||||
/// <param name="parsingMode"></param>
|
||||
public Command(Delegate callback, string description, ArgParseMode parsingMode)
|
||||
{
|
||||
_argDefinitions = new List<ArgDefinition>();
|
||||
_callback = callback;
|
||||
Description = description;
|
||||
ParsingMode = parsingMode;
|
||||
CreateArgDefinitions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call to issue this command
|
||||
/// </summary>
|
||||
/// <param name="args">The args to call the command with</param>
|
||||
public void Issue(string[]? args)
|
||||
{
|
||||
ParseArgs(args, out var parsedArgs);
|
||||
_callback.Method.Invoke(_callback.Target, parsedArgs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a readonly list of the arg definitions for this command
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArgDefinition> GetDefinitions => _argDefinitions;
|
||||
|
||||
private void ParseArgs(string[]? args, out object[]? outParsedArgs)
|
||||
{
|
||||
if (args?.Length > _argDefinitions.Count)
|
||||
throw new TerminalInterfaceException(
|
||||
"Command parsing failed,"
|
||||
+ $" too many arguments for command: {_callback.Method.Name}."
|
||||
+ $" Expected: {_argDefinitions.Count}, got: {args.Length}."
|
||||
);
|
||||
|
||||
if (_argDefinitions.Count == 0)
|
||||
{
|
||||
outParsedArgs = null;
|
||||
return;
|
||||
}
|
||||
|
||||
outParsedArgs = new object[_argDefinitions.Count];
|
||||
|
||||
// Iterate through our defined definitions and try to parse the args into the correct types
|
||||
for (var i = 0; i < _argDefinitions.Count; i++)
|
||||
{
|
||||
var definition = _argDefinitions[i];
|
||||
ref var outArg = ref outParsedArgs[i];
|
||||
|
||||
if (args is null || args.Length <= i)
|
||||
{
|
||||
// If an arg is optional pass Type.Missing to use the function's defined default
|
||||
if (definition.HasDefault)
|
||||
{
|
||||
outArg = Type.Missing;
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new TerminalInterfaceException(
|
||||
"Command parsing failed,"
|
||||
+ $" missing required argument: {definition.Name}"
|
||||
+ $" of type: {definition.Type.Name}"
|
||||
);
|
||||
}
|
||||
|
||||
var arg = args[i];
|
||||
|
||||
TryParse(arg, definition.Type, out outArg);
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryParse(string arg, Type type, out object value)
|
||||
{
|
||||
// TODO: Add specific cases that we want to handle with our own parsing logic - e.g. vectors
|
||||
|
||||
try
|
||||
{
|
||||
value = Convert.ChangeType(arg, type);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new TerminalInterfaceException($"Failed to parse command argument: {arg} to type: {type.Name}.");
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateArgDefinitions()
|
||||
{
|
||||
var parameters = _callback.Method.GetParameters();
|
||||
|
||||
// Validation of single string parsing mode
|
||||
if (ParsingMode == ArgParseMode.Unparsed)
|
||||
{
|
||||
if (parameters.Length != 1)
|
||||
throw new TerminalInterfaceException(
|
||||
"Failed to parse delegate parameters into argument types,"
|
||||
+ " single string parsing mode requires exactly one parameter"
|
||||
+ $" in callback: {_callback.Method.Name}"
|
||||
);
|
||||
|
||||
if (parameters[0].ParameterType != typeof(string))
|
||||
throw new TerminalInterfaceException(
|
||||
"Failed to parse delegate parameters into argument types,"
|
||||
+ " single string parsing mode requires a string parameter"
|
||||
+ $" in callback: {_callback.Method.Name}"
|
||||
);
|
||||
}
|
||||
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
if (!TypeIsSupported(parameter.ParameterType))
|
||||
throw new TerminalInterfaceException(
|
||||
"Failed to parse delegate parameters into argument types,"
|
||||
+ $" unsupported argument type: {parameter.ParameterType.Name}"
|
||||
+ $" in callback: {_callback.Method.Name}"
|
||||
);
|
||||
|
||||
var definition = new ArgDefinition
|
||||
{
|
||||
Name = parameter.Name ?? $"param_{parameter.Position}",
|
||||
Type = parameter.ParameterType,
|
||||
HasDefault = parameter.HasDefaultValue,
|
||||
};
|
||||
|
||||
_argDefinitions.Add(definition);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TypeIsSupported(Type type)
|
||||
{
|
||||
// Convert.ChangeType() supports primitives, strings, and DateTime
|
||||
if (type.IsPrimitive)
|
||||
return true;
|
||||
|
||||
if (type == typeof(string))
|
||||
return true;
|
||||
|
||||
if (type == typeof(DateTime))
|
||||
return true;
|
||||
|
||||
// TODO: add any types for which we offer custom parsing logic
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,272 @@
|
|||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using Brutal.Logging;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// The type of message the terminal interface is outputting
|
||||
/// </summary>
|
||||
public enum TerminalInterfaceOutputType
|
||||
{
|
||||
/// <summary>
|
||||
/// An informative message
|
||||
/// </summary>
|
||||
Message,
|
||||
|
||||
/// <summary>
|
||||
/// An error with the processing of a command
|
||||
/// </summary>
|
||||
Error,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides an interface which can be used to register terminal commands and handle terminal input.
|
||||
/// </summary>
|
||||
public class TerminalInterface
|
||||
{
|
||||
public static LogCategory Log = LogCategory.Make("TerminalInterface");
|
||||
|
||||
private readonly Dictionary<object, Dictionary<string, Command>> CommandLibrary = new();
|
||||
private readonly Dictionary<string, Command> StaticCommandLibrary = new();
|
||||
private readonly ConsoleWindow _consoleWindow;
|
||||
|
||||
/// <summary>
|
||||
/// Invoked with a message when the terminal interface wants to output something
|
||||
/// </summary>
|
||||
public event Action<string, TerminalInterfaceOutputType>? OnOutput;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public TerminalInterface(ConsoleWindow consoleWindow)
|
||||
{
|
||||
_consoleWindow = consoleWindow;
|
||||
RegisterCommand(ListCommands);
|
||||
RegisterCommand(ClearConsole);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a batch of terminal input commands.
|
||||
/// </summary>
|
||||
/// <param name="inInput">A collection of terminal input strings.</param>
|
||||
public void Execute(params ReadOnlySpan<string> inInput)
|
||||
{
|
||||
foreach (var commandLine in inInput)
|
||||
Execute(commandLine);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses terminal input and processes it as commands.
|
||||
/// </summary>
|
||||
/// <param name="inInput">The input string from the terminal</param>
|
||||
public bool Execute(string inInput)
|
||||
{
|
||||
// Split full input into individual command statements
|
||||
foreach (var commandString in Parser.SplitToCommands(inInput))
|
||||
try
|
||||
{
|
||||
ProcessCommand(commandString);
|
||||
}
|
||||
catch (TerminalInterfaceException e)
|
||||
{
|
||||
OutputProcessCommandError(commandString, e.Message);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Type? GetDelegateTypeForMethod(MethodBase inMethodInfo)
|
||||
{
|
||||
var parameterTypes = Array.ConvertAll(inMethodInfo.GetParameters(), p => p.ParameterType);
|
||||
// Direct lookup of the right Action arity. Returns false when no Action can represent the
|
||||
// signature: more than 16 parameters, or ByRef/pointer parameter types.
|
||||
return Expression.TryGetActionType(parameterTypes, out var delegateType) ? delegateType : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register an object with TerminalAction methods
|
||||
/// </summary>
|
||||
/// <param name="inObject">The object we want to register commands from</param>
|
||||
/// <exception cref="TerminalInterfaceException"></exception>
|
||||
public void RegisterObject(object inObject)
|
||||
{
|
||||
var methods = GetMethodInfos(inObject);
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var delegateType = GetDelegateTypeForMethod(method);
|
||||
|
||||
if (delegateType != null)
|
||||
{
|
||||
if (method.IsStatic)
|
||||
RegisterCommand(Delegate.CreateDelegate(delegateType, method), inObject);
|
||||
else
|
||||
RegisterCommand(Delegate.CreateDelegate(delegateType, inObject, method), inObject);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new TerminalInterfaceException(
|
||||
$"Error registering command: callback {method.Name} has an unsupported signature"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<MethodInfo> GetMethodInfos(object inObject)
|
||||
{
|
||||
const BindingFlags flags =
|
||||
BindingFlags.Instance
|
||||
| BindingFlags.Public
|
||||
| BindingFlags.NonPublic
|
||||
| BindingFlags.FlattenHierarchy
|
||||
| BindingFlags.Static;
|
||||
|
||||
var objectType = inObject.GetType();
|
||||
var allMethods = objectType.GetMethods(flags);
|
||||
return allMethods.Where(m => m.GetCustomAttribute<TerminalActionAttribute>() != null);
|
||||
}
|
||||
|
||||
public void UnregisterObject(object inObject)
|
||||
{
|
||||
if (CommandLibrary.ContainsKey(inObject))
|
||||
CommandLibrary.Remove(inObject);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers commands which can be called from the terminal.
|
||||
/// </summary>
|
||||
/// <param name="inCallback">The function which the command will call</param>
|
||||
/// <param name="inObject">Object to which the command delegate is bound to. Null for methods</param>
|
||||
public void RegisterCommand(Delegate inCallback, object? inObject = null)
|
||||
{
|
||||
var attribute = inCallback.Method.GetCustomAttribute<TerminalActionAttribute>();
|
||||
|
||||
if (attribute is null)
|
||||
throw new TerminalInterfaceException(
|
||||
$"Error registering command:" + $" callback {inCallback.Method.Name} has no TerminalActionAttribute"
|
||||
);
|
||||
|
||||
if (inObject is not null)
|
||||
{
|
||||
if (!CommandLibrary.ContainsKey(inObject))
|
||||
CommandLibrary[inObject] = new Dictionary<string, Command>();
|
||||
|
||||
CommandLibrary[inObject][attribute.CommandName] = new Command(
|
||||
inCallback,
|
||||
attribute.Description,
|
||||
attribute.ParsingMode
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
StaticCommandLibrary[attribute.CommandName] = new Command(
|
||||
inCallback,
|
||||
attribute.Description,
|
||||
attribute.ParsingMode
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessCommand(string inCommandString)
|
||||
{
|
||||
// Split command into command name and arguments
|
||||
Parser.SplitCommand(inCommandString, out var commandName, out var argsString);
|
||||
|
||||
if (StaticCommandLibrary.ContainsKey(commandName))
|
||||
{
|
||||
var args = Parser.SplitToArgs(argsString, StaticCommandLibrary[commandName].ParsingMode);
|
||||
|
||||
// Issue the command
|
||||
StaticCommandLibrary[commandName].Issue(args);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var (_, commands) in CommandLibrary)
|
||||
{
|
||||
if (commands.ContainsKey(commandName))
|
||||
{
|
||||
var args = Parser.SplitToArgs(argsString, commands[commandName].ParsingMode);
|
||||
|
||||
// Issue the command
|
||||
commands[commandName].Issue(args);
|
||||
return;
|
||||
}
|
||||
}
|
||||
Log.Error($"unknown command {commandName}, use 'help' for a list of commands");
|
||||
}
|
||||
|
||||
[TerminalAction("clear", "Clears the console output")]
|
||||
private void ClearConsole() => _consoleWindow.ClearConsole();
|
||||
|
||||
[TerminalAction("help", "Lists all registered commands and their descriptions")]
|
||||
private void ListCommands()
|
||||
{
|
||||
var commandCount = 0;
|
||||
var tableString = new TableString();
|
||||
|
||||
var cmds = new Dictionary<string, Command>();
|
||||
|
||||
// commands
|
||||
foreach (var (command, args) in StaticCommandLibrary)
|
||||
cmds.Add(command, args);
|
||||
|
||||
// instanced commands
|
||||
foreach (var (_, commands) in CommandLibrary)
|
||||
foreach (var (command, args) in commands)
|
||||
cmds.Add(command, args);
|
||||
|
||||
foreach (var cmd in cmds)
|
||||
PrintHelpLine(cmd.Key, cmd.Value);
|
||||
|
||||
_consoleWindow.Print($"listing {commandCount} commands");
|
||||
_consoleWindow.Print(
|
||||
"Multiple commands can be called in a single statement by separating them with a ';' semicolon"
|
||||
);
|
||||
tableString.Sort();
|
||||
tableString.ToConsole(_consoleWindow);
|
||||
OnOutput?.Invoke(string.Empty, TerminalInterfaceOutputType.Message);
|
||||
return;
|
||||
|
||||
void PrintHelpLine(string command, Command args)
|
||||
{
|
||||
commandCount++;
|
||||
|
||||
var definitions = args.GetDefinitions;
|
||||
if (definitions.Count == 0)
|
||||
{
|
||||
tableString.AddRow(command, args.Description);
|
||||
return;
|
||||
}
|
||||
|
||||
var argSb = new StringBuilder();
|
||||
for (var i = 0; i < definitions.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
argSb.Append(", ");
|
||||
var definition = args.GetDefinitions[i];
|
||||
argSb.Append('<');
|
||||
var type = definition.Type.ToString();
|
||||
// remove "System." from the type name
|
||||
if (type.StartsWith("System."))
|
||||
type = type[7..];
|
||||
type = type.ToLowerInvariant();
|
||||
argSb.Append(type);
|
||||
argSb.Append('>');
|
||||
if (definition.HasDefault)
|
||||
argSb.Append('?');
|
||||
argSb.Append(' ');
|
||||
argSb.Append(definition.Name);
|
||||
}
|
||||
tableString.AddRow(command, args.Description, argSb.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private void OutputProcessCommandError(string inCommand, string inErrorMessage)
|
||||
{
|
||||
var message = $"Terminal interface failed to process command: {inCommand}, error: {inErrorMessage}";
|
||||
OnOutput?.Invoke(message, TerminalInterfaceOutputType.Error);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// An exception which is thrown when a terminal command fails to issue
|
||||
/// </summary>
|
||||
public class TerminalInterfaceException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public TerminalInterfaceException(string message)
|
||||
: base(message) { }
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
using System.CommandLine.Parsing;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// A parsing utility class for the terminal interface
|
||||
/// </summary>
|
||||
internal static class Parser
|
||||
{
|
||||
private const char CommandDelimiter = ';';
|
||||
|
||||
/// <summary>
|
||||
/// Splits an input string into individual command strings
|
||||
/// </summary>
|
||||
/// <param name="inInput">The raw string from terminal input</param>
|
||||
/// <returns>A list of individual command strings</returns>
|
||||
public static List<string> SplitToCommands(string inInput)
|
||||
{
|
||||
var commands = new List<string>();
|
||||
var withinQuotes = false;
|
||||
var startIndex = 0;
|
||||
|
||||
void TryAddCommand(string command)
|
||||
{
|
||||
var trimmedCommand = command.Trim();
|
||||
if (trimmedCommand.Length > 0)
|
||||
commands.Add(trimmedCommand);
|
||||
}
|
||||
|
||||
// Ignore our delimiter if it's part of a quoted string
|
||||
for (var i = 0; i < inInput.Length; i++)
|
||||
if (inInput[i] == '\"')
|
||||
{
|
||||
withinQuotes = !withinQuotes;
|
||||
}
|
||||
else if (inInput[i] == CommandDelimiter && !withinQuotes)
|
||||
{
|
||||
// Split input into individual commands by delimiter
|
||||
TryAddCommand(inInput.Substring(startIndex, i - startIndex));
|
||||
startIndex = i + 1;
|
||||
}
|
||||
|
||||
// Add the last command if there is one
|
||||
if (startIndex < inInput.Length)
|
||||
TryAddCommand(inInput.Substring(startIndex).Trim());
|
||||
|
||||
return commands;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits a command string into a command name and args string
|
||||
/// </summary>
|
||||
/// <param name="inCommandString">The command string to split</param>
|
||||
/// <param name="inCommandName">The command name part of the input string</param>
|
||||
/// <param name="inArgsString">The args part of the input string</param>
|
||||
public static void SplitCommand(string inCommandString, out string inCommandName, out string inArgsString)
|
||||
{
|
||||
const StringSplitOptions flags = StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries;
|
||||
|
||||
// Split at first whitespace
|
||||
var split = inCommandString.Split(Array.Empty<char>(), 2, flags);
|
||||
|
||||
if (split.Length == 0)
|
||||
throw new TerminalInterfaceException("Command parsing failed, command string was empty.");
|
||||
|
||||
inCommandName = split[0].ToLower();
|
||||
inArgsString = split.Length > 1 ? split[1] : "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits an arg string into individual args according to the parsing mode
|
||||
/// </summary>
|
||||
/// <param name="inArgsString">The string to split</param>
|
||||
/// <param name="inArgParseMode">The parsing mode to use</param>
|
||||
/// <returns>An array of arg strings, or null if the args string was empty</returns>
|
||||
public static string[]? SplitToArgs(string inArgsString, ArgParseMode inArgParseMode)
|
||||
{
|
||||
// If we're using single string parsing mode, return the args as a single string
|
||||
if (inArgParseMode == ArgParseMode.Unparsed)
|
||||
// Remove outer whitespace and quotes if they exist
|
||||
return new[] { inArgsString };
|
||||
|
||||
// If there are no args, return null
|
||||
if (string.IsNullOrEmpty(inArgsString))
|
||||
return null;
|
||||
|
||||
// If we're using default parsing mode, split the args into individual strings
|
||||
return CommandLineParser.SplitCommandLine(inArgsString).ToArray();
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue