UICatalog.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. }