UICatalog.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. }
  403. ),
  404. new (
  405. Key.F10,
  406. "~F10~ Status Bar",
  407. () =>
  408. {
  409. StatusBar.Visible = !StatusBar.Visible;
  410. //ContentPane!.Height = Dim.Fill(StatusBar.Visible ? 1 : 0);
  411. LayoutSubviews ();
  412. SetSubViewNeedsDisplay ();
  413. }
  414. ),
  415. DriverName,
  416. OS
  417. };
  418. // Create the Category list view. This list never changes.
  419. CategoryList = new ()
  420. {
  421. X = 0,
  422. Y = 1,
  423. Width = Dim.Percent (30),
  424. Height = Dim.Fill (1),
  425. AllowsMarking = false,
  426. CanFocus = true,
  427. Title = "_Categories",
  428. BorderStyle = LineStyle.Single,
  429. SuperViewRendersLineCanvas = true,
  430. Source = new ListWrapper (_categories)
  431. };
  432. CategoryList.OpenSelectedItem += (s, a) => { ScenarioList!.SetFocus (); };
  433. CategoryList.SelectedItemChanged += CategoryView_SelectedChanged;
  434. // Create the scenario list. The contents of the scenario list changes whenever the
  435. // Category list selection changes (to show just the scenarios that belong to the selected
  436. // category).
  437. ScenarioList = new ()
  438. {
  439. X = Pos.Right (CategoryList) - 1,
  440. Y = 1,
  441. Width = Dim.Fill (),
  442. Height = Dim.Fill (1),
  443. //AllowsMarking = false,
  444. CanFocus = true,
  445. Title = "_Scenarios",
  446. BorderStyle = LineStyle.Single,
  447. SuperViewRendersLineCanvas = true
  448. };
  449. // TableView provides many options for table headers. For simplicity we turn all
  450. // of these off. By enabling FullRowSelect and turning off headers, TableView looks just
  451. // like a ListView
  452. ScenarioList.FullRowSelect = true;
  453. ScenarioList.Style.ShowHeaders = false;
  454. ScenarioList.Style.ShowHorizontalHeaderOverline = false;
  455. ScenarioList.Style.ShowHorizontalHeaderUnderline = false;
  456. ScenarioList.Style.ShowHorizontalBottomline = false;
  457. ScenarioList.Style.ShowVerticalCellLines = false;
  458. ScenarioList.Style.ShowVerticalHeaderLines = false;
  459. /* By default TableView lays out columns at render time and only
  460. * measures y rows of data at a time. Where y is the height of the
  461. * console. This is for the following reasons:
  462. *
  463. * - Performance, when tables have a large amount of data
  464. * - Defensive, prevents a single wide cell value pushing other
  465. * columns off screen (requiring horizontal scrolling
  466. *
  467. * In the case of UICatalog here, such an approach is overkill so
  468. * we just measure all the data ourselves and set the appropriate
  469. * max widths as ColumnStyles
  470. */
  471. int longestName = _scenarios!.Max (s => s.GetName ().Length);
  472. ScenarioList.Style.ColumnStyles.Add (
  473. 0,
  474. new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  475. );
  476. ScenarioList.Style.ColumnStyles.Add (1, new () { MaxWidth = 1 });
  477. // Enable user to find & select a scenario by typing text
  478. // TableView does not (currently) have built-in CollectionNavigator support (the ability for the
  479. // user to type and the items that match get selected). We implement it in the app instead.
  480. ScenarioList.KeyDown += (s, a) =>
  481. {
  482. if (CollectionNavigatorBase.IsCompatibleKey (a))
  483. {
  484. int? newItem =
  485. _scenarioCollectionNav?.GetNextMatchingItem (
  486. ScenarioList.SelectedRow,
  487. (char)a
  488. );
  489. if (newItem is int v && newItem != -1)
  490. {
  491. ScenarioList.SelectedRow = v;
  492. ScenarioList.EnsureSelectedCellIsVisible ();
  493. ScenarioList.SetNeedsDisplay ();
  494. a.Handled = true;
  495. }
  496. }
  497. };
  498. ScenarioList.CellActivated += ScenarioView_OpenSelectedItem;
  499. // TableView typically is a grid where nav keys are biased for moving left/right.
  500. ScenarioList.KeyBindings.Add (Key.Home, Command.TopHome);
  501. ScenarioList.KeyBindings.Add (Key.End, Command.BottomEnd);
  502. // Ideally, TableView.MultiSelect = false would turn off any keybindings for
  503. // multi-select options. But it currently does not. UI Catalog uses Ctrl-A for
  504. // a shortcut to About.
  505. ScenarioList.MultiSelect = false;
  506. ScenarioList.KeyBindings.Remove (Key.A.WithCtrl);
  507. Add (CategoryList);
  508. Add (ScenarioList);
  509. Add (MenuBar);
  510. Add (StatusBar);
  511. Loaded += LoadedHandler;
  512. Unloaded += UnloadedHandler;
  513. // Restore previous selections
  514. CategoryList.SelectedItem = _cachedCategoryIndex;
  515. ScenarioList.SelectedRow = _cachedScenarioIndex;
  516. Applied += ConfigAppliedHandler;
  517. }
  518. public void ConfigChanged ()
  519. {
  520. if (_topLevelColorScheme == null || !Colors.ColorSchemes.ContainsKey (_topLevelColorScheme))
  521. {
  522. _topLevelColorScheme = "Base";
  523. }
  524. _cachedTheme = Themes?.Theme;
  525. _themeMenuItems = CreateThemeMenuItems ();
  526. _themeMenuBarItem!.Children = _themeMenuItems;
  527. foreach (MenuItem mi in _themeMenuItems!)
  528. {
  529. if (mi is { Parent: null })
  530. {
  531. mi.Parent = _themeMenuBarItem;
  532. }
  533. }
  534. ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
  535. MenuBar.Menus [0].Children [0].Shortcut = (KeyCode)Application.QuitKey;
  536. StatusBar.Items [0].Shortcut = Application.QuitKey;
  537. StatusBar.Items [0].Title = $"~{Application.QuitKey} to quit";
  538. miIsMouseDisabled!.Checked = Application.IsMouseDisabled;
  539. int height = ShowStatusBar ? 1 : 0; // + (MenuBar.Visible ? 1 : 0);
  540. //ContentPane.Height = Dim.Fill (height);
  541. StatusBar.Visible = ShowStatusBar;
  542. Application.Top.SetNeedsDisplay ();
  543. }
  544. public MenuItem []? CreateThemeMenuItems ()
  545. {
  546. List<MenuItem> menuItems = CreateForce16ColorItems ().ToList ();
  547. menuItems.Add (null!);
  548. var schemeCount = 0;
  549. foreach (KeyValuePair<string, ThemeScope> theme in Themes!)
  550. {
  551. var item = new MenuItem
  552. {
  553. Title = $"_{theme.Key}",
  554. Shortcut = (KeyCode)new Key ((KeyCode)((uint)KeyCode.D1 + schemeCount++))
  555. .WithCtrl
  556. };
  557. item.CheckType |= MenuItemCheckStyle.Checked;
  558. item.Checked = theme.Key == _cachedTheme; // CM.Themes.Theme;
  559. item.Action += () =>
  560. {
  561. Themes.Theme = _cachedTheme = theme.Key;
  562. Apply ();
  563. };
  564. menuItems.Add (item);
  565. }
  566. List<MenuItem> schemeMenuItems = new ();
  567. foreach (KeyValuePair<string, ColorScheme> sc in Colors.ColorSchemes)
  568. {
  569. var item = new MenuItem { Title = $"_{sc.Key}", Data = sc.Key };
  570. item.CheckType |= MenuItemCheckStyle.Radio;
  571. item.Checked = sc.Key == _topLevelColorScheme;
  572. item.Action += () =>
  573. {
  574. _topLevelColorScheme = (string)item.Data;
  575. foreach (MenuItem schemeMenuItem in schemeMenuItems)
  576. {
  577. schemeMenuItem.Checked = (string)schemeMenuItem.Data == _topLevelColorScheme;
  578. }
  579. ColorScheme = Colors.ColorSchemes [_topLevelColorScheme];
  580. Application.Top.SetNeedsDisplay ();
  581. };
  582. schemeMenuItems.Add (item);
  583. }
  584. menuItems.Add (null!);
  585. var mbi = new MenuBarItem ("_Color Scheme for Application.Top", schemeMenuItems.ToArray ());
  586. menuItems.Add (mbi);
  587. return menuItems.ToArray ();
  588. }
  589. private void CategoryView_SelectedChanged (object? sender, ListViewItemEventArgs? e)
  590. {
  591. string item = _categories! [e!.Item];
  592. List<Scenario> newlist;
  593. if (e.Item == 0)
  594. {
  595. // First category is "All"
  596. newlist = _scenarios!;
  597. newlist = _scenarios!;
  598. }
  599. else
  600. {
  601. newlist = _scenarios!.Where (s => s.GetCategories ().Contains (item)).ToList ();
  602. }
  603. ScenarioList.Table = new EnumerableTableSource<Scenario> (
  604. newlist,
  605. new ()
  606. {
  607. { "Name", s => s.GetName () }, { "Description", s => s.GetDescription () }
  608. }
  609. );
  610. // Create a collection of just the scenario names (the 1st column in our TableView)
  611. // for CollectionNavigator.
  612. List<object> firstColumnList = new ();
  613. for (var i = 0; i < ScenarioList.Table.Rows; i++)
  614. {
  615. firstColumnList.Add (ScenarioList.Table [i, 0]);
  616. }
  617. _scenarioCollectionNav.Collection = firstColumnList;
  618. }
  619. private void ConfigAppliedHandler (object? sender, ConfigurationManagerEventArgs? a) { ConfigChanged (); }
  620. private MenuItem [] CreateDiagnosticFlagsMenuItems ()
  621. {
  622. const string OFF = "View Diagnostics: _Off";
  623. const string RULER = "View Diagnostics: _Ruler";
  624. const string PADDING = "View Diagnostics: _Padding";
  625. const string MOUSEENTER = "View Diagnostics: _MouseEnter";
  626. var index = 0;
  627. List<MenuItem> menuItems = new ();
  628. foreach (Enum diag in Enum.GetValues (_diagnosticFlags.GetType ()))
  629. {
  630. var item = new MenuItem
  631. {
  632. Title = GetDiagnosticsTitle (diag), Shortcut = (KeyCode)new Key (index.ToString () [0]).WithAlt
  633. };
  634. index++;
  635. item.CheckType |= MenuItemCheckStyle.Checked;
  636. if (GetDiagnosticsTitle (ViewDiagnosticFlags.Off) == item.Title)
  637. {
  638. item.Checked = !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Padding)
  639. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Ruler)
  640. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.MouseEnter);
  641. }
  642. else
  643. {
  644. item.Checked = _diagnosticFlags.HasFlag (diag);
  645. }
  646. item.Action += () =>
  647. {
  648. string t = GetDiagnosticsTitle (ViewDiagnosticFlags.Off);
  649. if (item.Title == t && item.Checked == false)
  650. {
  651. _diagnosticFlags &= ~(ViewDiagnosticFlags.Padding | ViewDiagnosticFlags.Ruler | ViewDiagnosticFlags.MouseEnter);
  652. item.Checked = true;
  653. }
  654. else if (item.Title == t && item.Checked == true)
  655. {
  656. _diagnosticFlags |= ViewDiagnosticFlags.Padding | ViewDiagnosticFlags.Ruler | ViewDiagnosticFlags.MouseEnter;
  657. item.Checked = false;
  658. }
  659. else
  660. {
  661. Enum f = GetDiagnosticsEnumValue (item.Title);
  662. if (_diagnosticFlags.HasFlag (f))
  663. {
  664. SetDiagnosticsFlag (f, false);
  665. }
  666. else
  667. {
  668. SetDiagnosticsFlag (f, true);
  669. }
  670. }
  671. foreach (MenuItem menuItem in menuItems)
  672. {
  673. if (menuItem.Title == t)
  674. {
  675. menuItem.Checked = !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Ruler)
  676. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.Padding)
  677. && !_diagnosticFlags.HasFlag (ViewDiagnosticFlags.MouseEnter);
  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. "MouseEnter" => MOUSEENTER,
  698. _ => ""
  699. };
  700. }
  701. Enum GetDiagnosticsEnumValue (string title)
  702. {
  703. return title switch
  704. {
  705. RULER => ViewDiagnosticFlags.Ruler,
  706. PADDING => ViewDiagnosticFlags.Padding,
  707. MOUSEENTER => ViewDiagnosticFlags.MouseEnter,
  708. _ => null!
  709. };
  710. }
  711. void SetDiagnosticsFlag (Enum diag, bool add)
  712. {
  713. switch (diag)
  714. {
  715. case ViewDiagnosticFlags.Ruler:
  716. if (add)
  717. {
  718. _diagnosticFlags |= ViewDiagnosticFlags.Ruler;
  719. }
  720. else
  721. {
  722. _diagnosticFlags &= ~ViewDiagnosticFlags.Ruler;
  723. }
  724. break;
  725. case ViewDiagnosticFlags.Padding:
  726. if (add)
  727. {
  728. _diagnosticFlags |= ViewDiagnosticFlags.Padding;
  729. }
  730. else
  731. {
  732. _diagnosticFlags &= ~ViewDiagnosticFlags.Padding;
  733. }
  734. break;
  735. case ViewDiagnosticFlags.MouseEnter:
  736. if (add)
  737. {
  738. _diagnosticFlags |= ViewDiagnosticFlags.MouseEnter;
  739. }
  740. else
  741. {
  742. _diagnosticFlags &= ~ViewDiagnosticFlags.MouseEnter;
  743. }
  744. break;
  745. default:
  746. _diagnosticFlags = default (ViewDiagnosticFlags);
  747. break;
  748. }
  749. }
  750. }
  751. private List<MenuItem []> CreateDiagnosticMenuItems ()
  752. {
  753. List<MenuItem []> menuItems = new ()
  754. {
  755. CreateDiagnosticFlagsMenuItems (),
  756. new MenuItem [] { null! },
  757. CreateDisabledEnabledMouseItems (),
  758. CreateDisabledEnabledMenuBorder (),
  759. CreateDisabledEnableUseSubMenusSingleFrame (),
  760. CreateKeyBindingsMenuItems ()
  761. };
  762. return menuItems;
  763. }
  764. // TODO: This should be an ConfigurationManager setting
  765. private MenuItem [] CreateDisabledEnabledMenuBorder ()
  766. {
  767. List<MenuItem> menuItems = new ();
  768. miIsMenuBorderDisabled = new () { Title = "Disable Menu _Border" };
  769. miIsMenuBorderDisabled.Shortcut =
  770. (KeyCode)new Key (miIsMenuBorderDisabled!.Title!.Substring (14, 1) [0]).WithAlt
  771. .WithCtrl;
  772. miIsMenuBorderDisabled.CheckType |= MenuItemCheckStyle.Checked;
  773. miIsMenuBorderDisabled.Action += () =>
  774. {
  775. miIsMenuBorderDisabled.Checked = (bool)!miIsMenuBorderDisabled.Checked!;
  776. MenuBar.MenusBorderStyle = !(bool)miIsMenuBorderDisabled.Checked
  777. ? LineStyle.Single
  778. : LineStyle.None;
  779. };
  780. menuItems.Add (miIsMenuBorderDisabled);
  781. return menuItems.ToArray ();
  782. }
  783. private MenuItem [] CreateDisabledEnabledMouseItems ()
  784. {
  785. List<MenuItem> menuItems = new ();
  786. miIsMouseDisabled = new () { Title = "_Disable Mouse" };
  787. miIsMouseDisabled.Shortcut =
  788. (KeyCode)new Key (miIsMouseDisabled!.Title!.Substring (1, 1) [0]).WithAlt.WithCtrl;
  789. miIsMouseDisabled.CheckType |= MenuItemCheckStyle.Checked;
  790. miIsMouseDisabled.Action += () =>
  791. {
  792. miIsMouseDisabled.Checked =
  793. Application.IsMouseDisabled = (bool)!miIsMouseDisabled.Checked!;
  794. };
  795. menuItems.Add (miIsMouseDisabled);
  796. return menuItems.ToArray ();
  797. }
  798. // TODO: This should be an ConfigurationManager setting
  799. private MenuItem [] CreateDisabledEnableUseSubMenusSingleFrame ()
  800. {
  801. List<MenuItem> menuItems = new ();
  802. miUseSubMenusSingleFrame = new () { Title = "Enable _Sub-Menus Single Frame" };
  803. miUseSubMenusSingleFrame.Shortcut = KeyCode.CtrlMask
  804. | KeyCode.AltMask
  805. | (KeyCode)miUseSubMenusSingleFrame!.Title!.Substring (8, 1) [
  806. 0];
  807. miUseSubMenusSingleFrame.CheckType |= MenuItemCheckStyle.Checked;
  808. miUseSubMenusSingleFrame.Action += () =>
  809. {
  810. miUseSubMenusSingleFrame.Checked = (bool)!miUseSubMenusSingleFrame.Checked!;
  811. MenuBar.UseSubMenusSingleFrame = (bool)miUseSubMenusSingleFrame.Checked;
  812. };
  813. menuItems.Add (miUseSubMenusSingleFrame);
  814. return menuItems.ToArray ();
  815. }
  816. private MenuItem [] CreateForce16ColorItems ()
  817. {
  818. List<MenuItem> menuItems = new ();
  819. miForce16Colors = new ()
  820. {
  821. Title = "Force _16 Colors",
  822. Shortcut = (KeyCode)Key.F6,
  823. Checked = Application.Force16Colors,
  824. CanExecute = () => Application.Driver.SupportsTrueColor
  825. };
  826. miForce16Colors.CheckType |= MenuItemCheckStyle.Checked;
  827. miForce16Colors.Action += () =>
  828. {
  829. miForce16Colors.Checked = Application.Force16Colors = (bool)!miForce16Colors.Checked!;
  830. Application.Refresh ();
  831. };
  832. menuItems.Add (miForce16Colors);
  833. return menuItems.ToArray ();
  834. }
  835. private MenuItem [] CreateKeyBindingsMenuItems ()
  836. {
  837. List<MenuItem> menuItems = new ();
  838. var item = new MenuItem { Title = "_Key Bindings", Help = "Change which keys do what" };
  839. item.Action += () =>
  840. {
  841. var dlg = new KeyBindingsDialog ();
  842. Application.Run (dlg);
  843. dlg.Dispose ();
  844. };
  845. menuItems.Add (null!);
  846. menuItems.Add (item);
  847. return menuItems.ToArray ();
  848. }
  849. private void LoadedHandler (object? sender, EventArgs? args)
  850. {
  851. ConfigChanged ();
  852. miIsMouseDisabled!.Checked = Application.IsMouseDisabled;
  853. DriverName.Title = $"Driver: {Driver.GetVersionInfo ()}";
  854. OS.Title =
  855. $"OS: {RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}";
  856. if (_selectedScenario != null)
  857. {
  858. _selectedScenario = null;
  859. _isFirstRunning = false;
  860. }
  861. if (!_isFirstRunning)
  862. {
  863. ScenarioList.SetFocus ();
  864. }
  865. StatusBar.VisibleChanged += (s, e) =>
  866. {
  867. ShowStatusBar = StatusBar.Visible;
  868. int height = StatusBar.Visible ? 1 : 0;
  869. CategoryList.Height = Dim.Fill (height);
  870. ScenarioList.Height = Dim.Fill (height);
  871. // ContentPane.Height = Dim.Fill (height);
  872. LayoutSubviews ();
  873. SetSubViewNeedsDisplay ();
  874. };
  875. Loaded -= LoadedHandler;
  876. CategoryList.EnsureSelectedItemVisible ();
  877. ScenarioList.EnsureSelectedCellIsVisible ();
  878. }
  879. /// <summary>Launches the selected scenario, setting the global _selectedScenario</summary>
  880. /// <param name="e"></param>
  881. private void ScenarioView_OpenSelectedItem (object? sender, EventArgs? e)
  882. {
  883. if (_selectedScenario is null)
  884. {
  885. // Save selected item state
  886. _cachedCategoryIndex = CategoryList.SelectedItem;
  887. _cachedScenarioIndex = ScenarioList.SelectedRow;
  888. // Create new instance of scenario (even though Scenarios contains instances)
  889. var selectedScenarioName = (string)ScenarioList.Table [ScenarioList.SelectedRow, 0];
  890. _selectedScenario = (Scenario)Activator.CreateInstance (
  891. _scenarios!.FirstOrDefault (
  892. s => s.GetName ()
  893. == selectedScenarioName
  894. )!
  895. .GetType ()
  896. )!;
  897. // Tell the main app to stop
  898. Application.RequestStop ();
  899. }
  900. }
  901. private void UnloadedHandler (object? sender, EventArgs? args)
  902. {
  903. Applied -= ConfigAppliedHandler;
  904. Unloaded -= UnloadedHandler;
  905. Dispose ();
  906. }
  907. }
  908. private struct Options
  909. {
  910. public string Driver;
  911. public string Scenario;
  912. /* etc. */
  913. }
  914. }