NetInput.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using Microsoft.Extensions.Logging;
  2. namespace Terminal.Gui.Drivers;
  3. /// <summary>
  4. /// Console input implementation that uses native dotnet methods e.g. <see cref="System.Console"/>.
  5. /// </summary>
  6. public class NetInput : ConsoleInput<ConsoleKeyInfo>, INetInput
  7. {
  8. private readonly NetWinVTConsole _adjustConsole;
  9. /// <summary>
  10. /// Creates a new instance of the class. Implicitly sends
  11. /// console mode settings that enable virtual input (mouse
  12. /// reporting etc).
  13. /// </summary>
  14. public NetInput ()
  15. {
  16. Logging.Logger.LogInformation ($"Creating {nameof (NetInput)}");
  17. if (ConsoleDriver.RunningUnitTests)
  18. {
  19. return;
  20. }
  21. PlatformID p = Environment.OSVersion.Platform;
  22. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  23. {
  24. try
  25. {
  26. _adjustConsole = new ();
  27. }
  28. catch (ApplicationException ex)
  29. {
  30. // Likely running as a unit test, or in a non-interactive session.
  31. Logging.Logger.LogCritical (
  32. ex,
  33. "NetWinVTConsole could not be constructed i.e. could not configure terminal modes. May indicate running in non-interactive session e.g. unit testing CI");
  34. }
  35. }
  36. //Enable alternative screen buffer.
  37. Console.Out.Write (EscSeqUtils.CSI_SaveCursorAndActivateAltBufferNoBackscroll);
  38. //Set cursor key to application.
  39. Console.Out.Write (EscSeqUtils.CSI_HideCursor);
  40. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  41. Console.TreatControlCAsInput = true;
  42. }
  43. /// <inheritdoc/>
  44. protected override bool Peek ()
  45. {
  46. if (ConsoleDriver.RunningUnitTests)
  47. {
  48. return false;
  49. }
  50. return Console.KeyAvailable;
  51. }
  52. /// <inheritdoc/>
  53. protected override IEnumerable<ConsoleKeyInfo> Read ()
  54. {
  55. while (Console.KeyAvailable)
  56. {
  57. yield return Console.ReadKey (true);
  58. }
  59. }
  60. private void FlushConsoleInput ()
  61. {
  62. if (!ConsoleDriver.RunningUnitTests)
  63. {
  64. while (Console.KeyAvailable)
  65. {
  66. Console.ReadKey (intercept: true);
  67. }
  68. }
  69. }
  70. /// <inheritdoc/>
  71. public override void Dispose ()
  72. {
  73. base.Dispose ();
  74. // Disable mouse events first
  75. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  76. //Disable alternative screen buffer.
  77. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  78. //Set cursor key to cursor.
  79. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  80. _adjustConsole?.Cleanup ();
  81. // Flush any pending input so no stray events appear
  82. FlushConsoleInput ();
  83. }
  84. }