private static async Task StartAsyncInputAsync(ConsoleInputType type) { await StopAsyncInputAsync().ConfigureAwait(false); cancellation = new CancellationTokenSource(); Func <Task> input = type switch { ConsoleInputType.None => StopAsyncInputAsync, ConsoleInputType.Line => LineInputHandlerAsync, ConsoleInputType.KeyInfo => KeyInfoInputHandlerAsync, ConsoleInputType.KeyInfoIntercept => KeyInfoInterceptInputHandlerAsync, ConsoleInputType.KeyCode => KeyCodeInputHandlerAsync, _ => throw new NotSupportedException() }; try { await Task.Run(input, cancellation.Token).ConfigureAwait(false); } catch (OperationCanceledException) { await StopAsyncInputAsync().ConfigureAwait(false); } }
public static object ReadFromConsole(string promptMessage = "", ConsoleInputType inputType = ConsoleInputType.String, bool canEscape = false, ConsoleColor color = ConsoleColor.White, int maxChars = -1, char charMask = Char.MinValue) { // set vars ConsoleColor initialColor = Console.ForegroundColor; bool maskChars = (charMask != Char.MinValue); bool pressedEnter = false; string prompt = (promptMessage == "" ? _readPrompt : promptMessage); cursorPos = 0; historyIndex = 0; _readBuffer = ""; // Show a prompt Console.ForegroundColor = color; Console.Write(prompt); // Get input while (!pressedEnter) { ConsoleKeyInfo key = Console.ReadKey(true); // ENTER KEY if (key.Key == ConsoleKey.Enter) { ValidateHistory(); AddToHistory(_readBuffer); Console.ForegroundColor = initialColor; CFormat.WriteLine(""); if (inputType == ConsoleInputType.String) { return(_readBuffer); } else if (inputType == ConsoleInputType.Int) { return(int.Parse(_readBuffer)); // we can parse safely because input keys were filtered } else if (inputType == ConsoleInputType.Double) { return(Double.Parse(_readBuffer.Replace(".", ","))); // we can parse safely because input keys were filtered } else if (inputType == ConsoleInputType.Ulong) { return(ulong.Parse(_readBuffer)); // we can parse safely because input keys were filtered } } // BACKSPACE KEY else if (key.Key == ConsoleKey.Backspace) { ValidateHistory(); if (cursorPos <= 0) { continue; } if (cursorPos != _readBuffer.Length) { string beforeChar = _readBuffer.Substring(0, cursorPos - 1); string afterChar = _readBuffer.Substring(cursorPos, _readBuffer.Length - cursorPos); _readBuffer = beforeChar + afterChar; MoveCursorBack(); UserWrite(afterChar + " "); for (int i = 0; i < (afterChar.Length + 1); i++) { MoveCursorBack(); } } else { _readBuffer = _readBuffer.Substring(0, _readBuffer.Length - 1); MoveCursorBack(); UserWrite(" "); MoveCursorBack(); } } // DELETE KEY else if (key.Key == ConsoleKey.Delete) { ValidateHistory(); if (cursorPos >= _readBuffer.Length) { continue; } string beforeChar = _readBuffer.Substring(0, cursorPos); string afterChar = _readBuffer.Substring(cursorPos + 1, _readBuffer.Length - cursorPos - 1); _readBuffer = beforeChar + afterChar; UserWrite(afterChar + " "); for (int i = 0; i < (afterChar.Length + 1); i++) { MoveCursorBack(); } } // DEBUT KEY else if (key.Key == ConsoleKey.Home) { for (int i = cursorPos; i > 0; i--) { MoveCursorBack(); } } // END KEY else if (key.Key == ConsoleKey.End) { for (int i = cursorPos; i < _readBuffer.Length; i++) { MoveCursorAhead(); } } // ESCAPE KEY else if (key.Key == ConsoleKey.Escape) { if (canEscape) { return(null); } } // INSERT KEY else if (key.Key == ConsoleKey.Insert) { insertMode = !insertMode; if (insertMode) { Console.CursorSize = 100; } else { Console.CursorSize = 1; } } // Do not seek for specific kees after this line: --- // ARROW KEYS and WHITE SPACE KEYS else if (key.Key != ConsoleKey.Spacebar && key.KeyChar == Char.MinValue) { if (key.Key == ConsoleKey.RightArrow && cursorPos < _readBuffer.Length) { MoveCursorAhead(); } else if (key.Key == ConsoleKey.LeftArrow && cursorPos > 0) { MoveCursorBack(); } else if (key.Key == ConsoleKey.UpArrow) { OlderHistory(); } else if (key.Key == ConsoleKey.DownArrow) { NewerHistory(); } } // ANY OTHER KEY else { ValidateHistory(); // MAX CHARS CHECK if (maxChars > 0 && _readBuffer.Length >= maxChars) { continue; } // INPUT TYPE CHECK if (inputType == ConsoleInputType.Int) { if (!int.TryParse(key.KeyChar.ToString(), out int temp) && (key.KeyChar.ToString() != "-" || (key.KeyChar.ToString() == "-" && _readBuffer.Length != 0))) // If input is not a number in int mode, continue { continue; } } else if (inputType == ConsoleInputType.Double) { if (!int.TryParse(key.KeyChar.ToString(), out int temp) && (key.KeyChar.ToString() != "." || (key.KeyChar.ToString() == "." && _readBuffer.Contains("."))) && (key.KeyChar.ToString() != "-" || (key.KeyChar.ToString() == "-" && (_readBuffer.Length != 0 || _readBuffer.Contains("."))))) // good luck { continue; } } else if (inputType == ConsoleInputType.Ulong) { if (!int.TryParse(key.KeyChar.ToString(), out int temp) && (key.KeyChar.ToString() != "." || (key.KeyChar.ToString() == "." && _readBuffer.Contains(".")))) // good luck { continue; } } if (cursorPos != _readBuffer.Length && !insertMode) { _readBuffer = _readBuffer.Substring(0, cursorPos) + key.KeyChar + _readBuffer.Substring(cursorPos, _readBuffer.Length - cursorPos); } else if (cursorPos != _readBuffer.Length && insertMode) { _readBuffer = _readBuffer.Substring(0, cursorPos) + key.KeyChar + _readBuffer.Substring(cursorPos + 1, _readBuffer.Length - cursorPos - 1); } else { _readBuffer += key.KeyChar; } if (maskChars) { UserWrite(charMask.ToString()); } else { UserWrite(key.KeyChar.ToString()); if (cursorPos != _readBuffer.Length && !insertMode) { string aheadCursor = _readBuffer.Substring(cursorPos, _readBuffer.Length - cursorPos); UserWrite(aheadCursor); // Re write text that was ahead cursor for (int i = 0; i < (aheadCursor.Length); i++) { MoveCursorBack(); } } } } //System.Diagnostics.Debug.WriteLine(_readBuffer); } return(null); }
public static object ReadFromConsole( string promptMessage = "", ConsoleInputType inputType = ConsoleInputType.String, bool canEscape = false, int maxChars = -1, char charMask = '\0') { ConsoleColor foregroundColor = Console.ForegroundColor; bool maskFlag = charMask > char.MinValue; bool runFlag = true; promptMessage = promptMessage == "" ? "MMaster> " : promptMessage; cursorPos = 0; historyIndex = 0; tabAllowed = true; _readBuffer = ""; Console.ForegroundColor = ConsoleColor.White; Console.Write(promptMessage); while (runFlag) { ConsoleKeyInfo consoleKeyInfo = Console.ReadKey(true); // READ BUFFER if (consoleKeyInfo.Key == ConsoleKey.Enter) { ValidateHistory(); if (!String.IsNullOrEmpty(_readBuffer)) { AddToHistory(_readBuffer); } Console.ForegroundColor = foregroundColor; CFormat.JumpLine(); switch (inputType) { case ConsoleInputType.String: return(_readBuffer); case ConsoleInputType.Int: if (String.IsNullOrEmpty(_readBuffer)) { return(null); } return(int.Parse(_readBuffer)); case ConsoleInputType.Double: if (String.IsNullOrEmpty(_readBuffer)) { return(null); } return(double.Parse(_readBuffer.Replace(".", ","))); } } else if (consoleKeyInfo.Key == ConsoleKey.Backspace) { ValidateHistory(); if (cursorPos > 0) { if (cursorPos != _readBuffer.Length) { string str2 = _readBuffer.Substring(0, cursorPos - 1); string str3 = _readBuffer.Substring(cursorPos, _readBuffer.Length - cursorPos); _readBuffer = str2 + str3; MoveCursorBack(); UserWrite(str3 + " "); for (int index = 0; index < str3.Length + 1; ++index) { MoveCursorBack(); } } else { _readBuffer = _readBuffer.Substring(0, _readBuffer.Length - 1); MoveCursorBack(); UserWrite(" "); MoveCursorBack(); } } } else if (consoleKeyInfo.Key == ConsoleKey.Delete) { ValidateHistory(); if (cursorPos < _readBuffer.Length) { string str2 = _readBuffer.Substring(0, cursorPos); string str3 = _readBuffer.Substring(cursorPos + 1, _readBuffer.Length - cursorPos - 1); _readBuffer = str2 + str3; UserWrite(str3 + " "); for (int index = 0; index < str3.Length + 1; ++index) { MoveCursorBack(); } } } else if (consoleKeyInfo.Key == ConsoleKey.Home) { for (int cursorPos = CInput.cursorPos; cursorPos > 0; --cursorPos) { MoveCursorBack(); } } else if (consoleKeyInfo.Key == ConsoleKey.End) { for (int cursorPos = CInput.cursorPos; cursorPos < _readBuffer.Length; ++cursorPos) { MoveCursorAhead(); } } else if (consoleKeyInfo.Key == ConsoleKey.Escape) { if (canEscape) { return(null); } } else if (consoleKeyInfo.Key == ConsoleKey.Insert) { insertMode = !insertMode; Console.CursorSize = !insertMode ? 1 : 100; } else if (consoleKeyInfo.Key != ConsoleKey.Spacebar && consoleKeyInfo.KeyChar == char.MinValue) { if (consoleKeyInfo.Key == ConsoleKey.RightArrow && cursorPos < _readBuffer.Length) { MoveCursorAhead(); } else if (consoleKeyInfo.Key == ConsoleKey.LeftArrow && cursorPos > 0) { MoveCursorBack(); } else if (consoleKeyInfo.Key == ConsoleKey.UpArrow) { OlderHistory(); } else if (consoleKeyInfo.Key == ConsoleKey.DownArrow) { NewerHistory(); } } // Tab auto-completition else if (consoleKeyInfo.Key == ConsoleKey.Tab) { if (String.IsNullOrEmpty(_readBuffer) || !tabAllowed || _readBuffer.Contains(" ")) { continue; } if (!_readBuffer.Contains(".")) // If looking for a library OR default command { //Try internal libraries first string result = CommandManager.InternalLibraryCallNames.Keys.FirstOrDefault(x => x.ToLower().StartsWith(_readBuffer.ToLower())); //Then try external libraries if (result == null) { result = CommandManager.ExternalLibraryCallNames.Keys.FirstOrDefault(x => x.ToLower().StartsWith(_readBuffer.ToLower())); } // If still null, no result at all in libraries if (result != null) { for (int i = 0; i < _readBuffer.Length; i++) { MoveCursorBack(); } UserWrite(result); _readBuffer = result; } // Then trying in Default library, the only one that can be called without library. result = CommandManager.InternalLibraries[typeof(Default)].Keys.FirstOrDefault(x => x.ToLower().StartsWith(_readBuffer.ToLower())); if (result == null) { continue; } else { for (int i = 0; i < _readBuffer.Length; i++) { MoveCursorBack(); } UserWrite(result); _readBuffer = result; } } else // If the buffer contains a point. { // PARSE LIBRARY Type library = CParsedInput.ParseLibrary(_readBuffer.Split('.')[0]); string commandInputLower = _readBuffer.Split('.')[1].ToLower(); if (library == null || commandInputLower == "") { continue; } // Try internal libraries string result = null; if (CommandManager.InternalLibraries.ContainsKey(library)) { result = CommandManager.InternalLibraries[library].Keys.FirstOrDefault(x => x.ToLower().StartsWith(commandInputLower)); } // Then try external else { result = CommandManager.ExternalLibraries[library].Keys.FirstOrDefault(x => x.ToLower().StartsWith(commandInputLower)); } // If result found if (result != null) { for (int i = 0; i < _readBuffer.Length; i++) { MoveCursorBack(); } string libraryCallName = library.GetCustomAttribute <MMasterLibrary>().CallName; UserWrite(libraryCallName + "." + result); _readBuffer = libraryCallName + "." + result; } } continue; } else { CInput.ValidateHistory(); if (maxChars <= 0 || CInput._readBuffer.Length < maxChars) { char keyChar; switch (inputType) { case ConsoleInputType.Int: keyChar = consoleKeyInfo.KeyChar; int num1; if (!int.TryParse(keyChar.ToString(), out _)) { keyChar = consoleKeyInfo.KeyChar; if (!(keyChar.ToString() != "-")) { keyChar = consoleKeyInfo.KeyChar; num1 = !(keyChar.ToString() == "-") ? 0 : ((uint)CInput._readBuffer.Length > 0U ? 1 : 0); } else { num1 = 1; } } else { num1 = 0; } if (num1 == 0) { break; } continue; case ConsoleInputType.Double: keyChar = consoleKeyInfo.KeyChar; int num2; if (!int.TryParse(keyChar.ToString(), out _)) { keyChar = consoleKeyInfo.KeyChar; if (!(keyChar.ToString() != ".")) { keyChar = consoleKeyInfo.KeyChar; if (!(keyChar.ToString() == ".") || !CInput._readBuffer.Contains(".")) { goto label_54; } } keyChar = consoleKeyInfo.KeyChar; if (!(keyChar.ToString() != "-")) { keyChar = consoleKeyInfo.KeyChar; num2 = !(keyChar.ToString() == "-") ? 0 : (CInput._readBuffer.Length != 0 ? 1 : (CInput._readBuffer.Contains(".") ? 1 : 0)); goto label_55; } else { num2 = 1; goto label_55; } } label_54: num2 = 0; label_55: if (num2 == 0) { break; } continue; } if (CInput.cursorPos != CInput._readBuffer.Length && !CInput.insertMode) // If in the word, insert mode off { string str2 = CInput._readBuffer.Substring(0, CInput.cursorPos); keyChar = consoleKeyInfo.KeyChar; string str3 = keyChar.ToString(); string str4 = CInput._readBuffer.Substring(CInput.cursorPos, CInput._readBuffer.Length - CInput.cursorPos); CInput._readBuffer = str2 + str3 + str4; } else if (CInput.cursorPos != CInput._readBuffer.Length && CInput.insertMode) // If in the word, insert mode on { string str2 = CInput._readBuffer.Substring(0, CInput.cursorPos); keyChar = consoleKeyInfo.KeyChar; string str3 = keyChar.ToString(); string str4 = CInput._readBuffer.Substring(CInput.cursorPos + 1, CInput._readBuffer.Length - CInput.cursorPos - 1); CInput._readBuffer = str2 + str3 + str4; } else { string readBuffer = CInput._readBuffer; keyChar = consoleKeyInfo.KeyChar; string str2 = keyChar.ToString(); CInput._readBuffer = readBuffer + str2; } // PRINT TO SCREEN if (maskFlag) { CInput.UserWrite(charMask.ToString()); } else { keyChar = consoleKeyInfo.KeyChar; CInput.UserWrite(keyChar.ToString()); if (CInput.cursorPos != CInput._readBuffer.Length && !CInput.insertMode) { string s = CInput._readBuffer.Substring(CInput.cursorPos, CInput._readBuffer.Length - CInput.cursorPos); CInput.UserWrite(s); for (int index = 0; index < s.Length; ++index) { CInput.MoveCursorBack(); } } } } } } return(null); }