UICatalog.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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.CommandLine;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Runtime.InteropServices;
  12. using System.Text;
  13. using System.Text.Json.Serialization;
  14. using Terminal.Gui;
  15. using static Terminal.Gui.ConfigurationManager;
  16. using Command = Terminal.Gui.Command;
  17. using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment;
  18. #nullable enable
  19. namespace UICatalog;
  20. /// <summary>
  21. /// UI Catalog is a comprehensive sample library for Terminal.Gui. It provides a simple UI for adding to the
  22. /// catalog of scenarios.
  23. /// </summary>
  24. /// <remarks>
  25. /// <para>UI Catalog attempts to satisfy the following goals:</para>
  26. /// <para>
  27. /// <list type="number">
  28. /// <item>
  29. /// <description>Be an easy to use showcase for Terminal.Gui concepts and features.</description>
  30. /// </item>
  31. /// <item>
  32. /// <description>Provide sample code that illustrates how to properly implement said concepts & features.</description>
  33. /// </item>
  34. /// <item>
  35. /// <description>Make it easy for contributors to add additional samples in a structured way.</description>
  36. /// </item>
  37. /// </list>
  38. /// </para>
  39. /// <para>
  40. /// See the project README for more details
  41. /// (https://github.com/gui-cs/Terminal.Gui/tree/master/UICatalog/README.md).
  42. /// </para>
  43. /// </remarks>
  44. internal class UICatalogApp
  45. {
  46. private static StringBuilder? _aboutMessage;
  47. private static int _cachedCategoryIndex;
  48. // When a scenario is run, the main app is killed. These items
  49. // are therefore cached so that when the scenario exits the
  50. // main app UI can be restored to previous state
  51. private static int _cachedScenarioIndex;
  52. private static string? _cachedTheme = string.Empty;
  53. private static List<string>? _categories;
  54. private static readonly FileSystemWatcher _currentDirWatcher = new ();
  55. private static ViewDiagnosticFlags _diagnosticFlags;
  56. private static string _forceDriver = string.Empty;
  57. private static readonly FileSystemWatcher _homeDirWatcher = new ();
  58. private static bool _isFirstRunning = true;
  59. private static Options _options;
  60. private static List<Scenario>? _scenarios;
  61. // If set, holds the scenario the user selected
  62. private static Scenario? _selectedScenario;
  63. private static MenuBarItem? _themeMenuBarItem;
  64. private static MenuItem []? _themeMenuItems;
  65. private static string _topLevelColorScheme = string.Empty;
  66. [SerializableConfigurationProperty (Scope = typeof (AppScope), OmitClassName = true)]
  67. [JsonPropertyName ("UICatalog.StatusBar")]
  68. public static bool ShowStatusBar { get; set; } = true;
  69. private static void ConfigFileChanged (object sender, FileSystemEventArgs e)
  70. {
  71. if (Application.Top == null)
  72. {
  73. return;
  74. }
  75. // TODO: This is a hack. Figure out how to ensure that the file is fully written before reading it.
  76. //Thread.Sleep (500);
  77. Load ();
  78. Apply ();
  79. }
  80. private static int Main (string [] args)
  81. {
  82. Console.OutputEncoding = Encoding.Default;
  83. if (Debugger.IsAttached)
  84. {
  85. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  86. }
  87. _scenarios = Scenario.GetScenarios ();
  88. _categories = Scenario.GetAllCategories ();
  89. // Process command line args
  90. // "UICatalog [-driver <driver>] [scenario name]"
  91. // If no driver is provided, the default driver is used.
  92. Option<string> driverOption = new Option<string> ("--driver", "The ConsoleDriver to use.").FromAmong (
  93. Application.GetDriverTypes ()
  94. .Select (d => d.Name)
  95. .ToArray ()
  96. );
  97. driverOption.AddAlias ("-d");
  98. driverOption.AddAlias ("--d");
  99. Argument<string> scenarioArgument = new Argument<string> (
  100. "scenario",
  101. description: "The name of the scenario to run.",
  102. getDefaultValue: () => "none"
  103. ).FromAmong (
  104. _scenarios.Select (s => s.GetName ())
  105. .Append ("none")
  106. .ToArray ()
  107. );
  108. var rootCommand =
  109. new RootCommand ("A comprehensive sample library for Terminal.Gui") { scenarioArgument, driverOption };
  110. rootCommand.SetHandler (
  111. context =>
  112. {
  113. var options = new Options
  114. {
  115. Driver = context.ParseResult.GetValueForOption (driverOption),
  116. Scenario = context.ParseResult.GetValueForArgument (scenarioArgument)
  117. /* etc. */
  118. };
  119. // See https://github.com/dotnet/command-line-api/issues/796 for the rationale behind this hackery
  120. _options = options;
  121. }
  122. );
  123. rootCommand.Invoke (args);
  124. UICatalogMain (_options);
  125. return 0;
  126. }
  127. private static void OpenUrl (string url)
  128. {
  129. if (RuntimeInformation.IsOSPlatform (OSPlatform.Windows))
  130. {
  131. url = url.Replace ("&", "^&");
  132. Process.Start (new ProcessStartInfo ("cmd", $"/c start {url}") { CreateNoWindow = true });
  133. }
  134. else if (RuntimeInformation.IsOSPlatform (OSPlatform.Linux))
  135. {
  136. using var process = new Process
  137. {
  138. StartInfo = new()
  139. {
  140. FileName = "xdg-open",
  141. Arguments = url,
  142. RedirectStandardError = true,
  143. RedirectStandardOutput = true,
  144. CreateNoWindow = true,
  145. UseShellExecute = false
  146. }
  147. };
  148. process.Start ();
  149. }
  150. else if (RuntimeInformation.IsOSPlatform (OSPlatform.OSX))
  151. {
  152. Process.Start ("open", url);
  153. }
  154. }
  155. /// <summary>
  156. /// Shows the UI Catalog selection UI. When the user selects a Scenario to run, the UI Catalog main app UI is
  157. /// killed and the Scenario is run as though it were Application.Top. When the Scenario exits, this function exits.
  158. /// </summary>
  159. /// <returns></returns>
  160. private static Scenario RunUICatalogTopLevel ()
  161. {
  162. // Run UI Catalog UI. When it exits, if _selectedScenario is != null then
  163. // a Scenario was selected. Otherwise, the user wants to quit UI Catalog.
  164. // If the user specified a driver on the command line then use it,
  165. // ignoring Config files.
  166. Application.Init (driverName: _forceDriver);
  167. if (_cachedTheme is null)
  168. {
  169. _cachedTheme = Themes?.Theme;
  170. }
  171. else
  172. {
  173. Themes!.Theme = _cachedTheme;
  174. Apply ();
  175. }
  176. Application.Run<UICatalogTopLevel> ();
  177. Application.Shutdown ();
  178. return _selectedScenario!;
  179. }
  180. private static void StartConfigFileWatcher ()
  181. {
  182. // Setup a file system watcher for `./.tui/`
  183. _currentDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
  184. string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
  185. string tuiDir;
  186. if (!string.IsNullOrEmpty (assemblyLocation))
  187. {
  188. var assemblyFile = new FileInfo (assemblyLocation);
  189. tuiDir = Path.Combine (assemblyFile.Directory!.FullName, ".tui");
  190. }
  191. else
  192. {
  193. tuiDir = Path.Combine (AppContext.BaseDirectory, ".tui");
  194. }
  195. if (!Directory.Exists (tuiDir))
  196. {
  197. Directory.CreateDirectory (tuiDir);
  198. }
  199. _currentDirWatcher.Path = tuiDir;
  200. _currentDirWatcher.Filter = "*config.json";
  201. // Setup a file system watcher for `~/.tui/`
  202. _homeDirWatcher.NotifyFilter = NotifyFilters.LastWrite;
  203. var f = new FileInfo (Environment.GetFolderPath (Environment.SpecialFolder.UserProfile));
  204. tuiDir = Path.Combine (f.FullName, ".tui");
  205. if (!Directory.Exists (tuiDir))
  206. {
  207. Directory.CreateDirectory (tuiDir);
  208. }
  209. _homeDirWatcher.Path = tuiDir;
  210. _homeDirWatcher.Filter = "*config.json";
  211. _currentDirWatcher.Changed += ConfigFileChanged;
  212. //_currentDirWatcher.Created += ConfigFileChanged;
  213. _currentDirWatcher.EnableRaisingEvents = true;
  214. _homeDirWatcher.Changed += ConfigFileChanged;
  215. //_homeDirWatcher.Created += ConfigFileChanged;
  216. _homeDirWatcher.EnableRaisingEvents = true;
  217. }
  218. private static void StopConfigFileWatcher ()
  219. {
  220. _currentDirWatcher.EnableRaisingEvents = false;
  221. _currentDirWatcher.Changed -= ConfigFileChanged;
  222. _currentDirWatcher.Created -= ConfigFileChanged;
  223. _homeDirWatcher.EnableRaisingEvents = false;
  224. _homeDirWatcher.Changed -= ConfigFileChanged;
  225. _homeDirWatcher.Created -= ConfigFileChanged;
  226. }
  227. private static void UICatalogMain (Options options)
  228. {
  229. StartConfigFileWatcher ();
  230. // By setting _forceDriver we ensure that if the user has specified a driver on the command line, it will be used
  231. // regardless of what's in a config file.
  232. Application.ForceDriver = _forceDriver = options.Driver;
  233. // If a Scenario name has been provided on the commandline
  234. // run it and exit when done.
  235. if (options.Scenario != "none")
  236. {
  237. _topLevelColorScheme = "Base";
  238. int item = _scenarios!.FindIndex (
  239. s =>
  240. s.GetName ()
  241. .Equals (options.Scenario, StringComparison.OrdinalIgnoreCase)
  242. );
  243. _selectedScenario = (Scenario)Activator.CreateInstance (_scenarios [item].GetType ())!;
  244. Application.Init (driverName: _forceDriver);
  245. _selectedScenario.Theme = _cachedTheme;
  246. _selectedScenario.TopLevelColorScheme = _topLevelColorScheme;
  247. _selectedScenario.Init ();
  248. _selectedScenario.Setup ();
  249. _selectedScenario.Run ();
  250. _selectedScenario.Dispose ();
  251. _selectedScenario = null;
  252. Application.Shutdown ();
  253. VerifyObjectsWereDisposed ();
  254. return;
  255. }
  256. _aboutMessage = new ();
  257. _aboutMessage.AppendLine (@"A comprehensive sample library for");
  258. _aboutMessage.AppendLine (@"");
  259. _aboutMessage.AppendLine (@" _______ _ _ _____ _ ");
  260. _aboutMessage.AppendLine (@" |__ __| (_) | | / ____| (_) ");
  261. _aboutMessage.AppendLine (@" | | ___ _ __ _ __ ___ _ _ __ __ _| || | __ _ _ _ ");
  262. _aboutMessage.AppendLine (@" | |/ _ \ '__| '_ ` _ \| | '_ \ / _` | || | |_ | | | | | ");
  263. _aboutMessage.AppendLine (@" | | __/ | | | | | | | | | | | (_| | || |__| | |_| | | ");
  264. _aboutMessage.AppendLine (@" |_|\___|_| |_| |_| |_|_|_| |_|\__,_|_(_)_____|\__,_|_| ");
  265. _aboutMessage.AppendLine (@"");
  266. _aboutMessage.AppendLine (@"v2 - Work in Progress");
  267. _aboutMessage.AppendLine (@"");
  268. _aboutMessage.AppendLine (@"https://github.com/gui-cs/Terminal.Gui");
  269. while (RunUICatalogTopLevel () is { } scenario)
  270. {
  271. VerifyObjectsWereDisposed ();
  272. Themes!.Theme = _cachedTheme!;
  273. Apply ();
  274. scenario.Theme = _cachedTheme;
  275. scenario.TopLevelColorScheme = _topLevelColorScheme;
  276. scenario.Init ();
  277. scenario.Setup ();
  278. scenario.Run ();
  279. scenario.Dispose ();
  280. // This call to Application.Shutdown brackets the Application.Init call
  281. // made by Scenario.Init() above
  282. Application.Shutdown ();
  283. VerifyObjectsWereDisposed ();
  284. }
  285. StopConfigFileWatcher ();
  286. VerifyObjectsWereDisposed ();
  287. }
  288. private static void VerifyObjectsWereDisposed ()
  289. {
  290. #if DEBUG_IDISPOSABLE
  291. // Validate there are no outstanding Responder-based instances
  292. // after a scenario was selected to run. This proves the main UI Catalog
  293. // 'app' closed cleanly.
  294. foreach (Responder? inst in Responder.Instances)
  295. {
  296. Debug.Assert (inst.WasDisposed);
  297. }
  298. Responder.Instances.Clear ();
  299. // Validate there are no outstanding Application.RunState-based instances
  300. // after a scenario was selected to run. This proves the main UI Catalog
  301. // 'app' closed cleanly.
  302. foreach (RunState? inst in RunState.Instances)
  303. {
  304. Debug.Assert (inst.WasDisposed);
  305. }
  306. RunState.Instances.Clear ();
  307. #endif
  308. }
  309. /// <summary>
  310. /// This is the main UI Catalog app view. It is run fresh when the app loads (if a Scenario has not been passed on
  311. /// the command line) and each time a Scenario ends.
  312. /// </summary>
  313. public class UICatalogTopLevel : Toplevel
  314. {
  315. public ListView CategoryList;
  316. public StatusItem DriverName;
  317. public MenuItem? miForce16Colors;
  318. public MenuItem? miIsMenuBorderDisabled;
  319. public MenuItem? miIsMouseDisabled;
  320. public MenuItem? miUseSubMenusSingleFrame;
  321. public StatusItem OS;
  322. // UI Catalog uses TableView for the scenario list instead of a ListView to demonstate how
  323. // TableView works. There's no real reason not to use ListView. Because we use TableView, and TableView
  324. // doesn't (currently) have CollectionNavigator support built in, we implement it here, within the app.
  325. public TableView ScenarioList;
  326. private readonly CollectionNavigator _scenarioCollectionNav = new ();
  327. public UICatalogTopLevel ()
  328. {
  329. _themeMenuItems = CreateThemeMenuItems ();
  330. _themeMenuBarItem = new ("_Themes", _themeMenuItems);
  331. MenuBar = new()
  332. {
  333. Menus =
  334. [
  335. new (
  336. "_File",
  337. new MenuItem []
  338. {
  339. new (
  340. "_Quit",
  341. "Quit UI Catalog",
  342. RequestStop
  343. )
  344. }
  345. ),
  346. _themeMenuBarItem,
  347. new ("Diag_nostics", CreateDiagnosticMenuItems ()),
  348. new (
  349. "_Help",
  350. new MenuItem []
  351. {
  352. new (
  353. "_Documentation",
  354. "",
  355. () => OpenUrl ("https://gui-cs.github.io/Terminal.GuiV2Docs"),
  356. null,
  357. null,
  358. (KeyCode)Key.F1
  359. ),
  360. new (
  361. "_README",
  362. "",
  363. () => OpenUrl ("https://github.com/gui-cs/Terminal.Gui"),
  364. null,
  365. null,
  366. (KeyCode)Key.F2
  367. ),
  368. new (
  369. "_About...",
  370. "About UI Catalog",
  371. () => MessageBox.Query (
  372. "About UI Catalog",
  373. _aboutMessage!.ToString (),
  374. 0,
  375. false,
  376. "_Ok"
  377. ),
  378. null,
  379. null,
  380. (KeyCode)Key.A.WithCtrl
  381. )
  382. }
  383. )
  384. ]
  385. };
  386. DriverName = new (Key.Empty, "Driver:", null);
  387. OS = new (Key.Empty, "OS:", null);
  388. StatusBar = new() { Visible = ShowStatusBar };
  389. StatusBar.Items = new []
  390. {
  391. new (
  392. Application.QuitKey,
  393. $"~{Application.QuitKey} to quit",
  394. () =>
  395. {
  396. if (_selectedScenario is null)
  397. {
  398. // This causes GetScenarioToRun to return null
  399. _selectedScenario = null;
  400. RequestStop ();
  401. }
  402. else
  403. {
  404. _selectedScenario.RequestStop ();
  405. }
  406. }
  407. ),
  408. new (
  409. Key.F10,
  410. "~F10~ Status Bar",
  411. () =>
  412. {
  413. StatusBar.Visible = !StatusBar.Visible;
  414. //ContentPane!.Height = Dim.Fill(StatusBar.Visible ? 1 : 0);
  415. LayoutSubviews ();
  416. SetSubViewNeedsDisplay ();
  417. }
  418. ),
  419. DriverName,
  420. OS
  421. };
  422. // Create the Category list view. This list never changes.
  423. CategoryList = new()
  424. {
  425. X = 0,
  426. Y = 1,
  427. Width = Dim.Percent (30),
  428. Height = Dim.Fill (1),
  429. AllowsMarking = false,
  430. CanFocus = true,
  431. Title = "_Categories",
  432. BorderStyle = LineStyle.Single,
  433. SuperViewRendersLineCanvas = true,
  434. Source = new ListWrapper (_categories)
  435. };
  436. CategoryList.OpenSelectedItem += (s, a) => { ScenarioList!.SetFocus (); };
  437. CategoryList.SelectedItemChanged += CategoryView_SelectedChanged;
  438. // Create the scenario list. The contents of the scenario list changes whenever the
  439. // Category list selection changes (to show just the scenarios that belong to the selected
  440. // category).
  441. ScenarioList = new()
  442. {
  443. X = Pos.Right (CategoryList) - 1,
  444. Y = 1,
  445. Width = Dim.Fill (),
  446. Height = Dim.Fill (1),
  447. //AllowsMarking = false,
  448. CanFocus = true,
  449. Title = "_Scenarios",
  450. BorderStyle = LineStyle.Single,
  451. SuperViewRendersLineCanvas = true
  452. };
  453. // TableView provides many options for table headers. For simplicity we turn all
  454. // of these off. By enabling FullRowSelect and turning off headers, TableView looks just
  455. // like a ListView
  456. ScenarioList.FullRowSelect = true;
  457. ScenarioList.Style.ShowHeaders = false;
  458. ScenarioList.Style.ShowHorizontalHeaderOverline = false;
  459. ScenarioList.Style.ShowHorizontalHeaderUnderline = false;
  460. ScenarioList.Style.ShowHorizontalBottomline = false;
  461. ScenarioList.Style.ShowVerticalCellLines = false;
  462. ScenarioList.Style.ShowVerticalHeaderLines = false;
  463. /* By default TableView lays out columns at render time and only
  464. * measures y rows of data at a time. Where y is the height of the
  465. * console. This is for the following reasons:
  466. *
  467. * - Performance, when tables have a large amount of data
  468. * - Defensive, prevents a single wide cell value pushing other
  469. * columns off screen (requiring horizontal scrolling
  470. *
  471. * In the case of UICatalog here, such an approach is overkill so
  472. * we just measure all the data ourselves and set the appropriate
  473. * max widths as ColumnStyles
  474. */
  475. int longestName = _scenarios!.Max (s => s.GetName ().Length);
  476. ScenarioList.Style.ColumnStyles.Add (
  477. 0,
  478. new() { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  479. );
  480. ScenarioList.Style.ColumnStyles.Add (1, new() { MaxWidth = 1 });
  481. // Enable user to find & select a scenario by typing text
  482. // TableView does not (currently) have built-in CollectionNavigator support (the ability for the
  483. // user to type and the items that match get selected). We implement it in the app instead.
  484. ScenarioList.KeyDown += (s, a) =>
  485. {
  486. if (CollectionNavigatorBase.IsCompatibleKey (a))
  487. {
  488. int? newItem =
  489. _scenarioCollectionNav?.GetNextMatchingItem (
  490. ScenarioList.SelectedRow,
  491. (char)a
  492. );
  493. if (newItem is int v && newItem != -1)
  494. {
  495. ScenarioList.SelectedRow = v;
  496. ScenarioList.EnsureSelectedCellIsVisible ();
  497. ScenarioList.SetNeedsDisplay ();
  498. a.Handled = true;
  499. }
  500. }
  501. };
  502. ScenarioList.CellActivated += ScenarioView_OpenSelectedItem;
  503. // TableView typically is a grid where nav keys are biased for moving left/right.
  504. ScenarioList.KeyBindings.Add (Key.Home, Command.TopHome);
  505. ScenarioList.KeyBindings.Add (Key.End, Command.BottomEnd);
  506. // Ideally, TableView.MultiSelect = false would turn off any keybindings for
  507. // multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
  508. // a shortcut to About.
  509. ScenarioList.MultiSelect = false;
  510. ScenarioList.KeyBindings.Remove (Key.A.WithCtrl);
  511. Add (CategoryList);
  512. Add (ScenarioList);
  513. Add (MenuBar);
  514. Add (StatusBar);
  515. Loaded += LoadedHandler;
  516. Unloaded += UnloadedHandler;
  517. // Restore previous selections
  518. CategoryList.SelectedItem = _cachedCategoryIndex;
  519. ScenarioList.SelectedRow = _cachedScenarioIndex;
  520. Applied += ConfigAppliedHandler;
  521. }
  522. public void ConfigChanged ()
  523. {
  524. if (_topLevelColorScheme == null || !Colors.ColorSchemes.ContainsKey (_topLevelColorScheme))
  525. {
  526. _topLevelColorScheme = "Base";
  527. }
  528. _cachedTheme = Themes?.Theme;
  529. _themeMenuItems = CreateThemeMenuItems ();
  530. _themeMenuBarItem!.Children = _themeMenuItems;
  531. foreach (MenuItem mi in _themeMenuItems!)
  532. {
  533. if (mi is { Parent: null })
  534. {
  535. mi.Parent = _themeMenuBarItem;
  536. }
  537. }
  538. ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
  539. MenuBar.Menus [0].Children [0].Shortcut = (KeyCode)Application.QuitKey;
  540. StatusBar.Items [0].Shortcut = Application.QuitKey;
  541. StatusBar.Items [0].Title = $"~{Application.QuitKey} to quit";
  542. miIsMouseDisabled!.Checked = Application.IsMouseDisabled;
  543. int height = ShowStatusBar ? 1 : 0; // + (MenuBar.Visible ? 1 : 0);
  544. //ContentPane.Height = Dim.Fill (height);
  545. StatusBar.Visible = ShowStatusBar;
  546. Application.Top.SetNeedsDisplay ();
  547. }
  548. public MenuItem []? CreateThemeMenuItems ()
  549. {
  550. List<MenuItem> menuItems = CreateForce16ColorItems ().ToList ();
  551. menuItems.Add (null!);
  552. var schemeCount = 0;
  553. foreach (KeyValuePair<string, ThemeScope> theme in Themes!)
  554. {
  555. var item = new MenuItem
  556. {
  557. Title = $"_{theme.Key}",
  558. Shortcut = (KeyCode)new Key ((KeyCode)((uint)KeyCode.D1 + schemeCount++))
  559. .WithCtrl
  560. };
  561. item.CheckType |= MenuItemCheckStyle.Checked;
  562. item.Checked = theme.Key == _cachedTheme; // CM.Themes.Theme;
  563. item.Action += () =>
  564. {
  565. Themes.Theme = _cachedTheme = theme.Key;
  566. Apply ();
  567. };
  568. menuItems.Add (item);
  569. }
  570. List<MenuItem> schemeMenuItems = new ();
  571. foreach (KeyValuePair<string, ColorScheme> sc in Colors.ColorSchemes)
  572. {
  573. var item = new MenuItem { Title = $"_{sc.Key}", Data = sc.Key };
  574. item.CheckType |= MenuItemCheckStyle.Radio;
  575. item.Checked = sc.Key == _topLevelColorScheme;
  576. item.Action += () =>
  577. {
  578. _topLevelColorScheme = (string)item.Data;
  579. foreach (MenuItem schemeMenuItem in schemeMenuItems)
  580. {
  581. schemeMenuItem.Checked = (string)schemeMenuItem.Data == _topLevelColorScheme;
  582. }
  583. ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
  584. Application.Top.SetNeedsDisplay ();
  585. };
  586. schemeMenuItems.Add (item);
  587. }
  588. menuItems.Add (null!);
  589. var mbi = new MenuBarItem ("_Color Scheme for Application.Top", schemeMenuItems.ToArray ());
  590. menuItems.Add (mbi);
  591. return menuItems.ToArray ();
  592. }
  593. private void CategoryView_SelectedChanged (object? sender, ListViewItemEventArgs? e)
  594. {
  595. string item = _categories! [e!.Item];
  596. List<Scenario> newlist;
  597. if (e.Item == 0)
  598. {
  599. // First category is "All"
  600. newlist = _scenarios!;
  601. newlist = _scenarios!;
  602. }
  603. else
  604. {
  605. newlist = _scenarios!.Where (s => s.GetCategories ().Contains (item)).ToList ();
  606. }
  607. ScenarioList.Table = new EnumerableTableSource<Scenario> (
  608. newlist,
  609. new()
  610. {
  611. { "Name", s => s.GetName () }, { "Description", s => s.GetDescription () }
  612. }
  613. );
  614. // Create a collection of just the scenario names (the 1st column in our TableView)
  615. // for CollectionNavigator.
  616. List<object> firstColumnList = new ();
  617. for (var i = 0; i < ScenarioList.Table.Rows; i++)
  618. {
  619. firstColumnList.Add (ScenarioList.Table [i, 0]);
  620. }
  621. _scenarioCollectionNav.Collection = firstColumnList;
  622. }
  623. private void ConfigAppliedHandler (object? sender, ConfigurationManagerEventArgs? a) { ConfigChanged (); }
  624. private MenuItem [] CreateDiagnosticFlagsMenuItems ()
  625. {
  626. const string OFF = "View Diagnostics: _Off";
  627. const string RULER = "View Diagnostics: _Ruler";
  628. const string PADDING = "View Diagnostics: _Padding";
  629. var index = 0;
  630. List<MenuItem> menuItems = new ();
  631. foreach (Enum diag in Enum.GetValues (_diagnosticFlags.GetType ()))
  632. {
  633. var item = new MenuItem
  634. {
  635. Title = GetDiagnosticsTitle (diag), Shortcut = (KeyCode)new Key (index.ToString () [0]).WithAlt
  636. };
  637. index++;
  638. item.CheckType |= MenuItemCheckStyle.Checked;
  639. if (GetDiagnosticsTitle (ViewDiagnosticFlags.Off) == item.Title)
  640. {
  641. item.Checked = !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Padding) && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Ruler);
  642. }
  643. else
  644. {
  645. item.Checked = _diagnosticFlags.HasFlag (diag);
  646. }
  647. item.Action += () =>
  648. {
  649. string t = GetDiagnosticsTitle (ViewDiagnosticFlags.Off);
  650. if (item.Title == t && item.Checked == false)
  651. {
  652. _diagnosticFlags &= ~(ViewDiagnosticFlags.Padding | ViewDiagnosticFlags.Ruler);
  653. item.Checked = true;
  654. }
  655. else if (item.Title == t && item.Checked == true)
  656. {
  657. _diagnosticFlags |= ViewDiagnosticFlags.Padding | ViewDiagnosticFlags.Ruler;
  658. item.Checked = false;
  659. }
  660. else
  661. {
  662. Enum f = GetDiagnosticsEnumValue (item.Title);
  663. if (_diagnosticFlags.HasFlag (f))
  664. {
  665. SetDiagnosticsFlag (f, false);
  666. }
  667. else
  668. {
  669. SetDiagnosticsFlag (f, true);
  670. }
  671. }
  672. foreach (MenuItem menuItem in menuItems)
  673. {
  674. if (menuItem.Title == t)
  675. {
  676. menuItem.Checked = !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Ruler)
  677. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Padding);
  678. }
  679. else if (menuItem.Title != t)
  680. {
  681. menuItem.Checked = _diagnosticFlags.HasFlag (GetDiagnosticsEnumValue (menuItem.Title));
  682. }
  683. }
  684. Diagnostics = _diagnosticFlags;
  685. Application.Top.SetNeedsDisplay ();
  686. };
  687. menuItems.Add (item);
  688. }
  689. return menuItems.ToArray ();
  690. string GetDiagnosticsTitle (Enum diag)
  691. {
  692. return Enum.GetName (_diagnosticFlags.GetType (), diag) switch
  693. {
  694. "Off" => OFF,
  695. "Ruler" => RULER,
  696. "Padding" => PADDING,
  697. _ => ""
  698. };
  699. }
  700. Enum GetDiagnosticsEnumValue (string title)
  701. {
  702. return title switch
  703. {
  704. RULER => ViewDiagnosticFlags.Ruler,
  705. PADDING => ViewDiagnosticFlags.Padding,
  706. _ => null!
  707. };
  708. }
  709. void SetDiagnosticsFlag (Enum diag, bool add)
  710. {
  711. switch (diag)
  712. {
  713. case ViewDiagnosticFlags.Ruler:
  714. if (add)
  715. {
  716. _diagnosticFlags |= ViewDiagnosticFlags.Ruler;
  717. }
  718. else
  719. {
  720. _diagnosticFlags &= ~ViewDiagnosticFlags.Ruler;
  721. }
  722. break;
  723. case ViewDiagnosticFlags.Padding:
  724. if (add)
  725. {
  726. _diagnosticFlags |= ViewDiagnosticFlags.Padding;
  727. }
  728. else
  729. {
  730. _diagnosticFlags &= ~ViewDiagnosticFlags.Padding;
  731. }
  732. break;
  733. default:
  734. _diagnosticFlags = default (ViewDiagnosticFlags);
  735. break;
  736. }
  737. }
  738. }
  739. private List<MenuItem []> CreateDiagnosticMenuItems ()
  740. {
  741. List<MenuItem []> menuItems = new ()
  742. {
  743. CreateDiagnosticFlagsMenuItems (),
  744. new MenuItem [] { null! },
  745. CreateDisabledEnabledMouseItems (),
  746. CreateDisabledEnabledMenuBorder (),
  747. CreateDisabledEnableUseSubMenusSingleFrame (),
  748. CreateKeyBindingsMenuItems ()
  749. };
  750. return menuItems;
  751. }
  752. // TODO: This should be an ConfigurationManager setting
  753. private MenuItem [] CreateDisabledEnabledMenuBorder ()
  754. {
  755. List<MenuItem> menuItems = new ();
  756. miIsMenuBorderDisabled = new() { Title = "Disable Menu _Border" };
  757. miIsMenuBorderDisabled.Shortcut =
  758. (KeyCode)new Key (miIsMenuBorderDisabled!.Title!.Substring (14, 1) [0]).WithAlt
  759. .WithCtrl;
  760. miIsMenuBorderDisabled.CheckType |= MenuItemCheckStyle.Checked;
  761. miIsMenuBorderDisabled.Action += () =>
  762. {
  763. miIsMenuBorderDisabled.Checked = (bool)!miIsMenuBorderDisabled.Checked!;
  764. MenuBar.MenusBorderStyle = !(bool)miIsMenuBorderDisabled.Checked
  765. ? LineStyle.Single
  766. : LineStyle.None;
  767. };
  768. menuItems.Add (miIsMenuBorderDisabled);
  769. return menuItems.ToArray ();
  770. }
  771. private MenuItem [] CreateDisabledEnabledMouseItems ()
  772. {
  773. List<MenuItem> menuItems = new ();
  774. miIsMouseDisabled = new() { Title = "_Disable Mouse" };
  775. miIsMouseDisabled.Shortcut =
  776. (KeyCode)new Key (miIsMouseDisabled!.Title!.Substring (1, 1) [0]).WithAlt.WithCtrl;
  777. miIsMouseDisabled.CheckType |= MenuItemCheckStyle.Checked;
  778. miIsMouseDisabled.Action += () =>
  779. {
  780. miIsMouseDisabled.Checked =
  781. Application.IsMouseDisabled = (bool)!miIsMouseDisabled.Checked!;
  782. };
  783. menuItems.Add (miIsMouseDisabled);
  784. return menuItems.ToArray ();
  785. }
  786. // TODO: This should be an ConfigurationManager setting
  787. private MenuItem [] CreateDisabledEnableUseSubMenusSingleFrame ()
  788. {
  789. List<MenuItem> menuItems = new ();
  790. miUseSubMenusSingleFrame = new() { Title = "Enable _Sub-Menus Single Frame" };
  791. miUseSubMenusSingleFrame.Shortcut = KeyCode.CtrlMask
  792. | KeyCode.AltMask
  793. | (KeyCode)miUseSubMenusSingleFrame!.Title!.Substring (8, 1) [
  794. 0];
  795. miUseSubMenusSingleFrame.CheckType |= MenuItemCheckStyle.Checked;
  796. miUseSubMenusSingleFrame.Action += () =>
  797. {
  798. miUseSubMenusSingleFrame.Checked = (bool)!miUseSubMenusSingleFrame.Checked!;
  799. MenuBar.UseSubMenusSingleFrame = (bool)miUseSubMenusSingleFrame.Checked;
  800. };
  801. menuItems.Add (miUseSubMenusSingleFrame);
  802. return menuItems.ToArray ();
  803. }
  804. private MenuItem [] CreateForce16ColorItems ()
  805. {
  806. List<MenuItem> menuItems = new ();
  807. miForce16Colors = new()
  808. {
  809. Title = "Force _16 Colors",
  810. Shortcut = (KeyCode)Key.F6,
  811. Checked = Application.Force16Colors,
  812. CanExecute = () => Application.Driver.SupportsTrueColor
  813. };
  814. miForce16Colors.CheckType |= MenuItemCheckStyle.Checked;
  815. miForce16Colors.Action += () =>
  816. {
  817. miForce16Colors.Checked = Application.Force16Colors = (bool)!miForce16Colors.Checked!;
  818. Application.Refresh ();
  819. };
  820. menuItems.Add (miForce16Colors);
  821. return menuItems.ToArray ();
  822. }
  823. private MenuItem [] CreateKeyBindingsMenuItems ()
  824. {
  825. List<MenuItem> menuItems = new ();
  826. var item = new MenuItem { Title = "_Key Bindings", Help = "Change which keys do what" };
  827. item.Action += () =>
  828. {
  829. var dlg = new KeyBindingsDialog ();
  830. Application.Run (dlg);
  831. };
  832. menuItems.Add (null!);
  833. menuItems.Add (item);
  834. return menuItems.ToArray ();
  835. }
  836. private void LoadedHandler (object? sender, EventArgs? args)
  837. {
  838. ConfigChanged ();
  839. miIsMouseDisabled!.Checked = Application.IsMouseDisabled;
  840. DriverName.Title = $"Driver: {Driver.GetVersionInfo ()}";
  841. OS.Title =
  842. $"OS: {RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}";
  843. if (_selectedScenario != null)
  844. {
  845. _selectedScenario = null;
  846. _isFirstRunning = false;
  847. }
  848. if (!_isFirstRunning)
  849. {
  850. ScenarioList.SetFocus ();
  851. }
  852. StatusBar.VisibleChanged += (s, e) =>
  853. {
  854. ShowStatusBar = StatusBar.Visible;
  855. int height = StatusBar.Visible ? 1 : 0;
  856. CategoryList.Height = Dim.Fill (height);
  857. ScenarioList.Height = Dim.Fill (height);
  858. // ContentPane.Height = Dim.Fill (height);
  859. LayoutSubviews ();
  860. SetSubViewNeedsDisplay ();
  861. };
  862. Loaded -= LoadedHandler;
  863. CategoryList.EnsureSelectedItemVisible ();
  864. ScenarioList.EnsureSelectedCellIsVisible ();
  865. }
  866. /// <summary>Launches the selected scenario, setting the global _selectedScenario</summary>
  867. /// <param name="e"></param>
  868. private void ScenarioView_OpenSelectedItem (object? sender, EventArgs? e)
  869. {
  870. if (_selectedScenario is null)
  871. {
  872. // Save selected item state
  873. _cachedCategoryIndex = CategoryList.SelectedItem;
  874. _cachedScenarioIndex = ScenarioList.SelectedRow;
  875. // Create new instance of scenario (even though Scenarios contains instances)
  876. var selectedScenarioName = (string)ScenarioList.Table [ScenarioList.SelectedRow, 0];
  877. _selectedScenario = (Scenario)Activator.CreateInstance (
  878. _scenarios!.FirstOrDefault (
  879. s => s.GetName ()
  880. == selectedScenarioName
  881. )!
  882. .GetType ()
  883. )!;
  884. // Tell the main app to stop
  885. Application.RequestStop ();
  886. }
  887. }
  888. private void UnloadedHandler (object? sender, EventArgs? args)
  889. {
  890. Applied -= ConfigAppliedHandler;
  891. Unloaded -= UnloadedHandler;
  892. }
  893. }
  894. private struct Options
  895. {
  896. public string Driver;
  897. public string Scenario;
  898. /* etc. */
  899. }
  900. }