ScenarioTests.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. using System.Collections.ObjectModel;
  2. using System.Diagnostics;
  3. using System.Reflection;
  4. using Xunit.Abstractions;
  5. namespace UICatalog.Tests;
  6. public class ScenarioTests : TestsAllViews
  7. {
  8. public ScenarioTests (ITestOutputHelper output)
  9. {
  10. #if DEBUG_IDISPOSABLE
  11. Responder.Instances.Clear ();
  12. #endif
  13. _output = output;
  14. }
  15. private readonly ITestOutputHelper _output;
  16. private object _timeoutLock;
  17. /// <summary>
  18. /// <para>This runs through all Scenarios defined in UI Catalog, calling Init, Setup, and Run.</para>
  19. /// <para>Should find any Scenarios which crash on load or do not respond to <see cref="Application.RequestStop()"/>.</para>
  20. /// </summary>
  21. [Theory]
  22. [MemberData (nameof (AllScenarioTypes))]
  23. public void All_Scenarios_Quit_And_Init_Shutdown_Properly (Type scenarioType)
  24. {
  25. Assert.Null (_timeoutLock);
  26. _timeoutLock = new ();
  27. // Disable any UIConfig settings
  28. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  29. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  30. // If a previous test failed, this will ensure that the Application is in a clean state
  31. Application.ResetState (true);
  32. _output.WriteLine ($"Running Scenario '{scenarioType}'");
  33. var scenario = (Scenario)Activator.CreateInstance (scenarioType);
  34. uint abortTime = 1500;
  35. object timeout = null;
  36. var initialized = false;
  37. var shutdown = false;
  38. int iterationCount = 0;
  39. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  40. Application.ForceDriver = "FakeDriver";
  41. scenario.Main ();
  42. scenario.Dispose ();
  43. scenario = null;
  44. Application.ForceDriver = string.Empty;
  45. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  46. lock (_timeoutLock)
  47. {
  48. if (timeout is { })
  49. {
  50. timeout = null;
  51. }
  52. }
  53. Assert.True (initialized);
  54. Assert.True (shutdown);
  55. #if DEBUG_IDISPOSABLE
  56. Assert.Empty (Responder.Instances);
  57. #endif
  58. lock (_timeoutLock)
  59. {
  60. _timeoutLock = null;
  61. }
  62. // Restore the configuration locations
  63. ConfigurationManager.Locations = savedConfigLocations;
  64. ConfigurationManager.Reset ();
  65. return;
  66. void OnApplicationOnInitializedChanged (object s, EventArgs<bool> a)
  67. {
  68. if (a.CurrentValue)
  69. {
  70. Application.Iteration += OnApplicationOnIteration;
  71. initialized = true;
  72. lock (_timeoutLock)
  73. {
  74. timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
  75. }
  76. }
  77. else
  78. {
  79. Application.Iteration -= OnApplicationOnIteration;
  80. shutdown = true;
  81. }
  82. _output.WriteLine ($"Initialized == {a.CurrentValue}");
  83. }
  84. // If the scenario doesn't close within 500ms, this will force it to quit
  85. bool ForceCloseCallback ()
  86. {
  87. lock (_timeoutLock)
  88. {
  89. if (timeout is { })
  90. {
  91. timeout = null;
  92. }
  93. }
  94. Assert.Fail (
  95. $"'{scenario.GetName ()}' failed to Quit with {Application.QuitKey} after {abortTime}ms and {iterationCount} iterations. Force quit.");
  96. // Restore the configuration locations
  97. ConfigurationManager.Locations = savedConfigLocations;
  98. ConfigurationManager.Reset ();
  99. Application.ResetState (true);
  100. return false;
  101. }
  102. void OnApplicationOnIteration (object s, IterationEventArgs a)
  103. {
  104. iterationCount++;
  105. if (Application.Initialized)
  106. {
  107. // Press QuitKey
  108. _output.WriteLine ($"Attempting to quit with {Application.QuitKey}");
  109. Application.RaiseKeyDownEvent (Application.QuitKey);
  110. }
  111. }
  112. }
  113. /// <summary>
  114. /// <para>This runs through all Scenarios defined in UI Catalog, calling Init, Setup, and Run and measuring the perf of each.</para>
  115. /// </summary>
  116. [Theory]
  117. [MemberData (nameof (AllScenarioTypes))]
  118. public void All_Scenarios_Benchmark (Type scenarioType)
  119. {
  120. Assert.Null (_timeoutLock);
  121. _timeoutLock = new ();
  122. // Disable any UIConfig settings
  123. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  124. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  125. // If a previous test failed, this will ensure that the Application is in a clean state
  126. Application.ResetState (true);
  127. uint maxIterations = 1000;
  128. uint abortTime = 2000;
  129. object timeout = null;
  130. var initialized = false;
  131. var shutdown = false;
  132. int iterationCount = 0;
  133. int clearedContentCount = 0;
  134. int refreshedCount = 0;
  135. int updatedCount = 0;
  136. int drawCompleteCount = 0;
  137. int addedCount = 0;
  138. int laidOutCount = 0;
  139. _output.WriteLine ($"Running Scenario '{scenarioType}'");
  140. var scenario = (Scenario)Activator.CreateInstance (scenarioType);
  141. Stopwatch stopwatch = null;
  142. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  143. Application.ForceDriver = "FakeDriver";
  144. scenario!.Main ();
  145. scenario.Dispose ();
  146. scenario = null;
  147. Application.ForceDriver = string.Empty;
  148. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  149. lock (_timeoutLock)
  150. {
  151. if (timeout is { })
  152. {
  153. timeout = null;
  154. }
  155. }
  156. lock (_timeoutLock)
  157. {
  158. _timeoutLock = null;
  159. }
  160. _output.WriteLine ($"Scenario {scenarioType}");
  161. _output.WriteLine ($" took {stopwatch.ElapsedMilliseconds} ms to run.");
  162. _output.WriteLine ($" called Driver.ClearContents {clearedContentCount} times.");
  163. _output.WriteLine ($" called Driver.Refresh {refreshedCount} times.");
  164. _output.WriteLine ($" which updated the screen {updatedCount} times.");
  165. _output.WriteLine ($" called View.Draw {drawCompleteCount} times.");
  166. _output.WriteLine ($" added {addedCount} views.");
  167. _output.WriteLine ($" called View.LayoutComplete {laidOutCount} times.");
  168. // Restore the configuration locations
  169. ConfigurationManager.Locations = savedConfigLocations;
  170. ConfigurationManager.Reset ();
  171. return;
  172. void OnApplicationOnInitializedChanged (object s, EventArgs<bool> a)
  173. {
  174. if (a.CurrentValue)
  175. {
  176. lock (_timeoutLock)
  177. {
  178. timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (abortTime), ForceCloseCallback);
  179. }
  180. initialized = true;
  181. Application.Iteration += OnApplicationOnIteration;
  182. Application.Driver!.ClearedContents += (sender, args) => clearedContentCount++;
  183. Application.Driver!.Refreshed += (sender, args) =>
  184. {
  185. refreshedCount++;
  186. if (args.CurrentValue)
  187. {
  188. updatedCount++;
  189. }
  190. };
  191. Application.NotifyNewRunState += OnApplicationNotifyNewRunState;
  192. stopwatch = Stopwatch.StartNew ();
  193. }
  194. else
  195. {
  196. shutdown = true;
  197. Application.NotifyNewRunState -= OnApplicationNotifyNewRunState;
  198. Application.Iteration -= OnApplicationOnIteration;
  199. stopwatch!.Stop ();
  200. }
  201. _output.WriteLine ($"Initialized == {a.CurrentValue}");
  202. }
  203. void OnApplicationOnIteration (object s, IterationEventArgs a)
  204. {
  205. iterationCount++;
  206. if (iterationCount > maxIterations)
  207. {
  208. // Press QuitKey
  209. _output.WriteLine ($"Attempting to quit scenario with RequestStop");
  210. Application.RequestStop ();
  211. }
  212. }
  213. void OnApplicationNotifyNewRunState (object sender, RunStateEventArgs e)
  214. {
  215. // Get a list of all subviews under Application.Top (and their subviews, etc.)
  216. // and subscribe to their DrawComplete event
  217. void SubscribeAllSubviews (View view)
  218. {
  219. view.DrawComplete += (s, a) => drawCompleteCount++;
  220. view.SubviewsLaidOut += (s, a) => laidOutCount++;
  221. view.Added += (s, a) => addedCount++;
  222. foreach (View subview in view.Subviews)
  223. {
  224. SubscribeAllSubviews (subview);
  225. }
  226. }
  227. SubscribeAllSubviews (Application.Top);
  228. }
  229. // If the scenario doesn't close within the abort time, this will force it to quit
  230. bool ForceCloseCallback ()
  231. {
  232. lock (_timeoutLock)
  233. {
  234. if (timeout is { })
  235. {
  236. timeout = null;
  237. }
  238. }
  239. _output.WriteLine(
  240. $"'{scenario.GetName ()}' failed to Quit with {Application.QuitKey} after {abortTime}ms and {iterationCount} iterations. Force quit.");
  241. Application.RequestStop ();
  242. return false;
  243. }
  244. }
  245. public static IEnumerable<object []> AllScenarioTypes =>
  246. typeof (Scenario).Assembly
  247. .GetTypes ()
  248. .Where (type => type.IsClass && !type.IsAbstract && type.IsSubclassOf (typeof (Scenario)))
  249. .Select (type => new object [] { type });
  250. [Fact]
  251. public void Run_All_Views_Tester_Scenario ()
  252. {
  253. // Disable any UIConfig settings
  254. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  255. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  256. Window _leftPane;
  257. ListView _classListView;
  258. FrameView _hostPane;
  259. Dictionary<string, Type> _viewClasses;
  260. View _curView = null;
  261. // Settings
  262. FrameView _settingsPane;
  263. FrameView _locationFrame;
  264. RadioGroup _xRadioGroup;
  265. TextField _xText;
  266. var _xVal = 0;
  267. RadioGroup _yRadioGroup;
  268. TextField _yText;
  269. var _yVal = 0;
  270. FrameView _sizeFrame;
  271. RadioGroup _wRadioGroup;
  272. TextField _wText;
  273. var _wVal = 0;
  274. RadioGroup _hRadioGroup;
  275. TextField _hText;
  276. var _hVal = 0;
  277. List<string> posNames = new () { "Percent", "AnchorEnd", "Center", "Absolute" };
  278. List<string> dimNames = new () { "Auto", "Percent", "Fill", "Absolute" };
  279. Application.Init (new FakeDriver ());
  280. var top = new Toplevel ();
  281. _viewClasses = TestHelpers.GetAllViewClasses ().ToDictionary (t => t.Name);
  282. _leftPane = new ()
  283. {
  284. Title = "Classes",
  285. X = 0,
  286. Y = 0,
  287. Width = 15,
  288. Height = Dim.Fill (1), // for status bar
  289. CanFocus = false,
  290. ColorScheme = Colors.ColorSchemes ["TopLevel"]
  291. };
  292. _classListView = new ()
  293. {
  294. X = 0,
  295. Y = 0,
  296. Width = Dim.Fill (),
  297. Height = Dim.Fill (),
  298. AllowsMarking = false,
  299. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  300. Source = new ListWrapper<string> (new (_viewClasses.Keys.ToList ()))
  301. };
  302. _leftPane.Add (_classListView);
  303. _settingsPane = new ()
  304. {
  305. X = Pos.Right (_leftPane),
  306. Y = 0, // for menu
  307. Width = Dim.Fill (),
  308. Height = 10,
  309. CanFocus = false,
  310. ColorScheme = Colors.ColorSchemes ["TopLevel"],
  311. Title = "Settings"
  312. };
  313. var radioItems = new [] { "Percent(x)", "AnchorEnd(x)", "Center", "Absolute(x)" };
  314. _locationFrame = new ()
  315. {
  316. X = 0,
  317. Y = 0,
  318. Height = 3 + radioItems.Length,
  319. Width = 36,
  320. Title = "Location (Pos)"
  321. };
  322. _settingsPane.Add (_locationFrame);
  323. var label = new Label { X = 0, Y = 0, Text = "x:" };
  324. _locationFrame.Add (label);
  325. _xRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = radioItems };
  326. _xText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_xVal}" };
  327. _locationFrame.Add (_xText);
  328. _locationFrame.Add (_xRadioGroup);
  329. radioItems = new [] { "Percent(y)", "AnchorEnd(y)", "Center", "Absolute(y)" };
  330. label = new () { X = Pos.Right (_xRadioGroup) + 1, Y = 0, Text = "y:" };
  331. _locationFrame.Add (label);
  332. _yText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_yVal}" };
  333. _locationFrame.Add (_yText);
  334. _yRadioGroup = new () { X = Pos.X (label), Y = Pos.Bottom (label), RadioLabels = radioItems };
  335. _locationFrame.Add (_yRadioGroup);
  336. _sizeFrame = new ()
  337. {
  338. X = Pos.Right (_locationFrame),
  339. Y = Pos.Y (_locationFrame),
  340. Height = 3 + radioItems.Length,
  341. Width = 40,
  342. Title = "Size (Dim)"
  343. };
  344. radioItems = new [] { "Auto()", "Percent(width)", "Fill(width)", "Absolute(width)" };
  345. label = new () { X = 0, Y = 0, Text = "width:" };
  346. _sizeFrame.Add (label);
  347. _wRadioGroup = new () { X = 0, Y = Pos.Bottom (label), RadioLabels = radioItems };
  348. _wText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_wVal}" };
  349. _sizeFrame.Add (_wText);
  350. _sizeFrame.Add (_wRadioGroup);
  351. radioItems = new [] { "Auto()", "Percent(height)", "Fill(height)", "Absolute(height)" };
  352. label = new () { X = Pos.Right (_wRadioGroup) + 1, Y = 0, Text = "height:" };
  353. _sizeFrame.Add (label);
  354. _hText = new () { X = Pos.Right (label) + 1, Y = 0, Width = 4, Text = $"{_hVal}" };
  355. _sizeFrame.Add (_hText);
  356. _hRadioGroup = new () { X = Pos.X (label), Y = Pos.Bottom (label), RadioLabels = radioItems };
  357. _sizeFrame.Add (_hRadioGroup);
  358. _settingsPane.Add (_sizeFrame);
  359. _hostPane = new ()
  360. {
  361. X = Pos.Right (_leftPane),
  362. Y = Pos.Bottom (_settingsPane),
  363. Width = Dim.Fill (),
  364. Height = Dim.Fill (1), // + 1 for status bar
  365. ColorScheme = Colors.ColorSchemes ["Dialog"]
  366. };
  367. _classListView.OpenSelectedItem += (s, a) => { _settingsPane.SetFocus (); };
  368. _classListView.SelectedItemChanged += (s, args) =>
  369. {
  370. // Remove existing class, if any
  371. if (_curView != null)
  372. {
  373. _curView.SubviewsLaidOut -= LayoutCompleteHandler;
  374. _hostPane.Remove (_curView);
  375. _curView.Dispose ();
  376. _curView = null;
  377. _hostPane.FillRect (_hostPane.Viewport);
  378. }
  379. _curView = CreateClass (_viewClasses.Values.ToArray () [_classListView.SelectedItem]);
  380. };
  381. _xRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  382. _xText.TextChanged += (s, args) =>
  383. {
  384. try
  385. {
  386. _xVal = int.Parse (_xText.Text);
  387. DimPosChanged (_curView);
  388. }
  389. catch
  390. { }
  391. };
  392. _yText.TextChanged += (s, e) =>
  393. {
  394. try
  395. {
  396. _yVal = int.Parse (_yText.Text);
  397. DimPosChanged (_curView);
  398. }
  399. catch
  400. { }
  401. };
  402. _yRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  403. _wRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  404. _wText.TextChanged += (s, args) =>
  405. {
  406. try
  407. {
  408. _wVal = int.Parse (_wText.Text);
  409. DimPosChanged (_curView);
  410. }
  411. catch
  412. { }
  413. };
  414. _hText.TextChanged += (s, args) =>
  415. {
  416. try
  417. {
  418. _hVal = int.Parse (_hText.Text);
  419. DimPosChanged (_curView);
  420. }
  421. catch
  422. { }
  423. };
  424. _hRadioGroup.SelectedItemChanged += (s, selected) => DimPosChanged (_curView);
  425. top.Add (_leftPane, _settingsPane, _hostPane);
  426. top.LayoutSubviews ();
  427. _curView = CreateClass (_viewClasses.First ().Value);
  428. var iterations = 0;
  429. Application.Iteration += (s, a) =>
  430. {
  431. iterations++;
  432. if (iterations < _viewClasses.Count)
  433. {
  434. _classListView.MoveDown ();
  435. Assert.Equal (
  436. _curView.GetType ().Name,
  437. _viewClasses.Values.ToArray () [_classListView.SelectedItem].Name
  438. );
  439. }
  440. else
  441. {
  442. Application.RequestStop ();
  443. }
  444. };
  445. Application.Run (top);
  446. Assert.Equal (_viewClasses.Count, iterations);
  447. top.Dispose ();
  448. Application.Shutdown ();
  449. // Restore the configuration locations
  450. ConfigurationManager.Locations = savedConfigLocations;
  451. ConfigurationManager.Reset ();
  452. void DimPosChanged (View view)
  453. {
  454. if (view == null)
  455. {
  456. return;
  457. }
  458. try
  459. {
  460. switch (_xRadioGroup.SelectedItem)
  461. {
  462. case 0:
  463. view.X = Pos.Percent (_xVal);
  464. break;
  465. case 1:
  466. view.X = Pos.AnchorEnd (_xVal);
  467. break;
  468. case 2:
  469. view.X = Pos.Center ();
  470. break;
  471. case 3:
  472. view.X = Pos.Absolute (_xVal);
  473. break;
  474. }
  475. switch (_yRadioGroup.SelectedItem)
  476. {
  477. case 0:
  478. view.Y = Pos.Percent (_yVal);
  479. break;
  480. case 1:
  481. view.Y = Pos.AnchorEnd (_yVal);
  482. break;
  483. case 2:
  484. view.Y = Pos.Center ();
  485. break;
  486. case 3:
  487. view.Y = Pos.Absolute (_yVal);
  488. break;
  489. }
  490. switch (_wRadioGroup.SelectedItem)
  491. {
  492. case 0:
  493. view.Width = Dim.Percent (_wVal);
  494. break;
  495. case 1:
  496. view.Width = Dim.Fill (_wVal);
  497. break;
  498. case 2:
  499. view.Width = Dim.Absolute (_wVal);
  500. break;
  501. }
  502. switch (_hRadioGroup.SelectedItem)
  503. {
  504. case 0:
  505. view.Height = Dim.Percent (_hVal);
  506. break;
  507. case 1:
  508. view.Height = Dim.Fill (_hVal);
  509. break;
  510. case 2:
  511. view.Height = Dim.Absolute (_hVal);
  512. break;
  513. }
  514. }
  515. catch (Exception e)
  516. {
  517. MessageBox.ErrorQuery ("Exception", e.Message, "Ok");
  518. }
  519. UpdateTitle (view);
  520. }
  521. void UpdateSettings (View view)
  522. {
  523. var x = view.X.ToString ();
  524. var y = view.Y.ToString ();
  525. try
  526. {
  527. _xRadioGroup.SelectedItem = posNames.IndexOf (posNames.First (s => x.Contains (s)));
  528. _yRadioGroup.SelectedItem = posNames.IndexOf (posNames.First (s => y.Contains (s)));
  529. }
  530. catch (InvalidOperationException e)
  531. {
  532. // This is a hack to work around the fact that the Pos enum doesn't have an "Align" value yet
  533. Debug.WriteLine ($"{e}");
  534. }
  535. _xText.Text = $"{view.Frame.X}";
  536. _yText.Text = $"{view.Frame.Y}";
  537. var w = view.Width.ToString ();
  538. var h = view.Height.ToString ();
  539. _wRadioGroup.SelectedItem = dimNames.IndexOf (dimNames.First (s => w.Contains (s)));
  540. _hRadioGroup.SelectedItem = dimNames.IndexOf (dimNames.First (s => h.Contains (s)));
  541. _wText.Text = $"{view.Frame.Width}";
  542. _hText.Text = $"{view.Frame.Height}";
  543. }
  544. void UpdateTitle (View view) { _hostPane.Title = $"{view.GetType ().Name} - {view.X}, {view.Y}, {view.Width}, {view.Height}"; }
  545. View CreateClass (Type type)
  546. {
  547. // If we are to create a generic Type
  548. if (type.IsGenericType)
  549. {
  550. // For each of the <T> arguments
  551. List<Type> typeArguments = new ();
  552. // use <object>
  553. foreach (Type arg in type.GetGenericArguments ())
  554. {
  555. typeArguments.Add (typeof (object));
  556. }
  557. // And change what type we are instantiating from MyClass<T> to MyClass<object>
  558. type = type.MakeGenericType (typeArguments.ToArray ());
  559. }
  560. // Instantiate view
  561. var view = (View)Activator.CreateInstance (type);
  562. if (view is null)
  563. {
  564. return null;
  565. }
  566. if (view.Width is not DimAuto)
  567. {
  568. view.Width = Dim.Percent (75);
  569. }
  570. if (view.Height is not DimAuto)
  571. {
  572. view.Height = Dim.Percent (75);
  573. }
  574. // Set the colorscheme to make it stand out if is null by default
  575. view.ColorScheme ??= Colors.ColorSchemes ["Base"];
  576. // If the view supports a Text property, set it so we have something to look at
  577. if (view.GetType ().GetProperty ("Text") != null)
  578. {
  579. try
  580. {
  581. view.GetType ().GetProperty ("Text")?.GetSetMethod ()?.Invoke (view, new [] { "Test Text" });
  582. }
  583. catch (TargetInvocationException e)
  584. {
  585. MessageBox.ErrorQuery ("Exception", e.InnerException.Message, "Ok");
  586. view = null;
  587. }
  588. }
  589. // If the view supports a Title property, set it so we have something to look at
  590. if (view != null && view.GetType ().GetProperty ("Title") != null)
  591. {
  592. if (view.GetType ().GetProperty ("Title").PropertyType == typeof (string))
  593. {
  594. view?.GetType ().GetProperty ("Title")?.GetSetMethod ()?.Invoke (view, new [] { "Test Title" });
  595. }
  596. else
  597. {
  598. view?.GetType ().GetProperty ("Title")?.GetSetMethod ()?.Invoke (view, new [] { "Test Title" });
  599. }
  600. }
  601. // If the view supports a Source property, set it so we have something to look at
  602. if (view != null
  603. && view.GetType ().GetProperty ("Source") != null
  604. && view.GetType ().GetProperty ("Source").PropertyType == typeof (IListDataSource))
  605. {
  606. ListWrapper<string> source = new (["Test Text #1", "Test Text #2", "Test Text #3"]);
  607. view?.GetType ().GetProperty ("Source")?.GetSetMethod ()?.Invoke (view, new [] { source });
  608. }
  609. // Add
  610. _hostPane.Add (view);
  611. //DimPosChanged ();
  612. _hostPane.LayoutSubviews ();
  613. _hostPane.ClearViewport ();
  614. _hostPane.SetNeedsDraw ();
  615. UpdateSettings (view);
  616. UpdateTitle (view);
  617. view.SubviewsLaidOut += LayoutCompleteHandler;
  618. return view;
  619. }
  620. void LayoutCompleteHandler (object sender, LayoutEventArgs args) { UpdateTitle (_curView); }
  621. }
  622. [Fact]
  623. public void Run_Generic ()
  624. {
  625. // Disable any UIConfig settings
  626. ConfigurationManager.ConfigLocations savedConfigLocations = ConfigurationManager.Locations;
  627. ConfigurationManager.Locations = ConfigurationManager.ConfigLocations.DefaultOnly;
  628. ObservableCollection<Scenario> scenarios = Scenario.GetScenarios ();
  629. Assert.NotEmpty (scenarios);
  630. int item = scenarios.IndexOf (s => s.GetName ().Equals ("Generic", StringComparison.OrdinalIgnoreCase));
  631. Scenario generic = scenarios [item];
  632. Application.Init (new FakeDriver ());
  633. // BUGBUG: (#2474) For some reason ReadKey is not returning the QuitKey for some Scenarios
  634. // by adding this Space it seems to work.
  635. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  636. var ms = 100;
  637. var abortCount = 0;
  638. Func<bool> abortCallback = () =>
  639. {
  640. abortCount++;
  641. _output.WriteLine ($"'Generic' abortCount {abortCount}");
  642. Application.RequestStop ();
  643. return false;
  644. };
  645. var iterations = 0;
  646. object token = null;
  647. Application.Iteration += (s, a) =>
  648. {
  649. if (token == null)
  650. {
  651. // Timeout only must start at first iteration
  652. token = Application.MainLoop.AddTimeout (TimeSpan.FromMilliseconds (ms), abortCallback);
  653. }
  654. iterations++;
  655. _output.WriteLine ($"'Generic' iteration {iterations}");
  656. // Stop if we run out of control...
  657. if (iterations == 10)
  658. {
  659. _output.WriteLine ("'Generic' had to be force quit!");
  660. Application.RequestStop ();
  661. }
  662. };
  663. Application.KeyDown += (sender, args) =>
  664. {
  665. Assert.Equal (Application.QuitKey, args.KeyCode);
  666. };
  667. generic.Main ();
  668. Assert.Equal (0, abortCount);
  669. // # of key up events should match # of iterations
  670. Assert.Equal (1, iterations);
  671. generic.Dispose ();
  672. // Shutdown must be called to safely clean up Application if Init has been called
  673. Application.Shutdown ();
  674. // Restore the configuration locations
  675. ConfigurationManager.Locations = savedConfigLocations;
  676. ConfigurationManager.Reset ();
  677. #if DEBUG_IDISPOSABLE
  678. Assert.Empty (Responder.Instances);
  679. #endif
  680. }
  681. private int CreateInput (string input)
  682. {
  683. FakeConsole.MockKeyPresses.Clear ();
  684. // Put a QuitKey in at the end
  685. FakeConsole.PushMockKeyPress ((KeyCode)Application.QuitKey);
  686. foreach (char c in input.Reverse ())
  687. {
  688. var key = KeyCode.Null;
  689. if (char.IsLetter (c))
  690. {
  691. key = (KeyCode)char.ToUpper (c) | (char.IsUpper (c) ? KeyCode.ShiftMask : 0);
  692. }
  693. else
  694. {
  695. key = (KeyCode)c;
  696. }
  697. FakeConsole.PushMockKeyPress (key);
  698. }
  699. return FakeConsole.MockKeyPresses.Count;
  700. }
  701. }