NetInputProcessor.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Collections.Concurrent;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>
  4. /// Input processor for <see cref="NetInput"/>, deals in <see cref="ConsoleKeyInfo"/> stream
  5. /// </summary>
  6. public class NetInputProcessor : InputProcessor<ConsoleKeyInfo>
  7. {
  8. #pragma warning disable CA2211
  9. /// <summary>
  10. /// Set to true to generate code in <see cref="Logging"/> (verbose only) for test cases in NetInputProcessorTests.
  11. /// <remarks>
  12. /// This makes the task of capturing user/language/terminal specific keyboard issues easier to
  13. /// diagnose. By turning this on and searching logs user can send us exactly the input codes that are released
  14. /// to input stream.
  15. /// </remarks>
  16. /// </summary>
  17. public static bool GenerateTestCasesForKeyPresses = false;
  18. #pragma warning restore CA2211
  19. /// <inheritdoc/>
  20. public NetInputProcessor (ConcurrentQueue<ConsoleKeyInfo> inputBuffer) : base (inputBuffer, new NetKeyConverter ()) { }
  21. /// <inheritdoc/>
  22. protected override void Process (ConsoleKeyInfo consoleKeyInfo)
  23. {
  24. // For building test cases
  25. if (GenerateTestCasesForKeyPresses)
  26. {
  27. Logging.Trace (FormatConsoleKeyInfoForTestCase (consoleKeyInfo));
  28. }
  29. foreach (Tuple<char, ConsoleKeyInfo> released in Parser.ProcessInput (Tuple.Create (consoleKeyInfo.KeyChar, consoleKeyInfo)))
  30. {
  31. ProcessAfterParsing (released.Item2);
  32. }
  33. }
  34. /// <inheritdoc/>
  35. protected override void ProcessAfterParsing (ConsoleKeyInfo input)
  36. {
  37. var key = KeyConverter.ToKey (input);
  38. // If the key is not valid, we don't want to raise any events.
  39. if (IsValidInput (key, out key))
  40. {
  41. OnKeyDown (key);
  42. OnKeyUp (key);
  43. }
  44. }
  45. /* For building test cases */
  46. private static string FormatConsoleKeyInfoForTestCase (ConsoleKeyInfo input)
  47. {
  48. string charLiteral = input.KeyChar == '\0' ? @"'\0'" : $"'{input.KeyChar}'";
  49. return $"new ConsoleKeyInfo({charLiteral}, ConsoleKey.{input.Key}, "
  50. + $"{input.Modifiers.HasFlag (ConsoleModifiers.Shift).ToString ().ToLower ()}, "
  51. + $"{input.Modifiers.HasFlag (ConsoleModifiers.Alt).ToString ().ToLower ()}, "
  52. + $"{input.Modifiers.HasFlag (ConsoleModifiers.Control).ToString ().ToLower ()}),";
  53. }
  54. }