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