UICatalog.cs 26 KB

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