UICatalog.cs 26 KB

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