UICatalog.cs 56 KB

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