2
0

Scenario.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. namespace UICatalog;
  8. /// <summary>
  9. /// <para>Base class for each demo/scenario.</para>
  10. /// <para>
  11. /// To define a new scenario:
  12. /// <list type="number">
  13. /// <item>
  14. /// <description>
  15. /// Create a new <c>.cs</c> file in the <cs>Scenarios</cs> directory that derives from
  16. /// <see cref="Scenario"/>.
  17. /// </description>
  18. /// </item>
  19. /// <item>
  20. /// <description>
  21. /// Annotate the <see cref="Scenario"/> derived class with a
  22. /// <see cref="ScenarioMetadata"/> attribute specifying the scenario's name and description.
  23. /// </description>
  24. /// </item>
  25. /// <item>
  26. /// <description>
  27. /// Add one or more <see cref="ScenarioCategory"/> attributes to the class specifying
  28. /// which categories the scenario belongs to. If you don't specify a category the scenario will show up
  29. /// in "_All".
  30. /// </description>
  31. /// </item>
  32. /// <item>
  33. /// <description>
  34. /// Implement the <see cref="Main"/> override which will be called when a user selects the
  35. /// scenario to run.
  36. /// </description>
  37. /// </item>
  38. /// </list>
  39. /// </para>
  40. /// <para>
  41. /// The UI Catalog program uses reflection to find all scenarios and adds them to the ListViews. Press ENTER to
  42. /// run the selected scenario. Press the default quit key to quit.
  43. /// </para>
  44. /// </summary>
  45. /// <example>
  46. /// The example below is provided in the `Scenarios` directory as a generic sample that can be copied and re-named:
  47. /// <code>
  48. /// using Terminal.Gui;
  49. ///
  50. /// namespace UICatalog.Scenarios;
  51. ///
  52. /// [ScenarioMetadata ("Generic", "Generic sample - A template for creating new Scenarios")]
  53. /// [ScenarioCategory ("Controls")]
  54. /// public sealed class MyScenario : Scenario
  55. /// {
  56. /// public override void Main ()
  57. /// {
  58. /// // Init
  59. /// Application.Init ();
  60. ///
  61. /// // Setup - Create a top-level application window and configure it.
  62. /// Window appWindow = new ()
  63. /// {
  64. /// Title = GetQuitKeyAndName (),
  65. /// };
  66. ///
  67. /// var button = new Button { X = Pos.Center (), Y = Pos.Center (), Text = "Press me!" };
  68. /// button.Accept += (s, e) => MessageBox.ErrorQuery (App, "Error", "You pressed the button!", "Ok");
  69. /// appWindow.Add (button);
  70. ///
  71. /// // Run - Start the application.
  72. /// Application.Run (appWindow);
  73. /// appWindow.Dispose ();
  74. ///
  75. /// // Shutdown - Calling Application.Shutdown is required.
  76. /// Application.Shutdown ();
  77. /// }
  78. /// }
  79. /// </code>
  80. /// </example>
  81. public class Scenario : IDisposable
  82. {
  83. private static int _maxScenarioNameLen = 30;
  84. public BenchmarkResults BenchmarkResults
  85. {
  86. get { return _benchmarkResults; }
  87. }
  88. private bool _disposedValue;
  89. /// <summary>
  90. /// Helper function to get the list of categories a <see cref="Scenario"/> belongs to (defined in
  91. /// <see cref="ScenarioCategory"/>)
  92. /// </summary>
  93. /// <returns>list of category names</returns>
  94. public List<string> GetCategories () { return ScenarioCategory.GetCategories (GetType ()); }
  95. /// <summary>Helper to get the <see cref="Scenario"/> Description (defined in <see cref="ScenarioMetadata"/>)</summary>
  96. /// <returns></returns>
  97. public string GetDescription () { return ScenarioMetadata.GetDescription (GetType ()); }
  98. /// <summary>Helper to get the <see cref="Scenario"/> Name (defined in <see cref="ScenarioMetadata"/>)</summary>
  99. /// <returns></returns>
  100. public string GetName () { return ScenarioMetadata.GetName (GetType ()); }
  101. /// <summary>
  102. /// Helper to get the <see cref="Application.QuitKey"/> and the <see cref="Scenario"/> Name (defined in
  103. /// <see cref="ScenarioMetadata"/>)
  104. /// </summary>
  105. /// <returns></returns>
  106. public string GetQuitKeyAndName () { return $"{Application.QuitKey} to Quit - Scenario: {GetName ()}"; }
  107. /// <summary>
  108. /// Returns a list of all <see cref="Scenario"/> instanaces defined in the project, sorted by
  109. /// <see cref="ScenarioMetadata.Name"/>.
  110. /// https://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class
  111. /// </summary>
  112. public static ObservableCollection<Scenario> GetScenarios ()
  113. {
  114. List<Scenario> objects = [];
  115. foreach (Type type in typeof (Scenario).Assembly.ExportedTypes
  116. .Where (
  117. myType => myType is { IsClass: true, IsAbstract: false }
  118. && myType.IsSubclassOf (typeof (Scenario))
  119. ))
  120. {
  121. if (Activator.CreateInstance (type) is not Scenario { } scenario)
  122. {
  123. continue;
  124. }
  125. objects.Add (scenario);
  126. _maxScenarioNameLen = Math.Max (_maxScenarioNameLen, scenario.GetName ().Length + 1);
  127. }
  128. return new (objects.OrderBy (s => s.GetName ()).ToList ());
  129. }
  130. /// <summary>
  131. /// Called by UI Catalog to run the <see cref="Scenario"/>. This is the main entry point for the <see cref="Scenario"/>
  132. /// .
  133. /// </summary>
  134. public virtual void Main () { }
  135. private const uint BENCHMARK_MAX_NATURAL_ITERATIONS = 500; // not including needed for demo keys
  136. private const int BENCHMARK_KEY_PACING = 10; // Must be non-zero
  137. public static uint BenchmarkTimeout { get; set; } = 2500;
  138. private readonly object _timeoutLock = new ();
  139. private object? _timeout;
  140. private Stopwatch? _stopwatch;
  141. private readonly BenchmarkResults _benchmarkResults = new ();
  142. public void StartBenchmark ()
  143. {
  144. BenchmarkResults.Scenario = GetName ();
  145. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  146. }
  147. public BenchmarkResults EndBenchmark ()
  148. {
  149. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  150. lock (_timeoutLock)
  151. {
  152. if (_timeout is { })
  153. {
  154. _timeout = null;
  155. }
  156. }
  157. return _benchmarkResults;
  158. }
  159. private List<Key>? _demoKeys;
  160. private int _currentDemoKey;
  161. private void OnApplicationOnInitializedChanged (object? s, EventArgs<bool> a)
  162. {
  163. if (a.Value)
  164. {
  165. lock (_timeoutLock!)
  166. {
  167. _timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (BenchmarkTimeout), ForceCloseCallback);
  168. }
  169. Application.Iteration += OnApplicationOnIteration;
  170. Application.Driver!.ClearedContents += OnClearedContents;
  171. Application.SessionBegun += OnApplicationSessionBegun;
  172. _stopwatch = Stopwatch.StartNew ();
  173. }
  174. else
  175. {
  176. Application.Driver!.ClearedContents -= OnClearedContents;
  177. Application.SessionBegun -= OnApplicationSessionBegun;
  178. Application.Iteration -= OnApplicationOnIteration;
  179. BenchmarkResults.Duration = _stopwatch!.Elapsed;
  180. _stopwatch?.Stop ();
  181. }
  182. return;
  183. void OnClearedContents (object? sender, EventArgs args) => BenchmarkResults.ClearedContentCount++;
  184. }
  185. private void OnApplicationOnIteration (object? s, EventArgs<IApplication?> a)
  186. {
  187. BenchmarkResults.IterationCount++;
  188. if (BenchmarkResults.IterationCount > BENCHMARK_MAX_NATURAL_ITERATIONS + (_demoKeys!.Count * BENCHMARK_KEY_PACING))
  189. {
  190. a.Value?.RequestStop ();
  191. }
  192. }
  193. // BUGBUG: This is incompatible with modals. This should be using the new equivalent of Runnable.Ready
  194. // BUGBUG: which will be IsRunningChanged with newIsRunning == true
  195. private void OnApplicationSessionBegun (object? sender, SessionTokenEventArgs e)
  196. {
  197. SubscribeAllSubViews (Application.TopRunnableView!);
  198. _demoKeys = GetDemoKeyStrokes ();
  199. Application.AddTimeout (
  200. new TimeSpan (0, 0, 0, 0, BENCHMARK_KEY_PACING),
  201. () =>
  202. {
  203. if (_currentDemoKey >= _demoKeys.Count)
  204. {
  205. return false;
  206. }
  207. Application.RaiseKeyDownEvent (_demoKeys [_currentDemoKey++]);
  208. return true;
  209. });
  210. return;
  211. // Get a list of all subviews under Application.TopRunnable (and their subviews, etc.)
  212. // and subscribe to their DrawComplete event
  213. void SubscribeAllSubViews (View view)
  214. {
  215. view.DrawComplete += (s, a) => BenchmarkResults.DrawCompleteCount++;
  216. view.SubViewsLaidOut += (s, a) => BenchmarkResults.LaidOutCount++;
  217. foreach (View subview in view.SubViews)
  218. {
  219. SubscribeAllSubViews (subview);
  220. }
  221. }
  222. }
  223. // If the scenario doesn't close within the abort time, this will force it to quit
  224. private bool ForceCloseCallback ()
  225. {
  226. lock (_timeoutLock)
  227. {
  228. if (_timeout is { })
  229. {
  230. _timeout = null;
  231. }
  232. }
  233. Logging.Trace ($@" Failed to Quit with {Application.QuitKey} after {BenchmarkTimeout}ms and {BenchmarkResults.IterationCount} iterations. Force quit.");
  234. Application.RequestStop ();
  235. return false;
  236. }
  237. /// <summary>Gets the Scenario Name + Description with the Description padded based on the longest known Scenario name.</summary>
  238. /// <returns></returns>
  239. public override string ToString () { return $"{GetName ().PadRight (_maxScenarioNameLen)}{GetDescription ()}"; }
  240. #region IDispose
  241. public void Dispose ()
  242. {
  243. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  244. Dispose (true);
  245. GC.SuppressFinalize (this);
  246. }
  247. protected virtual void Dispose (bool disposing)
  248. {
  249. if (!_disposedValue)
  250. {
  251. if (disposing)
  252. { }
  253. _disposedValue = true;
  254. }
  255. }
  256. #endregion IDispose
  257. /// <summary>Returns a list of all Categories set by all of the <see cref="Scenario"/>s defined in the project.</summary>
  258. internal static ObservableCollection<string> GetAllCategories ()
  259. {
  260. List<string> aCategories = [];
  261. aCategories = typeof (Scenario).Assembly.GetTypes ()
  262. .Where (
  263. myType => myType is { IsClass: true, IsAbstract: false }
  264. && myType.IsSubclassOf (typeof (Scenario)))
  265. .Select (type => System.Attribute.GetCustomAttributes (type).ToList ())
  266. .Aggregate (
  267. aCategories,
  268. (current, attrs) => current
  269. .Union (
  270. attrs.Where (a => a is ScenarioCategory)
  271. .Select (a => ((ScenarioCategory)a).Name))
  272. .ToList ());
  273. // Sort
  274. ObservableCollection<string> categories = new (aCategories.OrderBy (c => c).ToList ());
  275. // Put "All" at the top
  276. categories.Insert (0, "All Scenarios");
  277. return categories;
  278. }
  279. public virtual List<Key> GetDemoKeyStrokes () => new List<Key> ();
  280. }