FakeInput.cs 1.3 KB

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