UICatalog.cs 46 KB

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