CharacterMap.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 = [];
  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 += (_, 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.Activating += (_, e) =>
  111. {
  112. // Only handle mouse clicks
  113. if (e.Context is not CommandContext<MouseBinding> { Binding.MouseEventArgs: { } mouseArgs })
  114. {
  115. return;
  116. }
  117. _categoryList.ScreenToCell (mouseArgs.Position, out int? clickedCol);
  118. if (clickedCol != null && mouseArgs.Flags.HasFlag (MouseFlags.Button1Clicked))
  119. {
  120. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  121. string prevSelection = table.Data.ElementAt (_categoryList.SelectedRow).Category;
  122. isDescending = !isDescending;
  123. _categoryList.Table = CreateCategoryTable (clickedCol.Value, isDescending);
  124. table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  125. _categoryList.SelectedRow = table.Data
  126. .Select ((item, index) => new { item, index })
  127. .FirstOrDefault (x => x.item.Category == prevSelection)
  128. ?.index
  129. ?? -1;
  130. }
  131. };
  132. int longestName = UnicodeRange.Ranges.Max (r => r.Category.GetColumns ());
  133. _categoryList.Style.ColumnStyles.Add (
  134. 0,
  135. new () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName }
  136. );
  137. _categoryList.Style.ColumnStyles.Add (1, new () { MaxWidth = 1, MinWidth = 6 });
  138. _categoryList.Style.ColumnStyles.Add (2, new () { MaxWidth = 1, MinWidth = 6 });
  139. _categoryList.Width = _categoryList.Style.ColumnStyles.Sum (c => c.Value.MinWidth) + 4;
  140. _categoryList.SelectedCellChanged += (_, args) =>
  141. {
  142. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  143. _charMap.StartCodePoint = table.Data.ToArray () [args.NewRow].Start;
  144. jumpEdit.Text = $"U+{_charMap.SelectedCodePoint:x5}";
  145. };
  146. top.Add (_categoryList);
  147. var menu = new MenuBar
  148. {
  149. Menus =
  150. [
  151. new (
  152. "_File",
  153. new MenuItem []
  154. {
  155. new (
  156. "_Quit",
  157. $"{Application.QuitKey}",
  158. () => Application.RequestStop ()
  159. )
  160. }
  161. ),
  162. new (
  163. "_Options",
  164. [CreateMenuShowWidth (), CreateMenuUnicodeCategorySelector ()]
  165. )
  166. ]
  167. };
  168. top.Add (menu);
  169. _charMap.Width = Dim.Fill (Dim.Func (v => v!.Frame.Width, _categoryList));
  170. _charMap.SelectedCodePoint = 0;
  171. _charMap.SetFocus ();
  172. Application.Run (top);
  173. top.Dispose ();
  174. Application.Shutdown ();
  175. return;
  176. void JumpEditOnAccept (object? sender, CommandEventArgs e)
  177. {
  178. if (jumpEdit.Text.Length == 0)
  179. {
  180. return;
  181. }
  182. _errorLabel.Visible = true;
  183. uint result;
  184. if (jumpEdit.Text.Length == 1)
  185. {
  186. result = (uint)jumpEdit.Text.ToRunes () [0].Value;
  187. }
  188. else if (jumpEdit.Text.StartsWith ("U+", StringComparison.OrdinalIgnoreCase) || jumpEdit.Text.StartsWith ("\\u"))
  189. {
  190. try
  191. {
  192. result = uint.Parse (jumpEdit.Text [2..], NumberStyles.HexNumber);
  193. }
  194. catch (FormatException)
  195. {
  196. _errorLabel.Text = "Invalid hex value";
  197. return;
  198. }
  199. }
  200. else if (jumpEdit.Text.StartsWith ("0", StringComparison.OrdinalIgnoreCase) || jumpEdit.Text.StartsWith ("\\u"))
  201. {
  202. try
  203. {
  204. result = uint.Parse (jumpEdit.Text, NumberStyles.HexNumber);
  205. }
  206. catch (FormatException)
  207. {
  208. _errorLabel.Text = "Invalid hex value";
  209. return;
  210. }
  211. }
  212. else
  213. {
  214. try
  215. {
  216. result = uint.Parse (jumpEdit.Text, NumberStyles.Integer);
  217. }
  218. catch (FormatException)
  219. {
  220. _errorLabel.Text = "Invalid value";
  221. return;
  222. }
  223. }
  224. if (result > RuneExtensions.MaxUnicodeCodePoint)
  225. {
  226. _errorLabel.Text = "Beyond maximum codepoint";
  227. return;
  228. }
  229. _errorLabel.Visible = false;
  230. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList!.Table;
  231. _categoryList.SelectedRow = table.Data
  232. .Select ((item, index) => new { item, index })
  233. .FirstOrDefault (x => x.item.Start <= result && x.item.End >= result)
  234. ?.index
  235. ?? -1;
  236. _categoryList.EnsureSelectedCellIsVisible ();
  237. // Ensure the typed glyph is selected
  238. _charMap.SelectedCodePoint = (int)result;
  239. _charMap.SetFocus ();
  240. // Cancel the event to prevent ENTER from being handled elsewhere
  241. e.Handled = true;
  242. }
  243. }
  244. private EnumerableTableSource<UnicodeRange> CreateCategoryTable (int sortByColumn, bool descending)
  245. {
  246. Func<UnicodeRange, object> orderBy;
  247. var categorySort = string.Empty;
  248. var startSort = string.Empty;
  249. var endSort = string.Empty;
  250. string sortIndicator = descending ? Glyphs.DownArrow.ToString () : Glyphs.UpArrow.ToString ();
  251. switch (sortByColumn)
  252. {
  253. case 0:
  254. orderBy = r => r.Category;
  255. categorySort = sortIndicator;
  256. break;
  257. case 1:
  258. orderBy = r => r.Start;
  259. startSort = sortIndicator;
  260. break;
  261. case 2:
  262. orderBy = r => r.End;
  263. endSort = sortIndicator;
  264. break;
  265. default:
  266. throw new ArgumentException ("Invalid column number.");
  267. }
  268. IOrderedEnumerable<UnicodeRange> sortedRanges = descending
  269. ? UnicodeRange.Ranges.OrderByDescending (orderBy)
  270. : UnicodeRange.Ranges.OrderBy (orderBy);
  271. return new (
  272. sortedRanges,
  273. new ()
  274. {
  275. { $"Category{categorySort}", s => s.Category },
  276. { $"Start{startSort}", s => $"{s.Start:x5}" },
  277. { $"End{endSort}", s => $"{s.End:x5}" }
  278. }
  279. );
  280. }
  281. private MenuItem CreateMenuShowWidth ()
  282. {
  283. CheckBox cb = new ()
  284. {
  285. Title = "_Show Glyph Width",
  286. CheckedState = _charMap!.ShowGlyphWidths ? CheckState.Checked : CheckState.None
  287. };
  288. var item = new MenuItem { CommandView = cb };
  289. item.Action += () =>
  290. {
  291. if (_charMap is { })
  292. {
  293. _charMap.ShowGlyphWidths = cb.CheckedState == CheckState.Checked;
  294. }
  295. };
  296. return item;
  297. }
  298. private MenuItem CreateMenuUnicodeCategorySelector ()
  299. {
  300. // First option is "All" (no filter), followed by all UnicodeCategory names
  301. string [] allCategoryNames = Enum.GetNames<UnicodeCategory> ();
  302. var options = new string [allCategoryNames.Length + 1];
  303. options [0] = "All";
  304. Array.Copy (allCategoryNames, 0, options, 1, allCategoryNames.Length);
  305. // TODO: Add a "None" option
  306. OptionSelector<UnicodeCategory> selector = new ();
  307. _unicodeCategorySelector = selector;
  308. selector.Value = null;
  309. _charMap!.ShowUnicodeCategory = null;
  310. selector.ValueChanged += (_, e) => _charMap.ShowUnicodeCategory = e.Value;
  311. return new () { CommandView = selector };
  312. }
  313. }