Refactor CLI command system to support async execution and central command history

This commit is contained in:
Stone_Red
2026-06-11 20:40:26 +02:00
parent 2b091e6e7c
commit 160d0559e8
14 changed files with 114 additions and 63 deletions
+19 -19
View File
@@ -7,20 +7,23 @@ internal class CliProcess() : Process("Cli")
{ {
private string currentInput = string.Empty; private string currentInput = string.Empty;
private readonly List<string> commandHistory = [];
private int historyIndex = -1; private int historyIndex = -1;
private bool commandRunning = false;
internal override void Start(string[] args) internal override void Start(string[] args)
{ {
Console.Clear(); Console.Clear();
Console.WriteLine("Welcome RemSox!"); Console.WriteLine("Welcome RemSox!");
Console.WriteLine("Type 'help' to see available commands."); Console.WriteLine("Type 'help' to see available commands.");
Console.Write("> "); Console.Write("> ");
historyIndex = CommandManager.GetCommandHistory().Count;
} }
internal override void Tick() internal override async void Tick()
{ {
while (Console.KeyAvailable) while (Console.KeyAvailable && !commandRunning)
{ {
ConsoleKeyInfo key = Console.ReadKey(intercept: true); ConsoleKeyInfo key = Console.ReadKey(intercept: true);
@@ -29,14 +32,9 @@ internal class CliProcess() : Process("Cli")
case ConsoleKey.Enter: case ConsoleKey.Enter:
Console.WriteLine(); Console.WriteLine();
if (!string.IsNullOrWhiteSpace(currentInput) && (commandHistory.Count == 0 || commandHistory[^1] != currentInput)) await HandleCommand(currentInput);
{
commandHistory.Add(currentInput);
}
historyIndex = commandHistory.Count; historyIndex = CommandManager.GetCommandHistory().Count;
HandleCommand(currentInput);
currentInput = string.Empty; currentInput = string.Empty;
Console.Write("> "); Console.Write("> ");
@@ -50,10 +48,10 @@ internal class CliProcess() : Process("Cli")
} }
break; break;
case ConsoleKey.UpArrow: case ConsoleKey.UpArrow:
if (commandHistory.Count > 0) if (CommandManager.GetCommandHistory().Count > 0)
{ {
historyIndex = Math.Max(historyIndex - 1, 0); historyIndex = Math.Max(historyIndex - 1, 0);
currentInput = commandHistory[historyIndex]; currentInput = CommandManager.GetCommandHistory()[historyIndex];
Console.Write("\r> " + currentInput + new string('#', Console.WindowWidth - currentInput.Length - 2)); Console.Write("\r> " + currentInput + new string('#', Console.WindowWidth - currentInput.Length - 2));
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.CursorTop--; Console.CursorTop--;
@@ -61,10 +59,10 @@ internal class CliProcess() : Process("Cli")
} }
break; break;
case ConsoleKey.DownArrow: case ConsoleKey.DownArrow:
if (commandHistory.Count > 0) if (CommandManager.GetCommandHistory().Count > 0)
{ {
historyIndex = Math.Min(historyIndex + 1, commandHistory.Count - 1); historyIndex = Math.Min(historyIndex + 1, CommandManager.GetCommandHistory().Count - 1);
currentInput = commandHistory[historyIndex]; currentInput = CommandManager.GetCommandHistory()[historyIndex];
Console.Write("\r> " + currentInput + new string('#', Console.WindowWidth - currentInput.Length - 2)); Console.Write("\r> " + currentInput + new string('#', Console.WindowWidth - currentInput.Length - 2));
Console.CursorLeft = 0; Console.CursorLeft = 0;
Console.CursorTop--; Console.CursorTop--;
@@ -82,20 +80,22 @@ internal class CliProcess() : Process("Cli")
} }
} }
private static void HandleCommand(string input) private async Task HandleCommand(string input)
{ {
if (string.IsNullOrWhiteSpace(input)) if (string.IsNullOrWhiteSpace(input))
{ {
return; return;
} }
bool handled = CommandManager.TryExecute( commandRunning = true;
input,
line => Console.WriteLine(line)); bool handled = await CommandManager.TryExecute(input, Console.WriteLine);
if (!handled) if (!handled)
{ {
Console.WriteLine($"\"{input}\" is not a command"); Console.WriteLine($"\"{input}\" is not a command");
} }
commandRunning = false;
} }
} }
+17 -15
View File
@@ -13,7 +13,6 @@ public class TerminalProcess() : Process("Terminal")
{ {
private Window window = null!; private Window window = null!;
private readonly List<string> history = []; private readonly List<string> history = [];
private readonly List<string> commandHistory = [];
private int historyIndex = -1; private int historyIndex = -1;
private string currentInput = ""; private string currentInput = "";
private readonly List<Text> textLines = []; private readonly List<Text> textLines = [];
@@ -28,6 +27,8 @@ public class TerminalProcess() : Process("Terminal")
PrintLine("RemSox GUI Terminal v1.0"); PrintLine("RemSox GUI Terminal v1.0");
PrintLine("Type 'help' for commands."); PrintLine("Type 'help' for commands.");
historyIndex = CommandManager.GetCommandHistory().Count;
window.Flush(); window.Flush();
window.OnKeyEvent += HandleKey; window.OnKeyEvent += HandleKey;
} }
@@ -46,18 +47,12 @@ public class TerminalProcess() : Process("Terminal")
window.OnKeyEvent -= HandleKey; window.OnKeyEvent -= HandleKey;
} }
private void HandleKey(KeyEvent keyEvent) private async void HandleKey(KeyEvent keyEvent)
{ {
if (keyEvent.Key == ConsoleKeyEx.Enter) if (keyEvent.Key == ConsoleKeyEx.Enter)
{ {
string cmd = currentInput; string cmd = currentInput;
if (!string.IsNullOrWhiteSpace(currentInput) && (commandHistory.Count == 0 || commandHistory[^1] != currentInput))
{
commandHistory.Add(currentInput);
}
historyIndex = commandHistory.Count;
PrintLine("> " + cmd); PrintLine("> " + cmd);
currentInput = ""; currentInput = "";
@@ -77,12 +72,19 @@ public class TerminalProcess() : Process("Terminal")
} }
else else
{ {
bool found = CommandManager.TryExecute(cmd, PrintLine); window.OnKeyEvent -= HandleKey;
if (!found)
bool handled = await CommandManager.TryExecute(cmd, PrintLine);
if (!handled)
{ {
PrintLine($"\"{cmd}\" is not a command"); PrintLine($"\"{cmd}\" is not a command");
} }
window.OnKeyEvent += HandleKey;
} }
historyIndex = CommandManager.GetCommandHistory().Count;
} }
UpdateDisplay(); UpdateDisplay();
} }
@@ -96,19 +98,19 @@ public class TerminalProcess() : Process("Terminal")
} }
else if (keyEvent.Key == ConsoleKeyEx.UpArrow) else if (keyEvent.Key == ConsoleKeyEx.UpArrow)
{ {
if (commandHistory.Count > 0) if (CommandManager.GetCommandHistory().Count > 0)
{ {
historyIndex = Math.Max(historyIndex - 1, 0); historyIndex = Math.Max(historyIndex - 1, 0);
currentInput = commandHistory[historyIndex]; currentInput = CommandManager.GetCommandHistory()[historyIndex];
UpdateDisplay(); UpdateDisplay();
} }
} }
else if (keyEvent.Key == ConsoleKeyEx.DownArrow) else if (keyEvent.Key == ConsoleKeyEx.DownArrow)
{ {
if (commandHistory.Count > 0) if (CommandManager.GetCommandHistory().Count > 0)
{ {
historyIndex = Math.Min(historyIndex + 1, commandHistory.Count - 1); historyIndex = Math.Min(historyIndex + 1, CommandManager.GetCommandHistory().Count - 1);
currentInput = commandHistory[historyIndex]; currentInput = CommandManager.GetCommandHistory()[historyIndex];
UpdateDisplay(); UpdateDisplay();
} }
} }
+38 -12
View File
@@ -8,7 +8,7 @@ namespace RemSox.Processing;
public static class ProcessManager public static class ProcessManager
{ {
private static readonly ConcurrentDictionary<int, (Process Process, ProcessMetrics Metrics)> processes = new(); private static readonly ConcurrentDictionary<int, (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource)> processes = new();
private static readonly ConcurrentDictionary<Type, ConcurrentHashSet<int>> processesByType = new(); private static readonly ConcurrentDictionary<Type, ConcurrentHashSet<int>> processesByType = new();
@@ -57,15 +57,15 @@ public static class ProcessManager
logger.Log($"Process {process.Name} (ID: {process.Id}) terminated with an exception: {ex}", LogSeverity.Error); logger.Log($"Process {process.Name} (ID: {process.Id}) terminated with an exception: {ex}", LogSeverity.Error);
} }
_ = processes.TryAdd(id, (process, new ProcessMetrics())); _ = processes.TryAdd(id, (process, new ProcessMetrics(), new TaskCompletionSource()));
logger.Log($"Spawned process {process.Name} of type {typeof(T).Name} with ID {id}.", LogSeverity.Info); logger.Log($"Spawned process {process.Name} of type {typeof(T).Name} with ID {id}.", LogSeverity.Info);
return id; return id;
} }
public static void StopProcess(int processId, bool waitForExit = false) public static void StopProcess(int processId)
{ {
if (!processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics) entry)) if (!processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry))
{ {
return; return;
} }
@@ -76,18 +76,21 @@ public static class ProcessManager
public static async Task StopProcessAndWaitAsync(int processId) public static async Task StopProcessAndWaitAsync(int processId)
{ {
if (!processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics) entry)) if (!processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry))
{ {
return; return;
} }
logger.Log($"Requesting stop of process {entry.Process.Name} (ID: {entry.Process.Id}).", LogSeverity.Info); logger.Log($"Requesting stop of process {entry.Process.Name} (ID: {entry.Process.Id}).", LogSeverity.Info);
entry.Process.RequestStop(); entry.Process.RequestStop();
await entry.ExitSource.Task;
} }
public static void StopAllProcesses() public static void StopAllProcesses()
{ {
foreach ((Process Process, ProcessMetrics Metrics) entry in processes.Values) foreach ((Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry in processes.Values)
{ {
StopProcess(entry.Process.Id); StopProcess(entry.Process.Id);
} }
@@ -95,9 +98,29 @@ public static class ProcessManager
processes.Clear(); processes.Clear();
} }
public static void WaitForProcessExit(int processId)
{
if (!processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry))
{
return;
}
entry.ExitSource.Task.Wait();
}
public static async Task WaitForProcessExitAsync(int processId)
{
if (!processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry))
{
return;
}
await entry.ExitSource.Task;
}
public static Process? GetProcess(int processId) public static Process? GetProcess(int processId)
{ {
if (processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics) entry)) if (processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry))
{ {
return entry.Process; return entry.Process;
} }
@@ -116,7 +139,7 @@ public static class ProcessManager
{ {
foreach (int processId in set) foreach (int processId in set)
{ {
if (processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics) entry) && entry.Process is T typedProcess) if (processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry) && entry.Process is T typedProcess)
{ {
yield return typedProcess; yield return typedProcess;
} }
@@ -126,7 +149,7 @@ public static class ProcessManager
public static IEnumerable<Process> GetAllProcesses() public static IEnumerable<Process> GetAllProcesses()
{ {
foreach ((Process Process, ProcessMetrics Metrics) entry in processes.Values) foreach ((Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry in processes.Values)
{ {
yield return entry.Process; yield return entry.Process;
} }
@@ -134,7 +157,7 @@ public static class ProcessManager
public static bool TryGetProcess(int processId, out Process? process) public static bool TryGetProcess(int processId, out Process? process)
{ {
if (processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics) entry)) if (processes.TryGetValue(processId, out (Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry))
{ {
process = entry.Process; process = entry.Process;
return true; return true;
@@ -161,7 +184,7 @@ public static class ProcessManager
internal static void TickAllProcesses() internal static void TickAllProcesses()
{ {
foreach ((Process Process, ProcessMetrics Metrics) entry in processes.Values) foreach ((Process Process, ProcessMetrics Metrics, TaskCompletionSource ExitSource) entry in processes.Values)
{ {
if (entry.Process.IsRunning) if (entry.Process.IsRunning)
{ {
@@ -193,7 +216,10 @@ public static class ProcessManager
{ {
process.Stop(); process.Stop();
_ = processes.TryRemove(process.Id, out _); if (processes.TryRemove(process.Id, out var processEntry))
{
_ = processEntry.ExitSource.TrySetResult();
}
if (processesByType.TryGetValue(process.GetType(), out ConcurrentHashSet<int>? set)) if (processesByType.TryGetValue(process.GetType(), out ConcurrentHashSet<int>? set))
{ {
+14 -2
View File
@@ -4,6 +4,8 @@ public static class CommandManager
{ {
private static readonly Dictionary<string, ICommand> commands = new(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, ICommand> commands = new(StringComparer.OrdinalIgnoreCase);
private static readonly List<string> commandHistory = [];
public static void RegisterCommand(ICommand command) public static void RegisterCommand(ICommand command)
{ {
commands[command.Name] = command; commands[command.Name] = command;
@@ -22,7 +24,12 @@ public static class CommandManager
return commands.Values.OrderBy(command => command.Name); return commands.Values.OrderBy(command => command.Name);
} }
public static bool TryExecute(string input, Action<string> printLine) public static IList<string> GetCommandHistory()
{
return commandHistory;
}
public static async Task<bool> TryExecute(string input, Action<string> printLine)
{ {
string trimmedInput = input.Trim(); string trimmedInput = input.Trim();
@@ -31,6 +38,11 @@ public static class CommandManager
return false; return false;
} }
if (commandHistory.Count == 0 || commandHistory[^1] != trimmedInput)
{
commandHistory.Add(trimmedInput);
}
foreach (KeyValuePair<string, ICommand> entry in commands foreach (KeyValuePair<string, ICommand> entry in commands
.OrderByDescending(entry => entry.Key.Length)) .OrderByDescending(entry => entry.Key.Length))
{ {
@@ -49,7 +61,7 @@ public static class CommandManager
arguments = trimmedInput[commandName.Length..].TrimStart(); arguments = trimmedInput[commandName.Length..].TrimStart();
} }
entry.Value.Execute(arguments, printLine); await entry.Value.ExecuteAsync(arguments, printLine);
return true; return true;
} }
+2 -1
View File
@@ -6,8 +6,9 @@ public sealed class ClearCommand : ICommand
public string Description => "Clear the screen"; public string Description => "Clear the screen";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
Console.Clear(); Console.Clear();
return Task.CompletedTask;
} }
} }
+2 -1
View File
@@ -6,9 +6,10 @@ public sealed class ShutdownCommand : ICommand
public string Description => "Shutdown the system"; public string Description => "Shutdown the system";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
printLine("Shutting down system..."); printLine("Shutting down system...");
Sys.Power.Shutdown(); Sys.Power.Shutdown();
return Task.CompletedTask;
} }
} }
+3 -1
View File
@@ -6,7 +6,7 @@ public sealed class HelpCommand : ICommand
public string Description => "Show this help message"; public string Description => "Show this help message";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
printLine("Available commands:"); printLine("Available commands:");
@@ -14,5 +14,7 @@ public sealed class HelpCommand : ICommand
{ {
printLine($" {command.Name,-12} - {command.Description}"); printLine($" {command.Name,-12} - {command.Description}");
} }
return Task.CompletedTask;
} }
} }
+9 -5
View File
@@ -9,7 +9,7 @@ public sealed class SpawnProcessCommand : ICommand
public string Description => "Spawn a new process"; public string Description => "Spawn a new process";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
arguments = arguments?.Trim(); arguments = arguments?.Trim();
@@ -29,6 +29,7 @@ public sealed class SpawnProcessCommand : ICommand
printLine("Usage: spawn <process-name>"); printLine("Usage: spawn <process-name>");
printLine("Available processes: test, terminal"); printLine("Available processes: test, terminal");
} }
return Task.CompletedTask;
} }
} }
@@ -38,7 +39,7 @@ public sealed class ListProcessesCommand : ICommand
public string Description => "List running processes"; public string Description => "List running processes";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
IEnumerable<Process> processes = ProcessManager.GetAllProcesses(); IEnumerable<Process> processes = ProcessManager.GetAllProcesses();
@@ -48,6 +49,8 @@ public sealed class ListProcessesCommand : ICommand
{ {
printLine($" ID: {process.Id}, Name: {process.Name}"); printLine($" ID: {process.Id}, Name: {process.Name}");
} }
return Task.CompletedTask;
} }
} }
@@ -57,23 +60,24 @@ public sealed class StopProcessCommand : ICommand
public string Description => "Stop a process by ID"; public string Description => "Stop a process by ID";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
string? idText = arguments; string? idText = arguments;
if (string.IsNullOrWhiteSpace(idText)) if (string.IsNullOrWhiteSpace(idText))
{ {
printLine("Usage: stop <process-id>"); printLine("Usage: stop <process-id>");
return; return Task.CompletedTask;
} }
if (int.TryParse(idText, out int processId)) if (int.TryParse(idText, out int processId))
{ {
ProcessManager.StopProcess(processId); ProcessManager.StopProcess(processId);
printLine($"Stopped process with ID {processId}"); printLine($"Stopped process with ID {processId}");
return; return Task.CompletedTask;
} }
printLine("Invalid process ID"); printLine("Invalid process ID");
return Task.CompletedTask;
} }
} }
+2 -1
View File
@@ -6,9 +6,10 @@ public class RebootCommand : ICommand
public string Description => "Reboot the system"; public string Description => "Reboot the system";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
printLine("Rebooting system..."); printLine("Rebooting system...");
Sys.Power.Reboot(); Sys.Power.Reboot();
return Task.CompletedTask;
} }
} }
+3 -2
View File
@@ -8,14 +8,14 @@ public class StartGuiCommand : ICommand
public string Name => "start-gui"; public string Name => "start-gui";
public string Description => "Starts the Graphical User Interface (Desktop Process)"; public string Description => "Starts the Graphical User Interface (Desktop Process)";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
printLine("Starting Desktop Process..."); printLine("Starting Desktop Process...");
if (ProcessManager.IsProcessRunning<DesktopProcess>()) if (ProcessManager.IsProcessRunning<DesktopProcess>())
{ {
printLine("Desktop Process is already running."); printLine("Desktop Process is already running.");
return; return Task.CompletedTask;
} }
foreach (Process process in ProcessManager.GetProcessesOfType<CliProcess>()) foreach (Process process in ProcessManager.GetProcessesOfType<CliProcess>())
@@ -24,5 +24,6 @@ public class StartGuiCommand : ICommand
} }
_ = ProcessManager.SpawnProcess<DesktopProcess>(); _ = ProcessManager.SpawnProcess<DesktopProcess>();
return Task.CompletedTask;
} }
} }
+1 -1
View File
@@ -8,7 +8,7 @@ public class StopGuiCommand : ICommand
public string Name => "stop-gui"; public string Name => "stop-gui";
public string Description => "Stops the Graphical User Interface (Desktop Process)"; public string Description => "Stops the Graphical User Interface (Desktop Process)";
public async void Execute(string? arguments, Action<string> printLine) public async Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
printLine("Stopping Desktop Process..."); printLine("Stopping Desktop Process...");
+2 -1
View File
@@ -9,7 +9,7 @@ public class ViewProcessLogs : ICommand
public string Description => "View logs for a process"; public string Description => "View logs for a process";
public void Execute(string? arguments, Action<string> printLine) public Task ExecuteAsync(string? arguments, Action<string> printLine)
{ {
if (int.TryParse(arguments, out int processId)) if (int.TryParse(arguments, out int processId))
{ {
@@ -21,6 +21,7 @@ public class ViewProcessLogs : ICommand
IEnumerable<LogEntry> logs = ProcessManager.GetLogs(); IEnumerable<LogEntry> logs = ProcessManager.GetLogs();
PrintLogs(logs, printLine); PrintLogs(logs, printLine);
} }
return Task.CompletedTask;
} }
private static void PrintLogs(IEnumerable<LogEntry> logs, Action<string> printLine) private static void PrintLogs(IEnumerable<LogEntry> logs, Action<string> printLine)
+1 -1
View File
@@ -19,5 +19,5 @@ public interface ICommand
/// </summary> /// </summary>
/// <param name="arguments">The arguments provided to the command.</param> /// <param name="arguments">The arguments provided to the command.</param>
/// <param name="printLine">A delegate to stream output lines to the current console or terminal.</param> /// <param name="printLine">A delegate to stream output lines to the current console or terminal.</param>
void Execute(string? arguments, Action<string> printLine); Task ExecuteAsync(string? arguments, Action<string> printLine);
} }
+1 -1
View File
@@ -32,7 +32,7 @@ public static class WindowManager
/// <summary> /// <summary>
/// Processes input, updates interaction state, and triggers rendering of all windows. /// Processes input, updates interaction state, and triggers rendering of all windows.
/// </summary> /// </summary>
public static void Update() internal static void Update()
{ {
Point pointerPosition = new(MouseManager.X, MouseManager.Y); Point pointerPosition = new(MouseManager.X, MouseManager.Y);
bool leftButtonDown = MouseManager.LeftButton; bool leftButtonDown = MouseManager.LeftButton;