GuiTestContext.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. using System.Drawing;
  2. using System.Text;
  3. using Microsoft.Extensions.Logging;
  4. namespace TerminalGuiFluentTesting;
  5. /// <summary>
  6. /// Fluent API context for testing a Terminal.Gui application. Create
  7. /// an instance using <see cref="With"/> static class.
  8. /// </summary>
  9. public class GuiTestContext : IDisposable
  10. {
  11. private readonly CancellationTokenSource _cts = new ();
  12. private readonly CancellationTokenSource _hardStop = new (With.Timeout);
  13. private readonly Task _runTask;
  14. private Exception _ex;
  15. private readonly FakeOutput _output = new ();
  16. private readonly FakeWindowsInput _winInput;
  17. private readonly FakeNetInput _netInput;
  18. private View? _lastView;
  19. private readonly StringBuilder _logsSb;
  20. private readonly V2TestDriver _driver;
  21. private bool _finished;
  22. private readonly object _threadLock = new ();
  23. internal GuiTestContext (Func<Toplevel> topLevelBuilder, int width, int height, V2TestDriver driver)
  24. {
  25. IApplication origApp = ApplicationImpl.Instance;
  26. ILogger? origLogger = Logging.Logger;
  27. _logsSb = new ();
  28. _driver = driver;
  29. _netInput = new (_cts.Token);
  30. _winInput = new (_cts.Token);
  31. _output.Size = new (width, height);
  32. var v2 = new ApplicationV2 (
  33. () => _netInput,
  34. () => _output,
  35. () => _winInput,
  36. () => _output);
  37. var booting = new SemaphoreSlim (0, 1);
  38. lock (_threadLock)
  39. {
  40. // Start the application in a background thread
  41. _runTask = Task.Run (
  42. () =>
  43. {
  44. try
  45. {
  46. ApplicationImpl.ChangeInstance (v2);
  47. ILogger logger = LoggerFactory.Create (
  48. builder =>
  49. builder.SetMinimumLevel (LogLevel.Trace)
  50. .AddProvider (new TextWriterLoggerProvider (new StringWriter (_logsSb))))
  51. .CreateLogger ("Test Logging");
  52. Logging.Logger = logger;
  53. v2.Init (null, GetDriverName ());
  54. booting.Release ();
  55. Toplevel t = topLevelBuilder ();
  56. t.Closed += (s, e) => { _finished = true; };
  57. Application.Run (t); // This will block, but it's on a background thread now
  58. t.Dispose ();
  59. Application.Shutdown ();
  60. }
  61. catch (OperationCanceledException)
  62. { }
  63. catch (Exception ex)
  64. {
  65. _ex = ex;
  66. }
  67. finally
  68. {
  69. ApplicationImpl.ChangeInstance (origApp);
  70. Logging.Logger = origLogger;
  71. _finished = true;
  72. }
  73. },
  74. _cts.Token);
  75. }
  76. // Wait for booting to complete with a timeout to avoid hangs
  77. if (!booting.WaitAsync (TimeSpan.FromSeconds (5)).Result)
  78. {
  79. throw new TimeoutException ("Application failed to start within the allotted time.");
  80. }
  81. WaitIteration ();
  82. }
  83. private string GetDriverName ()
  84. {
  85. return _driver switch
  86. {
  87. V2TestDriver.V2Win => "v2win",
  88. V2TestDriver.V2Net => "v2net",
  89. _ =>
  90. throw new ArgumentOutOfRangeException ()
  91. };
  92. }
  93. /// <summary>
  94. /// Stops the application and waits for the background thread to exit.
  95. /// </summary>
  96. public GuiTestContext Stop ()
  97. {
  98. if (_runTask.IsCompleted)
  99. {
  100. return this;
  101. }
  102. Application.Invoke (() => { Application.RequestStop (); });
  103. // Wait for the application to stop, but give it a 1-second timeout
  104. if (!_runTask.Wait (TimeSpan.FromMilliseconds (1000)))
  105. {
  106. _cts.Cancel ();
  107. // Timeout occurred, force the task to stop
  108. _hardStop.Cancel ();
  109. throw new TimeoutException ("Application failed to stop within the allotted time.");
  110. }
  111. _cts.Cancel ();
  112. if (_ex != null)
  113. {
  114. throw _ex; // Propagate any exception that happened in the background task
  115. }
  116. return this;
  117. }
  118. /// <summary>
  119. /// Hard stops the application and waits for the background thread to exit.
  120. /// </summary>
  121. public void HardStop ()
  122. {
  123. _hardStop.Cancel ();
  124. Stop ();
  125. }
  126. /// <summary>
  127. /// Cleanup to avoid state bleed between tests
  128. /// </summary>
  129. public void Dispose ()
  130. {
  131. Stop ();
  132. if (_hardStop.IsCancellationRequested)
  133. {
  134. throw new (
  135. "Application was hard stopped, typically this means it timed out or did not shutdown gracefully. Ensure you call Stop in your test");
  136. }
  137. _hardStop.Cancel ();
  138. }
  139. /// <summary>
  140. /// Adds the given <paramref name="v"/> to the current top level view
  141. /// and performs layout.
  142. /// </summary>
  143. /// <param name="v"></param>
  144. /// <returns></returns>
  145. public GuiTestContext Add (View v)
  146. {
  147. WaitIteration (
  148. () =>
  149. {
  150. Toplevel top = Application.Top ?? throw new ("Top was null so could not add view");
  151. top.Add (v);
  152. top.Layout ();
  153. _lastView = v;
  154. });
  155. return this;
  156. }
  157. /// <summary>
  158. /// Simulates changing the console size e.g. by resizing window in your operating system
  159. /// </summary>
  160. /// <param name="width">new Width for the console.</param>
  161. /// <param name="height">new Height for the console.</param>
  162. /// <returns></returns>
  163. public GuiTestContext ResizeConsole (int width, int height)
  164. {
  165. _output.Size = new (width, height);
  166. return WaitIteration ();
  167. }
  168. public GuiTestContext ScreenShot (string title, TextWriter writer)
  169. {
  170. writer.WriteLine (title + ":");
  171. var text = Application.ToString ();
  172. writer.WriteLine (text);
  173. return this; //WaitIteration();
  174. }
  175. /// <summary>
  176. /// Writes all Terminal.Gui engine logs collected so far to the <paramref name="writer"/>
  177. /// </summary>
  178. /// <param name="writer"></param>
  179. /// <returns></returns>
  180. public GuiTestContext WriteOutLogs (TextWriter writer)
  181. {
  182. writer.WriteLine (_logsSb.ToString ());
  183. return this; //WaitIteration();
  184. }
  185. /// <summary>
  186. /// Waits until the end of the current iteration of the main loop. Optionally
  187. /// running a given <paramref name="a"/> action on the UI thread at that time.
  188. /// </summary>
  189. /// <param name="a"></param>
  190. /// <returns></returns>
  191. public GuiTestContext WaitIteration (Action? a = null)
  192. {
  193. // If application has already exited don't wait!
  194. if (_finished || _cts.Token.IsCancellationRequested || _hardStop.Token.IsCancellationRequested)
  195. {
  196. return this;
  197. }
  198. a ??= () => { };
  199. var ctsLocal = new CancellationTokenSource ();
  200. Application.Invoke (
  201. () =>
  202. {
  203. a ();
  204. ctsLocal.Cancel ();
  205. });
  206. // Blocks until either the token or the hardStopToken is cancelled.
  207. WaitHandle.WaitAny (
  208. new []
  209. {
  210. _cts.Token.WaitHandle,
  211. _hardStop.Token.WaitHandle,
  212. ctsLocal.Token.WaitHandle
  213. });
  214. return this;
  215. }
  216. /// <summary>
  217. /// Performs the supplied <paramref name="doAction"/> immediately.
  218. /// Enables running commands without breaking the Fluent API calls.
  219. /// </summary>
  220. /// <param name="doAction"></param>
  221. /// <returns></returns>
  222. public GuiTestContext Then (Action doAction)
  223. {
  224. try
  225. {
  226. doAction ();
  227. }
  228. catch (Exception)
  229. {
  230. HardStop ();
  231. throw;
  232. }
  233. return this;
  234. }
  235. /// <summary>
  236. /// Simulates a right click at the given screen coordinates on the current driver.
  237. /// This is a raw input event that goes through entire processing pipeline as though
  238. /// user had pressed the mouse button physically.
  239. /// </summary>
  240. /// <param name="screenX">0 indexed screen coordinates</param>
  241. /// <param name="screenY">0 indexed screen coordinates</param>
  242. /// <returns></returns>
  243. public GuiTestContext RightClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button3Pressed, screenX, screenY); }
  244. /// <summary>
  245. /// Simulates a left click at the given screen coordinates on the current driver.
  246. /// This is a raw input event that goes through entire processing pipeline as though
  247. /// user had pressed the mouse button physically.
  248. /// </summary>
  249. /// <param name="screenX">0 indexed screen coordinates</param>
  250. /// <param name="screenY">0 indexed screen coordinates</param>
  251. /// <returns></returns>
  252. public GuiTestContext LeftClick (int screenX, int screenY) { return Click (WindowsConsole.ButtonState.Button1Pressed, screenX, screenY); }
  253. public GuiTestContext LeftClick<T> (Func<T, bool> evaluator) where T : View { return Click (WindowsConsole.ButtonState.Button1Pressed, evaluator); }
  254. private GuiTestContext Click<T> (WindowsConsole.ButtonState btn, Func<T, bool> evaluator) where T : View
  255. {
  256. T v = Find (evaluator);
  257. Point screen = v.ViewportToScreen (new Point (0, 0));
  258. return Click (btn, screen.X, screen.Y);
  259. }
  260. private GuiTestContext Click (WindowsConsole.ButtonState btn, int screenX, int screenY)
  261. {
  262. switch (_driver)
  263. {
  264. case V2TestDriver.V2Win:
  265. _winInput.InputBuffer.Enqueue (
  266. new ()
  267. {
  268. EventType = WindowsConsole.EventType.Mouse,
  269. MouseEvent = new ()
  270. {
  271. ButtonState = btn,
  272. MousePosition = new ((short)screenX, (short)screenY)
  273. }
  274. });
  275. _winInput.InputBuffer.Enqueue (
  276. new ()
  277. {
  278. EventType = WindowsConsole.EventType.Mouse,
  279. MouseEvent = new ()
  280. {
  281. ButtonState = WindowsConsole.ButtonState.NoButtonPressed,
  282. MousePosition = new ((short)screenX, (short)screenY)
  283. }
  284. });
  285. break;
  286. case V2TestDriver.V2Net:
  287. int netButton = btn switch
  288. {
  289. WindowsConsole.ButtonState.Button1Pressed => 0,
  290. WindowsConsole.ButtonState.Button2Pressed => 1,
  291. WindowsConsole.ButtonState.Button3Pressed => 2,
  292. WindowsConsole.ButtonState.RightmostButtonPressed => 2,
  293. _ => throw new ArgumentOutOfRangeException (nameof (btn))
  294. };
  295. foreach (ConsoleKeyInfo k in NetSequences.Click (netButton, screenX, screenY))
  296. {
  297. SendNetKey (k);
  298. }
  299. break;
  300. default:
  301. throw new ArgumentOutOfRangeException ();
  302. }
  303. return WaitIteration ();
  304. ;
  305. }
  306. public GuiTestContext Down ()
  307. {
  308. switch (_driver)
  309. {
  310. case V2TestDriver.V2Win:
  311. SendWindowsKey (ConsoleKeyMapping.VK.DOWN);
  312. break;
  313. case V2TestDriver.V2Net:
  314. foreach (ConsoleKeyInfo k in NetSequences.Down)
  315. {
  316. SendNetKey (k);
  317. }
  318. break;
  319. default:
  320. throw new ArgumentOutOfRangeException ();
  321. }
  322. return WaitIteration ();
  323. ;
  324. }
  325. /// <summary>
  326. /// Simulates the Right cursor key
  327. /// </summary>
  328. /// <returns></returns>
  329. /// <exception cref="ArgumentOutOfRangeException"></exception>
  330. public GuiTestContext Right ()
  331. {
  332. switch (_driver)
  333. {
  334. case V2TestDriver.V2Win:
  335. SendWindowsKey (ConsoleKeyMapping.VK.RIGHT);
  336. break;
  337. case V2TestDriver.V2Net:
  338. foreach (ConsoleKeyInfo k in NetSequences.Right)
  339. {
  340. SendNetKey (k);
  341. }
  342. WaitIteration ();
  343. break;
  344. default:
  345. throw new ArgumentOutOfRangeException ();
  346. }
  347. return WaitIteration ();
  348. }
  349. /// <summary>
  350. /// Simulates the Left cursor key
  351. /// </summary>
  352. /// <returns></returns>
  353. /// <exception cref="ArgumentOutOfRangeException"></exception>
  354. public GuiTestContext Left ()
  355. {
  356. switch (_driver)
  357. {
  358. case V2TestDriver.V2Win:
  359. SendWindowsKey (ConsoleKeyMapping.VK.LEFT);
  360. break;
  361. case V2TestDriver.V2Net:
  362. foreach (ConsoleKeyInfo k in NetSequences.Left)
  363. {
  364. SendNetKey (k);
  365. }
  366. break;
  367. default:
  368. throw new ArgumentOutOfRangeException ();
  369. }
  370. return WaitIteration ();
  371. }
  372. /// <summary>
  373. /// Simulates the up cursor key
  374. /// </summary>
  375. /// <returns></returns>
  376. /// <exception cref="ArgumentOutOfRangeException"></exception>
  377. public GuiTestContext Up ()
  378. {
  379. switch (_driver)
  380. {
  381. case V2TestDriver.V2Win:
  382. SendWindowsKey (ConsoleKeyMapping.VK.UP);
  383. break;
  384. case V2TestDriver.V2Net:
  385. foreach (ConsoleKeyInfo k in NetSequences.Up)
  386. {
  387. SendNetKey (k);
  388. }
  389. break;
  390. default:
  391. throw new ArgumentOutOfRangeException ();
  392. }
  393. return WaitIteration ();
  394. }
  395. /// <summary>
  396. /// Simulates pressing the Return/Enter (newline) key.
  397. /// </summary>
  398. /// <returns></returns>
  399. /// <exception cref="ArgumentOutOfRangeException"></exception>
  400. public GuiTestContext Enter ()
  401. {
  402. switch (_driver)
  403. {
  404. case V2TestDriver.V2Win:
  405. SendWindowsKey (
  406. new WindowsConsole.KeyEventRecord
  407. {
  408. UnicodeChar = '\r',
  409. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  410. wRepeatCount = 1,
  411. wVirtualKeyCode = ConsoleKeyMapping.VK.RETURN,
  412. wVirtualScanCode = 28
  413. });
  414. break;
  415. case V2TestDriver.V2Net:
  416. SendNetKey (new ('\r', ConsoleKey.Enter, false, false, false));
  417. break;
  418. default:
  419. throw new ArgumentOutOfRangeException ();
  420. }
  421. return WaitIteration ();
  422. }
  423. /// <summary>
  424. /// Simulates pressing the Esc (Escape) key.
  425. /// </summary>
  426. /// <returns></returns>
  427. /// <exception cref="ArgumentOutOfRangeException"></exception>
  428. public GuiTestContext Escape ()
  429. {
  430. switch (_driver)
  431. {
  432. case V2TestDriver.V2Win:
  433. SendWindowsKey (
  434. new WindowsConsole.KeyEventRecord
  435. {
  436. UnicodeChar = '\u001b',
  437. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  438. wRepeatCount = 1,
  439. wVirtualKeyCode = ConsoleKeyMapping.VK.ESCAPE,
  440. wVirtualScanCode = 1
  441. });
  442. break;
  443. case V2TestDriver.V2Net:
  444. // Note that this accurately describes how Esc comes in. Typically, ConsoleKey is None
  445. // even though you would think it would be Escape - it isn't
  446. SendNetKey (new ('\u001b', ConsoleKey.None, false, false, false));
  447. break;
  448. default:
  449. throw new ArgumentOutOfRangeException ();
  450. }
  451. return this;
  452. }
  453. /// <summary>
  454. /// Simulates pressing the Tab key.
  455. /// </summary>
  456. /// <returns></returns>
  457. /// <exception cref="ArgumentOutOfRangeException"></exception>
  458. public GuiTestContext Tab ()
  459. {
  460. switch (_driver)
  461. {
  462. case V2TestDriver.V2Win:
  463. SendWindowsKey (
  464. new WindowsConsole.KeyEventRecord
  465. {
  466. UnicodeChar = '\t',
  467. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed,
  468. wRepeatCount = 1,
  469. wVirtualKeyCode = 0,
  470. wVirtualScanCode = 0
  471. });
  472. break;
  473. case V2TestDriver.V2Net:
  474. // Note that this accurately describes how Tab comes in. Typically, ConsoleKey is None
  475. // even though you would think it would be Tab - it isn't
  476. SendNetKey (new ('\t', ConsoleKey.None, false, false, false));
  477. break;
  478. default:
  479. throw new ArgumentOutOfRangeException ();
  480. }
  481. return this;
  482. }
  483. /// <summary>
  484. /// Registers a right click handler on the <see cref="LastView"/> added view (or root view) that
  485. /// will open the supplied <paramref name="contextMenu"/>.
  486. /// </summary>
  487. /// <param name="contextMenu"></param>
  488. /// <returns></returns>
  489. public GuiTestContext WithContextMenu (PopoverMenu? contextMenu)
  490. {
  491. LastView.MouseEvent += (s, e) =>
  492. {
  493. if (e.Flags.HasFlag (MouseFlags.Button3Clicked))
  494. {
  495. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  496. // and the context menu is disposed when it is closed.
  497. Application.Popover?.Register (contextMenu);
  498. contextMenu?.MakeVisible (e.ScreenPosition);
  499. }
  500. };
  501. return this;
  502. }
  503. /// <summary>
  504. /// The last view added (e.g. with <see cref="Add"/>) or the root/current top.
  505. /// </summary>
  506. public View LastView => _lastView ?? Application.Top ?? throw new ("Could not determine which view to add to");
  507. /// <summary>
  508. /// Send a full windows OS key including both down and up.
  509. /// </summary>
  510. /// <param name="fullKey"></param>
  511. private void SendWindowsKey (WindowsConsole.KeyEventRecord fullKey)
  512. {
  513. WindowsConsole.KeyEventRecord down = fullKey;
  514. WindowsConsole.KeyEventRecord up = fullKey; // because struct this is new copy
  515. down.bKeyDown = true;
  516. up.bKeyDown = false;
  517. _winInput.InputBuffer.Enqueue (
  518. new ()
  519. {
  520. EventType = WindowsConsole.EventType.Key,
  521. KeyEvent = down
  522. });
  523. _winInput.InputBuffer.Enqueue (
  524. new ()
  525. {
  526. EventType = WindowsConsole.EventType.Key,
  527. KeyEvent = up
  528. });
  529. WaitIteration ();
  530. }
  531. private void SendNetKey (ConsoleKeyInfo consoleKeyInfo) { _netInput.InputBuffer.Enqueue (consoleKeyInfo); }
  532. /// <summary>
  533. /// Sends a special key e.g. cursor key that does not map to a specific character
  534. /// </summary>
  535. /// <param name="specialKey"></param>
  536. private void SendWindowsKey (ConsoleKeyMapping.VK specialKey)
  537. {
  538. _winInput.InputBuffer.Enqueue (
  539. new ()
  540. {
  541. EventType = WindowsConsole.EventType.Key,
  542. KeyEvent = new ()
  543. {
  544. bKeyDown = true,
  545. wRepeatCount = 0,
  546. wVirtualKeyCode = specialKey,
  547. wVirtualScanCode = 0,
  548. UnicodeChar = '\0',
  549. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  550. }
  551. });
  552. _winInput.InputBuffer.Enqueue (
  553. new ()
  554. {
  555. EventType = WindowsConsole.EventType.Key,
  556. KeyEvent = new ()
  557. {
  558. bKeyDown = false,
  559. wRepeatCount = 0,
  560. wVirtualKeyCode = specialKey,
  561. wVirtualScanCode = 0,
  562. UnicodeChar = '\0',
  563. dwControlKeyState = WindowsConsole.ControlKeyState.NoControlKeyPressed
  564. }
  565. });
  566. WaitIteration ();
  567. }
  568. /// <summary>
  569. /// Sends a key to the application. This goes directly to Application and does not go through
  570. /// a driver.
  571. /// </summary>
  572. /// <param name="key"></param>
  573. /// <returns></returns>
  574. public GuiTestContext RaiseKeyDownEvent (Key key)
  575. {
  576. Application.RaiseKeyDownEvent (key);
  577. return this; //WaitIteration();
  578. }
  579. /// <summary>
  580. /// Sets the input focus to the given <see cref="View"/>.
  581. /// Throws <see cref="ArgumentException"/> if focus did not change due to system
  582. /// constraints e.g. <paramref name="toFocus"/>
  583. /// <see cref="View.CanFocus"/> is <see langword="false"/>
  584. /// </summary>
  585. /// <param name="toFocus"></param>
  586. /// <returns></returns>
  587. /// <exception cref="ArgumentException"></exception>
  588. public GuiTestContext Focus (View toFocus)
  589. {
  590. toFocus.FocusDeepest (NavigationDirection.Forward, TabBehavior.TabStop);
  591. if (!toFocus.HasFocus)
  592. {
  593. throw new ArgumentException ("Failed to set focus, FocusDeepest did not result in HasFocus becoming true. Ensure view is added and focusable");
  594. }
  595. return WaitIteration ();
  596. }
  597. /// <summary>
  598. /// Tabs through the UI until a View matching the <paramref name="evaluator"/>
  599. /// is found (of Type T) or all views are looped through (back to the beginning)
  600. /// in which case triggers hard stop and Exception
  601. /// </summary>
  602. /// <param name="evaluator">Delegate that returns true if the passed View is the one
  603. /// you are trying to focus. Leave <see langword="null"/> to focus the first view of type
  604. /// <typeparamref name="T"/></param>
  605. /// <returns></returns>
  606. /// <exception cref="ArgumentException"></exception>
  607. public GuiTestContext Focus<T> (Func<T, bool>? evaluator = null) where T : View
  608. {
  609. evaluator ??= _ => true;
  610. Toplevel? t = Application.Top;
  611. HashSet<View> seen = new ();
  612. if (t == null)
  613. {
  614. Fail ("Application.Top was null when trying to set focus");
  615. return this;
  616. }
  617. do
  618. {
  619. View? next = t.MostFocused;
  620. // Is view found?
  621. if (next is T v && evaluator (v))
  622. {
  623. return this;
  624. }
  625. // No, try tab to the next (or first)
  626. Tab ();
  627. WaitIteration ();
  628. next = t.MostFocused;
  629. if (next is null)
  630. {
  631. Fail ("Failed to tab to a view which matched the Type and evaluator constraints of the test because MostFocused became or was always null");
  632. return this;
  633. }
  634. // Track the views we have seen
  635. // We have looped around to the start again if it was already there
  636. if (!seen.Add (next))
  637. {
  638. Fail ("Failed to tab to a view which matched the Type and evaluator constraints of the test before looping back to the original View");
  639. return this;
  640. }
  641. }
  642. while (true);
  643. }
  644. private T Find<T> (Func<T, bool> evaluator) where T : View
  645. {
  646. Toplevel? t = Application.Top;
  647. if (t == null)
  648. {
  649. Fail ("Application.Top was null when attempting to find view");
  650. }
  651. T? f = FindRecursive (t!, evaluator);
  652. if (f == null)
  653. {
  654. Fail ("Failed to tab to a view which matched the Type and evaluator constraints in any SubViews of top");
  655. }
  656. return f!;
  657. }
  658. private T? FindRecursive<T> (View current, Func<T, bool> evaluator) where T : View
  659. {
  660. foreach (View subview in current.SubViews)
  661. {
  662. if (subview is T match && evaluator (match))
  663. {
  664. return match;
  665. }
  666. // Recursive call
  667. T? result = FindRecursive (subview, evaluator);
  668. if (result != null)
  669. {
  670. return result;
  671. }
  672. }
  673. return null;
  674. }
  675. private void Fail (string reason)
  676. {
  677. Stop ();
  678. throw new (reason);
  679. }
  680. public GuiTestContext Send (Key key)
  681. {
  682. if (Application.Driver is IConsoleDriverFacade facade)
  683. {
  684. facade.InputProcessor.OnKeyDown (key);
  685. facade.InputProcessor.OnKeyUp (key);
  686. }
  687. else
  688. {
  689. Fail ("Expected Application.Driver to be IConsoleDriverFacade");
  690. }
  691. return this;
  692. }
  693. /// <summary>
  694. /// Returns the last set position of the cursor.
  695. /// </summary>
  696. /// <returns></returns>
  697. public Point GetCursorPosition ()
  698. {
  699. return _output.CursorPosition;
  700. }
  701. }