CharMap.cs 34 KB

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