NetInput.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Microsoft.Extensions.Logging;
  2. namespace Terminal.Gui;
  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. PlatformID p = Environment.OSVersion.Platform;
  18. if (p == PlatformID.Win32NT || p == PlatformID.Win32S || p == PlatformID.Win32Windows)
  19. {
  20. try
  21. {
  22. _adjustConsole = new ();
  23. }
  24. catch (ApplicationException ex)
  25. {
  26. // Likely running as a unit test, or in a non-interactive session.
  27. Logging.Logger.LogCritical (
  28. ex,
  29. "NetWinVTConsole could not be constructed i.e. could not configure terminal modes. May indicate running in non-interactive session e.g. unit testing CI");
  30. }
  31. }
  32. Console.Out.Write (EscSeqUtils.CSI_EnableMouseEvents);
  33. Console.TreatControlCAsInput = true;
  34. }
  35. /// <inheritdoc/>
  36. protected override bool Peek () { return Console.KeyAvailable; }
  37. /// <inheritdoc/>
  38. protected override IEnumerable<ConsoleKeyInfo> Read ()
  39. {
  40. while (Console.KeyAvailable)
  41. {
  42. yield return Console.ReadKey (true);
  43. }
  44. }
  45. /// <inheritdoc/>
  46. public override void Dispose ()
  47. {
  48. base.Dispose ();
  49. _adjustConsole?.Cleanup ();
  50. Console.Out.Write (EscSeqUtils.CSI_DisableMouseEvents);
  51. }
  52. }