UICatalog.cs 8.9 KB

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