GuiTestContext.cs 30 KB

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