UICatalog.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using NStack;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using Terminal.Gui;
  9. /// <remarks>
  10. /// <para>
  11. /// UI Catalog attempts to satisfy the following goals:
  12. /// </para>
  13. /// <para>
  14. /// <list type="number">
  15. /// <item>
  16. /// <description>
  17. /// Be an easy to use showcase for Terminal.Gui concepts and features.
  18. /// </description>
  19. /// </item>
  20. /// <item>
  21. /// <description>
  22. /// Provide sample code that illustrates how to properly implement said concepts & features.
  23. /// </description>
  24. /// </item>
  25. /// <item>
  26. /// <description>
  27. /// Make it easy for contributors to add additional samples in a structured way.
  28. /// </description>
  29. /// </item>
  30. /// </list>
  31. /// </para>
  32. /// <para>
  33. /// See the project README for more details (https://github.com/migueldeicaza/gui.cs/tree/master/UICatalog/README.md).
  34. /// </para>
  35. /// </remarks>
  36. namespace UICatalog {
  37. /// <summary>
  38. /// UI Catalog is a comprehensive sample app and scenario library for <see cref="Terminal.Gui"/>
  39. /// </summary>
  40. public class UICatalogApp {
  41. private static Toplevel _top;
  42. private static MenuBar _menu;
  43. private static int _nameColumnWidth;
  44. private static Window _leftPane;
  45. private static List<string> _categories;
  46. private static ListView _categoryListView;
  47. private static Window _rightPane;
  48. private static List<Type> _scenarios;
  49. private static ListView _scenarioListView;
  50. private static StatusBar _statusBar;
  51. private static StatusItem _capslock;
  52. private static StatusItem _numlock;
  53. private static StatusItem _scrolllock;
  54. private static Scenario _runningScenario = null;
  55. private static bool _useSystemConsole = false;
  56. private static MenuItem _sysConsoleMenu;
  57. static void Main (string [] args)
  58. {
  59. if (Debugger.IsAttached)
  60. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  61. _scenarios = Scenario.GetDerivedClassesCollection ().OrderBy (t => Scenario.ScenarioMetadata.GetName (t)).ToList ();
  62. if (args.Length > 0) {
  63. var item = _scenarios.FindIndex (t => Scenario.ScenarioMetadata.GetName (t).Equals (args [0], StringComparison.OrdinalIgnoreCase));
  64. _runningScenario = (Scenario)Activator.CreateInstance (_scenarios [item]);
  65. Application.Init ();
  66. _runningScenario.Init (Application.Top);
  67. _runningScenario.Setup ();
  68. _runningScenario.Run ();
  69. _runningScenario = null;
  70. return;
  71. }
  72. Scenario scenario = GetScenarioToRun ();
  73. while (scenario != null) {
  74. Application.UseSystemConsole = _useSystemConsole;
  75. Application.Init ();
  76. scenario.Init (Application.Top);
  77. scenario.Setup ();
  78. scenario.Run ();
  79. scenario = GetScenarioToRun ();
  80. }
  81. // Now closes the driver too.
  82. Application.Shutdown ();
  83. }
  84. /// <summary>
  85. /// This shows the selection UI. Each time it is run, it calls Application.Init to reset everything.
  86. /// </summary>
  87. /// <returns></returns>
  88. private static Scenario GetScenarioToRun ()
  89. {
  90. Application.UseSystemConsole = false;
  91. Application.Init ();
  92. if (_menu == null) {
  93. Setup ();
  94. }
  95. _top = Application.Top;
  96. _top.KeyDown += KeyDownHandler;
  97. _top.Add (_menu);
  98. _top.Add (_leftPane);
  99. _top.Add (_rightPane);
  100. _top.Add (_statusBar);
  101. _top.Ready += (o, a) => {
  102. if (_runningScenario != null) {
  103. _top.SetFocus (_rightPane);
  104. _runningScenario = null;
  105. }
  106. };
  107. Application.Run (_top, false);
  108. Application.Shutdown ();
  109. return _runningScenario;
  110. }
  111. /// <summary>
  112. /// Create all controls. This gets called once and the controls remain with their state between Sceanrio runs.
  113. /// </summary>
  114. private static void Setup ()
  115. {
  116. void HandleSysConsoleMenuChange ()
  117. {
  118. _useSystemConsole = !_useSystemConsole;
  119. _sysConsoleMenu.Title = $"[{(_useSystemConsole ? 'x' : ' ')}] _Use System Console";
  120. }
  121. _sysConsoleMenu = new MenuItem ($"[{(_useSystemConsole ? 'x' : ' ')}] _Use System Console", "", () => HandleSysConsoleMenuChange ());
  122. _menu = new MenuBar (new MenuBarItem [] {
  123. new MenuBarItem ("_File", new MenuItem [] {
  124. new MenuItem ("_Quit", "", () => Application.RequestStop() )
  125. }),
  126. new MenuBarItem ("_Settings", new MenuItem [] { _sysConsoleMenu }),
  127. new MenuBarItem ("_About...", "About this app", () => MessageBox.Query (50, 10, "About UI Catalog", "UI Catalog is a comprehensive sample library for Terminal.Gui", "Ok")),
  128. });
  129. _leftPane = new Window ("Categories") {
  130. X = 0,
  131. Y = 1, // for menu
  132. Width = 25,
  133. Height = Dim.Fill (),
  134. CanFocus = false,
  135. };
  136. _categories = Scenario.GetAllCategories ().OrderBy (c => c).ToList ();
  137. _categoryListView = new ListView (_categories) {
  138. X = 0,
  139. Y = 0,
  140. Width = Dim.Fill (0),
  141. Height = Dim.Fill (0),
  142. AllowsMarking = false,
  143. CanFocus = true,
  144. };
  145. _categoryListView.OpenSelectedItem += (o, a) => {
  146. _top.SetFocus (_rightPane);
  147. };
  148. _categoryListView.SelectedChanged += CategoryListView_SelectedChanged;
  149. _leftPane.Add (_categoryListView);
  150. _rightPane = new Window ("Scenarios") {
  151. X = 25,
  152. Y = 1, // for menu
  153. Width = Dim.Fill (),
  154. Height = Dim.Fill (),
  155. CanFocus = false,
  156. };
  157. _nameColumnWidth = Scenario.ScenarioMetadata.GetName (_scenarios.OrderByDescending (t => Scenario.ScenarioMetadata.GetName (t).Length).FirstOrDefault ()).Length;
  158. _scenarioListView = new ListView () {
  159. X = 0,
  160. Y = 0,
  161. Width = Dim.Fill (0),
  162. Height = Dim.Fill (0),
  163. AllowsMarking = false,
  164. CanFocus = true,
  165. };
  166. _scenarioListView.OpenSelectedItem += _scenarioListView_OpenSelectedItem;
  167. _rightPane.Add (_scenarioListView);
  168. _categoryListView.SelectedItem = 0;
  169. _categoryListView.OnSelectedChanged ();
  170. _capslock = new StatusItem (Key.CharMask, "Capslock", null);
  171. _numlock = new StatusItem (Key.CharMask, "Numlock", null);
  172. _scrolllock = new StatusItem (Key.CharMask, "Scrolllock", null);
  173. _statusBar = new StatusBar (new StatusItem [] {
  174. new StatusItem(Key.ControlQ, "~CTRL-Q~ Quit", () => {
  175. if (_runningScenario is null){
  176. // This causes GetScenarioToRun to return null
  177. _runningScenario = null;
  178. Application.RequestStop();
  179. } else {
  180. _runningScenario.RequestStop();
  181. }
  182. }),
  183. _capslock,
  184. _numlock,
  185. _scrolllock
  186. });
  187. }
  188. private static void _scenarioListView_OpenSelectedItem (object sender, EventArgs e)
  189. {
  190. if (_runningScenario is null) {
  191. var source = _scenarioListView.Source as ScenarioListDataSource;
  192. _runningScenario = (Scenario)Activator.CreateInstance (source.Scenarios [_scenarioListView.SelectedItem]);
  193. Application.RequestStop ();
  194. }
  195. }
  196. internal class ScenarioListDataSource : IListDataSource {
  197. public List<Type> Scenarios { get; set; }
  198. public bool IsMarked (int item) => false;
  199. public int Count => Scenarios.Count;
  200. public ScenarioListDataSource (List<Type> itemList) => Scenarios = itemList;
  201. public void Render (ListView container, ConsoleDriver driver, bool selected, int item, int col, int line, int width)
  202. {
  203. container.Move (col, line);
  204. // Equivalent to an interpolated string like $"{Scenarios[item].Name, -widtestname}"; if such a thing were possible
  205. var s = String.Format (String.Format ("{{0,{0}}}", -_nameColumnWidth), Scenario.ScenarioMetadata.GetName (Scenarios [item]));
  206. RenderUstr (driver, $"{s} {Scenario.ScenarioMetadata.GetDescription (Scenarios [item])}", col, line, width);
  207. }
  208. public void SetMark (int item, bool value)
  209. {
  210. }
  211. // A slightly adapted method from: https://github.com/migueldeicaza/gui.cs/blob/fc1faba7452ccbdf49028ac49f0c9f0f42bbae91/Terminal.Gui/Views/ListView.cs#L433-L461
  212. private void RenderUstr (ConsoleDriver driver, ustring ustr, int col, int line, int width)
  213. {
  214. int used = 0;
  215. int index = 0;
  216. while (index < ustr.Length) {
  217. (var rune, var size) = Utf8.DecodeRune (ustr, index, index - ustr.Length);
  218. var count = Rune.ColumnWidth (rune);
  219. if (used + count >= width) break;
  220. driver.AddRune (rune);
  221. used += count;
  222. index += size;
  223. }
  224. while (used < width) {
  225. driver.AddRune (' ');
  226. used++;
  227. }
  228. }
  229. public IList ToList ()
  230. {
  231. return Scenarios;
  232. }
  233. }
  234. /// <summary>
  235. /// When Scenarios are running we need to override the behavior of the Menu
  236. /// and Statusbar to enable Scenarios that use those (or related key input)
  237. /// to not be impacted. Same as for tabs.
  238. /// </summary>
  239. /// <param name="ke"></param>
  240. private static void KeyDownHandler (object sender, View.KeyEventEventArgs a)
  241. {
  242. if (a.KeyEvent.Key == Key.Tab || a.KeyEvent.Key == Key.BackTab) {
  243. // BUGBUG: Work around Issue #434 by implementing our own TAB navigation
  244. if (_top.MostFocused == _categoryListView)
  245. _top.SetFocus (_rightPane);
  246. else
  247. _top.SetFocus (_leftPane);
  248. }
  249. if (a.KeyEvent.IsCapslock) {
  250. _capslock.Title = "Capslock On";
  251. _statusBar.SetNeedsDisplay ();
  252. } else {
  253. _capslock.Title = "Capslock Off";
  254. _statusBar.SetNeedsDisplay ();
  255. }
  256. if (a.KeyEvent.IsNumlock) {
  257. _numlock.Title = "Numlock On";
  258. _statusBar.SetNeedsDisplay ();
  259. } else {
  260. _numlock.Title = "Numlock Off";
  261. _statusBar.SetNeedsDisplay ();
  262. }
  263. if (a.KeyEvent.IsScrolllock) {
  264. _scrolllock.Title = "Scrolllock On";
  265. _statusBar.SetNeedsDisplay ();
  266. } else {
  267. _scrolllock.Title = "Scrolllock Off";
  268. _statusBar.SetNeedsDisplay ();
  269. }
  270. }
  271. private static void CategoryListView_SelectedChanged (object sender, ListViewItemEventArgs e)
  272. {
  273. var item = _categories [_categoryListView.SelectedItem];
  274. List<Type> newlist;
  275. if (item.Equals ("All")) {
  276. newlist = _scenarios;
  277. } else {
  278. newlist = _scenarios.Where (t => Scenario.ScenarioCategory.GetCategories (t).Contains (item)).ToList ();
  279. }
  280. _scenarioListView.Source = new ScenarioListDataSource (newlist);
  281. _scenarioListView.SelectedItem = 0;
  282. }
  283. }
  284. }