CharacterMap.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.Linq;
  6. using System.Text;
  7. using Terminal.Gui;
  8. namespace UICatalog.Scenarios;
  9. /// <summary>
  10. /// This Scenario demonstrates building a custom control (a class deriving from View) that: - Provides a
  11. /// "Character Map" application (like Windows' charmap.exe). - Helps test unicode character rendering in Terminal.Gui -
  12. /// Illustrates how to do infinite scrolling
  13. /// </summary>
  14. [ScenarioMetadata ("Character Map", "Unicode viewer. Demos infinite content drawing and scrolling.")]
  15. [ScenarioCategory ("Text and Formatting")]
  16. [ScenarioCategory ("Drawing")]
  17. [ScenarioCategory ("Controls")]
  18. [ScenarioCategory ("Layout")]
  19. [ScenarioCategory ("Scrolling")]
  20. public class CharacterMap : Scenario
  21. {
  22. private Label? _errorLabel;
  23. private TableView? _categoryList;
  24. private CharMap? _charMap;
  25. // Don't create a Window, just return the top-level view
  26. public override void Main ()
  27. {
  28. Application.Init ();
  29. var top = new Window
  30. {
  31. BorderStyle = LineStyle.None
  32. };
  33. _charMap = new ()
  34. {
  35. X = 0,
  36. Y = 1,
  37. Width = Dim.Fill (Dim.Func (() => _categoryList!.Frame.Width)),
  38. Height = Dim.Fill ()
  39. };
  40. top.Add (_charMap);
  41. var jumpLabel = new Label
  42. {
  43. X = Pos.Right (_charMap) + 1,
  44. Y = Pos.Y (_charMap),
  45. HotKeySpecifier = (Rune)'_',
  46. Text = "_Jump To:"
  47. };
  48. top.Add (jumpLabel);
  49. var jumpEdit = new TextField
  50. {
  51. X = Pos.Right (jumpLabel) + 1,
  52. Y = Pos.Y (_charMap),
  53. Width = 17,
  54. Caption = "e.g. 01BE3 or ✈",
  55. };
  56. top.Add (jumpEdit);
  57. _charMap.SelectedCodePointChanged += (sender, args) =>
  58. {
  59. if (Rune.IsValid (args.CurrentValue))
  60. {
  61. jumpEdit.Text = ((Rune)args.CurrentValue).ToString ();
  62. }
  63. else
  64. {
  65. jumpEdit.Text = $"U+{args.CurrentValue:x5}";
  66. }
  67. };
  68. _errorLabel = new ()
  69. {
  70. X = Pos.Right (jumpEdit) + 1,
  71. Y = Pos.Y (_charMap),
  72. ColorScheme = Colors.ColorSchemes ["error"],
  73. Text = "err",
  74. Visible = false
  75. };
  76. top.Add (_errorLabel);
  77. jumpEdit.Accepting += JumpEditOnAccept;
  78. _categoryList = new () {
  79. X = Pos.Right (_charMap),
  80. Y = Pos.Bottom (jumpLabel),
  81. Height = Dim.Fill (),
  82. };
  83. _categoryList.FullRowSelect = true;
  84. _categoryList.MultiSelect = false;
  85. _categoryList.Style.ShowVerticalCellLines = false;
  86. _categoryList.Style.AlwaysShowHeaders = true;
  87. var isDescending = false;
  88. _categoryList.Table = CreateCategoryTable (0, isDescending);
  89. // if user clicks the mouse in TableView
  90. _categoryList.MouseClick += (s, e) =>
  91. {
  92. _categoryList.ScreenToCell (e.Position, out int? clickedCol);
  93. if (clickedCol != null && e.Flags.HasFlag (MouseFlags.Button1Clicked))
  94. {
  95. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  96. string prevSelection = table.Data.ElementAt (_categoryList.SelectedRow).Category;
  97. isDescending = !isDescending;
  98. _categoryList.Table = CreateCategoryTable (clickedCol.Value, isDescending);
  99. table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  100. _categoryList.SelectedRow = table.Data
  101. .Select ((item, index) => new { item, index })
  102. .FirstOrDefault (x => x.item.Category == prevSelection)
  103. ?.index
  104. ?? -1;
  105. }
  106. };
  107. int longestName = UnicodeRange.Ranges.Max (r => r.Category.GetColumns ());
  108. _categoryList.Style.ColumnStyles.Add (
  109. 0,
  110. new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  111. );
  112. _categoryList.Style.ColumnStyles.Add (1, new () { MaxWidth = 1, MinWidth = 6 });
  113. _categoryList.Style.ColumnStyles.Add (2, new () { MaxWidth = 1, MinWidth = 6 });
  114. _categoryList.Width = _categoryList.Style.ColumnStyles.Sum (c => c.Value.MinWidth) + 4;
  115. _categoryList.SelectedCellChanged += (s, args) =>
  116. {
  117. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  118. _charMap.StartCodePoint = table.Data.ToArray () [args.NewRow].Start;
  119. jumpEdit.Text = $"U+{_charMap.SelectedCodePoint:x5}";
  120. };
  121. top.Add (_categoryList);
  122. var menu = new MenuBar
  123. {
  124. Menus =
  125. [
  126. new (
  127. "_File",
  128. new MenuItem []
  129. {
  130. new (
  131. "_Quit",
  132. $"{Application.QuitKey}",
  133. () => Application.RequestStop ()
  134. )
  135. }
  136. ),
  137. new (
  138. "_Options",
  139. new [] { CreateMenuShowWidth () }
  140. )
  141. ]
  142. };
  143. top.Add (menu);
  144. _charMap.SelectedCodePoint = 0;
  145. _charMap.SetFocus ();
  146. Application.Run (top);
  147. top.Dispose ();
  148. Application.Shutdown ();
  149. return;
  150. void JumpEditOnAccept (object? sender, CommandEventArgs e)
  151. {
  152. if (jumpEdit.Text.Length == 0)
  153. {
  154. return;
  155. }
  156. _errorLabel.Visible = true;
  157. uint result = 0;
  158. if (jumpEdit.Text.Length == 1)
  159. {
  160. result = (uint)jumpEdit.Text.ToRunes () [0].Value;
  161. }
  162. else if (jumpEdit.Text.StartsWith ("U+", StringComparison.OrdinalIgnoreCase) || jumpEdit.Text.StartsWith ("\\u"))
  163. {
  164. try
  165. {
  166. result = uint.Parse (jumpEdit.Text [2..], NumberStyles.HexNumber);
  167. }
  168. catch (FormatException)
  169. {
  170. _errorLabel.Text = "Invalid hex value";
  171. return;
  172. }
  173. }
  174. else if (jumpEdit.Text.StartsWith ("0", StringComparison.OrdinalIgnoreCase) || jumpEdit.Text.StartsWith ("\\u"))
  175. {
  176. try
  177. {
  178. result = uint.Parse (jumpEdit.Text, NumberStyles.HexNumber);
  179. }
  180. catch (FormatException)
  181. {
  182. _errorLabel.Text = "Invalid hex value";
  183. return;
  184. }
  185. }
  186. else
  187. {
  188. try
  189. {
  190. result = uint.Parse (jumpEdit.Text, NumberStyles.Integer);
  191. }
  192. catch (FormatException)
  193. {
  194. _errorLabel.Text = "Invalid value";
  195. return;
  196. }
  197. }
  198. if (result > RuneExtensions.MaxUnicodeCodePoint)
  199. {
  200. _errorLabel.Text = "Beyond maximum codepoint";
  201. return;
  202. }
  203. _errorLabel.Visible = false;
  204. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList!.Table;
  205. _categoryList.SelectedRow = table.Data
  206. .Select ((item, index) => new { item, index })
  207. .FirstOrDefault (x => x.item.Start <= result && x.item.End >= result)
  208. ?.index
  209. ?? -1;
  210. _categoryList.EnsureSelectedCellIsVisible ();
  211. // Ensure the typed glyph is selected
  212. _charMap.SelectedCodePoint = (int)result;
  213. _charMap.SetFocus ();
  214. // Cancel the event to prevent ENTER from being handled elsewhere
  215. e.Cancel = true;
  216. }
  217. }
  218. private EnumerableTableSource<UnicodeRange> CreateCategoryTable (int sortByColumn, bool descending)
  219. {
  220. Func<UnicodeRange, object> orderBy;
  221. var categorySort = string.Empty;
  222. var startSort = string.Empty;
  223. var endSort = string.Empty;
  224. string sortIndicator = descending ? Glyphs.DownArrow.ToString () : Glyphs.UpArrow.ToString ();
  225. switch (sortByColumn)
  226. {
  227. case 0:
  228. orderBy = r => r.Category;
  229. categorySort = sortIndicator;
  230. break;
  231. case 1:
  232. orderBy = r => r.Start;
  233. startSort = sortIndicator;
  234. break;
  235. case 2:
  236. orderBy = r => r.End;
  237. endSort = sortIndicator;
  238. break;
  239. default:
  240. throw new ArgumentException ("Invalid column number.");
  241. }
  242. IOrderedEnumerable<UnicodeRange> sortedRanges = descending
  243. ? UnicodeRange.Ranges.OrderByDescending (orderBy)
  244. : UnicodeRange.Ranges.OrderBy (orderBy);
  245. return new (
  246. sortedRanges,
  247. new ()
  248. {
  249. { $"Category{categorySort}", s => s.Category },
  250. { $"Start{startSort}", s => $"{s.Start:x5}" },
  251. { $"End{endSort}", s => $"{s.End:x5}" }
  252. }
  253. );
  254. }
  255. private MenuItem CreateMenuShowWidth ()
  256. {
  257. var item = new MenuItem { Title = "_Show Glyph Width" };
  258. item.CheckType |= MenuItemCheckStyle.Checked;
  259. item.Checked = _charMap?.ShowGlyphWidths;
  260. item.Action += () =>
  261. {
  262. if (_charMap is { })
  263. {
  264. _charMap.ShowGlyphWidths = (bool)(item.Checked = !item.Checked)!;
  265. }
  266. };
  267. return item;
  268. }
  269. public override List<Key> GetDemoKeyStrokes ()
  270. {
  271. List<Key> keys = new ();
  272. for (var i = 0; i < 200; i++)
  273. {
  274. keys.Add (Key.CursorDown);
  275. }
  276. // Category table
  277. keys.Add (Key.Tab.WithShift);
  278. // Block elements
  279. keys.Add (Key.B);
  280. keys.Add (Key.L);
  281. keys.Add (Key.Tab);
  282. for (var i = 0; i < 200; i++)
  283. {
  284. keys.Add (Key.CursorLeft);
  285. }
  286. return keys;
  287. }
  288. }