UICatalog.cs 25 KB

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