UICatalog.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. global using Attribute = Terminal.Gui.Attribute;
  2. global using CM = Terminal.Gui.ConfigurationManager;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.CommandLine;
  7. using System.CommandLine.Builder;
  8. using System.CommandLine.Help;
  9. using System.CommandLine.Parsing;
  10. using System.Data;
  11. using System.Diagnostics;
  12. using System.Diagnostics.CodeAnalysis;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Runtime.InteropServices;
  18. using System.Text;
  19. using System.Text.Json;
  20. using System.Text.Json.Serialization;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using Terminal.Gui;
  24. using UICatalog.Scenarios;
  25. using static Terminal.Gui.ConfigurationManager;
  26. using Command = Terminal.Gui.Command;
  27. using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
  28. #nullable enable
  29. namespace UICatalog;
  30. /// <summary>
  31. /// UI Catalog is a comprehensive sample library for Terminal.Gui. It provides a simple UI for adding to the
  32. /// catalog of scenarios.
  33. /// </summary>
  34. /// <remarks>
  35. /// <para>UI Catalog attempts to satisfy the following goals:</para>
  36. /// <para>
  37. /// <list type="number">
  38. /// <item>
  39. /// <description>Be an easy-to-use showcase for Terminal.Gui concepts and features.</description>
  40. /// </item>
  41. /// <item>
  42. /// <description>Provide sample code that illustrates how to properly implement said concepts & features.</description>
  43. /// </item>
  44. /// <item>
  45. /// <description>Make it easy for contributors to add additional samples in a structured way.</description>
  46. /// </item>
  47. /// </list>
  48. /// </para>
  49. /// </remarks>
  50. public class UICatalogApp
  51. {
  52. private static int _cachedCategoryIndex;
  53. // When a scenario is run, the main app is killed. These items
  54. // are therefore cached so that when the scenario exits the
  55. // main app UI can be restored to previous state
  56. private static int _cachedScenarioIndex;
  57. private static string? _cachedTheme = string.Empty;
  58. private static ObservableCollection<string>? _categories;
  59. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  60. private static readonly FileSystemWatcher _currentDirWatcher = new ();
  61. private static ViewDiagnosticFlags _diagnosticFlags;
  62. private static string _forceDriver = string.Empty;
  63. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  64. private static readonly FileSystemWatcher _homeDirWatcher = new ();
  65. private static bool _isFirstRunning = true;
  66. private static Options _options;
  67. private static ObservableCollection<Scenario>? _scenarios;
  68. // If set, holds the scenario the user selected
  69. private static Scenario? _selectedScenario;
  70. private static MenuBarItem? _themeMenuBarItem;
  71. private static MenuItem []? _themeMenuItems;
  72. private static string _topLevelColorScheme = string.Empty;
  73. [SerializableConfigurationProperty (Scope = typeof (AppScope), OmitClassName = true)]
  74. [JsonPropertyName ("UICatalog.StatusBar")]
  75. public static bool ShowStatusBar { get; set; } = true;
  76. /// <summary>
  77. /// Gets the message displayed in the About Box. `public` so it can be used from Unit tests.
  78. /// </summary>
  79. /// <returns></returns>
  80. public static string GetAboutBoxMessage ()
  81. {
  82. // NOTE: Do not use multiline verbatim strings here.
  83. // WSL gets all confused.
  84. StringBuilder msg = new ();
  85. msg.AppendLine ("UI Catalog: A comprehensive sample library for");
  86. msg.AppendLine ();
  87. msg.AppendLine ("""
  88. _______ _ _ _____ _
  89. |__ __| (_) | | / ____| (_)
  90. | | ___ _ __ _ __ ___ _ _ __ __ _| || | __ _ _ _
  91. | |/ _ \ '__| '_ ` _ \| | '_ \ / _` | || | |_ | | | | |
  92. | | __/ | | | | | | | | | | | (_| | || |__| | |_| | |
  93. |_|\___|_| |_| |_| |_|_|_| |_|\__,_|_(_)_____|\__,_|_|
  94. """);
  95. msg.AppendLine ();
  96. msg.AppendLine ("v2 - Pre-Alpha");
  97. msg.AppendLine ();
  98. msg.AppendLine ("https://github.com/gui-cs/Terminal.Gui");
  99. return msg.ToString ();
  100. }
  101. private static void ConfigFileChanged (object sender, FileSystemEventArgs e)
  102. {
  103. if (Application.Top == null)
  104. {
  105. return;
  106. }
  107. // TODO: This is a hack. Figure out how to ensure that the file is fully written before reading it.
  108. //Thread.Sleep (500);
  109. Load ();
  110. Apply ();
  111. }
  112. private static int Main (string [] args)
  113. {
  114. Console.OutputEncoding = Encoding.Default;
  115. if (Debugger.IsAttached)
  116. {
  117. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  118. }
  119. _scenarios = Scenario.GetScenarios ();
  120. _categories = Scenario.GetAllCategories ();
  121. // Process command line args
  122. // "UICatalog [--driver <driver>] [--benchmark] [scenario name]"
  123. // If no driver is provided, the default driver is used.
  124. Option<string> driverOption = new Option<string> ("--driver", "The IConsoleDriver to use.").FromAmong (
  125. Application.GetDriverTypes ()
  126. .Select (d => d!.Name)
  127. .ToArray ()
  128. );
  129. driverOption.AddAlias ("-d");
  130. driverOption.AddAlias ("--d");
  131. Option<bool> benchmarkFlag = new Option<bool> ("--benchmark", "Enables benchmarking. If a Scenario is specified, just that Scenario will be benchmarked.");
  132. benchmarkFlag.AddAlias ("-b");
  133. benchmarkFlag.AddAlias ("--b");
  134. Option<string> resultsFile = new Option<string> ("--file", "The file to save benchmark results to. If not specified, the results will be displayed in a TableView.");
  135. resultsFile.AddAlias ("-f");
  136. resultsFile.AddAlias ("--f");
  137. Argument<string> scenarioArgument = new Argument<string> (
  138. name: "scenario",
  139. description: "The name of the Scenario to run. If not provided, the UI Catalog UI will be shown.",
  140. getDefaultValue: () => "none"
  141. ).FromAmong (
  142. _scenarios.Select (s => s.GetName ())
  143. .Append ("none")
  144. .ToArray ()
  145. );
  146. var rootCommand = new RootCommand ("A comprehensive sample library for Terminal.Gui")
  147. {
  148. scenarioArgument, benchmarkFlag, resultsFile, driverOption,
  149. };
  150. rootCommand.SetHandler (
  151. context =>
  152. {
  153. var options = new Options
  154. {
  155. Scenario = context.ParseResult.GetValueForArgument (scenarioArgument),
  156. Driver = context.ParseResult.GetValueForOption (driverOption) ?? string.Empty,
  157. Benchmark = context.ParseResult.GetValueForOption (benchmarkFlag),
  158. ResultsFile = context.ParseResult.GetValueForOption (resultsFile) ?? string.Empty,
  159. /* etc. */
  160. };
  161. // See https://github.com/dotnet/command-line-api/issues/796 for the rationale behind this hackery
  162. _options = options;
  163. }
  164. );
  165. bool helpShown = false;
  166. var parser = new CommandLineBuilder (rootCommand)
  167. .UseHelp (ctx => helpShown = true)
  168. .Build ();
  169. parser.Invoke (args);
  170. if (helpShown)
  171. {
  172. return 0;
  173. }
  174. UICatalogMain (_options);
  175. return 0;
  176. }
  177. private static void OpenUrl (string url)
  178. {
  179. if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  180. {
  181. url = url.Replace ("&", "^&");
  182. Process.Start (new ProcessStartInfo ("cmd", $"/c start {url}") { CreateNoWindow = true });
  183. }
  184. else if (RuntimeInformation.IsOSPlatform (OSPlatform.Linux))
  185. {
  186. using var process = new Process
  187. {
  188. StartInfo = new ()
  189. {
  190. FileName = "xdg-open",
  191. Arguments = url,
  192. RedirectStandardError = true,
  193. RedirectStandardOutput = true,
  194. CreateNoWindow = true,
  195. UseShellExecute = false
  196. }
  197. };
  198. process.Start ();
  199. }
  200. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  201. {
  202. Process.Start ("open", url);
  203. }
  204. }
  205. /// <summary>
  206. /// Shows the UI Catalog selection UI. When the user selects a Scenario to run, the UI Catalog main app UI is
  207. /// killed and the Scenario is run as though it were Application.Top. When the Scenario exits, this function exits.
  208. /// </summary>
  209. /// <returns></returns>
  210. private static Scenario RunUICatalogTopLevel ()
  211. {
  212. // Run UI Catalog UI. When it exits, if _selectedScenario is != null then
  213. // a Scenario was selected. Otherwise, the user wants to quit UI Catalog.
  214. // If the user specified a driver on the command line then use it,
  215. // ignoring Config files.
  216. Application.Init (driverName: _forceDriver);
  217. if (_cachedTheme is null)
  218. {
  219. _cachedTheme = Themes?.Theme;
  220. }
  221. else
  222. {
  223. Themes!.Theme = _cachedTheme;
  224. Apply ();
  225. }
  226. Application.Run<UICatalogTopLevel> ().Dispose ();
  227. Application.Shutdown ();
  228. return _selectedScenario!;
  229. }
  230. private static void StartConfigFileWatcher ()
  231. {
  232. // Setup a file system watcher for `./.tui/`
  233. _currentDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
  234. string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
  235. string tuiDir;
  236. if (!string.IsNullOrEmpty (assemblyLocation))
  237. {
  238. var assemblyFile = new FileInfo (assemblyLocation);
  239. tuiDir = Path.Combine (assemblyFile.Directory!.FullName, ".tui");
  240. }
  241. else
  242. {
  243. tuiDir = Path.Combine (AppContext.BaseDirectory, ".tui");
  244. }
  245. if (!Directory.Exists (tuiDir))
  246. {
  247. Directory.CreateDirectory (tuiDir);
  248. }
  249. _currentDirWatcher.Path = tuiDir;
  250. _currentDirWatcher.Filter = "*config.json";
  251. // Setup a file system watcher for `~/.tui/`
  252. _homeDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
  253. var f = new FileInfo (Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  254. tuiDir = Path.Combine (f.FullName, ".tui");
  255. if (!Directory.Exists (tuiDir))
  256. {
  257. Directory.CreateDirectory (tuiDir);
  258. }
  259. _homeDirWatcher.Path = tuiDir;
  260. _homeDirWatcher.Filter = "*config.json";
  261. _currentDirWatcher.Changed += ConfigFileChanged;
  262. //_currentDirWatcher.Created += ConfigFileChanged;
  263. _currentDirWatcher.EnableRaisingEvents = true;
  264. _homeDirWatcher.Changed += ConfigFileChanged;
  265. //_homeDirWatcher.Created += ConfigFileChanged;
  266. _homeDirWatcher.EnableRaisingEvents = true;
  267. }
  268. private static void StopConfigFileWatcher ()
  269. {
  270. _currentDirWatcher.EnableRaisingEvents = false;
  271. _currentDirWatcher.Changed -= ConfigFileChanged;
  272. _currentDirWatcher.Created -= ConfigFileChanged;
  273. _homeDirWatcher.EnableRaisingEvents = false;
  274. _homeDirWatcher.Changed -= ConfigFileChanged;
  275. _homeDirWatcher.Created -= ConfigFileChanged;
  276. }
  277. private static void UICatalogMain (Options options)
  278. {
  279. StartConfigFileWatcher ();
  280. // By setting _forceDriver we ensure that if the user has specified a driver on the command line, it will be used
  281. // regardless of what's in a config file.
  282. Application.ForceDriver = _forceDriver = options.Driver;
  283. // If a Scenario name has been provided on the commandline
  284. // run it and exit when done.
  285. if (options.Scenario != "none")
  286. {
  287. _topLevelColorScheme = "Base";
  288. int item = _scenarios!.IndexOf (
  289. _scenarios!.FirstOrDefault (
  290. s =>
  291. s.GetName ()
  292. .Equals (options.Scenario, StringComparison.OrdinalIgnoreCase)
  293. )!);
  294. _selectedScenario = (Scenario)Activator.CreateInstance (_scenarios [item].GetType ())!;
  295. var results = RunScenario (_selectedScenario, options.Benchmark);
  296. if (results is { })
  297. {
  298. Console.WriteLine (JsonSerializer.Serialize (results, new JsonSerializerOptions ()
  299. {
  300. WriteIndented = true
  301. }));
  302. }
  303. VerifyObjectsWereDisposed ();
  304. return;
  305. }
  306. // Benchmark all Scenarios
  307. if (options.Benchmark)
  308. {
  309. BenchmarkAllScenarios ();
  310. return;
  311. }
  312. while (RunUICatalogTopLevel () is { } scenario)
  313. {
  314. VerifyObjectsWereDisposed ();
  315. Themes!.Theme = _cachedTheme!;
  316. Apply ();
  317. scenario.TopLevelColorScheme = _topLevelColorScheme;
  318. #if DEBUG_IDISPOSABLE
  319. // Measure how long it takes for the app to shut down
  320. var sw = new Stopwatch ();
  321. string scenarioName = scenario.GetName ();
  322. Application.InitializedChanged += ApplicationOnInitializedChanged;
  323. #endif
  324. scenario.Main ();
  325. scenario.Dispose ();
  326. // This call to Application.Shutdown brackets the Application.Init call
  327. // made by Scenario.Init() above
  328. // TODO: Throw if shutdown was not called already
  329. Application.Shutdown ();
  330. VerifyObjectsWereDisposed ();
  331. #if DEBUG_IDISPOSABLE
  332. Application.InitializedChanged -= ApplicationOnInitializedChanged;
  333. void ApplicationOnInitializedChanged (object? sender, EventArgs<bool> e)
  334. {
  335. if (e.CurrentValue)
  336. {
  337. sw.Start ();
  338. }
  339. else
  340. {
  341. sw.Stop ();
  342. Debug.WriteLine ($"Shutdown of {scenarioName} Scenario took {sw.ElapsedMilliseconds}ms");
  343. }
  344. }
  345. #endif
  346. }
  347. StopConfigFileWatcher ();
  348. VerifyObjectsWereDisposed ();
  349. return;
  350. }
  351. private static BenchmarkResults? RunScenario (Scenario scenario, bool benchmark)
  352. {
  353. if (benchmark)
  354. {
  355. scenario.StartBenchmark ();
  356. }
  357. Application.Init (driverName: _forceDriver);
  358. scenario.TopLevelColorScheme = _topLevelColorScheme;
  359. if (benchmark)
  360. {
  361. Application.Screen = new (0, 0, 120, 40);
  362. }
  363. scenario.Main ();
  364. BenchmarkResults? results = null;
  365. if (benchmark)
  366. {
  367. results = scenario.EndBenchmark ();
  368. }
  369. scenario.Dispose ();
  370. // TODO: Throw if shutdown was not called already
  371. Application.Shutdown ();
  372. return results;
  373. }
  374. private static void BenchmarkAllScenarios ()
  375. {
  376. List<BenchmarkResults> resultsList = new List<BenchmarkResults> ();
  377. int maxScenarios = 5;
  378. foreach (var s in _scenarios!)
  379. {
  380. resultsList.Add (RunScenario (s, true)!);
  381. maxScenarios--;
  382. if (maxScenarios == 0)
  383. {
  384. // break;
  385. }
  386. }
  387. if (resultsList.Count > 0)
  388. {
  389. if (!string.IsNullOrEmpty (_options.ResultsFile))
  390. {
  391. var output = JsonSerializer.Serialize (
  392. resultsList,
  393. new JsonSerializerOptions ()
  394. {
  395. WriteIndented = true
  396. });
  397. using var file = File.CreateText (_options.ResultsFile);
  398. file.Write (output);
  399. file.Close ();
  400. return;
  401. }
  402. Application.Init ();
  403. var benchmarkWindow = new Window ()
  404. {
  405. Title = "Benchmark Results",
  406. };
  407. if (benchmarkWindow.Border is { })
  408. {
  409. benchmarkWindow.Border.Thickness = new (0, 0, 0, 0);
  410. }
  411. TableView resultsTableView = new ()
  412. {
  413. Width = Dim.Fill (),
  414. Height = Dim.Fill (),
  415. };
  416. // TableView provides many options for table headers. For simplicity we turn all
  417. // of these off. By enabling FullRowSelect and turning off headers, TableView looks just
  418. // like a ListView
  419. resultsTableView.FullRowSelect = true;
  420. resultsTableView.Style.ShowHeaders = true;
  421. resultsTableView.Style.ShowHorizontalHeaderOverline = false;
  422. resultsTableView.Style.ShowHorizontalHeaderUnderline = true;
  423. resultsTableView.Style.ShowHorizontalBottomline = false;
  424. resultsTableView.Style.ShowVerticalCellLines = true;
  425. resultsTableView.Style.ShowVerticalHeaderLines = true;
  426. /* By default TableView lays out columns at render time and only
  427. * measures y rows of data at a time. Where y is the height of the
  428. * console. This is for the following reasons:
  429. *
  430. * - Performance, when tables have a large amount of data
  431. * - Defensive, prevents a single wide cell value pushing other
  432. * columns off screen (requiring horizontal scrolling
  433. *
  434. * In the case of UICatalog here, such an approach is overkill so
  435. * we just measure all the data ourselves and set the appropriate
  436. * max widths as ColumnStyles
  437. */
  438. //int longestName = _scenarios!.Max (s => s.GetName ().Length);
  439. //resultsTableView.Style.ColumnStyles.Add (
  440. // 0,
  441. // new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  442. // );
  443. //resultsTableView.Style.ColumnStyles.Add (1, new () { MaxWidth = 1 });
  444. //resultsTableView.CellActivated += ScenarioView_OpenSelectedItem;
  445. // TableView typically is a grid where nav keys are biased for moving left/right.
  446. resultsTableView.KeyBindings.Remove (Key.Home);
  447. resultsTableView.KeyBindings.Add (Key.Home, Command.Start);
  448. resultsTableView.KeyBindings.Remove (Key.End);
  449. resultsTableView.KeyBindings.Add (Key.End, Command.End);
  450. // Ideally, TableView.MultiSelect = false would turn off any keybindings for
  451. // multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
  452. // a shortcut to About.
  453. resultsTableView.MultiSelect = false;
  454. var dt = new DataTable ();
  455. dt.Columns.Add (new DataColumn ("Scenario", typeof (string)));
  456. dt.Columns.Add (new DataColumn ("Duration", typeof (TimeSpan)));
  457. dt.Columns.Add (new DataColumn ("Refreshed", typeof (int)));
  458. dt.Columns.Add (new DataColumn ("LaidOut", typeof (int)));
  459. dt.Columns.Add (new DataColumn ("ClearedContent", typeof (int)));
  460. dt.Columns.Add (new DataColumn ("DrawComplete", typeof (int)));
  461. dt.Columns.Add (new DataColumn ("Updated", typeof (int)));
  462. dt.Columns.Add (new DataColumn ("Iterations", typeof (int)));
  463. foreach (var r in resultsList)
  464. {
  465. dt.Rows.Add (
  466. r.Scenario,
  467. r.Duration,
  468. r.RefreshedCount,
  469. r.LaidOutCount,
  470. r.ClearedContentCount,
  471. r.DrawCompleteCount,
  472. r.UpdatedCount,
  473. r.IterationCount
  474. );
  475. }
  476. BenchmarkResults totalRow = new ()
  477. {
  478. Scenario = "TOTAL",
  479. Duration = new TimeSpan (resultsList.Sum (r => r.Duration.Ticks)),
  480. RefreshedCount = resultsList.Sum (r => r.RefreshedCount),
  481. LaidOutCount = resultsList.Sum (r => r.LaidOutCount),
  482. ClearedContentCount = resultsList.Sum (r => r.ClearedContentCount),
  483. DrawCompleteCount = resultsList.Sum (r => r.DrawCompleteCount),
  484. UpdatedCount = resultsList.Sum (r => r.UpdatedCount),
  485. IterationCount = resultsList.Sum (r => r.IterationCount),
  486. };
  487. dt.Rows.Add (
  488. totalRow.Scenario,
  489. totalRow.Duration,
  490. totalRow.RefreshedCount,
  491. totalRow.LaidOutCount,
  492. totalRow.ClearedContentCount,
  493. totalRow.DrawCompleteCount,
  494. totalRow.UpdatedCount,
  495. totalRow.IterationCount
  496. );
  497. dt.DefaultView.Sort = "Duration";
  498. DataTable sortedCopy = dt.DefaultView.ToTable ();
  499. resultsTableView.Table = new DataTableSource (sortedCopy);
  500. benchmarkWindow.Add (resultsTableView);
  501. Application.Run (benchmarkWindow);
  502. benchmarkWindow.Dispose ();
  503. Application.Shutdown ();
  504. }
  505. }
  506. private static void VerifyObjectsWereDisposed ()
  507. {
  508. #if DEBUG_IDISPOSABLE
  509. // Validate there are no outstanding Responder-based instances
  510. // after a scenario was selected to run. This proves the main UI Catalog
  511. // 'app' closed cleanly.
  512. foreach (View? inst in View.Instances)
  513. {
  514. Debug.Assert (inst.WasDisposed);
  515. }
  516. View.Instances.Clear ();
  517. // Validate there are no outstanding Application.RunState-based instances
  518. // after a scenario was selected to run. This proves the main UI Catalog
  519. // 'app' closed cleanly.
  520. foreach (RunState? inst in RunState.Instances)
  521. {
  522. Debug.Assert (inst.WasDisposed);
  523. }
  524. RunState.Instances.Clear ();
  525. #endif
  526. }
  527. /// <summary>
  528. /// This is the main UI Catalog app view. It is run fresh when the app loads (if a Scenario has not been passed on
  529. /// the command line) and each time a Scenario ends.
  530. /// </summary>
  531. public class UICatalogTopLevel : Toplevel
  532. {
  533. public ListView? CategoryList;
  534. public MenuItem? MiForce16Colors;
  535. public MenuItem? MiIsMenuBorderDisabled;
  536. public MenuItem? MiIsMouseDisabled;
  537. public MenuItem? MiUseSubMenusSingleFrame;
  538. public Shortcut? ShForce16Colors;
  539. //public Shortcut? ShDiagnostics;
  540. public Shortcut? ShVersion;
  541. // UI Catalog uses TableView for the scenario list instead of a ListView to demonstate how
  542. // TableView works. There's no real reason not to use ListView. Because we use TableView, and TableView
  543. // doesn't (currently) have CollectionNavigator support built in, we implement it here, within the app.
  544. public TableView ScenarioList;
  545. private readonly StatusBar? _statusBar;
  546. private readonly CollectionNavigator _scenarioCollectionNav = new ();
  547. public UICatalogTopLevel ()
  548. {
  549. _diagnosticFlags = Diagnostics;
  550. _themeMenuItems = CreateThemeMenuItems ();
  551. _themeMenuBarItem = new ("_Themes", _themeMenuItems!);
  552. MenuBar menuBar = new ()
  553. {
  554. Menus =
  555. [
  556. new (
  557. "_File",
  558. new MenuItem []
  559. {
  560. new (
  561. "_Quit",
  562. "Quit UI Catalog",
  563. RequestStop
  564. )
  565. }
  566. ),
  567. _themeMenuBarItem,
  568. new ("Diag_nostics", CreateDiagnosticMenuItems ()),
  569. new (
  570. "_Help",
  571. new MenuItem []
  572. {
  573. new (
  574. "_Documentation",
  575. "",
  576. () => OpenUrl ("https://gui-cs.github.io/Terminal.GuiV2Docs"),
  577. null,
  578. null,
  579. (KeyCode)Key.F1
  580. ),
  581. new (
  582. "_README",
  583. "",
  584. () => OpenUrl ("https://github.com/gui-cs/Terminal.Gui"),
  585. null,
  586. null,
  587. (KeyCode)Key.F2
  588. ),
  589. new (
  590. "_About...",
  591. "About UI Catalog",
  592. () => MessageBox.Query (
  593. title: "",
  594. message: GetAboutBoxMessage (),
  595. wrapMessage: false,
  596. buttons: "_Ok"
  597. ),
  598. null,
  599. null,
  600. (KeyCode)Key.A.WithCtrl
  601. )
  602. }
  603. )
  604. ]
  605. };
  606. _statusBar = new ()
  607. {
  608. Visible = ShowStatusBar,
  609. AlignmentModes = AlignmentModes.IgnoreFirstOrLast,
  610. CanFocus = false
  611. };
  612. _statusBar.Height = Dim.Auto (DimAutoStyle.Auto, minimumContentDim: Dim.Func (() => _statusBar.Visible ? 1 : 0), maximumContentDim: Dim.Func (() => _statusBar.Visible ? 1 : 0));
  613. ShVersion = new ()
  614. {
  615. Title = "Version Info",
  616. CanFocus = false,
  617. };
  618. var statusBarShortcut = new Shortcut
  619. {
  620. Key = Key.F10,
  621. Title = "Show/Hide Status Bar",
  622. CanFocus = false,
  623. };
  624. statusBarShortcut.Accepting += (sender, args) =>
  625. {
  626. _statusBar.Visible = !_statusBar.Visible;
  627. args.Cancel = true;
  628. };
  629. ShForce16Colors = new ()
  630. {
  631. CanFocus = false,
  632. CommandView = new CheckBox
  633. {
  634. Title = "16 color mode",
  635. CheckedState = Application.Force16Colors ? CheckState.Checked : CheckState.UnChecked,
  636. CanFocus = false
  637. },
  638. HelpText = "",
  639. KeyBindingScope = KeyBindingScope.Application,
  640. Key = Key.F7
  641. };
  642. ((CheckBox)ShForce16Colors.CommandView).CheckedStateChanging += (sender, args) =>
  643. {
  644. Application.Force16Colors = args.NewValue == CheckState.Checked;
  645. MiForce16Colors!.Checked = Application.Force16Colors;
  646. Application.LayoutAndDraw ();
  647. };
  648. _statusBar.Add (
  649. new Shortcut
  650. {
  651. CanFocus = false,
  652. Title = "Quit",
  653. Key = Application.QuitKey
  654. },
  655. statusBarShortcut,
  656. ShForce16Colors,
  657. //ShDiagnostics,
  658. ShVersion
  659. );
  660. // Create the Category list view. This list never changes.
  661. CategoryList = new ()
  662. {
  663. X = 0,
  664. Y = Pos.Bottom (menuBar),
  665. Width = Dim.Auto (),
  666. Height = Dim.Fill (Dim.Func (() =>
  667. {
  668. if (_statusBar.NeedsLayout)
  669. {
  670. // throw new LayoutException ("DimFunc.Fn aborted because dependent View needs layout.");
  671. }
  672. return _statusBar.Frame.Height;
  673. })),
  674. AllowsMarking = false,
  675. CanFocus = true,
  676. Title = "_Categories",
  677. BorderStyle = LineStyle.Rounded,
  678. SuperViewRendersLineCanvas = true,
  679. Source = new ListWrapper<string> (_categories)
  680. };
  681. CategoryList.OpenSelectedItem += (s, a) => { ScenarioList!.SetFocus (); };
  682. CategoryList.SelectedItemChanged += CategoryView_SelectedChanged;
  683. // This enables the scrollbar by causing lazy instantiation to happen
  684. CategoryList.VerticalScrollBar.AutoShow = true;
  685. // Create the scenario list. The contents of the scenario list changes whenever the
  686. // Category list selection changes (to show just the scenarios that belong to the selected
  687. // category).
  688. ScenarioList = new ()
  689. {
  690. X = Pos.Right (CategoryList) - 1,
  691. Y = Pos.Bottom (menuBar),
  692. Width = Dim.Fill (),
  693. Height = Dim.Fill (Dim.Func (() =>
  694. {
  695. if (_statusBar.NeedsLayout)
  696. {
  697. // throw new LayoutException ("DimFunc.Fn aborted because dependent View needs layout.");
  698. }
  699. return _statusBar.Frame.Height;
  700. })),
  701. //AllowsMarking = false,
  702. CanFocus = true,
  703. Title = "_Scenarios",
  704. BorderStyle = CategoryList.BorderStyle,
  705. SuperViewRendersLineCanvas = true
  706. };
  707. //ScenarioList.VerticalScrollBar.AutoHide = false;
  708. //ScenarioList.HorizontalScrollBar.AutoHide = false;
  709. // TableView provides many options for table headers. For simplicity we turn all
  710. // of these off. By enabling FullRowSelect and turning off headers, TableView looks just
  711. // like a ListView
  712. ScenarioList.FullRowSelect = true;
  713. ScenarioList.Style.ShowHeaders = false;
  714. ScenarioList.Style.ShowHorizontalHeaderOverline = false;
  715. ScenarioList.Style.ShowHorizontalHeaderUnderline = false;
  716. ScenarioList.Style.ShowHorizontalBottomline = false;
  717. ScenarioList.Style.ShowVerticalCellLines = false;
  718. ScenarioList.Style.ShowVerticalHeaderLines = false;
  719. /* By default TableView lays out columns at render time and only
  720. * measures y rows of data at a time. Where y is the height of the
  721. * console. This is for the following reasons:
  722. *
  723. * - Performance, when tables have a large amount of data
  724. * - Defensive, prevents a single wide cell value pushing other
  725. * columns off screen (requiring horizontal scrolling
  726. *
  727. * In the case of UICatalog here, such an approach is overkill so
  728. * we just measure all the data ourselves and set the appropriate
  729. * max widths as ColumnStyles
  730. */
  731. int longestName = _scenarios!.Max (s => s.GetName ().Length);
  732. ScenarioList.Style.ColumnStyles.Add (
  733. 0,
  734. new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  735. );
  736. ScenarioList.Style.ColumnStyles.Add (1, new () { MaxWidth = 1 });
  737. ScenarioList.CellActivated += ScenarioView_OpenSelectedItem;
  738. // TableView typically is a grid where nav keys are biased for moving left/right.
  739. ScenarioList.KeyBindings.Remove (Key.Home);
  740. ScenarioList.KeyBindings.Add (Key.Home, Command.Start);
  741. ScenarioList.KeyBindings.Remove (Key.End);
  742. ScenarioList.KeyBindings.Add (Key.End, Command.End);
  743. // Ideally, TableView.MultiSelect = false would turn off any keybindings for
  744. // multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
  745. // a shortcut to About.
  746. ScenarioList.MultiSelect = false;
  747. ScenarioList.KeyBindings.Remove (Key.A.WithCtrl);
  748. Add (menuBar);
  749. Add (CategoryList);
  750. Add (ScenarioList);
  751. Add (_statusBar);
  752. Loaded += LoadedHandler;
  753. Unloaded += UnloadedHandler;
  754. // Restore previous selections
  755. CategoryList.SelectedItem = _cachedCategoryIndex;
  756. ScenarioList.SelectedRow = _cachedScenarioIndex;
  757. Applied += ConfigAppliedHandler;
  758. }
  759. public void ConfigChanged ()
  760. {
  761. if (_topLevelColorScheme == null || !Colors.ColorSchemes.ContainsKey (_topLevelColorScheme))
  762. {
  763. _topLevelColorScheme = "Base";
  764. }
  765. _cachedTheme = Themes?.Theme;
  766. _themeMenuItems = CreateThemeMenuItems ();
  767. _themeMenuBarItem!.Children = _themeMenuItems;
  768. foreach (MenuItem mi in _themeMenuItems!)
  769. {
  770. if (mi is { Parent: null })
  771. {
  772. mi.Parent = _themeMenuBarItem;
  773. }
  774. }
  775. ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
  776. MenuBar!.Menus [0].Children! [0]!.ShortcutKey = Application.QuitKey;
  777. ((Shortcut)_statusBar!.Subviews [0]).Key = Application.QuitKey;
  778. _statusBar.Visible = ShowStatusBar;
  779. MiIsMouseDisabled!.Checked = Application.IsMouseDisabled;
  780. ((CheckBox)ShForce16Colors!.CommandView!).CheckedState = Application.Force16Colors ? CheckState.Checked : CheckState.UnChecked;
  781. Application.Top!.SetNeedsDraw ();
  782. }
  783. public MenuItem []? CreateThemeMenuItems ()
  784. {
  785. List<MenuItem> menuItems = CreateForce16ColorItems ().ToList ();
  786. menuItems.Add (null!);
  787. var schemeCount = 0;
  788. foreach (KeyValuePair<string, ThemeScope> theme in Themes!)
  789. {
  790. var item = new MenuItem
  791. {
  792. Title = theme.Key == "Dark" ? $"{theme.Key.Substring (0, 3)}_{theme.Key.Substring (3, 1)}" : $"_{theme.Key}",
  793. ShortcutKey = new Key ((KeyCode)((uint)KeyCode.D1 + schemeCount++))
  794. .WithCtrl
  795. };
  796. item.CheckType |= MenuItemCheckStyle.Checked;
  797. item.Checked = theme.Key == _cachedTheme; // CM.Themes.Theme;
  798. item.Action += () =>
  799. {
  800. Themes.Theme = _cachedTheme = theme.Key;
  801. Apply ();
  802. };
  803. menuItems.Add (item);
  804. }
  805. List<MenuItem> schemeMenuItems = new ();
  806. foreach (KeyValuePair<string, ColorScheme?> sc in Colors.ColorSchemes)
  807. {
  808. var item = new MenuItem { Title = $"_{sc.Key}", Data = sc.Key };
  809. item.CheckType |= MenuItemCheckStyle.Radio;
  810. item.Checked = sc.Key == _topLevelColorScheme;
  811. item.Action += () =>
  812. {
  813. _topLevelColorScheme = (string)item.Data;
  814. foreach (MenuItem schemeMenuItem in schemeMenuItems)
  815. {
  816. schemeMenuItem.Checked = (string)schemeMenuItem.Data == _topLevelColorScheme;
  817. }
  818. ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
  819. };
  820. item.ShortcutKey = ((Key)sc.Key [0].ToString ().ToLower ()).WithCtrl;
  821. schemeMenuItems.Add (item);
  822. }
  823. menuItems.Add (null!);
  824. var mbi = new MenuBarItem ("_Color Scheme for Application.Top", schemeMenuItems.ToArray ());
  825. menuItems.Add (mbi);
  826. return menuItems.ToArray ();
  827. }
  828. private void CategoryView_SelectedChanged (object? sender, ListViewItemEventArgs? e)
  829. {
  830. string item = _categories! [e!.Item];
  831. ObservableCollection<Scenario> newlist;
  832. if (e.Item == 0)
  833. {
  834. // First category is "All"
  835. newlist = _scenarios!;
  836. }
  837. else
  838. {
  839. newlist = new (_scenarios!.Where (s => s.GetCategories ().Contains (item)).ToList ());
  840. }
  841. ScenarioList.Table = new EnumerableTableSource<Scenario> (
  842. newlist,
  843. new ()
  844. {
  845. { "Name", s => s.GetName () }, { "Description", s => s.GetDescription () }
  846. }
  847. );
  848. // Create a collection of just the scenario names (the 1st column in our TableView)
  849. // for CollectionNavigator.
  850. List<object> firstColumnList = new ();
  851. for (var i = 0; i < ScenarioList.Table.Rows; i++)
  852. {
  853. firstColumnList.Add (ScenarioList.Table [i, 0]);
  854. }
  855. _scenarioCollectionNav.Collection = firstColumnList;
  856. }
  857. private void ConfigAppliedHandler (object? sender, ConfigurationManagerEventArgs? a) { ConfigChanged (); }
  858. [SuppressMessage ("Style", "IDE1006:Naming Styles", Justification = "<Pending>")]
  859. private MenuItem [] CreateDiagnosticFlagsMenuItems ()
  860. {
  861. const string OFF = "View Diagnostics: _Off";
  862. const string RULER = "View Diagnostics: _Ruler";
  863. const string THICKNESS = "View Diagnostics: _Thickness";
  864. const string HOVER = "View Diagnostics: _Hover";
  865. const string DRAWINDICATOR = "View Diagnostics: _DrawIndicator";
  866. var index = 0;
  867. List<MenuItem> menuItems = new ();
  868. foreach (Enum diag in Enum.GetValues (_diagnosticFlags.GetType ()))
  869. {
  870. var item = new MenuItem
  871. {
  872. Title = GetDiagnosticsTitle (diag), ShortcutKey = new Key (index.ToString () [0]).WithAlt
  873. };
  874. index++;
  875. item.CheckType |= MenuItemCheckStyle.Checked;
  876. if (GetDiagnosticsTitle (ViewDiagnosticFlags.Off) == item.Title)
  877. {
  878. item.Checked = !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Thickness)
  879. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Ruler)
  880. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Hover)
  881. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.DrawIndicator);
  882. }
  883. else
  884. {
  885. item.Checked = _diagnosticFlags.HasFlag (diag);
  886. }
  887. item.Action += () =>
  888. {
  889. string t = GetDiagnosticsTitle (ViewDiagnosticFlags.Off);
  890. if (item.Title == t && item.Checked == false)
  891. {
  892. _diagnosticFlags &= ~(ViewDiagnosticFlags.Thickness | ViewDiagnosticFlags.Ruler | ViewDiagnosticFlags.Hover | ViewDiagnosticFlags.DrawIndicator);
  893. item.Checked = true;
  894. }
  895. else if (item.Title == t && item.Checked == true)
  896. {
  897. _diagnosticFlags |= ViewDiagnosticFlags.Thickness | ViewDiagnosticFlags.Ruler | ViewDiagnosticFlags.Hover | ViewDiagnosticFlags.DrawIndicator;
  898. item.Checked = false;
  899. }
  900. else
  901. {
  902. Enum f = GetDiagnosticsEnumValue (item.Title);
  903. if (_diagnosticFlags.HasFlag (f))
  904. {
  905. SetDiagnosticsFlag (f, false);
  906. }
  907. else
  908. {
  909. SetDiagnosticsFlag (f, true);
  910. }
  911. }
  912. foreach (MenuItem menuItem in menuItems)
  913. {
  914. if (menuItem.Title == t)
  915. {
  916. menuItem.Checked = !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Ruler)
  917. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Thickness)
  918. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Hover)
  919. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.DrawIndicator);
  920. }
  921. else if (menuItem.Title != t)
  922. {
  923. menuItem.Checked = _diagnosticFlags.HasFlag (GetDiagnosticsEnumValue (menuItem.Title));
  924. }
  925. }
  926. Diagnostics = _diagnosticFlags;
  927. };
  928. menuItems.Add (item);
  929. }
  930. return menuItems.ToArray ();
  931. string GetDiagnosticsTitle (Enum diag)
  932. {
  933. return Enum.GetName (_diagnosticFlags.GetType (), diag) switch
  934. {
  935. "Off" => OFF,
  936. "Ruler" => RULER,
  937. "Thickness" => THICKNESS,
  938. "Hover" => HOVER,
  939. "DrawIndicator" => DRAWINDICATOR,
  940. _ => ""
  941. };
  942. }
  943. Enum GetDiagnosticsEnumValue (string? title)
  944. {
  945. return title switch
  946. {
  947. RULER => ViewDiagnosticFlags.Ruler,
  948. THICKNESS => ViewDiagnosticFlags.Thickness,
  949. HOVER => ViewDiagnosticFlags.Hover,
  950. DRAWINDICATOR => ViewDiagnosticFlags.DrawIndicator,
  951. _ => null!
  952. };
  953. }
  954. void SetDiagnosticsFlag (Enum diag, bool add)
  955. {
  956. switch (diag)
  957. {
  958. case ViewDiagnosticFlags.Ruler:
  959. if (add)
  960. {
  961. _diagnosticFlags |= ViewDiagnosticFlags.Ruler;
  962. }
  963. else
  964. {
  965. _diagnosticFlags &= ~ViewDiagnosticFlags.Ruler;
  966. }
  967. break;
  968. case ViewDiagnosticFlags.Thickness:
  969. if (add)
  970. {
  971. _diagnosticFlags |= ViewDiagnosticFlags.Thickness;
  972. }
  973. else
  974. {
  975. _diagnosticFlags &= ~ViewDiagnosticFlags.Thickness;
  976. }
  977. break;
  978. case ViewDiagnosticFlags.Hover:
  979. if (add)
  980. {
  981. _diagnosticFlags |= ViewDiagnosticFlags.Hover;
  982. }
  983. else
  984. {
  985. _diagnosticFlags &= ~ViewDiagnosticFlags.Hover;
  986. }
  987. break;
  988. case ViewDiagnosticFlags.DrawIndicator:
  989. if (add)
  990. {
  991. _diagnosticFlags |= ViewDiagnosticFlags.DrawIndicator;
  992. }
  993. else
  994. {
  995. _diagnosticFlags &= ~ViewDiagnosticFlags.DrawIndicator;
  996. }
  997. break;
  998. default:
  999. _diagnosticFlags = default (ViewDiagnosticFlags);
  1000. break;
  1001. }
  1002. }
  1003. }
  1004. private List<MenuItem []> CreateDiagnosticMenuItems ()
  1005. {
  1006. List<MenuItem []> menuItems = new ()
  1007. {
  1008. CreateDiagnosticFlagsMenuItems (),
  1009. new MenuItem [] { null! },
  1010. CreateDisabledEnabledMouseItems (),
  1011. CreateDisabledEnabledMenuBorder (),
  1012. CreateDisabledEnableUseSubMenusSingleFrame (),
  1013. CreateKeyBindingsMenuItems ()
  1014. };
  1015. return menuItems;
  1016. }
  1017. // TODO: This should be an ConfigurationManager setting
  1018. private MenuItem [] CreateDisabledEnabledMenuBorder ()
  1019. {
  1020. List<MenuItem> menuItems = new ();
  1021. MiIsMenuBorderDisabled = new () { Title = "Disable Menu _Border" };
  1022. MiIsMenuBorderDisabled.ShortcutKey =
  1023. new Key (MiIsMenuBorderDisabled!.Title!.Substring (14, 1) [0]).WithAlt.WithCtrl.NoShift;
  1024. MiIsMenuBorderDisabled.CheckType |= MenuItemCheckStyle.Checked;
  1025. MiIsMenuBorderDisabled.Action += () =>
  1026. {
  1027. MiIsMenuBorderDisabled.Checked = (bool)!MiIsMenuBorderDisabled.Checked!;
  1028. MenuBar!.MenusBorderStyle = !(bool)MiIsMenuBorderDisabled.Checked
  1029. ? LineStyle.Single
  1030. : LineStyle.None;
  1031. };
  1032. menuItems.Add (MiIsMenuBorderDisabled);
  1033. return menuItems.ToArray ();
  1034. }
  1035. private MenuItem [] CreateDisabledEnabledMouseItems ()
  1036. {
  1037. List<MenuItem> menuItems = new ();
  1038. MiIsMouseDisabled = new () { Title = "_Disable Mouse" };
  1039. MiIsMouseDisabled.ShortcutKey =
  1040. new Key (MiIsMouseDisabled!.Title!.Substring (1, 1) [0]).WithAlt.WithCtrl.NoShift;
  1041. MiIsMouseDisabled.CheckType |= MenuItemCheckStyle.Checked;
  1042. MiIsMouseDisabled.Action += () =>
  1043. {
  1044. MiIsMouseDisabled.Checked =
  1045. Application.IsMouseDisabled = (bool)!MiIsMouseDisabled.Checked!;
  1046. };
  1047. menuItems.Add (MiIsMouseDisabled);
  1048. return menuItems.ToArray ();
  1049. }
  1050. // TODO: This should be an ConfigurationManager setting
  1051. private MenuItem [] CreateDisabledEnableUseSubMenusSingleFrame ()
  1052. {
  1053. List<MenuItem> menuItems = new ();
  1054. MiUseSubMenusSingleFrame = new () { Title = "Enable _Sub-Menus Single Frame" };
  1055. MiUseSubMenusSingleFrame.ShortcutKey = KeyCode.CtrlMask
  1056. | KeyCode.AltMask
  1057. | (KeyCode)MiUseSubMenusSingleFrame!.Title!.Substring (8, 1) [
  1058. 0];
  1059. MiUseSubMenusSingleFrame.CheckType |= MenuItemCheckStyle.Checked;
  1060. MiUseSubMenusSingleFrame.Action += () =>
  1061. {
  1062. MiUseSubMenusSingleFrame.Checked = (bool)!MiUseSubMenusSingleFrame.Checked!;
  1063. MenuBar!.UseSubMenusSingleFrame = (bool)MiUseSubMenusSingleFrame.Checked;
  1064. };
  1065. menuItems.Add (MiUseSubMenusSingleFrame);
  1066. return menuItems.ToArray ();
  1067. }
  1068. private MenuItem [] CreateForce16ColorItems ()
  1069. {
  1070. List<MenuItem> menuItems = new ();
  1071. MiForce16Colors = new ()
  1072. {
  1073. Title = "Force _16 Colors",
  1074. ShortcutKey = Key.F6,
  1075. Checked = Application.Force16Colors,
  1076. CanExecute = () => Application.Driver?.SupportsTrueColor ?? false
  1077. };
  1078. MiForce16Colors.CheckType |= MenuItemCheckStyle.Checked;
  1079. MiForce16Colors.Action += () =>
  1080. {
  1081. MiForce16Colors.Checked = Application.Force16Colors = (bool)!MiForce16Colors.Checked!;
  1082. ((CheckBox)ShForce16Colors!.CommandView!).CheckedState =
  1083. Application.Force16Colors ? CheckState.Checked : CheckState.UnChecked;
  1084. Application.LayoutAndDraw ();
  1085. };
  1086. menuItems.Add (MiForce16Colors);
  1087. return menuItems.ToArray ();
  1088. }
  1089. private MenuItem [] CreateKeyBindingsMenuItems ()
  1090. {
  1091. List<MenuItem> menuItems = new ();
  1092. var item = new MenuItem { Title = "_Key Bindings", Help = "Change which keys do what" };
  1093. item.Action += () =>
  1094. {
  1095. var dlg = new KeyBindingsDialog ();
  1096. Application.Run (dlg);
  1097. dlg.Dispose ();
  1098. };
  1099. menuItems.Add (null!);
  1100. menuItems.Add (item);
  1101. return menuItems.ToArray ();
  1102. }
  1103. private void LoadedHandler (object? sender, EventArgs? args)
  1104. {
  1105. ConfigChanged ();
  1106. MiIsMouseDisabled!.Checked = Application.IsMouseDisabled;
  1107. if (ShVersion is { })
  1108. {
  1109. ShVersion.Title = $"{RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}, {Driver!.GetVersionInfo ()}";
  1110. }
  1111. if (_selectedScenario != null)
  1112. {
  1113. _selectedScenario = null;
  1114. _isFirstRunning = false;
  1115. }
  1116. if (!_isFirstRunning)
  1117. {
  1118. ScenarioList.SetFocus ();
  1119. }
  1120. if (_statusBar is { })
  1121. {
  1122. _statusBar.VisibleChanged += (s, e) =>
  1123. {
  1124. ShowStatusBar = _statusBar.Visible;
  1125. };
  1126. }
  1127. Loaded -= LoadedHandler;
  1128. CategoryList!.EnsureSelectedItemVisible ();
  1129. ScenarioList.EnsureSelectedCellIsVisible ();
  1130. }
  1131. /// <summary>Launches the selected scenario, setting the global _selectedScenario</summary>
  1132. /// <param name="e"></param>
  1133. private void ScenarioView_OpenSelectedItem (object? sender, EventArgs? e)
  1134. {
  1135. if (_selectedScenario is null)
  1136. {
  1137. // Save selected item state
  1138. _cachedCategoryIndex = CategoryList!.SelectedItem;
  1139. _cachedScenarioIndex = ScenarioList.SelectedRow;
  1140. // Create new instance of scenario (even though Scenarios contains instances)
  1141. var selectedScenarioName = (string)ScenarioList.Table [ScenarioList.SelectedRow, 0];
  1142. _selectedScenario = (Scenario)Activator.CreateInstance (
  1143. _scenarios!.FirstOrDefault (
  1144. s => s.GetName ()
  1145. == selectedScenarioName
  1146. )!
  1147. .GetType ()
  1148. )!;
  1149. // Tell the main app to stop
  1150. Application.RequestStop ();
  1151. }
  1152. }
  1153. private void UnloadedHandler (object? sender, EventArgs? args)
  1154. {
  1155. Applied -= ConfigAppliedHandler;
  1156. Unloaded -= UnloadedHandler;
  1157. Dispose ();
  1158. }
  1159. }
  1160. private struct Options
  1161. {
  1162. public string Driver;
  1163. public string Scenario;
  1164. public bool Benchmark;
  1165. public string ResultsFile;
  1166. /* etc. */
  1167. }
  1168. }