UICatalog.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. global using Attribute = Terminal.Gui.Drawing.Attribute;
  2. global using Color = Terminal.Gui.Drawing.Color;
  3. global using CM = Terminal.Gui.Configuration.ConfigurationManager;
  4. global using Terminal.Gui.App;
  5. global using Terminal.Gui.ViewBase;
  6. global using Terminal.Gui.Drivers;
  7. global using Terminal.Gui.Input;
  8. global using Terminal.Gui.Configuration;
  9. global using Terminal.Gui.Views;
  10. global using Terminal.Gui.Drawing;
  11. global using Terminal.Gui.Text;
  12. global using Terminal.Gui.FileServices;
  13. using System.CommandLine;
  14. using System.CommandLine.Builder;
  15. using System.CommandLine.Parsing;
  16. using System.Data;
  17. using System.Diagnostics;
  18. using System.Diagnostics.CodeAnalysis;
  19. using System.Globalization;
  20. using System.Reflection;
  21. using System.Reflection.Metadata;
  22. using System.Text;
  23. using System.Text.Json;
  24. using Microsoft.Extensions.Logging;
  25. using Serilog;
  26. using Serilog.Core;
  27. using Serilog.Events;
  28. using Command = Terminal.Gui.Input.Command;
  29. using ILogger = Microsoft.Extensions.Logging.ILogger;
  30. #nullable enable
  31. namespace UICatalog;
  32. /// <summary>
  33. /// UI Catalog is a comprehensive sample library and test app for Terminal.Gui. It provides a simple UI for adding to
  34. /// the
  35. /// catalog of scenarios.
  36. /// </summary>
  37. /// <remarks>
  38. /// <para>UI Catalog attempts to satisfy the following goals:</para>
  39. /// <para>
  40. /// <list type="number">
  41. /// <item>
  42. /// <description>Be an easy-to-use showcase for Terminal.Gui concepts and features.</description>
  43. /// </item>
  44. /// <item>
  45. /// <description>Provide sample code that illustrates how to properly implement said concepts & features.</description>
  46. /// </item>
  47. /// <item>
  48. /// <description>Make it easy for contributors to add additional samples in a structured way.</description>
  49. /// </item>
  50. /// </list>
  51. /// </para>
  52. /// </remarks>
  53. public class UICatalog
  54. {
  55. private static string? _forceDriver = null;
  56. public static string LogFilePath { get; set; } = string.Empty;
  57. public static LoggingLevelSwitch LogLevelSwitch { get; } = new ();
  58. public const string LOGFILE_LOCATION = "logs";
  59. public static UICatalogCommandLineOptions Options { get; set; }
  60. private static int Main (string [] args)
  61. {
  62. Console.OutputEncoding = Encoding.Default;
  63. if (Debugger.IsAttached)
  64. {
  65. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  66. }
  67. UICatalogTop.CachedScenarios = Scenario.GetScenarios ();
  68. UICatalogTop.CachedCategories = Scenario.GetAllCategories ();
  69. // Process command line args
  70. // If no driver is provided, the default driver is used.
  71. // Get allowed driver names
  72. string? [] allowedDrivers = Application.GetDriverTypes ().Item2.ToArray ();
  73. Option<string> driverOption = new Option<string> ("--driver", "The IDriver to use.")
  74. .FromAmong (allowedDrivers!);
  75. driverOption.SetDefaultValue (string.Empty);
  76. driverOption.AddAlias ("-d");
  77. driverOption.AddAlias ("--d");
  78. // Add validator separately (not chained)
  79. driverOption.AddValidator (result =>
  80. {
  81. var value = result.GetValueOrDefault<string> ();
  82. if (result.Tokens.Count > 0 && !allowedDrivers.Contains (value))
  83. {
  84. result.ErrorMessage = $"Invalid driver name '{value}'. Allowed values: {string.Join (", ", allowedDrivers)}";
  85. }
  86. });
  87. // Configuration Management
  88. Option<bool> disableConfigManagement = new (
  89. "--disable-cm",
  90. "Indicates Configuration Management should not be enabled. Only `ConfigLocations.HardCoded` settings will be loaded.");
  91. disableConfigManagement.AddAlias ("-dcm");
  92. disableConfigManagement.AddAlias ("--dcm");
  93. Option<bool> benchmarkFlag = new ("--benchmark", "Enables benchmarking. If a Scenario is specified, just that Scenario will be benchmarked.");
  94. benchmarkFlag.AddAlias ("-b");
  95. benchmarkFlag.AddAlias ("--b");
  96. Option<uint> benchmarkTimeout = new (
  97. "--timeout",
  98. () => Scenario.BenchmarkTimeout,
  99. $"The maximum time in milliseconds to run a benchmark for. Default is {Scenario.BenchmarkTimeout}ms.");
  100. benchmarkTimeout.AddAlias ("-t");
  101. benchmarkTimeout.AddAlias ("--t");
  102. Option<string> resultsFile = new ("--file", "The file to save benchmark results to. If not specified, the results will be displayed in a TableView.");
  103. resultsFile.AddAlias ("-f");
  104. resultsFile.AddAlias ("--f");
  105. // what's the app name?
  106. LogFilePath = $"{LOGFILE_LOCATION}/{Assembly.GetExecutingAssembly ().GetName ().Name}";
  107. Option<string> debugLogLevel = new Option<string> ("--debug-log-level", $"The level to use for logging (debug console and {LogFilePath})").FromAmong (
  108. Enum.GetNames<LogLevel> ()
  109. );
  110. debugLogLevel.SetDefaultValue ("Warning");
  111. debugLogLevel.AddAlias ("-dl");
  112. debugLogLevel.AddAlias ("--dl");
  113. Argument<string> scenarioArgument = new Argument<string> (
  114. "scenario",
  115. description:
  116. "The name of the Scenario to run. If not provided, the UI Catalog UI will be shown.",
  117. getDefaultValue: () => "none"
  118. ).FromAmong (
  119. UICatalogTop.CachedScenarios.Select (s => s.GetName ())
  120. .Append ("none")
  121. .ToArray ()
  122. );
  123. var rootCommand = new RootCommand ("A comprehensive sample library and test app for Terminal.Gui")
  124. {
  125. scenarioArgument, debugLogLevel, benchmarkFlag, benchmarkTimeout, resultsFile, driverOption, disableConfigManagement
  126. };
  127. rootCommand.SetHandler (
  128. context =>
  129. {
  130. var options = new UICatalogCommandLineOptions
  131. {
  132. Scenario = context.ParseResult.GetValueForArgument (scenarioArgument),
  133. Driver = context.ParseResult.GetValueForOption (driverOption) ?? string.Empty,
  134. DontEnableConfigurationManagement = context.ParseResult.GetValueForOption (disableConfigManagement),
  135. Benchmark = context.ParseResult.GetValueForOption (benchmarkFlag),
  136. BenchmarkTimeout = context.ParseResult.GetValueForOption (benchmarkTimeout),
  137. ResultsFile = context.ParseResult.GetValueForOption (resultsFile) ?? string.Empty,
  138. DebugLogLevel = context.ParseResult.GetValueForOption (debugLogLevel) ?? "Warning"
  139. /* etc. */
  140. };
  141. // See https://github.com/dotnet/command-line-api/issues/796 for the rationale behind this hackery
  142. Options = options;
  143. }
  144. );
  145. var helpShown = false;
  146. Parser parser = new CommandLineBuilder (rootCommand)
  147. .UseHelp (ctx => helpShown = true)
  148. .Build ();
  149. parser.Invoke (args);
  150. if (helpShown)
  151. {
  152. return 0;
  153. }
  154. var parseResult = parser.Parse (args);
  155. if (parseResult.Errors.Count > 0)
  156. {
  157. foreach (var error in parseResult.Errors)
  158. {
  159. Console.Error.WriteLine (error.Message);
  160. }
  161. return 1; // Non-zero exit code for error
  162. }
  163. Scenario.BenchmarkTimeout = Options.BenchmarkTimeout;
  164. Logging.Logger = CreateLogger ();
  165. UICatalogMain (Options);
  166. return 0;
  167. }
  168. public static LogEventLevel LogLevelToLogEventLevel (LogLevel logLevel)
  169. {
  170. return logLevel switch
  171. {
  172. LogLevel.Trace => LogEventLevel.Verbose,
  173. LogLevel.Debug => LogEventLevel.Debug,
  174. LogLevel.Information => LogEventLevel.Information,
  175. LogLevel.Warning => LogEventLevel.Warning,
  176. LogLevel.Error => LogEventLevel.Error,
  177. LogLevel.Critical => LogEventLevel.Fatal,
  178. LogLevel.None => LogEventLevel.Fatal, // Default to Fatal if None is specified
  179. _ => LogEventLevel.Fatal // Default to Information for any unspecified LogLevel
  180. };
  181. }
  182. private static ILogger CreateLogger ()
  183. {
  184. // Configure Serilog to write logs to a file
  185. LogLevelSwitch.MinimumLevel = LogLevelToLogEventLevel (Enum.Parse<LogLevel> (Options.DebugLogLevel));
  186. Log.Logger = new LoggerConfiguration ()
  187. .MinimumLevel.ControlledBy (LogLevelSwitch)
  188. .Enrich.FromLogContext () // Enables dynamic enrichment
  189. .WriteTo.Debug ()
  190. .WriteTo.File (
  191. LogFilePath,
  192. rollingInterval: RollingInterval.Day,
  193. outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  194. .CreateLogger ();
  195. // Create a logger factory compatible with Microsoft.Extensions.Logging
  196. using ILoggerFactory loggerFactory = LoggerFactory.Create (
  197. builder =>
  198. {
  199. builder
  200. .AddSerilog (dispose: true) // Integrate Serilog with ILogger
  201. .SetMinimumLevel (LogLevel.Trace); // Set minimum log level
  202. });
  203. // Get an ILogger instance
  204. return loggerFactory.CreateLogger ("Global Logger");
  205. }
  206. /// <summary>
  207. /// Shows the UI Catalog selection UI. When the user selects a Scenario to run, the UI Catalog main app UI is
  208. /// killed and the Scenario is run as though it were Application.Top. When the Scenario exits, this function exits.
  209. /// </summary>
  210. /// <returns></returns>
  211. private static Scenario RunUICatalogTopLevel ()
  212. {
  213. // Run UI Catalog UI. When it exits, if _selectedScenario is != null then
  214. // a Scenario was selected. Otherwise, the user wants to quit UI Catalog.
  215. // If the user specified a driver on the command line then use it,
  216. // ignoring Config files.
  217. Application.Init (driverName: _forceDriver);
  218. var top = Application.Run<UICatalogTop> ();
  219. top.Dispose ();
  220. Application.Shutdown ();
  221. VerifyObjectsWereDisposed ();
  222. return UICatalogTop.CachedSelectedScenario!;
  223. }
  224. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  225. private static readonly FileSystemWatcher _currentDirWatcher = new ();
  226. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  227. private static readonly FileSystemWatcher _homeDirWatcher = new ();
  228. private static void StartConfigFileWatcher ()
  229. {
  230. // Set up a file system watcher for `./.tui/`
  231. _currentDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
  232. string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
  233. string tuiDir;
  234. if (!string.IsNullOrEmpty (assemblyLocation))
  235. {
  236. var assemblyFile = new FileInfo (assemblyLocation);
  237. tuiDir = Path.Combine (assemblyFile.Directory!.FullName, ".tui");
  238. }
  239. else
  240. {
  241. tuiDir = Path.Combine (AppContext.BaseDirectory, ".tui");
  242. }
  243. if (!Directory.Exists (tuiDir))
  244. {
  245. Directory.CreateDirectory (tuiDir);
  246. }
  247. _currentDirWatcher.Path = tuiDir;
  248. _currentDirWatcher.Filter = "*config.json";
  249. // Set up a file system watcher for `~/.tui/`
  250. _homeDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
  251. var f = new FileInfo (Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  252. tuiDir = Path.Combine (f.FullName, ".tui");
  253. if (!Directory.Exists (tuiDir))
  254. {
  255. Directory.CreateDirectory (tuiDir);
  256. }
  257. _homeDirWatcher.Path = tuiDir;
  258. _homeDirWatcher.Filter = "*config.json";
  259. _currentDirWatcher.Changed += ConfigFileChanged;
  260. //_currentDirWatcher.Created += ConfigFileChanged;
  261. _currentDirWatcher.EnableRaisingEvents = true;
  262. _homeDirWatcher.Changed += ConfigFileChanged;
  263. //_homeDirWatcher.Created += ConfigFileChanged;
  264. _homeDirWatcher.EnableRaisingEvents = true;
  265. }
  266. private static void StopConfigFileWatcher ()
  267. {
  268. _currentDirWatcher.EnableRaisingEvents = false;
  269. _currentDirWatcher.Changed -= ConfigFileChanged;
  270. _currentDirWatcher.Created -= ConfigFileChanged;
  271. _homeDirWatcher.EnableRaisingEvents = false;
  272. _homeDirWatcher.Changed -= ConfigFileChanged;
  273. _homeDirWatcher.Created -= ConfigFileChanged;
  274. }
  275. private static void ConfigFileChanged (object sender, FileSystemEventArgs e)
  276. {
  277. if (Application.Top == null)
  278. {
  279. return;
  280. }
  281. Logging.Debug ($"{e.FullPath} {e.ChangeType} - Loading and Applying");
  282. ConfigurationManager.Load (ConfigLocations.All);
  283. ConfigurationManager.Apply ();
  284. }
  285. private static void UICatalogMain (UICatalogCommandLineOptions options)
  286. {
  287. // By setting _forceDriver we ensure that if the user has specified a driver on the command line, it will be used
  288. // regardless of what's in a config file.
  289. _forceDriver = options.Driver;
  290. // If a driver has been specified, set it in RuntimeConfig so it persists through Init/Shutdown cycles
  291. if (!string.IsNullOrEmpty (_forceDriver))
  292. {
  293. ConfigurationManager.RuntimeConfig = $$"""
  294. {
  295. "Application.ForceDriver": "{{_forceDriver}}"
  296. }
  297. """;
  298. }
  299. // If a Scenario name has been provided on the commandline
  300. // run it and exit when done.
  301. if (options.Scenario != "none")
  302. {
  303. if (!Options.DontEnableConfigurationManagement)
  304. {
  305. ConfigurationManager.Enable (ConfigLocations.All);
  306. }
  307. int item = UICatalogTop.CachedScenarios!.IndexOf (
  308. UICatalogTop.CachedScenarios!.FirstOrDefault (
  309. s =>
  310. s.GetName ()
  311. .Equals (options.Scenario, StringComparison.OrdinalIgnoreCase)
  312. )!);
  313. UICatalogTop.CachedSelectedScenario = (Scenario)Activator.CreateInstance (UICatalogTop.CachedScenarios [item].GetType ())!;
  314. BenchmarkResults? results = RunScenario (UICatalogTop.CachedSelectedScenario, options.Benchmark);
  315. if (results is { })
  316. {
  317. Console.WriteLine (
  318. JsonSerializer.Serialize (
  319. results,
  320. new JsonSerializerOptions
  321. {
  322. WriteIndented = true
  323. }));
  324. }
  325. VerifyObjectsWereDisposed ();
  326. return;
  327. }
  328. // Benchmark all Scenarios
  329. if (options.Benchmark)
  330. {
  331. BenchmarkAllScenarios ();
  332. return;
  333. }
  334. #if DEBUG_IDISPOSABLE
  335. View.EnableDebugIDisposableAsserts = true;
  336. #endif
  337. if (!Options.DontEnableConfigurationManagement)
  338. {
  339. ConfigurationManager.Enable (ConfigLocations.All);
  340. StartConfigFileWatcher ();
  341. }
  342. while (RunUICatalogTopLevel () is { } scenario)
  343. {
  344. #if DEBUG_IDISPOSABLE
  345. VerifyObjectsWereDisposed ();
  346. // Measure how long it takes for the app to shut down
  347. var sw = new Stopwatch ();
  348. string scenarioName = scenario.GetName ();
  349. Application.InitializedChanged += ApplicationOnInitializedChanged;
  350. #endif
  351. // Ensure RuntimeConfig is applied before each scenario to preserve ForceDriver setting
  352. if (!Options.DontEnableConfigurationManagement && !string.IsNullOrEmpty (_forceDriver))
  353. {
  354. ConfigurationManager.Load (ConfigLocations.Runtime);
  355. ConfigurationManager.Apply ();
  356. }
  357. scenario.Main ();
  358. scenario.Dispose ();
  359. // This call to Application.Shutdown brackets the Application.Init call
  360. // made by Scenario.Init() above
  361. // TODO: Throw if shutdown was not called already
  362. Application.Shutdown ();
  363. VerifyObjectsWereDisposed ();
  364. #if DEBUG_IDISPOSABLE
  365. Application.InitializedChanged -= ApplicationOnInitializedChanged;
  366. void ApplicationOnInitializedChanged (object? sender, EventArgs<bool> e)
  367. {
  368. if (e.Value)
  369. {
  370. sw.Start ();
  371. }
  372. else
  373. {
  374. sw.Stop ();
  375. Logging.Trace ($"Shutdown of {scenarioName} Scenario took {sw.ElapsedMilliseconds}ms");
  376. }
  377. }
  378. #endif
  379. }
  380. StopConfigFileWatcher ();
  381. VerifyObjectsWereDisposed ();
  382. }
  383. private static BenchmarkResults? RunScenario (Scenario scenario, bool benchmark)
  384. {
  385. if (benchmark)
  386. {
  387. scenario.StartBenchmark ();
  388. }
  389. scenario.Main ();
  390. BenchmarkResults? results = null;
  391. if (benchmark)
  392. {
  393. results = scenario.EndBenchmark ();
  394. }
  395. scenario.Dispose ();
  396. // TODO: Throw if shutdown was not called already
  397. Application.Shutdown ();
  398. return results;
  399. }
  400. private static void BenchmarkAllScenarios ()
  401. {
  402. List<BenchmarkResults> resultsList = [];
  403. var maxScenarios = 5;
  404. foreach (Scenario s in UICatalogTop.CachedScenarios!)
  405. {
  406. resultsList.Add (RunScenario (s, true)!);
  407. maxScenarios--;
  408. if (maxScenarios == 0)
  409. {
  410. // break;
  411. }
  412. }
  413. if (resultsList.Count <= 0)
  414. {
  415. return;
  416. }
  417. if (!string.IsNullOrEmpty (Options.ResultsFile))
  418. {
  419. string output = JsonSerializer.Serialize (
  420. resultsList,
  421. new JsonSerializerOptions
  422. {
  423. WriteIndented = true
  424. });
  425. using StreamWriter file = File.CreateText (Options.ResultsFile);
  426. file.Write (output);
  427. file.Close ();
  428. return;
  429. }
  430. Application.Init ();
  431. var benchmarkWindow = new Window
  432. {
  433. Title = "Benchmark Results"
  434. };
  435. if (benchmarkWindow.Border is { })
  436. {
  437. benchmarkWindow.Border!.Thickness = new (0, 0, 0, 0);
  438. }
  439. TableView resultsTableView = new ()
  440. {
  441. Width = Dim.Fill (),
  442. Height = Dim.Fill ()
  443. };
  444. // TableView provides many options for table headers. For simplicity we turn all
  445. // of these off. By enabling FullRowSelect and turning off headers, TableView looks just
  446. // like a ListView
  447. resultsTableView.FullRowSelect = true;
  448. resultsTableView.Style.ShowHeaders = true;
  449. resultsTableView.Style.ShowHorizontalHeaderOverline = false;
  450. resultsTableView.Style.ShowHorizontalHeaderUnderline = true;
  451. resultsTableView.Style.ShowHorizontalBottomline = false;
  452. resultsTableView.Style.ShowVerticalCellLines = true;
  453. resultsTableView.Style.ShowVerticalHeaderLines = true;
  454. /* By default, TableView lays out columns at render time and only
  455. * measures y rows of data at a time. Where y is the height of the
  456. * console. This is for the following reasons:
  457. *
  458. * - Performance, when tables have a large amount of data
  459. * - Defensive, prevents a single wide cell value pushing other
  460. * columns off-screen (requiring horizontal scrolling
  461. *
  462. * In the case of UICatalog here, such an approach is overkill so
  463. * we just measure all the data ourselves and set the appropriate
  464. * max widths as ColumnStyles
  465. */
  466. //int longestName = _scenarios!.Max (s => s.GetName ().Length);
  467. //resultsTableView.Style.ColumnStyles.Add (
  468. // 0,
  469. // new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  470. // );
  471. //resultsTableView.Style.ColumnStyles.Add (1, new () { MaxWidth = 1 });
  472. //resultsTableView.CellActivated += ScenarioView_OpenSelectedItem;
  473. // TableView typically is a grid where nav keys are biased for moving left/right.
  474. resultsTableView.KeyBindings.Remove (Key.Home);
  475. resultsTableView.KeyBindings.Add (Key.Home, Command.Start);
  476. resultsTableView.KeyBindings.Remove (Key.End);
  477. resultsTableView.KeyBindings.Add (Key.End, Command.End);
  478. // Ideally, TableView.MultiSelect = false would turn off any keybindings for
  479. // multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
  480. // a shortcut to About.
  481. resultsTableView.MultiSelect = false;
  482. var dt = new DataTable ();
  483. dt.Columns.Add (new DataColumn ("Scenario", typeof (string)));
  484. dt.Columns.Add (new DataColumn ("Duration", typeof (TimeSpan)));
  485. dt.Columns.Add (new DataColumn ("Refreshed", typeof (int)));
  486. dt.Columns.Add (new DataColumn ("LaidOut", typeof (int)));
  487. dt.Columns.Add (new DataColumn ("ClearedContent", typeof (int)));
  488. dt.Columns.Add (new DataColumn ("DrawComplete", typeof (int)));
  489. dt.Columns.Add (new DataColumn ("Updated", typeof (int)));
  490. dt.Columns.Add (new DataColumn ("Iterations", typeof (int)));
  491. foreach (BenchmarkResults r in resultsList)
  492. {
  493. dt.Rows.Add (
  494. r.Scenario,
  495. r.Duration,
  496. r.RefreshedCount,
  497. r.LaidOutCount,
  498. r.ClearedContentCount,
  499. r.DrawCompleteCount,
  500. r.UpdatedCount,
  501. r.IterationCount
  502. );
  503. }
  504. BenchmarkResults totalRow = new ()
  505. {
  506. Scenario = "TOTAL",
  507. Duration = new (resultsList.Sum (r => r.Duration.Ticks)),
  508. RefreshedCount = resultsList.Sum (r => r.RefreshedCount),
  509. LaidOutCount = resultsList.Sum (r => r.LaidOutCount),
  510. ClearedContentCount = resultsList.Sum (r => r.ClearedContentCount),
  511. DrawCompleteCount = resultsList.Sum (r => r.DrawCompleteCount),
  512. UpdatedCount = resultsList.Sum (r => r.UpdatedCount),
  513. IterationCount = resultsList.Sum (r => r.IterationCount)
  514. };
  515. dt.Rows.Add (
  516. totalRow.Scenario,
  517. totalRow.Duration,
  518. totalRow.RefreshedCount,
  519. totalRow.LaidOutCount,
  520. totalRow.ClearedContentCount,
  521. totalRow.DrawCompleteCount,
  522. totalRow.UpdatedCount,
  523. totalRow.IterationCount
  524. );
  525. dt.DefaultView.Sort = "Duration";
  526. DataTable sortedCopy = dt.DefaultView.ToTable ();
  527. resultsTableView.Table = new DataTableSource (sortedCopy);
  528. benchmarkWindow.Add (resultsTableView);
  529. Application.Run (benchmarkWindow);
  530. benchmarkWindow.Dispose ();
  531. Application.Shutdown ();
  532. }
  533. private static void VerifyObjectsWereDisposed ()
  534. {
  535. #if DEBUG_IDISPOSABLE
  536. if (!View.EnableDebugIDisposableAsserts)
  537. {
  538. View.Instances.Clear ();
  539. SessionToken.Instances.Clear ();
  540. return;
  541. }
  542. // Validate there are no outstanding View instances
  543. // after a scenario was selected to run. This proves the main UI Catalog
  544. // 'app' closed cleanly.
  545. foreach (View? inst in View.Instances)
  546. {
  547. Debug.Assert (inst.WasDisposed);
  548. }
  549. View.Instances.Clear ();
  550. // Validate there are no outstanding Application sessions
  551. // after a scenario was selected to run. This proves the main UI Catalog
  552. // 'app' closed cleanly.
  553. foreach (SessionToken? inst in SessionToken.Instances)
  554. {
  555. Debug.Assert (inst.WasDisposed);
  556. }
  557. SessionToken.Instances.Clear ();
  558. #endif
  559. }
  560. }