MainWindow.axaml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Avalonia;
  5. using Avalonia.Controls;
  6. using Avalonia.Controls.Primitives;
  7. using Avalonia.Input;
  8. using Avalonia.Interactivity;
  9. using Avalonia.Media;
  10. using Avalonia.Media.TextFormatting;
  11. namespace TextTestApp
  12. {
  13. public partial class MainWindow : Window
  14. {
  15. private SelectionAdorner? _selectionAdorner;
  16. public MainWindow()
  17. {
  18. InitializeComponent();
  19. _selectionAdorner = new();
  20. _selectionAdorner.Stroke = Brushes.Red;
  21. _selectionAdorner.Fill = new SolidColorBrush(Colors.LightSkyBlue, 0.25);
  22. _selectionAdorner.IsHitTestVisible = false;
  23. AdornerLayer.SetIsClipEnabled(_selectionAdorner, false);
  24. AdornerLayer.SetAdorner(_rendering, _selectionAdorner);
  25. _rendering.TextLineChanged += OnShapeBufferChanged;
  26. OnShapeBufferChanged();
  27. }
  28. private void OnNewWindowClick(object? sender, RoutedEventArgs e)
  29. {
  30. MainWindow win = new MainWindow();
  31. win.Show();
  32. }
  33. protected override void OnKeyDown(KeyEventArgs e)
  34. {
  35. if (e.Key == Key.F5)
  36. {
  37. _rendering.InvalidateVisual();
  38. OnShapeBufferChanged();
  39. e.Handled = true;
  40. }
  41. else if (e.Key == Key.Escape)
  42. {
  43. if (_hits.IsKeyboardFocusWithin && _hits.SelectedIndex != -1)
  44. {
  45. _hits.SelectedIndex = -1;
  46. e.Handled = true;
  47. }
  48. else if (_buffer.IsKeyboardFocusWithin && _buffer.SelectedIndex != -1)
  49. {
  50. _buffer.SelectedIndex = -1;
  51. e.Handled = true;
  52. }
  53. }
  54. base.OnKeyDown(e);
  55. }
  56. private void OnShapeBufferChanged(object? sender, EventArgs e) => OnShapeBufferChanged();
  57. private void OnShapeBufferChanged()
  58. {
  59. if (_selectionAdorner == null)
  60. return;
  61. ListBuffers();
  62. ListHits();
  63. Rect bounds = _rendering.LineRenderBounds;
  64. _selectionAdorner!.Transform = Matrix.CreateTranslation(bounds.X, bounds.Y);
  65. }
  66. private void ListBuffers()
  67. {
  68. for (int i = _buffer.ItemCount - 1; i >= 1; i--)
  69. _buffer.Items.RemoveAt(i);
  70. TextLine? textLine = _rendering.TextLine;
  71. if (textLine == null)
  72. return;
  73. double currentX = _rendering.LineRenderBounds.Left;
  74. foreach (TextRun run in textLine.TextRuns)
  75. {
  76. if (run is ShapedTextRun shapedRun)
  77. {
  78. _buffer.Items.Add(new TextBlock
  79. {
  80. Text = $"{run.GetType().Name}: Bidi = {shapedRun.BidiLevel}, Font = {shapedRun.ShapedBuffer.GlyphTypeface.FamilyName}",
  81. FontWeight = FontWeight.Bold,
  82. Padding = new Thickness(10, 0),
  83. Tag = run,
  84. });
  85. ListBuffer(textLine, shapedRun, ref currentX);
  86. }
  87. else
  88. _buffer.Items.Add(new TextBlock
  89. {
  90. Text = run.GetType().Name,
  91. FontWeight = FontWeight.Bold,
  92. Padding = new Thickness(10, 0),
  93. Tag = run
  94. });
  95. }
  96. }
  97. private void ListHits()
  98. {
  99. for (int i = _hits.ItemCount - 1; i >= 1; i--)
  100. _hits.Items.RemoveAt(i);
  101. TextLine? textLine = _rendering.TextLine;
  102. if (textLine == null)
  103. return;
  104. for (int i = 0; i < textLine.Length; i++)
  105. {
  106. string? clusterText = _rendering.Text!.Substring(i, 1);
  107. string? clusterHex = ToHex(clusterText);
  108. var hit = new CharacterHit(i);
  109. var prevHit = textLine.GetPreviousCaretCharacterHit(hit);
  110. var nextHit = textLine.GetNextCaretCharacterHit(hit);
  111. var bkspHit = textLine.GetBackspaceCaretCharacterHit(hit);
  112. GridRow row = new GridRow { ColumnSpacing = 10 };
  113. row.Children.Add(new Control());
  114. row.Children.Add(new TextBlock { Text = $"{bkspHit.FirstCharacterIndex}+{bkspHit.TrailingLength}" });
  115. row.Children.Add(new TextBlock { Text = $"{prevHit.FirstCharacterIndex}+{prevHit.TrailingLength}" });
  116. row.Children.Add(new TextBlock { Text = i.ToString(), FontWeight = FontWeight.Bold });
  117. row.Children.Add(new TextBlock { Text = $"{nextHit.FirstCharacterIndex}+{nextHit.TrailingLength}" });
  118. row.Children.Add(new TextBlock { Text = clusterHex });
  119. row.Children.Add(new TextBlock { Text = clusterText });
  120. row.Children.Add(new TextBlock { Text = textLine.GetDistanceFromCharacterHit(hit).ToString() });
  121. row.Tag = i;
  122. _hits.Items.Add(row);
  123. }
  124. }
  125. private static readonly IBrush TransparentAliceBlue = new SolidColorBrush(0x0F0188FF);
  126. private static readonly IBrush TransparentAntiqueWhite = new SolidColorBrush(0x28DF8000);
  127. private void ListBuffer(TextLine textLine, ShapedTextRun shapedRun, ref double currentX)
  128. {
  129. ShapedBuffer buffer = shapedRun.ShapedBuffer;
  130. int lastClusterStart = -1;
  131. bool oddCluster = false;
  132. IReadOnlyList<GlyphInfo> glyphInfos = buffer;
  133. currentX += shapedRun.GlyphRun.BaselineOrigin.X;
  134. for (var i = 0; i < glyphInfos.Count; i++)
  135. {
  136. GlyphInfo info = glyphInfos[i];
  137. int clusterStart = info.GlyphCluster;
  138. int clusterLength = FindClusterLenghtAt(i);
  139. string? clusterText = _rendering.Text!.Substring(clusterStart, clusterLength);
  140. string? clusterHex = ToHex(clusterText);
  141. Border border = new Border();
  142. if (clusterStart == lastClusterStart)
  143. {
  144. clusterText = clusterHex = null;
  145. }
  146. else
  147. {
  148. oddCluster = !oddCluster;
  149. lastClusterStart = clusterStart;
  150. }
  151. border.Background = oddCluster ? TransparentAliceBlue : TransparentAntiqueWhite;
  152. GridRow row = new GridRow { ColumnSpacing = 10 };
  153. row.Children.Add(new Control());
  154. row.Children.Add(new TextBlock { Text = clusterStart.ToString() });
  155. row.Children.Add(new TextBlock { Text = clusterText });
  156. row.Children.Add(new TextBlock { Text = clusterHex, TextWrapping = TextWrapping.Wrap });
  157. row.Children.Add(new Image { Source = CreateGlyphDrawing(shapedRun.GlyphRun.GlyphTypeface, FontSize, info), Margin = new Thickness(2) });
  158. row.Children.Add(new TextBlock { Text = info.GlyphIndex.ToString() });
  159. row.Children.Add(new TextBlock { Text = info.GlyphAdvance.ToString() });
  160. row.Children.Add(new TextBlock { Text = info.GlyphOffset.ToString() });
  161. Geometry glyph = GetGlyphOutline(shapedRun.GlyphRun.GlyphTypeface, shapedRun.GlyphRun.FontRenderingEmSize, info);
  162. Rect glyphBounds = glyph.Bounds;
  163. Rect offsetBounds = glyphBounds.Translate(new Vector(currentX + info.GlyphOffset.X, info.GlyphOffset.Y));
  164. TextBlock boundsBlock = new TextBlock { Text = offsetBounds.ToString() };
  165. ToolTip.SetTip(boundsBlock, "Origin bounds: " + glyphBounds);
  166. row.Children.Add(boundsBlock);
  167. border.Child = row;
  168. border.Tag = offsetBounds;
  169. _buffer.Items.Add(border);
  170. currentX += glyphInfos[i].GlyphAdvance;
  171. }
  172. int FindClusterLenghtAt(int index)
  173. {
  174. int cluster = glyphInfos[index].GlyphCluster;
  175. if (shapedRun.BidiLevel % 2 == 0)
  176. {
  177. while (++index < glyphInfos.Count)
  178. if (glyphInfos[index].GlyphCluster != cluster)
  179. return glyphInfos[index].GlyphCluster - cluster;
  180. return shapedRun.Length + glyphInfos[0].GlyphCluster - cluster;
  181. }
  182. else
  183. {
  184. while (--index >= 0)
  185. if (glyphInfos[index].GlyphCluster != cluster)
  186. return glyphInfos[index].GlyphCluster - cluster;
  187. return shapedRun.Length + glyphInfos[glyphInfos.Count - 1].GlyphCluster - cluster;
  188. }
  189. }
  190. }
  191. private IImage CreateGlyphDrawing(IGlyphTypeface glyphTypeface, double emSize, GlyphInfo info)
  192. {
  193. return new DrawingImage { Drawing = new GeometryDrawing { Brush = Brushes.Black, Geometry = GetGlyphOutline(glyphTypeface, emSize, info) } };
  194. }
  195. private Geometry GetGlyphOutline(IGlyphTypeface typeface, double emSize, GlyphInfo info)
  196. {
  197. // substitute for GlyphTypeface.GetGlyphOutline
  198. return new GlyphRun(typeface, emSize, new[] { '\0' }, [info]).BuildGeometry();
  199. }
  200. private void OnPointerMoved(object sender, PointerEventArgs e)
  201. {
  202. InteractiveLineControl lineControl = (InteractiveLineControl)sender;
  203. TextLayout textLayout = lineControl.TextLayout;
  204. Rect lineBounds = lineControl.LineRenderBounds;
  205. PointerPoint pointerPoint = e.GetCurrentPoint(lineControl);
  206. Point point = new Point(pointerPoint.Position.X - lineBounds.Left, pointerPoint.Position.Y - lineBounds.Top);
  207. _coordinates.Text = $"{pointerPoint.Position.X:F4}, {pointerPoint.Position.Y:F4}";
  208. TextHitTestResult textHit = textLayout.HitTestPoint(point);
  209. _hit.Text = $"{textHit.TextPosition} ({textHit.CharacterHit.FirstCharacterIndex}+{textHit.CharacterHit.TrailingLength})";
  210. if (textHit.IsTrailing)
  211. _hit.Text += " T";
  212. if (textHit.IsInside)
  213. {
  214. _hits.SelectedIndex = textHit.TextPosition + 1; // header
  215. }
  216. else
  217. _hits.SelectedIndex = -1;
  218. }
  219. private void OnHitTestMethodChanged(object? sender, RoutedEventArgs e)
  220. {
  221. _hits.SelectionMode = _hitRangeToggle.IsChecked == true ? SelectionMode.Multiple : SelectionMode.Single;
  222. }
  223. private void OnHitsSelectionChanged(object? sender, SelectionChangedEventArgs e)
  224. {
  225. if (_selectionAdorner == null)
  226. return;
  227. List<Rect> rectangles = new List<Rect>();
  228. TextLayout textLayout = _rendering.TextLayout;
  229. if (_hitRangeToggle.IsChecked == true)
  230. {
  231. // collect continuous selected indices
  232. List<(int start, int length)> selections = new(1);
  233. int[] indices = _hits.Selection.SelectedIndexes.ToArray();
  234. Array.Sort(indices);
  235. int currentIndex = -1;
  236. int currentLength = 0;
  237. for (int i = 0; i < indices.Length; i++)
  238. if (_hits.Items[indices[i]] is Control { Tag: int index })
  239. {
  240. if (index == currentIndex + currentLength)
  241. {
  242. currentLength++;
  243. }
  244. else
  245. {
  246. if (currentLength > 0)
  247. selections.Add((currentIndex, currentLength));
  248. currentIndex = index;
  249. currentLength = 1;
  250. }
  251. }
  252. if (currentLength > 0)
  253. selections.Add((currentIndex, currentLength));
  254. foreach (var selection in selections)
  255. {
  256. var selectionRectangles = textLayout.HitTestTextRange(selection.start, selection.length);
  257. rectangles.AddRange(selectionRectangles);
  258. }
  259. }
  260. else
  261. {
  262. if (_hits.SelectedItem is Control { Tag: int index })
  263. {
  264. Rect rect = textLayout.HitTestTextPosition(index);
  265. rectangles.Add(rect);
  266. }
  267. }
  268. _selectionAdorner.Rectangles = rectangles;
  269. }
  270. private void OnBufferSelectionChanged(object? sender, SelectionChangedEventArgs e)
  271. {
  272. List<Rect> rectangles = new List<Rect>(_buffer.Selection.Count);
  273. foreach (var row in _buffer.SelectedItems)
  274. if (row is Control { Tag: Rect rect })
  275. rectangles.Add(rect);
  276. _selectionAdorner.Rectangles = rectangles;
  277. }
  278. private static string ToHex(string s)
  279. {
  280. if (string.IsNullOrEmpty(s))
  281. return s;
  282. return string.Join(" ", s.Select(c => ((int)c).ToString("X4")));
  283. }
  284. }
  285. }