CharMap.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. using System.Diagnostics;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Globalization;
  4. using System.Text.Json;
  5. namespace Terminal.Gui.Views;
  6. /// <summary>
  7. /// A scrollable map of the Unicode codepoints.
  8. /// </summary>
  9. /// <remarks>
  10. /// See <see href="../docs/CharacterMap.md"/> for details.
  11. /// </remarks>
  12. public class CharMap : View, IDesignable
  13. {
  14. private const int COLUMN_WIDTH = 3; // Width of each column of glyphs
  15. private const int HEADER_HEIGHT = 1; // Height of the header
  16. // ReSharper disable once InconsistentNaming
  17. private static readonly int MAX_CODE_POINT = UnicodeRange.Ranges.Max (r => r.End);
  18. /// <summary>
  19. /// Initializes a new instance.
  20. /// </summary>
  21. [RequiresUnreferencedCode ("AOT")]
  22. [RequiresDynamicCode ("AOT")]
  23. public CharMap ()
  24. {
  25. CanFocus = true;
  26. CursorVisibility = CursorVisibility.Default;
  27. AddCommand (Command.Up, commandContext => Move (commandContext, -16));
  28. AddCommand (Command.Down, commandContext => Move (commandContext, 16));
  29. AddCommand (Command.Left, commandContext => Move (commandContext, -1));
  30. AddCommand (Command.Right, commandContext => Move (commandContext, 1));
  31. AddCommand (Command.PageUp, commandContext => Move (commandContext, -(Viewport.Height - HEADER_HEIGHT / _rowHeight) * 16));
  32. AddCommand (Command.PageDown, commandContext => Move (commandContext, (Viewport.Height - HEADER_HEIGHT / _rowHeight) * 16));
  33. AddCommand (Command.Start, commandContext => Move (commandContext, -SelectedCodePoint));
  34. AddCommand (Command.End, commandContext => Move (commandContext, MAX_CODE_POINT - SelectedCodePoint));
  35. AddCommand (Command.ScrollDown, () => ScrollVertical (1));
  36. AddCommand (Command.ScrollUp, () => ScrollVertical (-1));
  37. AddCommand (Command.ScrollRight, () => ScrollHorizontal (1));
  38. AddCommand (Command.ScrollLeft, () => ScrollHorizontal (-1));
  39. AddCommand (Command.Accept, HandleAcceptCommand);
  40. AddCommand (Command.Select, HandleSelectCommand);
  41. AddCommand (Command.Context, HandleContextCommand);
  42. KeyBindings.Add (Key.CursorUp, Command.Up);
  43. KeyBindings.Add (Key.CursorDown, Command.Down);
  44. KeyBindings.Add (Key.CursorLeft, Command.Left);
  45. KeyBindings.Add (Key.CursorRight, Command.Right);
  46. KeyBindings.Add (Key.PageUp, Command.PageUp);
  47. KeyBindings.Add (Key.PageDown, Command.PageDown);
  48. KeyBindings.Add (Key.Home, Command.Start);
  49. KeyBindings.Add (Key.End, Command.End);
  50. KeyBindings.Add (PopoverMenu.DefaultKey, Command.Context);
  51. MouseBindings.Add (MouseFlags.Button1DoubleClicked, Command.Accept);
  52. MouseBindings.ReplaceCommands (MouseFlags.Button3Clicked, Command.Context);
  53. MouseBindings.ReplaceCommands (MouseFlags.Button1Clicked | MouseFlags.ButtonCtrl, Command.Context);
  54. MouseBindings.Add (MouseFlags.WheeledDown, Command.ScrollDown);
  55. MouseBindings.Add (MouseFlags.WheeledUp, Command.ScrollUp);
  56. MouseBindings.Add (MouseFlags.WheeledLeft, Command.ScrollLeft);
  57. MouseBindings.Add (MouseFlags.WheeledRight, Command.ScrollRight);
  58. // Initial content size; height will be corrected by RebuildVisibleRows()
  59. SetContentSize (new (COLUMN_WIDTH * 16 + RowLabelWidth, HEADER_HEIGHT + _rowHeight));
  60. // Set up the horizontal scrollbar. Turn off AutoShow since we do it manually.
  61. HorizontalScrollBar.AutoShow = false;
  62. HorizontalScrollBar.Increment = COLUMN_WIDTH;
  63. // This prevents scrolling past the last column
  64. HorizontalScrollBar.ScrollableContentSize = GetContentSize ().Width - RowLabelWidth;
  65. HorizontalScrollBar.X = RowLabelWidth;
  66. HorizontalScrollBar.Y = Pos.AnchorEnd ();
  67. HorizontalScrollBar.Width = Dim.Fill (1);
  68. // We want the horizontal scrollbar to only show when needed.
  69. // We can't use ScrollBar.AutoShow because we are using custom ContentSize
  70. // So, we do it manually on ViewportChanged events.
  71. ViewportChanged += (sender, args) =>
  72. {
  73. if (Viewport.Width < GetContentSize ().Width)
  74. {
  75. HorizontalScrollBar.Visible = true;
  76. }
  77. else
  78. {
  79. HorizontalScrollBar.Visible = false;
  80. }
  81. };
  82. // Set up the vertical scrollbar. Turn off AutoShow since it's always visible.
  83. VerticalScrollBar.AutoShow = true;
  84. VerticalScrollBar.Visible = false;
  85. VerticalScrollBar.X = Pos.AnchorEnd ();
  86. VerticalScrollBar.Y = HEADER_HEIGHT; // Header
  87. // The scrollbars are in the Padding. VisualRole.Focus/Active are used to draw the
  88. // CharMap headers. Override Padding to force it to draw to match.
  89. Padding!.GettingAttributeForRole += PaddingOnGettingAttributeForRole;
  90. // Build initial visible rows (all rows with at least one valid codepoint)
  91. RebuildVisibleRows ();
  92. }
  93. // Visible rows management: each entry is the starting code point of a 16-wide row
  94. private readonly List<int> _visibleRowStarts = new ();
  95. private readonly Dictionary<int, int> _rowStartToVisibleIndex = new ();
  96. private void RebuildVisibleRows ()
  97. {
  98. _visibleRowStarts.Clear ();
  99. _rowStartToVisibleIndex.Clear ();
  100. int maxRow = MAX_CODE_POINT / 16;
  101. for (var row = 0; row <= maxRow; row++)
  102. {
  103. int start = row * 16;
  104. bool anyValid = false;
  105. bool anyVisible = false;
  106. for (var col = 0; col < 16; col++)
  107. {
  108. int cp = start + col;
  109. if (cp > RuneExtensions.MaxUnicodeCodePoint)
  110. {
  111. break;
  112. }
  113. if (!Rune.IsValid (cp))
  114. {
  115. continue;
  116. }
  117. anyValid = true;
  118. if (!ShowUnicodeCategory.HasValue)
  119. {
  120. // With no filter, a row is displayed if it has any valid codepoint
  121. anyVisible = true;
  122. break;
  123. }
  124. UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory (cp);
  125. if (cat == ShowUnicodeCategory.Value)
  126. {
  127. anyVisible = true;
  128. break;
  129. }
  130. }
  131. if (anyValid && (!ShowUnicodeCategory.HasValue ? anyValid : anyVisible))
  132. {
  133. _rowStartToVisibleIndex [start] = _visibleRowStarts.Count;
  134. _visibleRowStarts.Add (start);
  135. }
  136. }
  137. // Update content size to match visible rows
  138. SetContentSize (new (COLUMN_WIDTH * 16 + RowLabelWidth, _visibleRowStarts.Count * _rowHeight + HEADER_HEIGHT));
  139. // Keep vertical scrollbar aligned with new content size
  140. VerticalScrollBar.ScrollableContentSize = GetContentSize ().Height;
  141. }
  142. private int VisibleRowIndexForCodePoint (int codePoint)
  143. {
  144. int start = (codePoint / 16) * 16;
  145. return _rowStartToVisibleIndex.GetValueOrDefault (start, -1);
  146. }
  147. private int _rowHeight = 1; // Height of each row of 16 glyphs - changing this is not tested
  148. private int _selectedCodepoint; // Currently selected codepoint
  149. private int _startCodepoint; // The codepoint that will be displayed at the top of the Viewport
  150. /// <summary>
  151. /// Gets or sets the currently selected codepoint. Causes the Viewport to scroll to make the selected code point
  152. /// visible.
  153. /// </summary>
  154. public int SelectedCodePoint
  155. {
  156. get => _selectedCodepoint;
  157. set
  158. {
  159. if (_selectedCodepoint == value)
  160. {
  161. return;
  162. }
  163. int newSelectedCodePoint = Math.Clamp (value, 0, MAX_CODE_POINT);
  164. Point offsetToNewCursor = GetCursor (newSelectedCodePoint);
  165. _selectedCodepoint = newSelectedCodePoint;
  166. // Ensure the new cursor position is visible
  167. ScrollToMakeCursorVisible (offsetToNewCursor);
  168. SetNeedsDraw ();
  169. SelectedCodePointChanged?.Invoke (this, new (SelectedCodePoint));
  170. }
  171. }
  172. /// <summary>
  173. /// Raised when the selected code point changes.
  174. /// </summary>
  175. public event EventHandler<EventArgs<int>>? SelectedCodePointChanged;
  176. /// <summary>
  177. /// Gets or sets whether the number of columns each glyph is displayed.
  178. /// </summary>
  179. public bool ShowGlyphWidths
  180. {
  181. get => _rowHeight == 2;
  182. set
  183. {
  184. _rowHeight = value ? 2 : 1;
  185. // height changed => content height depends on row height
  186. RebuildVisibleRows ();
  187. SetNeedsDraw ();
  188. }
  189. }
  190. /// <summary>
  191. /// Specifies the starting offset for the character map. The default is 0x2500 which is the Box Drawing
  192. /// characters.
  193. /// </summary>
  194. public int StartCodePoint
  195. {
  196. get => _startCodepoint;
  197. set
  198. {
  199. _startCodepoint = value;
  200. SelectedCodePoint = value;
  201. }
  202. }
  203. private UnicodeCategory? _showUnicodeCategory;
  204. /// <summary>
  205. /// When set, only glyphs whose UnicodeCategory matches the value are rendered. If <see langword="null"/> (default),
  206. /// all glyphs are rendered.
  207. /// </summary>
  208. public UnicodeCategory? ShowUnicodeCategory
  209. {
  210. get => _showUnicodeCategory;
  211. set
  212. {
  213. if (_showUnicodeCategory == value)
  214. {
  215. return;
  216. }
  217. _showUnicodeCategory = value;
  218. RebuildVisibleRows ();
  219. // Ensure selection is on a visible row
  220. int desiredRowStart = (SelectedCodePoint / 16) * 16;
  221. if (!_rowStartToVisibleIndex.ContainsKey (desiredRowStart))
  222. {
  223. // Find nearest visible row (prefer next; fallback to last)
  224. int idx = _visibleRowStarts.FindIndex (s => s >= desiredRowStart);
  225. if (idx < 0 && _visibleRowStarts.Count > 0)
  226. {
  227. idx = _visibleRowStarts.Count - 1;
  228. }
  229. if (idx >= 0)
  230. {
  231. SelectedCodePoint = _visibleRowStarts [idx];
  232. }
  233. }
  234. SetNeedsDraw ();
  235. }
  236. }
  237. private void CopyCodePoint () { App?.Clipboard?.SetClipboardData($"U+{SelectedCodePoint:x5}"); }
  238. private void CopyGlyph () { App?.Clipboard?.SetClipboardData($"{new Rune (SelectedCodePoint)}"); }
  239. private bool? Move (ICommandContext? commandContext, int cpOffset)
  240. {
  241. if (RaiseSelecting (commandContext) is true)
  242. {
  243. return true;
  244. }
  245. SelectedCodePoint += cpOffset;
  246. return true;
  247. }
  248. private void PaddingOnGettingAttributeForRole (object? sender, VisualRoleEventArgs e)
  249. {
  250. if (e.Role != VisualRole.Focus && e.Role != VisualRole.Active)
  251. {
  252. e.Result = GetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Active);
  253. }
  254. e.Handled = true;
  255. }
  256. private void ScrollToMakeCursorVisible (Point offsetToNewCursor)
  257. {
  258. // Adjust vertical scrolling
  259. if (offsetToNewCursor.Y < 1) // Header is at Y = 0
  260. {
  261. ScrollVertical (offsetToNewCursor.Y - HEADER_HEIGHT);
  262. }
  263. else if (offsetToNewCursor.Y >= Viewport.Height)
  264. {
  265. ScrollVertical (offsetToNewCursor.Y - Viewport.Height + HEADER_HEIGHT);
  266. }
  267. // Adjust horizontal scrolling
  268. if (offsetToNewCursor.X < RowLabelWidth + 1)
  269. {
  270. ScrollHorizontal (offsetToNewCursor.X - (RowLabelWidth + 1));
  271. }
  272. else if (offsetToNewCursor.X >= Viewport.Width)
  273. {
  274. ScrollHorizontal (offsetToNewCursor.X - Viewport.Width + 1);
  275. }
  276. }
  277. #region Details Dialog
  278. [RequiresUnreferencedCode ("AOT")]
  279. [RequiresDynamicCode ("AOT")]
  280. private void ShowDetails ()
  281. {
  282. if (App is not { Initialized: true })
  283. {
  284. // Some unit tests invoke Accept without Init
  285. return;
  286. }
  287. UcdApiClient? client = new ();
  288. var decResponse = string.Empty;
  289. var getCodePointError = string.Empty;
  290. Dialog? waitIndicator = new ()
  291. {
  292. Title = Strings.charMapCPInfoDlgTitle,
  293. X = Pos.Center (),
  294. Y = Pos.Center (),
  295. Width = 40,
  296. Height = 10,
  297. Buttons = [new () { Text = Strings.btnCancel }]
  298. };
  299. var errorLabel = new Label
  300. {
  301. Text = UcdApiClient.BaseUrl,
  302. X = 0,
  303. Y = 0,
  304. Width = Dim.Fill (),
  305. Height = Dim.Fill (3),
  306. TextAlignment = Alignment.Center
  307. };
  308. var spinner = new SpinnerView
  309. {
  310. X = Pos.Center (),
  311. Y = Pos.Bottom (errorLabel),
  312. Style = new SpinnerStyle.Aesthetic ()
  313. };
  314. spinner.AutoSpin = true;
  315. waitIndicator.Add (errorLabel);
  316. waitIndicator.Add (spinner);
  317. waitIndicator.Ready += async (s, a) =>
  318. {
  319. try
  320. {
  321. decResponse = await client.GetCodepointDec (SelectedCodePoint).ConfigureAwait (false);
  322. App?.Invoke ((_) => (s as Dialog)?.RequestStop ());
  323. }
  324. catch (HttpRequestException e)
  325. {
  326. getCodePointError = errorLabel.Text = e.Message;
  327. App?.Invoke ((_) => (s as Dialog)?.RequestStop ());
  328. }
  329. };
  330. App?.Run (waitIndicator);
  331. waitIndicator.Dispose ();
  332. var name = string.Empty;
  333. if (!string.IsNullOrEmpty (decResponse))
  334. {
  335. using JsonDocument document = JsonDocument.Parse (decResponse);
  336. JsonElement root = document.RootElement;
  337. // Get a property by name and output its value
  338. if (root.TryGetProperty ("name", out JsonElement nameElement))
  339. {
  340. name = nameElement.GetString ();
  341. }
  342. decResponse = JsonSerializer.Serialize (
  343. document.RootElement,
  344. new
  345. JsonSerializerOptions
  346. { WriteIndented = true }
  347. );
  348. }
  349. else
  350. {
  351. decResponse = getCodePointError;
  352. }
  353. var title = $"{ToCamelCase (name!)} - {new Rune (SelectedCodePoint)} U+{SelectedCodePoint:x5}";
  354. Button? copyGlyph = new () { Text = Strings.charMapCopyGlyph };
  355. Button? copyCodepoint = new () { Text = Strings.charMapCopyCP };
  356. Button? cancel = new () { Text = Strings.btnCancel };
  357. var dlg = new Dialog { Title = title, Buttons = [copyGlyph, copyCodepoint, cancel] };
  358. copyGlyph.Accepting += (s, a) =>
  359. {
  360. CopyGlyph ();
  361. dlg!.RequestStop ();
  362. a.Handled = true;
  363. };
  364. copyCodepoint.Accepting += (s, a) =>
  365. {
  366. CopyCodePoint ();
  367. dlg!.RequestStop ();
  368. a.Handled = true;
  369. };
  370. cancel.Accepting += (s, a) =>
  371. {
  372. dlg!.RequestStop ();
  373. a.Handled = true;
  374. };
  375. var rune = (Rune)SelectedCodePoint;
  376. var label = new Label { Text = "IsAscii: ", X = 0, Y = 0 };
  377. dlg.Add (label);
  378. label = new () { Text = $"{rune.IsAscii}", X = Pos.Right (label), Y = Pos.Top (label) };
  379. dlg.Add (label);
  380. label = new () { Text = ", Bmp: ", X = Pos.Right (label), Y = Pos.Top (label) };
  381. dlg.Add (label);
  382. label = new () { Text = $"{rune.IsBmp}", X = Pos.Right (label), Y = Pos.Top (label) };
  383. dlg.Add (label);
  384. label = new () { Text = ", CombiningMark: ", X = Pos.Right (label), Y = Pos.Top (label) };
  385. dlg.Add (label);
  386. label = new () { Text = $"{rune.IsCombiningMark ()}", X = Pos.Right (label), Y = Pos.Top (label) };
  387. dlg.Add (label);
  388. label = new () { Text = ", SurrogatePair: ", X = Pos.Right (label), Y = Pos.Top (label) };
  389. dlg.Add (label);
  390. label = new () { Text = $"{rune.IsSurrogatePair ()}", X = Pos.Right (label), Y = Pos.Top (label) };
  391. dlg.Add (label);
  392. label = new () { Text = ", Plane: ", X = Pos.Right (label), Y = Pos.Top (label) };
  393. dlg.Add (label);
  394. label = new () { Text = $"{rune.Plane}", X = Pos.Right (label), Y = Pos.Top (label) };
  395. dlg.Add (label);
  396. label = new () { Text = "Columns: ", X = 0, Y = Pos.Bottom (label) };
  397. dlg.Add (label);
  398. label = new () { Text = $"{rune.GetColumns ()}", X = Pos.Right (label), Y = Pos.Top (label) };
  399. dlg.Add (label);
  400. label = new () { Text = ", Utf16SequenceLength: ", X = Pos.Right (label), Y = Pos.Top (label) };
  401. dlg.Add (label);
  402. label = new () { Text = $"{rune.Utf16SequenceLength}", X = Pos.Right (label), Y = Pos.Top (label) };
  403. dlg.Add (label);
  404. label = new () { Text = "Category: ", X = 0, Y = Pos.Bottom (label) };
  405. dlg.Add (label);
  406. Span<char> utf16 = stackalloc char [2];
  407. int charCount = rune.EncodeToUtf16 (utf16);
  408. // Get the bidi class for the first code unit
  409. // For most bidi characters, the first code unit is sufficient
  410. UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory (utf16 [0]);
  411. label = new () { Text = $"{category}", X = Pos.Right (label), Y = Pos.Top (label) };
  412. dlg.Add (label);
  413. label = new ()
  414. {
  415. Text =
  416. $"{Strings.charMapInfoDlgInfoLabel} {UcdApiClient.BaseUrl}codepoint/dec/{SelectedCodePoint}:",
  417. X = 0,
  418. Y = Pos.Bottom (label)
  419. };
  420. dlg.Add (label);
  421. var json = new TextView
  422. {
  423. X = 0,
  424. Y = Pos.Bottom (label),
  425. Width = Dim.Fill (),
  426. Height = Dim.Fill (2),
  427. ReadOnly = true,
  428. Text = decResponse
  429. };
  430. dlg.Add (json);
  431. App?.Run (dlg);
  432. dlg.Dispose ();
  433. }
  434. #endregion Details Dialog
  435. #region Cursor
  436. private Point GetCursor (int codePoint)
  437. {
  438. // + 1 for padding between label and first column
  439. int x = codePoint % 16 * COLUMN_WIDTH + RowLabelWidth + 1 - Viewport.X;
  440. int visibleRowIndex = VisibleRowIndexForCodePoint (codePoint);
  441. if (visibleRowIndex < 0)
  442. {
  443. // If filtered out, stick to current Y to avoid jumping; caller will clamp
  444. int fallbackY = HEADER_HEIGHT - Viewport.Y;
  445. return new (x, fallbackY);
  446. }
  447. int y = visibleRowIndex * _rowHeight + HEADER_HEIGHT - Viewport.Y;
  448. return new (x, y);
  449. }
  450. /// <inheritdoc/>
  451. public override Point? PositionCursor ()
  452. {
  453. Point cursor = GetCursor (SelectedCodePoint);
  454. if (HasFocus
  455. && cursor.X >= RowLabelWidth
  456. && cursor.X < Viewport.Width
  457. && cursor.Y > 0
  458. && cursor.Y < Viewport.Height)
  459. {
  460. Move (cursor.X, cursor.Y);
  461. }
  462. else
  463. {
  464. return null;
  465. }
  466. return cursor;
  467. }
  468. #endregion Cursor
  469. #region Drawing
  470. private static int RowLabelWidth => $"U+{MAX_CODE_POINT:x5}".Length + 1;
  471. /// <inheritdoc/>
  472. protected override bool OnDrawingContent ()
  473. {
  474. if (Viewport.Height == 0 || Viewport.Width == 0)
  475. {
  476. return true;
  477. }
  478. int selectedCol = SelectedCodePoint % 16;
  479. int selectedRowIndex = VisibleRowIndexForCodePoint (SelectedCodePoint);
  480. // Headers
  481. // Clear the header area
  482. Move (0, 0);
  483. SetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Active);
  484. AddStr (new (' ', Viewport.Width));
  485. int firstColumnX = RowLabelWidth - Viewport.X;
  486. // Header
  487. var x = 0;
  488. for (var hexDigit = 0; hexDigit < 16; hexDigit++)
  489. {
  490. x = firstColumnX + hexDigit * COLUMN_WIDTH;
  491. if (x > RowLabelWidth - 2)
  492. {
  493. Move (x, 0);
  494. SetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Active);
  495. AddStr (" ");
  496. // Swap Active/Focus so the selected column is highlighted
  497. if (hexDigit == selectedCol)
  498. {
  499. SetAttributeForRole (HasFocus ? VisualRole.Active : VisualRole.Focus);
  500. }
  501. AddStr ($"{hexDigit:x}");
  502. SetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Active);
  503. AddStr (" ");
  504. }
  505. }
  506. // Start at 1 because Header.
  507. for (var y = 1; y < Viewport.Height; y++)
  508. {
  509. // Which visible row is this?
  510. int visibleRow = (y + Viewport.Y - 1) / _rowHeight;
  511. if (visibleRow < 0 || visibleRow >= _visibleRowStarts.Count)
  512. {
  513. // No row at this y; clear label area and continue
  514. Move (0, y);
  515. AddStr (new (' ', Viewport.Width));
  516. continue;
  517. }
  518. int rowStart = _visibleRowStarts [visibleRow];
  519. // Draw the row label (U+XXXX_)
  520. SetAttributeForRole (HasFocus ? VisualRole.Focus : VisualRole.Active);
  521. Move (0, y);
  522. // Swap Active/Focus so the selected row is highlighted
  523. if (visibleRow == selectedRowIndex)
  524. {
  525. SetAttributeForRole (HasFocus ? VisualRole.Active : VisualRole.Focus);
  526. }
  527. if (!ShowGlyphWidths || (y + Viewport.Y) % _rowHeight > 0)
  528. {
  529. AddStr ($"U+{rowStart / 16:x5}_");
  530. }
  531. else
  532. {
  533. AddStr (new (' ', RowLabelWidth));
  534. }
  535. // Draw the row
  536. SetAttributeForRole (VisualRole.Normal);
  537. for (var col = 0; col < 16; col++)
  538. {
  539. x = firstColumnX + COLUMN_WIDTH * col + 1;
  540. if (x < RowLabelWidth || x > Viewport.Width - 1)
  541. {
  542. continue;
  543. }
  544. Move (x, y);
  545. // If we're at the cursor position highlight the cell
  546. if (visibleRow == selectedRowIndex && col == selectedCol)
  547. {
  548. SetAttributeForRole (VisualRole.Active);
  549. }
  550. int scalar = rowStart + col;
  551. // Don't render out-of-range scalars
  552. if (scalar > MAX_CODE_POINT)
  553. {
  554. AddStr (" ");
  555. if (visibleRow == selectedRowIndex && col == selectedCol)
  556. {
  557. SetAttributeForRole (VisualRole.Normal);
  558. }
  559. continue;
  560. }
  561. string grapheme = "?";
  562. if (Rune.IsValid (scalar))
  563. {
  564. grapheme = new Rune (scalar).ToString ();
  565. }
  566. int width = grapheme.GetColumns ();
  567. // Compute visibility based on ShowUnicodeCategory
  568. bool isVisible = Rune.IsValid (scalar);
  569. if (isVisible && ShowUnicodeCategory.HasValue)
  570. {
  571. UnicodeCategory cat = CharUnicodeInfo.GetUnicodeCategory (scalar);
  572. isVisible = cat == ShowUnicodeCategory.Value;
  573. }
  574. if (!ShowGlyphWidths || (y + Viewport.Y) % _rowHeight > 0)
  575. {
  576. // Glyph row
  577. if (isVisible)
  578. {
  579. RenderGrapheme (grapheme, width, scalar);
  580. }
  581. else
  582. {
  583. AddStr (" ");
  584. }
  585. }
  586. else
  587. {
  588. // Width row (ShowGlyphWidths)
  589. if (isVisible)
  590. {
  591. // Draw the width of the rune faint
  592. Attribute attr = GetAttributeForRole (VisualRole.Normal);
  593. SetAttribute (attr with { Style = attr.Style | TextStyle.Faint });
  594. AddStr ($"{width}");
  595. }
  596. else
  597. {
  598. AddStr (" ");
  599. }
  600. }
  601. // If we're at the cursor position, and we don't have focus
  602. if (visibleRow == selectedRowIndex && col == selectedCol)
  603. {
  604. SetAttributeForRole (VisualRole.Normal);
  605. }
  606. }
  607. }
  608. return true;
  609. void RenderGrapheme (string grapheme, int width, int scalar)
  610. {
  611. // Get the UnicodeCategory
  612. // Get the bidi class for the first code unit
  613. // For most bidi characters, the first code unit is sufficient
  614. UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory (scalar);
  615. switch (category)
  616. {
  617. case UnicodeCategory.OtherNotAssigned:
  618. SetAttributeForRole (VisualRole.Highlight);
  619. AddStr (Rune.ReplacementChar.ToString ());
  620. SetAttributeForRole (VisualRole.Normal);
  621. break;
  622. // Format character that affects the layout of text or the operation of text processes, but is not normally rendered.
  623. // These report width of 0 and don't render on their own.
  624. case UnicodeCategory.Format:
  625. SetAttributeForRole (VisualRole.Highlight);
  626. AddStr ("F");
  627. SetAttributeForRole (VisualRole.Normal);
  628. break;
  629. // Nonspacing character that indicates modifications of a base character.
  630. case UnicodeCategory.NonSpacingMark:
  631. // Spacing character that indicates modifications of a base character and affects the width of the glyph for that base character.
  632. case UnicodeCategory.SpacingCombiningMark:
  633. // Enclosing mark character, which is a nonspacing combining character that surrounds all previous characters up to and including a base character.
  634. case UnicodeCategory.EnclosingMark:
  635. if (width > 0)
  636. {
  637. AddStr (grapheme);
  638. }
  639. break;
  640. // These report width of 0, but render as 1
  641. case UnicodeCategory.Control:
  642. case UnicodeCategory.LineSeparator:
  643. case UnicodeCategory.ParagraphSeparator:
  644. case UnicodeCategory.Surrogate:
  645. AddStr (grapheme);
  646. break;
  647. case UnicodeCategory.OtherLetter:
  648. AddStr (grapheme);
  649. if (width == 0)
  650. {
  651. AddStr (" ");
  652. }
  653. break;
  654. default:
  655. // Draw the rune
  656. if (width > 0)
  657. {
  658. AddStr (grapheme);
  659. }
  660. else
  661. {
  662. throw new InvalidOperationException ($"The Rune \"{grapheme}\" (U+{Rune.GetRuneAt (grapheme, 0).Value:x6}) has zero width and no special-case UnicodeCategory logic applies.");
  663. }
  664. break;
  665. }
  666. }
  667. }
  668. /// <summary>
  669. /// Helper to convert a string into camel case.
  670. /// </summary>
  671. /// <param name="str"></param>
  672. /// <returns></returns>
  673. public static string ToCamelCase (string str)
  674. {
  675. if (string.IsNullOrEmpty (str))
  676. {
  677. return str;
  678. }
  679. TextInfo textInfo = new CultureInfo ("en-US", false).TextInfo;
  680. str = textInfo.ToLower (str);
  681. str = textInfo.ToTitleCase (str);
  682. return str;
  683. }
  684. #endregion Drawing
  685. #region Mouse Handling
  686. private bool? HandleSelectCommand (ICommandContext? commandContext)
  687. {
  688. Point position = GetCursor (SelectedCodePoint);
  689. if (commandContext is CommandContext<MouseBinding> { Binding.MouseEventArgs: { } } mouseCommandContext)
  690. {
  691. // If the mouse is clicked on the headers, map it to the first glyph of the row/col
  692. position = mouseCommandContext.Binding.MouseEventArgs.Position;
  693. if (position.Y == 0)
  694. {
  695. position = position with { Y = GetCursor (SelectedCodePoint).Y };
  696. }
  697. if (position.X < RowLabelWidth || position.X > RowLabelWidth + 16 * COLUMN_WIDTH - 1)
  698. {
  699. position = position with { X = GetCursor (SelectedCodePoint).X };
  700. }
  701. }
  702. if (RaiseSelecting (commandContext) is true)
  703. {
  704. return true;
  705. }
  706. if (!TryGetCodePointFromPosition (position, out int cp))
  707. {
  708. return false;
  709. }
  710. if (cp != SelectedCodePoint)
  711. {
  712. if (!HasFocus && CanFocus)
  713. {
  714. SetFocus ();
  715. }
  716. SelectedCodePoint = cp;
  717. }
  718. return true;
  719. }
  720. [RequiresUnreferencedCode ("AOT")]
  721. [RequiresDynamicCode ("AOT")]
  722. private bool? HandleAcceptCommand (ICommandContext? commandContext)
  723. {
  724. if (RaiseAccepting (commandContext) is true)
  725. {
  726. return true;
  727. }
  728. if (commandContext is CommandContext<MouseBinding> { Binding.MouseEventArgs: { } } mouseCommandContext)
  729. {
  730. if (!HasFocus && CanFocus)
  731. {
  732. SetFocus ();
  733. }
  734. if (!TryGetCodePointFromPosition (mouseCommandContext.Binding.MouseEventArgs.Position, out int cp))
  735. {
  736. return false;
  737. }
  738. SelectedCodePoint = cp;
  739. }
  740. ShowDetails ();
  741. return true;
  742. }
  743. private bool? HandleContextCommand (ICommandContext? commandContext)
  744. {
  745. int newCodePoint = SelectedCodePoint;
  746. if (commandContext is CommandContext<MouseBinding> { Binding.MouseEventArgs: { } } mouseCommandContext)
  747. {
  748. if (!TryGetCodePointFromPosition (mouseCommandContext.Binding.MouseEventArgs.Position, out newCodePoint))
  749. {
  750. return false;
  751. }
  752. }
  753. if (!HasFocus && CanFocus)
  754. {
  755. SetFocus ();
  756. }
  757. SelectedCodePoint = newCodePoint;
  758. // This demonstrates how to create an ephemeral Popover; one that exists
  759. // ony as long as the popover is visible.
  760. // Note, for ephemeral Popovers, hotkeys are not supported.
  761. PopoverMenu? contextMenu = new (
  762. [
  763. new (Strings.charMapCopyGlyph, string.Empty, CopyGlyph),
  764. new (Strings.charMapCopyCP, string.Empty, CopyCodePoint)
  765. ]);
  766. // Registering with the PopoverManager will ensure that the context menu is closed when the view is no longer focused
  767. // and the context menu is disposed when it is closed.
  768. App!.Popover?.Register (contextMenu);
  769. contextMenu?.MakeVisible (ViewportToScreen (GetCursor (SelectedCodePoint)));
  770. return true;
  771. }
  772. private bool TryGetCodePointFromPosition (Point position, out int codePoint)
  773. {
  774. if (position.X < RowLabelWidth || position.Y < 1)
  775. {
  776. codePoint = 0;
  777. return false;
  778. }
  779. int visibleRow = (position.Y - 1 - -Viewport.Y) / _rowHeight;
  780. if (visibleRow < 0 || visibleRow >= _visibleRowStarts.Count)
  781. {
  782. codePoint = 0;
  783. return false;
  784. }
  785. int col = (position.X - RowLabelWidth - -Viewport.X) / COLUMN_WIDTH;
  786. if (col > 15)
  787. {
  788. col = 15;
  789. }
  790. codePoint = _visibleRowStarts [visibleRow] + col;
  791. if (codePoint > MAX_CODE_POINT)
  792. {
  793. return false;
  794. }
  795. return true;
  796. }
  797. #endregion Mouse Handling
  798. }