UICatalog.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 Scenario _runningScenario = null;
  52. static void Main (string [] args)
  53. {
  54. if (Debugger.IsAttached)
  55. CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo ("en-US");
  56. _scenarios = Scenario.GetDerivedClassesCollection ().OrderBy (t => Scenario.ScenarioMetadata.GetName (t)).ToList ();
  57. if (args.Length > 0) {
  58. var item = _scenarios.FindIndex (t => Scenario.ScenarioMetadata.GetName (t).Equals (args [0], StringComparison.OrdinalIgnoreCase));
  59. _runningScenario = (Scenario)Activator.CreateInstance (_scenarios [item]);
  60. Application.Init ();
  61. _runningScenario.Init (Application.Top);
  62. _runningScenario.Setup ();
  63. _runningScenario.Run ();
  64. _runningScenario = null;
  65. return;
  66. }
  67. Scenario scenario = GetScenarioToRun ();
  68. while (scenario != null) {
  69. Application.Init ();
  70. scenario.Init (Application.Top);
  71. scenario.Setup ();
  72. scenario.Run ();
  73. scenario = GetScenarioToRun ();
  74. }
  75. // Now closes the driver too.
  76. Application.Shutdown ();
  77. }
  78. /// <summary>
  79. /// Create all controls. This gets called once and the controls remain with their state between Sceanrio runs.
  80. /// </summary>
  81. private static void Setup ()
  82. {
  83. _menu = new MenuBar (new MenuBarItem [] {
  84. new MenuBarItem ("_File", new MenuItem [] {
  85. new MenuItem ("_Quit", "", () => Application.RequestStop() )
  86. }),
  87. new MenuBarItem ("_About...", "About this app", () => MessageBox.Query (50, 10, "About UI Catalog", "UI Catalog is a comprehensive sample library for Terminal.Gui", "Ok")),
  88. });
  89. _leftPane = new Window ("Categories") {
  90. X = 0,
  91. Y = 1, // for menu
  92. Width = 25,
  93. Height = Dim.Fill (),
  94. CanFocus = false,
  95. };
  96. _categories = Scenario.GetAllCategories ().OrderBy (c => c).ToList ();
  97. _categoryListView = new ListView (_categories) {
  98. X = 0,
  99. Y = 0,
  100. Width = Dim.Fill (0),
  101. Height = Dim.Fill (0),
  102. AllowsMarking = false,
  103. CanFocus = true,
  104. };
  105. _categoryListView.OpenSelectedItem += (o, a) => {
  106. _top.SetFocus (_rightPane);
  107. };
  108. _categoryListView.SelectedChanged += CategoryListView_SelectedChanged;
  109. _leftPane.Add (_categoryListView);
  110. _rightPane = new Window ("Scenarios") {
  111. X = 25,
  112. Y = 1, // for menu
  113. Width = Dim.Fill (),
  114. Height = Dim.Fill (),
  115. CanFocus = false,
  116. };
  117. _nameColumnWidth = Scenario.ScenarioMetadata.GetName (_scenarios.OrderByDescending (t => Scenario.ScenarioMetadata.GetName (t).Length).FirstOrDefault ()).Length;
  118. _scenarioListView = new ListView () {
  119. X = 0,
  120. Y = 0,
  121. Width = Dim.Fill (0),
  122. Height = Dim.Fill (0),
  123. AllowsMarking = false,
  124. CanFocus = true,
  125. };
  126. //_scenarioListView.OnKeyPress += (KeyEvent ke) => {
  127. // if (_top.MostFocused == _scenarioListView && ke.Key == Key.Enter) {
  128. // _scenarioListView_OpenSelectedItem (null, null);
  129. // }
  130. //};
  131. _scenarioListView.OpenSelectedItem += _scenarioListView_OpenSelectedItem;
  132. _rightPane.Add (_scenarioListView);
  133. _categoryListView.SelectedItem = 0;
  134. _categoryListView.OnSelectedChanged ();
  135. _statusBar = new StatusBar (new StatusItem [] {
  136. //new StatusItem(Key.F1, "~F1~ Help", () => Help()),
  137. new StatusItem(Key.ControlQ, "~CTRL-Q~ Quit", () => {
  138. if (_runningScenario is null){
  139. // This causes GetScenarioToRun to return null
  140. _runningScenario = null;
  141. Application.RequestStop();
  142. } else {
  143. _runningScenario.RequestStop();
  144. }
  145. }),
  146. });
  147. }
  148. /// <summary>
  149. /// This shows the selection UI. Each time it is run, it calls Application.Init to reset everything.
  150. /// </summary>
  151. /// <returns></returns>
  152. private static Scenario GetScenarioToRun ()
  153. {
  154. Application.Init ();
  155. if (_menu == null) {
  156. Setup ();
  157. }
  158. _top = Application.Top;
  159. _top.KeyDown += KeyDownHandler;
  160. _top.Add (_menu);
  161. _top.Add (_leftPane);
  162. _top.Add (_rightPane);
  163. _top.Add (_statusBar);
  164. // HACK: There is no other way to SetFocus before Application.Run. See Issue #445
  165. #if false
  166. if (_runningScenario != null)
  167. Application.Iteration += Application_Iteration;
  168. #else
  169. _top.Ready += (o, a) => {
  170. if (_runningScenario != null) {
  171. _top.SetFocus (_rightPane);
  172. _runningScenario = null;
  173. }
  174. };
  175. #endif
  176. Application.Run (_top, false);
  177. return _runningScenario;
  178. }
  179. #if false
  180. private static void Application_Iteration (object sender, EventArgs e)
  181. {
  182. Application.Iteration -= Application_Iteration;
  183. _top.SetFocus (_rightPane);
  184. }
  185. #endif
  186. private static void _scenarioListView_OpenSelectedItem (object sender, EventArgs e)
  187. {
  188. if (_runningScenario is null) {
  189. var source = _scenarioListView.Source as ScenarioListDataSource;
  190. _runningScenario = (Scenario)Activator.CreateInstance (source.Scenarios [_scenarioListView.SelectedItem]);
  191. Application.RequestStop ();
  192. }
  193. }
  194. internal class ScenarioListDataSource : IListDataSource {
  195. public List<Type> Scenarios { get; set; }
  196. public bool IsMarked (int item) => false;// Scenarios [item].IsMarked;
  197. public int Count => Scenarios.Count;
  198. public ScenarioListDataSource (List<Type> itemList) => Scenarios = itemList;
  199. public void Render (ListView container, ConsoleDriver driver, bool selected, int item, int col, int line, int width)
  200. {
  201. container.Move (col, line);
  202. // Equivalent to an interpolated string like $"{Scenarios[item].Name, -widtestname}"; if such a thing were possible
  203. var s = String.Format (String.Format ("{{0,{0}}}", -_nameColumnWidth), Scenario.ScenarioMetadata.GetName (Scenarios [item]));
  204. RenderUstr (driver, $"{s} {Scenario.ScenarioMetadata.GetDescription (Scenarios [item])}", col, line, width);
  205. }
  206. public void SetMark (int item, bool value)
  207. {
  208. }
  209. // A slightly adapted method from: https://github.com/migueldeicaza/gui.cs/blob/fc1faba7452ccbdf49028ac49f0c9f0f42bbae91/Terminal.Gui/Views/ListView.cs#L433-L461
  210. private void RenderUstr (ConsoleDriver driver, ustring ustr, int col, int line, int width)
  211. {
  212. int used = 0;
  213. int index = 0;
  214. while (index < ustr.Length) {
  215. (var rune, var size) = Utf8.DecodeRune (ustr, index, index - ustr.Length);
  216. var count = Rune.ColumnWidth (rune);
  217. if (used + count >= width) break;
  218. driver.AddRune (rune);
  219. used += count;
  220. index += size;
  221. }
  222. while (used < width) {
  223. driver.AddRune (' ');
  224. used++;
  225. }
  226. }
  227. public IList ToList ()
  228. {
  229. return Scenarios;
  230. }
  231. }
  232. /// <summary>
  233. /// When Scenarios are running we need to override the behavior of the Menu
  234. /// and Statusbar to enable Scenarios that use those (or related key input)
  235. /// to not be impacted. Same as for tabs.
  236. /// </summary>
  237. /// <param name="ke"></param>
  238. private static void KeyDownHandler (object sender, View.KeyEventEventArgs a)
  239. {
  240. if (_runningScenario != null) {
  241. //switch (ke.Key) {
  242. //case Key.Esc:
  243. // //_runningScenario.RequestStop ();
  244. // break;
  245. //case Key.Enter:
  246. // break;
  247. //}<
  248. } else if (a.KeyEvent.Key == Key.Tab || a.KeyEvent.Key == Key.BackTab) {
  249. // BUGBUG: Work around Issue #434 by implementing our own TAB navigation
  250. if (_top.MostFocused == _categoryListView)
  251. _top.SetFocus (_rightPane);
  252. else
  253. _top.SetFocus (_leftPane);
  254. }
  255. }
  256. private static void CategoryListView_SelectedChanged (object sender, ListViewItemEventArgs e)
  257. {
  258. var item = _categories [_categoryListView.SelectedItem];
  259. List<Type> newlist;
  260. if (item.Equals ("All")) {
  261. newlist = _scenarios;
  262. } else {
  263. newlist = _scenarios.Where (t => Scenario.ScenarioCategory.GetCategories (t).Contains (item)).ToList ();
  264. }
  265. _scenarioListView.Source = new ScenarioListDataSource (newlist);
  266. _scenarioListView.SelectedItem = 0;
  267. }
  268. }
  269. }