Scenario.cs 12 KB

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