FakeInput.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. private int _peekCallCount;
  13. /// <summary>
  14. /// Gets the number of times <see cref="Peek"/> has been called.
  15. /// This is useful for verifying that the input loop throttling is working correctly.
  16. /// </summary>
  17. internal int PeekCallCount => _peekCallCount;
  18. /// <summary>
  19. /// Creates a new FakeInput.
  20. /// </summary>
  21. public FakeInput () { }
  22. /// <inheritdoc/>
  23. public override bool Peek ()
  24. {
  25. // Will be called on the input thread.
  26. Interlocked.Increment (ref _peekCallCount);
  27. return !_testInput.IsEmpty;
  28. }
  29. /// <inheritdoc/>
  30. public override IEnumerable<ConsoleKeyInfo> Read ()
  31. {
  32. // Will be called on the input thread.
  33. while (_testInput.TryDequeue (out ConsoleKeyInfo input))
  34. {
  35. yield return input;
  36. }
  37. }
  38. /// <inheritdoc/>
  39. public void AddInput (ConsoleKeyInfo input)
  40. {
  41. //Logging.Trace ($"Enqueuing input: {input.Key}");
  42. // Will be called on the main loop thread.
  43. _testInput.Enqueue (input);
  44. }
  45. }