UICatalog.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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.Current. 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 StartConfigWatcher ()
  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. ThemeManager.ThemeChanged += ThemeManagerOnThemeChanged;
  266. }
  267. private static void ThemeManagerOnThemeChanged (object? sender, EventArgs<string> e)
  268. {
  269. CM.Apply ();
  270. }
  271. private static void StopConfigWatcher ()
  272. {
  273. ThemeManager.ThemeChanged += ThemeManagerOnThemeChanged;
  274. _currentDirWatcher.EnableRaisingEvents = false;
  275. _currentDirWatcher.Changed -= ConfigFileChanged;
  276. _currentDirWatcher.Created -= ConfigFileChanged;
  277. _homeDirWatcher.EnableRaisingEvents = false;
  278. _homeDirWatcher.Changed -= ConfigFileChanged;
  279. _homeDirWatcher.Created -= ConfigFileChanged;
  280. }
  281. private static void ConfigFileChanged (object sender, FileSystemEventArgs e)
  282. {
  283. if (Application.Current == null)
  284. {
  285. return;
  286. }
  287. Logging.Debug ($"{e.FullPath} {e.ChangeType} - Loading and Applying");
  288. ConfigurationManager.Load (ConfigLocations.All);
  289. ConfigurationManager.Apply ();
  290. }
  291. private static void UICatalogMain (UICatalogCommandLineOptions options)
  292. {
  293. // By setting _forceDriver we ensure that if the user has specified a driver on the command line, it will be used
  294. // regardless of what's in a config file.
  295. Application.ForceDriver = _forceDriver = options.Driver;
  296. // If a Scenario name has been provided on the commandline
  297. // run it and exit when done.
  298. if (options.Scenario != "none")
  299. {
  300. if (!Options.DontEnableConfigurationManagement)
  301. {
  302. ConfigurationManager.Enable (ConfigLocations.All);
  303. }
  304. int item = UICatalogTop.CachedScenarios!.IndexOf (
  305. UICatalogTop.CachedScenarios!.FirstOrDefault (
  306. s =>
  307. s.GetName ()
  308. .Equals (options.Scenario, StringComparison.OrdinalIgnoreCase)
  309. )!);
  310. UICatalogTop.CachedSelectedScenario = (Scenario)Activator.CreateInstance (UICatalogTop.CachedScenarios [item].GetType ())!;
  311. BenchmarkResults? results = RunScenario (UICatalogTop.CachedSelectedScenario, options.Benchmark);
  312. if (results is { })
  313. {
  314. Console.WriteLine (
  315. JsonSerializer.Serialize (
  316. results,
  317. new JsonSerializerOptions
  318. {
  319. WriteIndented = true
  320. }));
  321. }
  322. VerifyObjectsWereDisposed ();
  323. return;
  324. }
  325. // Benchmark all Scenarios
  326. if (options.Benchmark)
  327. {
  328. BenchmarkAllScenarios ();
  329. return;
  330. }
  331. #if DEBUG_IDISPOSABLE
  332. View.EnableDebugIDisposableAsserts = true;
  333. #endif
  334. if (!Options.DontEnableConfigurationManagement)
  335. {
  336. ConfigurationManager.Enable (ConfigLocations.All);
  337. StartConfigWatcher ();
  338. }
  339. while (RunUICatalogTopLevel () is { } scenario)
  340. {
  341. #if DEBUG_IDISPOSABLE
  342. VerifyObjectsWereDisposed ();
  343. // Measure how long it takes for the app to shut down
  344. var sw = new Stopwatch ();
  345. string scenarioName = scenario.GetName ();
  346. Application.InitializedChanged += ApplicationOnInitializedChanged;
  347. #endif
  348. scenario.Main ();
  349. scenario.Dispose ();
  350. // This call to Application.Shutdown brackets the Application.Init call
  351. // made by Scenario.Init() above
  352. // TODO: Throw if shutdown was not called already
  353. Application.Shutdown ();
  354. VerifyObjectsWereDisposed ();
  355. #if DEBUG_IDISPOSABLE
  356. Application.InitializedChanged -= ApplicationOnInitializedChanged;
  357. void ApplicationOnInitializedChanged (object? sender, EventArgs<bool> e)
  358. {
  359. if (e.Value)
  360. {
  361. sw.Start ();
  362. }
  363. else
  364. {
  365. sw.Stop ();
  366. Logging.Trace ($"Shutdown of {scenarioName} Scenario took {sw.ElapsedMilliseconds}ms");
  367. }
  368. }
  369. #endif
  370. }
  371. StopConfigWatcher ();
  372. VerifyObjectsWereDisposed ();
  373. }
  374. private static BenchmarkResults? RunScenario (Scenario scenario, bool benchmark)
  375. {
  376. if (benchmark)
  377. {
  378. scenario.StartBenchmark ();
  379. }
  380. Application.ForceDriver = _forceDriver!;
  381. scenario.Main ();
  382. BenchmarkResults? results = null;
  383. if (benchmark)
  384. {
  385. results = scenario.EndBenchmark ();
  386. }
  387. scenario.Dispose ();
  388. // TODO: Throw if shutdown was not called already
  389. Application.Shutdown ();
  390. return results;
  391. }
  392. private static void BenchmarkAllScenarios ()
  393. {
  394. List<BenchmarkResults> resultsList = [];
  395. var maxScenarios = 5;
  396. foreach (Scenario s in UICatalogTop.CachedScenarios!)
  397. {
  398. resultsList.Add (RunScenario (s, true)!);
  399. maxScenarios--;
  400. if (maxScenarios == 0)
  401. {
  402. // break;
  403. }
  404. }
  405. if (resultsList.Count <= 0)
  406. {
  407. return;
  408. }
  409. if (!string.IsNullOrEmpty (Options.ResultsFile))
  410. {
  411. string output = JsonSerializer.Serialize (
  412. resultsList,
  413. new JsonSerializerOptions
  414. {
  415. WriteIndented = true
  416. });
  417. using StreamWriter file = File.CreateText (Options.ResultsFile);
  418. file.Write (output);
  419. file.Close ();
  420. return;
  421. }
  422. Application.Init ();
  423. var benchmarkWindow = new Window
  424. {
  425. Title = "Benchmark Results"
  426. };
  427. if (benchmarkWindow.Border is { })
  428. {
  429. benchmarkWindow.Border!.Thickness = new (0, 0, 0, 0);
  430. }
  431. TableView resultsTableView = new ()
  432. {
  433. Width = Dim.Fill (),
  434. Height = Dim.Fill ()
  435. };
  436. // TableView provides many options for table headers. For simplicity we turn all
  437. // of these off. By enabling FullRowSelect and turning off headers, TableView looks just
  438. // like a ListView
  439. resultsTableView.FullRowSelect = true;
  440. resultsTableView.Style.ShowHeaders = true;
  441. resultsTableView.Style.ShowHorizontalHeaderOverline = false;
  442. resultsTableView.Style.ShowHorizontalHeaderUnderline = true;
  443. resultsTableView.Style.ShowHorizontalBottomline = false;
  444. resultsTableView.Style.ShowVerticalCellLines = true;
  445. resultsTableView.Style.ShowVerticalHeaderLines = true;
  446. /* By default, TableView lays out columns at render time and only
  447. * measures y rows of data at a time. Where y is the height of the
  448. * console. This is for the following reasons:
  449. *
  450. * - Performance, when tables have a large amount of data
  451. * - Defensive, prevents a single wide cell value pushing other
  452. * columns off-screen (requiring horizontal scrolling
  453. *
  454. * In the case of UICatalog here, such an approach is overkill so
  455. * we just measure all the data ourselves and set the appropriate
  456. * max widths as ColumnStyles
  457. */
  458. //int longestName = _scenarios!.Max (s => s.GetName ().Length);
  459. //resultsTableView.Style.ColumnStyles.Add (
  460. // 0,
  461. // new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  462. // );
  463. //resultsTableView.Style.ColumnStyles.Add (1, new () { MaxWidth = 1 });
  464. //resultsTableView.CellActivated += ScenarioView_OpenSelectedItem;
  465. // TableView typically is a grid where nav keys are biased for moving left/right.
  466. resultsTableView.KeyBindings.Remove (Key.Home);
  467. resultsTableView.KeyBindings.Add (Key.Home, Command.Start);
  468. resultsTableView.KeyBindings.Remove (Key.End);
  469. resultsTableView.KeyBindings.Add (Key.End, Command.End);
  470. // Ideally, TableView.MultiSelect = false would turn off any keybindings for
  471. // multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
  472. // a shortcut to About.
  473. resultsTableView.MultiSelect = false;
  474. var dt = new DataTable ();
  475. dt.Columns.Add (new DataColumn ("Scenario", typeof (string)));
  476. dt.Columns.Add (new DataColumn ("Duration", typeof (TimeSpan)));
  477. dt.Columns.Add (new DataColumn ("Refreshed", typeof (int)));
  478. dt.Columns.Add (new DataColumn ("LaidOut", typeof (int)));
  479. dt.Columns.Add (new DataColumn ("ClearedContent", typeof (int)));
  480. dt.Columns.Add (new DataColumn ("DrawComplete", typeof (int)));
  481. dt.Columns.Add (new DataColumn ("Updated", typeof (int)));
  482. dt.Columns.Add (new DataColumn ("Iterations", typeof (int)));
  483. foreach (BenchmarkResults r in resultsList)
  484. {
  485. dt.Rows.Add (
  486. r.Scenario,
  487. r.Duration,
  488. r.RefreshedCount,
  489. r.LaidOutCount,
  490. r.ClearedContentCount,
  491. r.DrawCompleteCount,
  492. r.UpdatedCount,
  493. r.IterationCount
  494. );
  495. }
  496. BenchmarkResults totalRow = new ()
  497. {
  498. Scenario = "TOTAL",
  499. Duration = new (resultsList.Sum (r => r.Duration.Ticks)),
  500. RefreshedCount = resultsList.Sum (r => r.RefreshedCount),
  501. LaidOutCount = resultsList.Sum (r => r.LaidOutCount),
  502. ClearedContentCount = resultsList.Sum (r => r.ClearedContentCount),
  503. DrawCompleteCount = resultsList.Sum (r => r.DrawCompleteCount),
  504. UpdatedCount = resultsList.Sum (r => r.UpdatedCount),
  505. IterationCount = resultsList.Sum (r => r.IterationCount)
  506. };
  507. dt.Rows.Add (
  508. totalRow.Scenario,
  509. totalRow.Duration,
  510. totalRow.RefreshedCount,
  511. totalRow.LaidOutCount,
  512. totalRow.ClearedContentCount,
  513. totalRow.DrawCompleteCount,
  514. totalRow.UpdatedCount,
  515. totalRow.IterationCount
  516. );
  517. dt.DefaultView.Sort = "Duration";
  518. DataTable sortedCopy = dt.DefaultView.ToTable ();
  519. resultsTableView.Table = new DataTableSource (sortedCopy);
  520. benchmarkWindow.Add (resultsTableView);
  521. Application.Run (benchmarkWindow);
  522. benchmarkWindow.Dispose ();
  523. Application.Shutdown ();
  524. }
  525. private static void VerifyObjectsWereDisposed ()
  526. {
  527. #if DEBUG_IDISPOSABLE
  528. if (!View.EnableDebugIDisposableAsserts)
  529. {
  530. View.Instances.Clear ();
  531. SessionToken.Instances.Clear ();
  532. return;
  533. }
  534. // Validate there are no outstanding View instances
  535. // after a scenario was selected to run. This proves the main UI Catalog
  536. // 'app' closed cleanly.
  537. foreach (View? inst in View.Instances)
  538. {
  539. Debug.Assert (inst.WasDisposed);
  540. }
  541. View.Instances.Clear ();
  542. // Validate there are no outstanding Application sessions
  543. // after a scenario was selected to run. This proves the main UI Catalog
  544. // 'app' closed cleanly.
  545. foreach (SessionToken? inst in SessionToken.Instances)
  546. {
  547. Debug.Assert (inst.WasDisposed);
  548. }
  549. SessionToken.Instances.Clear ();
  550. #endif
  551. }
  552. }