CharacterMap.cs 13 KB

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