FakeInput.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #nullable enable
  2. using System.Collections.Concurrent;
  3. namespace Terminal.Gui.Drivers;
  4. /// <summary>
  5. /// <see cref="IInput{TInputRecord}"/> implementation that uses a fake input source for testing.
  6. /// The <see cref="Peek"/> and <see cref="Read"/> methods are executed
  7. /// on the input thread created by <see cref="MainLoopCoordinator{TInputRecord}.StartInputTaskAsync"/>.
  8. /// </summary>
  9. public class FakeInput : InputImpl<ConsoleKeyInfo>, ITestableInput<ConsoleKeyInfo>
  10. {
  11. // Queue for storing injected input that will be returned by Peek/Read
  12. private readonly ConcurrentQueue<ConsoleKeyInfo> _testInput = new ();
  13. /// <summary>
  14. /// Creates a new FakeInput.
  15. /// </summary>
  16. public FakeInput ()
  17. { }
  18. /// <inheritdoc/>
  19. public override bool Peek ()
  20. {
  21. // Will be called on the input thread.
  22. return !_testInput.IsEmpty;
  23. }
  24. /// <inheritdoc/>
  25. public override IEnumerable<ConsoleKeyInfo> Read ()
  26. {
  27. // Will be called on the input thread.
  28. while (_testInput.TryDequeue (out ConsoleKeyInfo input))
  29. {
  30. yield return input;
  31. }
  32. }
  33. /// <inheritdoc />
  34. public void AddInput (ConsoleKeyInfo input)
  35. {
  36. //Logging.Trace ($"Enqueuing input: {input.Key}");
  37. // Will be called on the main loop thread.
  38. _testInput.Enqueue (input);
  39. }
  40. }