CharacterMap.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. #define DRAW_CONTENT
  2. //#define BASE_DRAW_CONTENT
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Net.Http;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Text.Unicode;
  12. using System.Threading.Tasks;
  13. using Terminal.Gui;
  14. using static Terminal.Gui.SpinnerStyle;
  15. using static Terminal.Gui.TableView;
  16. namespace UICatalog.Scenarios;
  17. /// <summary>
  18. /// This Scenario demonstrates building a custom control (a class deriving from View) that:
  19. /// - Provides a "Character Map" application (like Windows' charmap.exe).
  20. /// - Helps test unicode character rendering in Terminal.Gui
  21. /// - Illustrates how to use ScrollView to do infinite scrolling
  22. /// </summary>
  23. [ScenarioMetadata (Name: "Character Map", Description: "Unicode viewer demonstrating the ScrollView control.")]
  24. [ScenarioCategory ("Text and Formatting")]
  25. [ScenarioCategory ("Controls")]
  26. [ScenarioCategory ("ScrollView")]
  27. public class CharacterMap : Scenario {
  28. CharMap _charMap;
  29. public Label _errorLabel;
  30. TableView _categoryList;
  31. // Don't create a Window, just return the top-level view
  32. public override void Init ()
  33. {
  34. Application.Init ();
  35. Application.Top.ColorScheme = Colors.Base;
  36. }
  37. public override void Setup ()
  38. {
  39. _charMap = new CharMap () {
  40. X = 0,
  41. Y = 1,
  42. Height = Dim.Fill ()
  43. };
  44. Application.Top.Add (_charMap);
  45. var jumpLabel = new Label ("Jump To Code Point:") { X = Pos.Right (_charMap) + 1, Y = Pos.Y (_charMap) };
  46. Application.Top.Add (jumpLabel);
  47. var jumpEdit = new TextField () { X = Pos.Right (jumpLabel) + 1, Y = Pos.Y (_charMap), Width = 10, Caption = "e.g. 01BE3" };
  48. Application.Top.Add (jumpEdit);
  49. _errorLabel = new Label ("err") { X = Pos.Right (jumpEdit) + 1, Y = Pos.Y (_charMap), ColorScheme = Colors.ColorSchemes ["error"] };
  50. Application.Top.Add (_errorLabel);
  51. jumpEdit.TextChanged += JumpEdit_TextChanged;
  52. _categoryList = new TableView () {
  53. X = Pos.Right (_charMap),
  54. Y = Pos.Bottom (jumpLabel),
  55. Height = Dim.Fill ()
  56. };
  57. _categoryList.FullRowSelect = true;
  58. //jumpList.Style.ShowHeaders = false;
  59. //jumpList.Style.ShowHorizontalHeaderOverline = false;
  60. //jumpList.Style.ShowHorizontalHeaderUnderline = false;
  61. _categoryList.Style.ShowHorizontalBottomline = true;
  62. //jumpList.Style.ShowVerticalCellLines = false;
  63. //jumpList.Style.ShowVerticalHeaderLines = false;
  64. _categoryList.Style.AlwaysShowHeaders = true;
  65. var isDescending = false;
  66. _categoryList.Table = CreateCategoryTable (0, isDescending);
  67. // if user clicks the mouse in TableView
  68. _categoryList.MouseClick += (s, e) => {
  69. _categoryList.ScreenToCell (e.MouseEvent.X, e.MouseEvent.Y, out int? clickedCol);
  70. if (clickedCol != null && e.MouseEvent.Flags.HasFlag (MouseFlags.Button1Clicked)) {
  71. var table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  72. var prevSelection = table.Data.ElementAt (_categoryList.SelectedRow).Category;
  73. isDescending = !isDescending;
  74. _categoryList.Table = CreateCategoryTable (clickedCol.Value, isDescending);
  75. table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  76. _categoryList.SelectedRow = table.Data
  77. .Select ((item, index) => new { item, index })
  78. .FirstOrDefault (x => x.item.Category == prevSelection)?.index ?? -1;
  79. }
  80. };
  81. var longestName = UnicodeRange.Ranges.Max (r => r.Category.GetColumns ());
  82. _categoryList.Style.ColumnStyles.Add (0, new ColumnStyle () { MaxWidth = longestName, MinWidth = longestName, MinAcceptableWidth = longestName });
  83. _categoryList.Style.ColumnStyles.Add (1, new ColumnStyle () { MaxWidth = 1, MinWidth = 6 });
  84. _categoryList.Style.ColumnStyles.Add (2, new ColumnStyle () { MaxWidth = 1, MinWidth = 6 });
  85. _categoryList.Width = _categoryList.Style.ColumnStyles.Sum (c => c.Value.MinWidth) + 4;
  86. _categoryList.SelectedCellChanged += (s, args) => {
  87. EnumerableTableSource<UnicodeRange> table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  88. _charMap.StartCodePoint = table.Data.ToArray () [args.NewRow].Start;
  89. };
  90. Application.Top.Add (_categoryList);
  91. _charMap.SelectedCodePoint = 0;
  92. //jumpList.Refresh ();
  93. _charMap.SetFocus ();
  94. _charMap.Width = Dim.Fill () - _categoryList.Width;
  95. var menu = new MenuBar (new MenuBarItem [] {
  96. new MenuBarItem ("_File", new MenuItem [] {
  97. new MenuItem ("_Quit", $"{Application.QuitKey}", () => Application.RequestStop ()),
  98. }),
  99. new MenuBarItem ("_Options", new MenuItem [] {
  100. CreateMenuShowWidth (),
  101. })
  102. });
  103. Application.Top.Add (menu);
  104. //_charMap.Hover += (s, a) => {
  105. // _errorLabel.Text = $"U+{a.Item:x5} {(Rune)a.Item}";
  106. //};
  107. }
  108. MenuItem CreateMenuShowWidth ()
  109. {
  110. var item = new MenuItem {
  111. Title = "_Show Glyph Width",
  112. };
  113. item.CheckType |= MenuItemCheckStyle.Checked;
  114. item.Checked = _charMap?.ShowGlyphWidths;
  115. item.Action += () => {
  116. _charMap.ShowGlyphWidths = (bool)(item.Checked = !item.Checked);
  117. };
  118. return item;
  119. }
  120. EnumerableTableSource<UnicodeRange> CreateCategoryTable (int sortByColumn, bool descending)
  121. {
  122. Func<UnicodeRange, object> orderBy;
  123. var categorySort = string.Empty;
  124. var startSort = string.Empty;
  125. var endSort = string.Empty;
  126. var sortIndicator = descending ? CM.Glyphs.DownArrow.ToString () : CM.Glyphs.UpArrow.ToString ();
  127. switch (sortByColumn) {
  128. case 0:
  129. orderBy = r => r.Category;
  130. categorySort = sortIndicator;
  131. break;
  132. case 1:
  133. orderBy = r => r.Start;
  134. startSort = sortIndicator;
  135. break;
  136. case 2:
  137. orderBy = r => r.End;
  138. endSort = sortIndicator;
  139. break;
  140. default:
  141. throw new ArgumentException ("Invalid column number.");
  142. }
  143. IOrderedEnumerable<UnicodeRange> sortedRanges = descending ?
  144. UnicodeRange.Ranges.OrderByDescending (orderBy) :
  145. UnicodeRange.Ranges.OrderBy (orderBy);
  146. return new EnumerableTableSource<UnicodeRange> (sortedRanges, new Dictionary<string, Func<UnicodeRange, object>> ()
  147. {
  148. { $"Category{categorySort}", s => s.Category },
  149. { $"Start{startSort}", s => $"{s.Start:x5}" },
  150. { $"End{endSort}", s => $"{s.End:x5}" },
  151. });
  152. }
  153. private void JumpEdit_TextChanged (object sender, TextChangedEventArgs e)
  154. {
  155. var jumpEdit = sender as TextField;
  156. if (jumpEdit.Text.Length == 0) {
  157. return;
  158. }
  159. uint result = 0;
  160. if (jumpEdit.Text.StartsWith ("U+", StringComparison.OrdinalIgnoreCase) || jumpEdit.Text.StartsWith ("\\u")) {
  161. try {
  162. result = uint.Parse (jumpEdit.Text [2..^0], NumberStyles.HexNumber);
  163. } catch (FormatException) {
  164. _errorLabel.Text = $"Invalid hex value";
  165. return;
  166. }
  167. } else if (jumpEdit.Text.StartsWith ("0", StringComparison.OrdinalIgnoreCase) || jumpEdit.Text.StartsWith ("\\u")) {
  168. try {
  169. result = uint.Parse (jumpEdit.Text, NumberStyles.HexNumber);
  170. } catch (FormatException) {
  171. _errorLabel.Text = $"Invalid hex value";
  172. return;
  173. }
  174. } else {
  175. try {
  176. result = uint.Parse (jumpEdit.Text, NumberStyles.Integer);
  177. } catch (FormatException) {
  178. _errorLabel.Text = $"Invalid value";
  179. return;
  180. }
  181. }
  182. if (result > RuneExtensions.MaxUnicodeCodePoint) {
  183. _errorLabel.Text = $"Beyond maximum codepoint";
  184. return;
  185. }
  186. _errorLabel.Text = $"U+{result:x5}";
  187. var table = (EnumerableTableSource<UnicodeRange>)_categoryList.Table;
  188. _categoryList.SelectedRow = table.Data
  189. .Select ((item, index) => new { item, index })
  190. .FirstOrDefault (x => x.item.Start <= result && x.item.End >= result)?.index ?? -1;
  191. _categoryList.EnsureSelectedCellIsVisible ();
  192. // Ensure the typed glyph is selected
  193. _charMap.SelectedCodePoint = (int)result;
  194. }
  195. }
  196. class CharMap : ScrollView {
  197. /// <summary>
  198. /// Specifies the starting offset for the character map. The default is 0x2500
  199. /// which is the Box Drawing characters.
  200. /// </summary>
  201. public int StartCodePoint {
  202. get => _start;
  203. set {
  204. _start = value;
  205. SelectedCodePoint = value;
  206. SetNeedsDisplay ();
  207. }
  208. }
  209. public event EventHandler<ListViewItemEventArgs> SelectedCodePointChanged;
  210. /// <summary>
  211. /// Specifies the starting offset for the character map. The default is 0x2500
  212. /// which is the Box Drawing characters.
  213. /// </summary>
  214. public int SelectedCodePoint {
  215. get => _selected;
  216. set {
  217. _selected = value;
  218. var row = (SelectedCodePoint / 16 * _rowHeight);
  219. var col = (SelectedCodePoint % 16 * COLUMN_WIDTH);
  220. var height = (Bounds.Height) - (ShowHorizontalScrollIndicator ? 2 : 1);
  221. if (row + ContentOffset.Y < 0) {
  222. // Moving up.
  223. ContentOffset = new Point (ContentOffset.X, row);
  224. } else if (row + ContentOffset.Y >= height) {
  225. // Moving down.
  226. ContentOffset = new Point (ContentOffset.X, Math.Min (row, row - height + _rowHeight));
  227. }
  228. var width = (Bounds.Width / COLUMN_WIDTH * COLUMN_WIDTH) - (ShowVerticalScrollIndicator ? RowLabelWidth + 1 : RowLabelWidth);
  229. if (col + ContentOffset.X < 0) {
  230. // Moving left.
  231. ContentOffset = new Point (col, ContentOffset.Y);
  232. } else if (col + ContentOffset.X >= width) {
  233. // Moving right.
  234. ContentOffset = new Point (Math.Min (col, col - width + COLUMN_WIDTH), ContentOffset.Y);
  235. }
  236. SetNeedsDisplay ();
  237. SelectedCodePointChanged?.Invoke (this, new ListViewItemEventArgs (SelectedCodePoint, null));
  238. }
  239. }
  240. public event EventHandler<ListViewItemEventArgs> Hover;
  241. /// <summary>
  242. /// Gets the coordinates of the Cursor based on the SelectedCodePoint in screen coordinates
  243. /// </summary>
  244. public Point Cursor {
  245. get {
  246. var row = (SelectedCodePoint / 16 * _rowHeight) + ContentOffset.Y + 1;
  247. var col = (SelectedCodePoint % 16 * COLUMN_WIDTH) + ContentOffset.X + RowLabelWidth + 1; // + 1 for padding
  248. return new Point (col, row);
  249. }
  250. set => throw new NotImplementedException ();
  251. }
  252. public override void PositionCursor ()
  253. {
  254. if (HasFocus &&
  255. Cursor.X >= RowLabelWidth &&
  256. Cursor.X < Bounds.Width - (ShowVerticalScrollIndicator ? 1 : 0) &&
  257. Cursor.Y > 0 &&
  258. Cursor.Y < Bounds.Height - (ShowHorizontalScrollIndicator ? 1 : 0)) {
  259. Driver.SetCursorVisibility (CursorVisibility.Default);
  260. Move (Cursor.X, Cursor.Y);
  261. } else {
  262. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  263. }
  264. }
  265. public bool ShowGlyphWidths {
  266. get => _rowHeight == 2;
  267. set {
  268. _rowHeight = value ? 2 : 1;
  269. SetNeedsDisplay ();
  270. }
  271. }
  272. int _start = 0;
  273. int _selected = 0;
  274. const int COLUMN_WIDTH = 3;
  275. int _rowHeight = 1;
  276. public static int MaxCodePoint => 0x10FFFF;
  277. static int RowLabelWidth => $"U+{MaxCodePoint:x5}".Length + 1;
  278. static int RowWidth => RowLabelWidth + (COLUMN_WIDTH * 16);
  279. public CharMap ()
  280. {
  281. ColorScheme = Colors.Dialog;
  282. CanFocus = true;
  283. ContentSize = new Size (CharMap.RowWidth, (int)((MaxCodePoint / 16 + (ShowHorizontalScrollIndicator ? 2 : 1)) * _rowHeight));
  284. AddCommand (Command.ScrollUp, () => {
  285. if (SelectedCodePoint >= 16) {
  286. SelectedCodePoint -= 16;
  287. }
  288. return true;
  289. });
  290. AddCommand (Command.ScrollDown, () => {
  291. if (SelectedCodePoint < MaxCodePoint - 16) {
  292. SelectedCodePoint += 16;
  293. }
  294. return true;
  295. });
  296. AddCommand (Command.ScrollLeft, () => {
  297. if (SelectedCodePoint > 0) {
  298. SelectedCodePoint--;
  299. }
  300. return true;
  301. });
  302. AddCommand (Command.ScrollRight, () => {
  303. if (SelectedCodePoint < MaxCodePoint) {
  304. SelectedCodePoint++;
  305. }
  306. return true;
  307. });
  308. AddCommand (Command.PageUp, () => {
  309. var page = (Bounds.Height / _rowHeight - 1) * 16;
  310. SelectedCodePoint -= Math.Min (page, SelectedCodePoint);
  311. return true;
  312. });
  313. AddCommand (Command.PageDown, () => {
  314. var page = (Bounds.Height / _rowHeight - 1) * 16;
  315. SelectedCodePoint += Math.Min (page, MaxCodePoint - SelectedCodePoint);
  316. return true;
  317. });
  318. AddCommand (Command.TopHome, () => {
  319. SelectedCodePoint = 0;
  320. return true;
  321. });
  322. AddCommand (Command.BottomEnd, () => {
  323. SelectedCodePoint = MaxCodePoint;
  324. return true;
  325. });
  326. AddKeyBinding (Key.Enter, Command.Accept);
  327. AddCommand (Command.Accept, () => {
  328. ShowDetails ();
  329. return true;
  330. });
  331. MouseClick += Handle_MouseClick;
  332. }
  333. private void CopyCodePoint () => Clipboard.Contents = $"U+{SelectedCodePoint:x5}";
  334. private void CopyGlyph () => Clipboard.Contents = $"{new Rune (SelectedCodePoint)}";
  335. public override void OnDrawContent (Rect contentArea)
  336. {
  337. //if (ShowHorizontalScrollIndicator && ContentSize.Height < (int)(MaxCodePoint / 16 + 2)) {
  338. // //ContentSize = new Size (CharMap.RowWidth, (int)(MaxCodePoint / 16 + 2));
  339. // //ContentSize = new Size (CharMap.RowWidth, (int)(MaxCodePoint / 16) * _rowHeight + 2);
  340. // var width = (Bounds.Width / COLUMN_WIDTH * COLUMN_WIDTH) - (ShowVerticalScrollIndicator ? RowLabelWidth + 1 : RowLabelWidth);
  341. // if (Cursor.X + ContentOffset.X >= width) {
  342. // // Snap to the selected glyph.
  343. // ContentOffset = new Point (
  344. // Math.Min (Cursor.X, Cursor.X - width + COLUMN_WIDTH),
  345. // ContentOffset.Y == -ContentSize.Height + Bounds.Height ? ContentOffset.Y - 1 : ContentOffset.Y);
  346. // } else {
  347. // ContentOffset = new Point (
  348. // ContentOffset.X - Cursor.X,
  349. // ContentOffset.Y == -ContentSize.Height + Bounds.Height ? ContentOffset.Y - 1 : ContentOffset.Y);
  350. // }
  351. //} else if (!ShowHorizontalScrollIndicator && ContentSize.Height > (int)(MaxCodePoint / 16 + 1)) {
  352. // //ContentSize = new Size (CharMap.RowWidth, (int)(MaxCodePoint / 16 + 1));
  353. // // Snap 1st column into view if it's been scrolled horizontally
  354. // ContentOffset = new Point (0, ContentOffset.Y < -ContentSize.Height + Bounds.Height ? ContentOffset.Y - 1 : ContentOffset.Y);
  355. //}
  356. base.OnDrawContent (contentArea);
  357. }
  358. //public void CharMap_DrawContent (object s, DrawEventArgs a)
  359. public override void OnDrawContentComplete (Rect contentArea)
  360. {
  361. if (contentArea.Height == 0 || contentArea.Width == 0) {
  362. return;
  363. }
  364. Rect viewport = new Rect (ContentOffset,
  365. new Size (Math.Max (Bounds.Width - (ShowVerticalScrollIndicator ? 1 : 0), 0),
  366. Math.Max (Bounds.Height - (ShowHorizontalScrollIndicator ? 1 : 0), 0)));
  367. var oldClip = ClipToBounds ();
  368. if (ShowHorizontalScrollIndicator) {
  369. // ClipToBounds doesn't know about the scroll indicators, so if off, subtract one from height
  370. Driver.Clip = new Rect (Driver.Clip.Location, new Size (Driver.Clip.Width, Driver.Clip.Height - 1));
  371. }
  372. if (ShowVerticalScrollIndicator) {
  373. // ClipToBounds doesn't know about the scroll indicators, so if off, subtract one from width
  374. Driver.Clip = new Rect (Driver.Clip.Location, new Size (Driver.Clip.Width - 1, Driver.Clip.Height));
  375. }
  376. var cursorCol = Cursor.X - ContentOffset.X - RowLabelWidth - 1;
  377. var cursorRow = Cursor.Y - ContentOffset.Y - 1;
  378. Driver.SetAttribute (GetHotNormalColor ());
  379. Move (0, 0);
  380. Driver.AddStr (new string (' ', RowLabelWidth + 1));
  381. for (int hexDigit = 0; hexDigit < 16; hexDigit++) {
  382. var x = ContentOffset.X + RowLabelWidth + (hexDigit * COLUMN_WIDTH);
  383. if (x > RowLabelWidth - 2) {
  384. Move (x, 0);
  385. Driver.SetAttribute (GetHotNormalColor ());
  386. Driver.AddStr (" ");
  387. Driver.SetAttribute (HasFocus && (cursorCol + ContentOffset.X + RowLabelWidth == x) ? ColorScheme.HotFocus : GetHotNormalColor ());
  388. Driver.AddStr ($"{hexDigit:x}");
  389. Driver.SetAttribute (GetHotNormalColor ());
  390. Driver.AddStr (" ");
  391. }
  392. }
  393. var firstColumnX = viewport.X + RowLabelWidth;
  394. for (int y = 1; y < Bounds.Height; y++) {
  395. // What row is this?
  396. var row = (y - ContentOffset.Y - 1) / _rowHeight;
  397. var val = (row) * 16;
  398. if (val > MaxCodePoint) {
  399. continue;
  400. }
  401. Move (firstColumnX + COLUMN_WIDTH, y);
  402. Driver.SetAttribute (GetNormalColor ());
  403. for (int col = 0; col < 16; col++) {
  404. var x = firstColumnX + COLUMN_WIDTH * col + 1;
  405. Move (x, y);
  406. if (cursorRow + ContentOffset.Y + 1 == y && cursorCol + ContentOffset.X + firstColumnX + 1 == x && !HasFocus) {
  407. Driver.SetAttribute (GetFocusColor ());
  408. }
  409. var scalar = val + col;
  410. Rune rune = (Rune)'?';
  411. if (Rune.IsValid (scalar)) {
  412. rune = new Rune (scalar);
  413. }
  414. var width = rune.GetColumns ();
  415. // are we at first row of the row?
  416. if (!ShowGlyphWidths || (y - ContentOffset.Y) % _rowHeight > 0) {
  417. Driver.AddRune (rune);
  418. } else {
  419. Driver.SetAttribute (ColorScheme.HotNormal);
  420. Driver.AddStr ($"{width}");
  421. }
  422. if (cursorRow + ContentOffset.Y + 1 == y && cursorCol + ContentOffset.X + firstColumnX + 1 == x && !HasFocus) {
  423. Driver.SetAttribute (GetNormalColor ());
  424. }
  425. }
  426. Move (0, y);
  427. Driver.SetAttribute (HasFocus && (cursorRow + ContentOffset.Y + 1 == y) ? ColorScheme.HotFocus : ColorScheme.HotNormal);
  428. if (!ShowGlyphWidths || (y - ContentOffset.Y) % _rowHeight > 0) {
  429. Driver.AddStr ($"U+{val / 16:x5}_ ");
  430. } else {
  431. Driver.AddStr (new string (' ', RowLabelWidth));
  432. }
  433. }
  434. Driver.Clip = oldClip;
  435. }
  436. ContextMenu _contextMenu = new ContextMenu ();
  437. void Handle_MouseClick (object sender, MouseEventEventArgs args)
  438. {
  439. var me = args.MouseEvent;
  440. if (me.Flags != MouseFlags.ReportMousePosition && me.Flags != MouseFlags.Button1Clicked &&
  441. me.Flags != MouseFlags.Button1DoubleClicked) {
  442. return;
  443. }
  444. if (me.Y == 0) {
  445. me.Y = Cursor.Y;
  446. }
  447. if (me.Y > 0) {
  448. }
  449. if (me.X < RowLabelWidth || me.X > RowLabelWidth + (16 * COLUMN_WIDTH) - 1) {
  450. me.X = Cursor.X;
  451. }
  452. var row = (me.Y - 1 - ContentOffset.Y) / _rowHeight; // -1 for header
  453. var col = (me.X - RowLabelWidth - ContentOffset.X) / COLUMN_WIDTH;
  454. if (col > 15) {
  455. col = 15;
  456. }
  457. var val = (row) * 16 + col;
  458. if (val > MaxCodePoint) {
  459. return;
  460. }
  461. if (me.Flags == MouseFlags.ReportMousePosition) {
  462. Hover?.Invoke (this, new ListViewItemEventArgs (val, null));
  463. }
  464. if (me.Flags == MouseFlags.Button1Clicked) {
  465. SelectedCodePoint = val;
  466. return;
  467. }
  468. if (me.Flags == MouseFlags.Button1DoubleClicked) {
  469. SelectedCodePoint = val;
  470. ShowDetails ();
  471. return;
  472. }
  473. if (me.Flags == _contextMenu.MouseFlags) {
  474. SelectedCodePoint = val;
  475. _contextMenu = new ContextMenu (me.X + 1, me.Y + 1,
  476. new MenuBarItem (new MenuItem [] {
  477. new MenuItem ("_Copy Glyph", "", () => CopyGlyph (), null, null, Key.C | Key.CtrlMask),
  478. new MenuItem ("Copy Code _Point", "", () => CopyCodePoint (), null, null, Key.C | Key.ShiftMask | Key.CtrlMask),
  479. }) {
  480. }
  481. );
  482. _contextMenu.Show ();
  483. }
  484. }
  485. public static string ToCamelCase (string str)
  486. {
  487. if (string.IsNullOrEmpty (str)) {
  488. return str;
  489. }
  490. TextInfo textInfo = new CultureInfo ("en-US", false).TextInfo;
  491. str = textInfo.ToLower (str);
  492. str = textInfo.ToTitleCase (str);
  493. return str;
  494. }
  495. void ShowDetails ()
  496. {
  497. var client = new UcdApiClient ();
  498. string decResponse = string.Empty;
  499. var waitIndicator = new Dialog (new Button ("Cancel")) {
  500. Title = "Getting Code Point Information",
  501. X = Pos.Center (),
  502. Y = Pos.Center (),
  503. Height = 7,
  504. Width = 50
  505. };
  506. var errorLabel = new Label () {
  507. Text = UcdApiClient.BaseUrl,
  508. AutoSize = false,
  509. X = 0,
  510. Y = 1,
  511. Width = Dim.Fill (),
  512. Height = Dim.Fill (1),
  513. TextAlignment = TextAlignment.Centered
  514. };
  515. var spinner = new SpinnerView () {
  516. X = Pos.Center (),
  517. Y = Pos.Center (),
  518. Style = new SpinnerStyle.Aesthetic (),
  519. };
  520. spinner.AutoSpin = true;
  521. waitIndicator.Add (errorLabel);
  522. waitIndicator.Add (spinner);
  523. waitIndicator.Ready += async (s, a) => {
  524. try {
  525. decResponse = await client.GetCodepointDec ((int)SelectedCodePoint);
  526. } catch (HttpRequestException e) {
  527. (s as Dialog).Text = e.Message;
  528. Application.MainLoop.Invoke (() => {
  529. spinner.Visible = false;
  530. errorLabel.Text = e.Message;
  531. errorLabel.ColorScheme = Colors.ColorSchemes ["Error"];
  532. errorLabel.Visible = true;
  533. });
  534. }
  535. (s as Dialog)?.RequestStop ();
  536. };
  537. Application.Run (waitIndicator);
  538. if (!string.IsNullOrEmpty (decResponse)) {
  539. string name = string.Empty;
  540. using (JsonDocument document = JsonDocument.Parse (decResponse)) {
  541. JsonElement root = document.RootElement;
  542. // Get a property by name and output its value
  543. if (root.TryGetProperty ("name", out JsonElement nameElement)) {
  544. name = nameElement.GetString ();
  545. }
  546. //// Navigate to a nested property and output its value
  547. //if (root.TryGetProperty ("property3", out JsonElement property3Element)
  548. //&& property3Element.TryGetProperty ("nestedProperty", out JsonElement nestedPropertyElement)) {
  549. // Console.WriteLine (nestedPropertyElement.GetString ());
  550. //}
  551. decResponse = JsonSerializer.Serialize (document.RootElement, new
  552. JsonSerializerOptions {
  553. WriteIndented = true
  554. });
  555. }
  556. var title = $"{ToCamelCase (name)} - {new Rune (SelectedCodePoint)} U+{SelectedCodePoint:x5}";
  557. var copyGlyph = new Button ("Copy _Glyph");
  558. var copyCP = new Button ("Copy Code _Point");
  559. var cancel = new Button ("Cancel");
  560. var dlg = new Dialog (copyGlyph, copyCP, cancel) {
  561. Title = title
  562. };
  563. copyGlyph.Clicked += (s, a) => {
  564. CopyGlyph ();
  565. dlg.RequestStop ();
  566. };
  567. copyCP.Clicked += (s, a) => {
  568. CopyCodePoint ();
  569. dlg.RequestStop ();
  570. };
  571. cancel.Clicked += (s, a) => dlg.RequestStop ();
  572. var rune = (Rune)SelectedCodePoint;
  573. var label = new Label () {
  574. Text = "IsAscii: ",
  575. X = 0,
  576. Y = 0
  577. };
  578. dlg.Add (label);
  579. label = new Label () {
  580. Text = $"{rune.IsAscii}",
  581. X = Pos.Right (label),
  582. Y = Pos.Top (label)
  583. };
  584. dlg.Add (label);
  585. label = new Label () {
  586. Text = ", Bmp: ",
  587. X = Pos.Right (label),
  588. Y = Pos.Top (label)
  589. };
  590. dlg.Add (label);
  591. label = new Label () {
  592. Text = $"{rune.IsBmp}",
  593. X = Pos.Right (label),
  594. Y = Pos.Top (label)
  595. };
  596. dlg.Add (label);
  597. label = new Label () {
  598. Text = ", CombiningMark: ",
  599. X = Pos.Right (label),
  600. Y = Pos.Top (label)
  601. };
  602. dlg.Add (label);
  603. label = new Label () {
  604. Text = $"{rune.IsCombiningMark ()}",
  605. X = Pos.Right (label),
  606. Y = Pos.Top (label)
  607. };
  608. dlg.Add (label);
  609. label = new Label () {
  610. Text = ", SurrogatePair: ",
  611. X = Pos.Right (label),
  612. Y = Pos.Top (label)
  613. };
  614. dlg.Add (label);
  615. label = new Label () {
  616. Text = $"{rune.IsSurrogatePair ()}",
  617. X = Pos.Right (label),
  618. Y = Pos.Top (label)
  619. };
  620. dlg.Add (label);
  621. label = new Label () {
  622. Text = ", Plane: ",
  623. X = Pos.Right (label),
  624. Y = Pos.Top (label)
  625. };
  626. dlg.Add (label);
  627. label = new Label () {
  628. Text = $"{rune.Plane}",
  629. X = Pos.Right (label),
  630. Y = Pos.Top (label)
  631. };
  632. dlg.Add (label);
  633. label = new Label () {
  634. Text = "Columns: ",
  635. X = 0,
  636. Y = Pos.Bottom (label)
  637. };
  638. dlg.Add (label);
  639. label = new Label () {
  640. Text = $"{rune.GetColumns ()}",
  641. X = Pos.Right (label),
  642. Y = Pos.Top (label)
  643. };
  644. dlg.Add (label);
  645. label = new Label () {
  646. Text = ", Utf16SequenceLength: ",
  647. X = Pos.Right (label),
  648. Y = Pos.Top (label)
  649. };
  650. dlg.Add (label);
  651. label = new Label () {
  652. Text = $"{rune.Utf16SequenceLength}",
  653. X = Pos.Right (label),
  654. Y = Pos.Top (label)
  655. };
  656. dlg.Add (label);
  657. label = new Label () {
  658. Text = $"Code Point Information from {UcdApiClient.BaseUrl}codepoint/dec/{SelectedCodePoint}:",
  659. X = 0,
  660. Y = Pos.Bottom (label)
  661. };
  662. dlg.Add (label);
  663. var json = new TextView () {
  664. X = 0,
  665. Y = Pos.Bottom (label),
  666. Width = Dim.Fill (),
  667. Height = Dim.Fill (2),
  668. ReadOnly = true,
  669. Text = decResponse
  670. };
  671. dlg.Add (json);
  672. Application.Run (dlg);
  673. } else {
  674. MessageBox.ErrorQuery ("Code Point API", $"{UcdApiClient.BaseUrl}codepoint/dec/{SelectedCodePoint} did not return a result for\r\n {new Rune (SelectedCodePoint)} U+{SelectedCodePoint:x5}.", "Ok");
  675. }
  676. // BUGBUG: This is a workaround for some weird ScrollView related mouse grab bug
  677. Application.GrabMouse (this);
  678. }
  679. public override bool OnEnter (View view)
  680. {
  681. if (IsInitialized) {
  682. Application.Driver.SetCursorVisibility (CursorVisibility.Default);
  683. }
  684. return base.OnEnter (view);
  685. }
  686. public override bool OnLeave (View view)
  687. {
  688. Driver.SetCursorVisibility (CursorVisibility.Invisible);
  689. return base.OnLeave (view);
  690. }
  691. }
  692. public class UcdApiClient {
  693. private static readonly HttpClient httpClient = new HttpClient ();
  694. public const string BaseUrl = "https://ucdapi.org/unicode/latest/";
  695. public async Task<string> GetCodepointHex (string hex)
  696. {
  697. var response = await httpClient.GetAsync ($"{BaseUrl}codepoint/hex/{hex}");
  698. response.EnsureSuccessStatusCode ();
  699. return await response.Content.ReadAsStringAsync ();
  700. }
  701. public async Task<string> GetCodepointDec (int dec)
  702. {
  703. var response = await httpClient.GetAsync ($"{BaseUrl}codepoint/dec/{dec}");
  704. response.EnsureSuccessStatusCode ();
  705. return await response.Content.ReadAsStringAsync ();
  706. }
  707. public async Task<string> GetChars (string chars)
  708. {
  709. var response = await httpClient.GetAsync ($"{BaseUrl}chars/{Uri.EscapeDataString (chars)}");
  710. response.EnsureSuccessStatusCode ();
  711. return await response.Content.ReadAsStringAsync ();
  712. }
  713. public async Task<string> GetCharsName (string chars)
  714. {
  715. var response = await httpClient.GetAsync ($"{BaseUrl}chars/{Uri.EscapeDataString (chars)}/name");
  716. response.EnsureSuccessStatusCode ();
  717. return await response.Content.ReadAsStringAsync ();
  718. }
  719. }
  720. class UnicodeRange {
  721. public int Start;
  722. public int End;
  723. public string Category;
  724. public UnicodeRange (int start, int end, string category)
  725. {
  726. this.Start = start;
  727. this.End = end;
  728. this.Category = category;
  729. }
  730. public static List<UnicodeRange> GetRanges ()
  731. {
  732. var ranges = (from r in typeof (UnicodeRanges).GetProperties (System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)
  733. let urange = r.GetValue (null) as System.Text.Unicode.UnicodeRange
  734. let name = string.IsNullOrEmpty (r.Name) ? $"U+{urange.FirstCodePoint:x5}-U+{urange.FirstCodePoint + urange.Length:x5}" : r.Name
  735. where name != "None" && name != "All"
  736. select new UnicodeRange (urange.FirstCodePoint, urange.FirstCodePoint + urange.Length, name));
  737. // .NET 8.0 only supports BMP in UnicodeRanges: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicode.unicoderanges?view=net-8.0
  738. var nonBmpRanges = new List<UnicodeRange> {
  739. new UnicodeRange (0x1F130, 0x1F149 ,"Squared Latin Capital Letters"),
  740. new UnicodeRange (0x12400, 0x1240f ,"Cuneiform Numbers and Punctuation"),
  741. new UnicodeRange (0x10000, 0x1007F ,"Linear B Syllabary"),
  742. new UnicodeRange (0x10080, 0x100FF ,"Linear B Ideograms"),
  743. new UnicodeRange (0x10100, 0x1013F ,"Aegean Numbers"),
  744. new UnicodeRange (0x10300, 0x1032F ,"Old Italic"),
  745. new UnicodeRange (0x10330, 0x1034F ,"Gothic"),
  746. new UnicodeRange (0x10380, 0x1039F ,"Ugaritic"),
  747. new UnicodeRange (0x10400, 0x1044F ,"Deseret"),
  748. new UnicodeRange (0x10450, 0x1047F ,"Shavian"),
  749. new UnicodeRange (0x10480, 0x104AF ,"Osmanya"),
  750. new UnicodeRange (0x10800, 0x1083F ,"Cypriot Syllabary"),
  751. new UnicodeRange (0x1D000, 0x1D0FF ,"Byzantine Musical Symbols"),
  752. new UnicodeRange (0x1D100, 0x1D1FF ,"Musical Symbols"),
  753. new UnicodeRange (0x1D300, 0x1D35F ,"Tai Xuan Jing Symbols"),
  754. new UnicodeRange (0x1D400, 0x1D7FF ,"Mathematical Alphanumeric Symbols"),
  755. new UnicodeRange (0x1F600, 0x1F532 ,"Emojis Symbols"),
  756. new UnicodeRange (0x20000, 0x2A6DF ,"CJK Unified Ideographs Extension B"),
  757. new UnicodeRange (0x2F800, 0x2FA1F ,"CJK Compatibility Ideographs Supplement"),
  758. new UnicodeRange (0xE0000, 0xE007F ,"Tags"),
  759. };
  760. return ranges.Concat (nonBmpRanges).OrderBy (r => r.Category).ToList ();
  761. }
  762. public static List<UnicodeRange> Ranges = GetRanges ();
  763. }