NetInput.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  37. Console.TreatControlCAsInput = true;
  38. }
  39. /// <inheritdoc/>
  40. protected override bool Peek ()
  41. {
  42. if (ConsoleDriver.RunningUnitTests)
  43. {
  44. return false;
  45. }
  46. return Console.KeyAvailable;
  47. }
  48. /// <inheritdoc/>
  49. protected override IEnumerable<ConsoleKeyInfo> Read ()
  50. {
  51. while (Console.KeyAvailable)
  52. {
  53. yield return Console.ReadKey (true);
  54. }
  55. }
  56. /// <inheritdoc/>
  57. public override void Dispose ()
  58. {
  59. base.Dispose ();
  60. _adjustConsole?.Cleanup ();
  61. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  62. }
  63. }