Class1.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. using System.Collections.Concurrent;
  2. using System.Drawing;
  3. using FluentAssertions;
  4. using FluentAssertions.Numeric;
  5. using Terminal.Gui;
  6. using Terminal.Gui.ConsoleDrivers;
  7. using static Unix.Terminal.Curses;
  8. namespace TerminalGuiFluentAssertions;
  9. class FakeInput<T>(CancellationToken hardStopToken) : IConsoleInput<T>
  10. {
  11. /// <inheritdoc />
  12. public void Dispose () { }
  13. /// <inheritdoc />
  14. public void Initialize (ConcurrentQueue<T> inputBuffer) { InputBuffer = inputBuffer;}
  15. public ConcurrentQueue<T> InputBuffer { get; set; }
  16. /// <inheritdoc />
  17. public void Run (CancellationToken token)
  18. {
  19. // Blocks until either the token or the hardStopToken is cancelled.
  20. WaitHandle.WaitAny (new [] { token.WaitHandle, hardStopToken.WaitHandle });
  21. }
  22. }
  23. class FakeNetInput (CancellationToken hardStopToken) : FakeInput<ConsoleKeyInfo> (hardStopToken), INetInput
  24. {
  25. }
  26. class FakeWindowsInput (CancellationToken hardStopToken) : FakeInput<WindowsConsole.InputRecord> (hardStopToken), IWindowsInput
  27. {
  28. }
  29. class FakeOutput : IConsoleOutput
  30. {
  31. public Size Size { get; set; }
  32. /// <inheritdoc />
  33. public void Dispose ()
  34. {
  35. }
  36. /// <inheritdoc />
  37. public void Write (ReadOnlySpan<char> text)
  38. {
  39. }
  40. /// <inheritdoc />
  41. public void Write (IOutputBuffer buffer)
  42. {
  43. }
  44. /// <inheritdoc />
  45. public Size GetWindowSize ()
  46. {
  47. return Size;
  48. }
  49. /// <inheritdoc />
  50. public void SetCursorVisibility (CursorVisibility visibility)
  51. {
  52. }
  53. /// <inheritdoc />
  54. public void SetCursorPosition (int col, int row)
  55. {
  56. }
  57. }
  58. /// <summary>
  59. /// Entry point to fluent assertions.
  60. /// </summary>
  61. public static class With
  62. {
  63. /// <summary>
  64. /// Entrypoint to fluent assertions
  65. /// </summary>
  66. /// <param name="width"></param>
  67. /// <param name="height"></param>
  68. /// <returns></returns>
  69. public static GuiTestContext<T> A<T> (int width, int height) where T : Toplevel, new ()
  70. {
  71. return new GuiTestContext<T> (width,height);
  72. }
  73. }
  74. public class GuiTestContext<T> : IDisposable where T : Toplevel, new()
  75. {
  76. private readonly CancellationTokenSource _cts = new ();
  77. private readonly CancellationTokenSource _hardStop = new ();
  78. private readonly Task _runTask;
  79. private Exception _ex;
  80. private readonly FakeOutput _output = new ();
  81. private readonly FakeWindowsInput winInput;
  82. private View _lastView;
  83. internal GuiTestContext (int width, int height)
  84. {
  85. IApplication origApp = ApplicationImpl.Instance;
  86. var netInput = new FakeNetInput (_cts.Token);
  87. winInput = new FakeWindowsInput (_cts.Token);
  88. _output.Size = new (width, height);
  89. var v2 = new ApplicationV2(
  90. () => netInput,
  91. ()=>_output,
  92. () => winInput,
  93. () => _output);
  94. // Start the application in a background thread
  95. _runTask = Task.Run (() =>
  96. {
  97. try
  98. {
  99. ApplicationImpl.ChangeInstance (v2);
  100. v2.Init (null,"v2win");
  101. Application.Run<T> (); // This will block, but it's on a background thread now
  102. Application.Shutdown ();
  103. }
  104. catch (OperationCanceledException)
  105. { }
  106. catch (Exception ex)
  107. {
  108. _ex = ex;
  109. }
  110. finally
  111. {
  112. ApplicationImpl.ChangeInstance (origApp);
  113. }
  114. }, _cts.Token);
  115. WaitIteration ();
  116. }
  117. /// <summary>
  118. /// Stops the application and waits for the background thread to exit.
  119. /// </summary>
  120. public GuiTestContext<T> Stop ()
  121. {
  122. if (_runTask.IsCompleted)
  123. {
  124. return this;
  125. }
  126. Application.Invoke (()=> Application.RequestStop ());
  127. // Wait for the application to stop, but give it a 1-second timeout
  128. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  129. {
  130. _cts.Cancel ();
  131. // Timeout occurred, force the task to stop
  132. _hardStop.Cancel ();
  133. throw new TimeoutException ("Application failed to stop within the allotted time.");
  134. }
  135. _cts.Cancel ();
  136. if (_ex != null)
  137. {
  138. throw _ex; // Propagate any exception that happened in the background task
  139. }
  140. return this;
  141. }
  142. // Cleanup to avoid state bleed between tests
  143. public void Dispose ()
  144. {
  145. Stop ();
  146. _hardStop.Cancel();
  147. }
  148. /// <summary>
  149. /// Adds the given <paramref name="v"/> to the current top level view
  150. /// and performs layout.
  151. /// </summary>
  152. /// <param name="v"></param>
  153. /// <returns></returns>
  154. public GuiTestContext<T> Add (View v)
  155. {
  156. WaitIteration (
  157. () =>
  158. {
  159. var top = Application.Top ?? throw new Exception("Top was null so could not add view");
  160. top.Add (v);
  161. top.Layout ();
  162. _lastView = v;
  163. });
  164. return this;
  165. }
  166. public GuiTestContext<T> ResizeConsole (int width, int height)
  167. {
  168. _output.Size = new Size (width,height);
  169. return WaitIteration ();
  170. }
  171. public GuiTestContext<T> WaitIteration (Action? a = null)
  172. {
  173. a ??= () => { };
  174. var ctsLocal = new CancellationTokenSource ();
  175. Application.Invoke (()=>
  176. {
  177. a();
  178. ctsLocal.Cancel ();
  179. });
  180. // Blocks until either the token or the hardStopToken is cancelled.
  181. WaitHandle.WaitAny (new []
  182. {
  183. _cts.Token.WaitHandle,
  184. _hardStop.Token.WaitHandle,
  185. ctsLocal.Token.WaitHandle
  186. });
  187. return this;
  188. }
  189. public GuiTestContext<T> Assert<T2> (AndConstraint<T2> be)
  190. {
  191. return this;
  192. }
  193. public GuiTestContext<T> RightClick (int screenX, int screenY)
  194. {
  195. return Click (WindowsConsole.ButtonState.Button3Pressed,screenX, screenY);
  196. }
  197. public GuiTestContext<T> LeftClick (int screenX, int screenY)
  198. {
  199. return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY);
  200. }
  201. private GuiTestContext<T> Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  202. {
  203. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  204. {
  205. EventType = WindowsConsole.EventType.Mouse,
  206. MouseEvent = new WindowsConsole.MouseEventRecord ()
  207. {
  208. ButtonState = btn,
  209. MousePosition = new WindowsConsole.Coord ((short)screenX, (short)screenY)
  210. }
  211. });
  212. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  213. {
  214. EventType = WindowsConsole.EventType.Mouse,
  215. MouseEvent = new WindowsConsole.MouseEventRecord ()
  216. {
  217. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  218. MousePosition = new WindowsConsole.Coord ((short)screenX, (short)screenY)
  219. }
  220. });
  221. WaitIteration ();
  222. return this;
  223. }
  224. public GuiTestContext<T> Down ()
  225. {
  226. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  227. {
  228. EventType = WindowsConsole.EventType.Key,
  229. KeyEvent = new WindowsConsole.KeyEventRecord
  230. {
  231. bKeyDown = true,
  232. wRepeatCount = 0,
  233. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  234. wVirtualScanCode = 0,
  235. UnicodeChar = '\0',
  236. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  237. }
  238. });
  239. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  240. {
  241. EventType = WindowsConsole.EventType.Key,
  242. KeyEvent = new WindowsConsole.KeyEventRecord
  243. {
  244. bKeyDown = false,
  245. wRepeatCount = 0,
  246. wVirtualKeyCode = ConsoleKeyMapping.VK.DOWN,
  247. wVirtualScanCode = 0,
  248. UnicodeChar = '\0',
  249. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  250. }
  251. });
  252. WaitIteration ();
  253. return this;
  254. }
  255. public GuiTestContext<T> Enter ()
  256. {
  257. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  258. {
  259. EventType = WindowsConsole.EventType.Key,
  260. KeyEvent = new WindowsConsole.KeyEventRecord
  261. {
  262. bKeyDown = true,
  263. wRepeatCount = 0,
  264. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  265. wVirtualScanCode = 0,
  266. UnicodeChar = '\0',
  267. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  268. }
  269. });
  270. winInput.InputBuffer.Enqueue (new WindowsConsole.InputRecord ()
  271. {
  272. EventType = WindowsConsole.EventType.Key,
  273. KeyEvent = new WindowsConsole.KeyEventRecord
  274. {
  275. bKeyDown = false,
  276. wRepeatCount = 0,
  277. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  278. wVirtualScanCode = 0,
  279. UnicodeChar = '\0',
  280. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  281. }
  282. });
  283. WaitIteration ();
  284. return this;
  285. }
  286. public GuiTestContext<T> WithContextMenu (ContextMenu ctx, MenuBarItem menuItems)
  287. {
  288. LastView.MouseEvent += (s, e) =>
  289. {
  290. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  291. {
  292. ctx.Show (menuItems);
  293. }
  294. };
  295. return this;
  296. }
  297. public View LastView => _lastView ?? Application.Top ?? throw new Exception ("Could not determine which view to add to");
  298. }