NetInput.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. /// <inheritdoc/>
  61. public override void Dispose ()
  62. {
  63. base.Dispose ();
  64. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  65. //Disable alternative screen buffer.
  66. Console.Out.Write (EscSeqUtils.CSI_RestoreCursorAndRestoreAltBufferWithBackscroll);
  67. //Set cursor key to cursor.
  68. Console.Out.Write (EscSeqUtils.CSI_ShowCursor);
  69. _adjustConsole?.Cleanup ();
  70. }
  71. }