Scenario.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 string TopLevelColorScheme { get; set; } = "Base";
  86. public BenchmarkResults BenchmarkResults
  87. {
  88. get { return _benchmarkResults; }
  89. }
  90. private bool _disposedValue;
  91. /// <summary>
  92. /// Helper function to get the list of categories a <see cref="Scenario"/> belongs to (defined in
  93. /// <see cref="ScenarioCategory"/>)
  94. /// </summary>
  95. /// <returns>list of category names</returns>
  96. public List<string> GetCategories () { return ScenarioCategory.GetCategories (GetType ()); }
  97. /// <summary>Helper to get the <see cref="Scenario"/> Description (defined in <see cref="ScenarioMetadata"/>)</summary>
  98. /// <returns></returns>
  99. public string GetDescription () { return ScenarioMetadata.GetDescription (GetType ()); }
  100. /// <summary>Helper to get the <see cref="Scenario"/> Name (defined in <see cref="ScenarioMetadata"/>)</summary>
  101. /// <returns></returns>
  102. public string GetName () { return ScenarioMetadata.GetName (GetType ()); }
  103. /// <summary>
  104. /// Helper to get the <see cref="Application.QuitKey"/> and the <see cref="Scenario"/> Name (defined in
  105. /// <see cref="ScenarioMetadata"/>)
  106. /// </summary>
  107. /// <returns></returns>
  108. public string GetQuitKeyAndName () { return $"{Application.QuitKey} to Quit - Scenario: {GetName ()}"; }
  109. /// <summary>
  110. /// Returns a list of all <see cref="Scenario"/> instanaces defined in the project, sorted by
  111. /// <see cref="ScenarioMetadata.Name"/>.
  112. /// https://stackoverflow.com/questions/5411694/get-all-inherited-classes-of-an-abstract-class
  113. /// </summary>
  114. public static ObservableCollection<Scenario> GetScenarios ()
  115. {
  116. List<Scenario> objects = [];
  117. foreach (Type type in typeof (Scenario).Assembly.ExportedTypes
  118. .Where (
  119. myType => myType is { IsClass: true, IsAbstract: false }
  120. && myType.IsSubclassOf (typeof (Scenario))
  121. ))
  122. {
  123. if (Activator.CreateInstance (type) is not Scenario { } scenario)
  124. {
  125. continue;
  126. }
  127. objects.Add (scenario);
  128. _maxScenarioNameLen = Math.Max (_maxScenarioNameLen, scenario.GetName ().Length + 1);
  129. }
  130. return new (objects.OrderBy (s => s.GetName ()).ToList ());
  131. }
  132. /// <summary>
  133. /// Called by UI Catalog to run the <see cref="Scenario"/>. This is the main entry point for the <see cref="Scenario"/>
  134. /// .
  135. /// </summary>
  136. public virtual void Main () { }
  137. private const uint MAX_NATURAL_ITERATIONS = 500; // not including needed for demo keys
  138. private const uint ABORT_TIMEOUT_MS = 2500;
  139. private const int DEMO_KEY_PACING_MS = 1; // Must be non-zero
  140. private readonly object _timeoutLock = new ();
  141. private object? _timeout;
  142. private Stopwatch? _stopwatch;
  143. private readonly BenchmarkResults _benchmarkResults = new BenchmarkResults ();
  144. public void StartBenchmark ()
  145. {
  146. BenchmarkResults.Scenario = GetName ();
  147. Application.InitializedChanged += OnApplicationOnInitializedChanged;
  148. }
  149. public BenchmarkResults EndBenchmark ()
  150. {
  151. Application.InitializedChanged -= OnApplicationOnInitializedChanged;
  152. lock (_timeoutLock)
  153. {
  154. if (_timeout is { })
  155. {
  156. _timeout = null;
  157. }
  158. }
  159. return _benchmarkResults;
  160. }
  161. private List<Key> _demoKeys;
  162. private int _currentDemoKey = 0;
  163. private void OnApplicationOnInitializedChanged (object? s, EventArgs<bool> a)
  164. {
  165. if (a.CurrentValue)
  166. {
  167. lock (_timeoutLock!)
  168. {
  169. _timeout = Application.AddTimeout (TimeSpan.FromMilliseconds (ABORT_TIMEOUT_MS), ForceCloseCallback);
  170. }
  171. Application.Iteration += OnApplicationOnIteration;
  172. Application.Driver!.ClearedContents += (sender, args) => BenchmarkResults.ClearedContentCount++;
  173. Application.Driver!.Refreshed += (sender, args) =>
  174. {
  175. BenchmarkResults.RefreshedCount++;
  176. if (args.CurrentValue)
  177. {
  178. BenchmarkResults.UpdatedCount++;
  179. }
  180. };
  181. Application.NotifyNewRunState += OnApplicationNotifyNewRunState;
  182. _stopwatch = Stopwatch.StartNew ();
  183. }
  184. else
  185. {
  186. Application.NotifyNewRunState -= OnApplicationNotifyNewRunState;
  187. Application.Iteration -= OnApplicationOnIteration;
  188. BenchmarkResults.Duration = _stopwatch!.Elapsed;
  189. _stopwatch?.Stop ();
  190. }
  191. }
  192. private void OnApplicationOnIteration (object? s, IterationEventArgs a)
  193. {
  194. BenchmarkResults.IterationCount++;
  195. if (BenchmarkResults.IterationCount > MAX_NATURAL_ITERATIONS + (_demoKeys.Count* DEMO_KEY_PACING_MS))
  196. {
  197. Application.RequestStop ();
  198. }
  199. }
  200. private void OnApplicationNotifyNewRunState (object? sender, RunStateEventArgs e)
  201. {
  202. // Get a list of all subviews under Application.Top (and their subviews, etc.)
  203. // and subscribe to their DrawComplete event
  204. void SubscribeAllSubviews (View view)
  205. {
  206. view.DrawComplete += (s, a) => BenchmarkResults.DrawCompleteCount++;
  207. view.SubviewsLaidOut += (s, a) => BenchmarkResults.LaidOutCount++;
  208. foreach (View subview in view.Subviews)
  209. {
  210. SubscribeAllSubviews (subview);
  211. }
  212. }
  213. SubscribeAllSubviews (Application.Top!);
  214. _currentDemoKey = 0;
  215. _demoKeys = GetDemoKeyStrokes ();
  216. Application.AddTimeout (
  217. new TimeSpan (0, 0, 0, 0, DEMO_KEY_PACING_MS),
  218. () =>
  219. {
  220. if (_currentDemoKey >= _demoKeys.Count)
  221. {
  222. return false;
  223. }
  224. Application.RaiseKeyDownEvent (_demoKeys [_currentDemoKey++]);
  225. return true;
  226. });
  227. }
  228. // If the scenario doesn't close within the abort time, this will force it to quit
  229. private bool ForceCloseCallback ()
  230. {
  231. lock (_timeoutLock)
  232. {
  233. if (_timeout is { })
  234. {
  235. _timeout = null;
  236. }
  237. }
  238. Debug.WriteLine ($@" Failed to Quit with {Application.QuitKey} after {ABORT_TIMEOUT_MS}ms and {BenchmarkResults.IterationCount} iterations. Force quit.");
  239. Application.RequestStop ();
  240. return false;
  241. }
  242. /// <summary>Gets the Scenario Name + Description with the Description padded based on the longest known Scenario name.</summary>
  243. /// <returns></returns>
  244. public override string ToString () { return $"{GetName ().PadRight (_maxScenarioNameLen)}{GetDescription ()}"; }
  245. #region IDispose
  246. public void Dispose ()
  247. {
  248. // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
  249. Dispose (true);
  250. GC.SuppressFinalize (this);
  251. }
  252. protected virtual void Dispose (bool disposing)
  253. {
  254. if (!_disposedValue)
  255. {
  256. if (disposing)
  257. { }
  258. _disposedValue = true;
  259. }
  260. }
  261. #endregion IDispose
  262. /// <summary>Returns a list of all Categories set by all of the <see cref="Scenario"/>s defined in the project.</summary>
  263. internal static ObservableCollection<string> GetAllCategories ()
  264. {
  265. List<string> aCategories = [];
  266. aCategories = typeof (Scenario).Assembly.GetTypes ()
  267. .Where (
  268. myType => myType is { IsClass: true, IsAbstract: false }
  269. && myType.IsSubclassOf (typeof (Scenario)))
  270. .Select (type => System.Attribute.GetCustomAttributes (type).ToList ())
  271. .Aggregate (
  272. aCategories,
  273. (current, attrs) => current
  274. .Union (
  275. attrs.Where (a => a is ScenarioCategory)
  276. .Select (a => ((ScenarioCategory)a).Name))
  277. .ToList ());
  278. // Sort
  279. ObservableCollection<string> categories = new (aCategories.OrderBy (c => c).ToList ());
  280. // Put "All" at the top
  281. categories.Insert (0, "All Scenarios");
  282. return categories;
  283. }
  284. public virtual List<Key> GetDemoKeyStrokes () => new List<Key> ();
  285. }