TextPresenter.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Reactive.Linq;
  5. using Avalonia.Media;
  6. using Avalonia.Threading;
  7. using Avalonia.VisualTree;
  8. namespace Avalonia.Controls.Presenters
  9. {
  10. public class TextPresenter : TextBlock
  11. {
  12. public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty =
  13. TextBox.CaretIndexProperty.AddOwner<TextPresenter>(
  14. o => o.CaretIndex,
  15. (o, v) => o.CaretIndex = v);
  16. public static readonly StyledProperty<char> PasswordCharProperty =
  17. AvaloniaProperty.Register<TextPresenter, char>(nameof(PasswordChar));
  18. public static readonly StyledProperty<IBrush> SelectionBrushProperty =
  19. AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionBrushProperty));
  20. public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty =
  21. AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionForegroundBrushProperty));
  22. public static readonly StyledProperty<IBrush> CaretBrushProperty =
  23. AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(CaretBrushProperty));
  24. public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty =
  25. TextBox.SelectionStartProperty.AddOwner<TextPresenter>(
  26. o => o.SelectionStart,
  27. (o, v) => o.SelectionStart = v);
  28. public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty =
  29. TextBox.SelectionEndProperty.AddOwner<TextPresenter>(
  30. o => o.SelectionEnd,
  31. (o, v) => o.SelectionEnd = v);
  32. private readonly DispatcherTimer _caretTimer;
  33. private int _caretIndex;
  34. private int _selectionStart;
  35. private int _selectionEnd;
  36. private bool _caretBlink;
  37. static TextPresenter()
  38. {
  39. AffectsRender<TextPresenter>(PasswordCharProperty,
  40. SelectionBrushProperty, SelectionForegroundBrushProperty,
  41. SelectionStartProperty, SelectionEndProperty);
  42. Observable.Merge(
  43. SelectionStartProperty.Changed,
  44. SelectionEndProperty.Changed,
  45. PasswordCharProperty.Changed
  46. ).AddClassHandler<TextPresenter>((x,_) => x.InvalidateFormattedText());
  47. CaretIndexProperty.Changed.AddClassHandler<TextPresenter>((x, e) => x.CaretIndexChanged((int)e.NewValue));
  48. }
  49. public TextPresenter()
  50. {
  51. _caretTimer = new DispatcherTimer();
  52. _caretTimer.Interval = TimeSpan.FromMilliseconds(500);
  53. _caretTimer.Tick += CaretTimerTick;
  54. }
  55. public int CaretIndex
  56. {
  57. get
  58. {
  59. return _caretIndex;
  60. }
  61. set
  62. {
  63. value = CoerceCaretIndex(value);
  64. SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
  65. }
  66. }
  67. public char PasswordChar
  68. {
  69. get => GetValue(PasswordCharProperty);
  70. set => SetValue(PasswordCharProperty, value);
  71. }
  72. public IBrush SelectionBrush
  73. {
  74. get => GetValue(SelectionBrushProperty);
  75. set => SetValue(SelectionBrushProperty, value);
  76. }
  77. public IBrush SelectionForegroundBrush
  78. {
  79. get => GetValue(SelectionForegroundBrushProperty);
  80. set => SetValue(SelectionForegroundBrushProperty, value);
  81. }
  82. public IBrush CaretBrush
  83. {
  84. get => GetValue(CaretBrushProperty);
  85. set => SetValue(CaretBrushProperty, value);
  86. }
  87. public int SelectionStart
  88. {
  89. get
  90. {
  91. return _selectionStart;
  92. }
  93. set
  94. {
  95. value = CoerceCaretIndex(value);
  96. SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
  97. }
  98. }
  99. public int SelectionEnd
  100. {
  101. get
  102. {
  103. return _selectionEnd;
  104. }
  105. set
  106. {
  107. value = CoerceCaretIndex(value);
  108. SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
  109. }
  110. }
  111. public int GetCaretIndex(Point point)
  112. {
  113. var hit = FormattedText.HitTestPoint(point);
  114. return hit.TextPosition + (hit.IsTrailing ? 1 : 0);
  115. }
  116. public override void Render(DrawingContext context)
  117. {
  118. var selectionStart = SelectionStart;
  119. var selectionEnd = SelectionEnd;
  120. if (selectionStart != selectionEnd)
  121. {
  122. var start = Math.Min(selectionStart, selectionEnd);
  123. var length = Math.Max(selectionStart, selectionEnd) - start;
  124. // issue #600: set constraint before any FormattedText manipulation
  125. // see base.Render(...) implementation
  126. FormattedText.Constraint = Bounds.Size;
  127. var rects = FormattedText.HitTestTextRange(start, length);
  128. foreach (var rect in rects)
  129. {
  130. context.FillRectangle(SelectionBrush, rect);
  131. }
  132. }
  133. base.Render(context);
  134. if (selectionStart == selectionEnd)
  135. {
  136. var caretBrush = CaretBrush;
  137. if (caretBrush is null)
  138. {
  139. var backgroundColor = (((Control)TemplatedParent).GetValue(BackgroundProperty) as SolidColorBrush)?.Color;
  140. if (backgroundColor.HasValue)
  141. {
  142. byte red = (byte)~(backgroundColor.Value.R);
  143. byte green = (byte)~(backgroundColor.Value.G);
  144. byte blue = (byte)~(backgroundColor.Value.B);
  145. caretBrush = new SolidColorBrush(Color.FromRgb(red, green, blue));
  146. }
  147. else
  148. caretBrush = Brushes.Black;
  149. }
  150. if (_caretBlink)
  151. {
  152. var charPos = FormattedText.HitTestTextPosition(CaretIndex);
  153. var x = Math.Floor(charPos.X) + 0.5;
  154. var y = Math.Floor(charPos.Y) + 0.5;
  155. var b = Math.Ceiling(charPos.Bottom) - 0.5;
  156. context.DrawLine(
  157. new Pen(caretBrush, 1),
  158. new Point(x, y),
  159. new Point(x, b));
  160. }
  161. }
  162. }
  163. public void ShowCaret()
  164. {
  165. _caretBlink = true;
  166. _caretTimer.Start();
  167. InvalidateVisual();
  168. }
  169. public void HideCaret()
  170. {
  171. _caretBlink = false;
  172. _caretTimer.Stop();
  173. InvalidateVisual();
  174. }
  175. internal void CaretIndexChanged(int caretIndex)
  176. {
  177. if (this.GetVisualParent() != null)
  178. {
  179. if (_caretTimer.IsEnabled)
  180. {
  181. _caretBlink = true;
  182. _caretTimer.Stop();
  183. _caretTimer.Start();
  184. InvalidateVisual();
  185. }
  186. else
  187. {
  188. _caretTimer.Start();
  189. InvalidateVisual();
  190. _caretTimer.Stop();
  191. }
  192. if (IsMeasureValid)
  193. {
  194. var rect = FormattedText.HitTestTextPosition(caretIndex);
  195. this.BringIntoView(rect);
  196. }
  197. else
  198. {
  199. // The measure is currently invalid so there's no point trying to bring the
  200. // current char into view until a measure has been carried out as the scroll
  201. // viewer extents may not be up-to-date.
  202. Dispatcher.UIThread.Post(
  203. () =>
  204. {
  205. var rect = FormattedText.HitTestTextPosition(caretIndex);
  206. this.BringIntoView(rect);
  207. },
  208. DispatcherPriority.Render);
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// Creates the <see cref="FormattedText"/> used to render the text.
  214. /// </summary>
  215. /// <param name="constraint">The constraint of the text.</param>
  216. /// <param name="text">The text to generated the <see cref="FormattedText"/> for.</param>
  217. /// <returns>A <see cref="FormattedText"/> object.</returns>
  218. protected override FormattedText CreateFormattedText(Size constraint, string text)
  219. {
  220. FormattedText result = null;
  221. if (PasswordChar != default(char))
  222. {
  223. result = base.CreateFormattedText(constraint, new string(PasswordChar, text?.Length ?? 0));
  224. }
  225. else
  226. {
  227. result = base.CreateFormattedText(constraint, text);
  228. }
  229. var selectionStart = SelectionStart;
  230. var selectionEnd = SelectionEnd;
  231. var start = Math.Min(selectionStart, selectionEnd);
  232. var length = Math.Max(selectionStart, selectionEnd) - start;
  233. if (length > 0)
  234. {
  235. result.Spans = new[]
  236. {
  237. new FormattedTextStyleSpan(start, length, SelectionForegroundBrush),
  238. };
  239. }
  240. return result;
  241. }
  242. protected override Size MeasureOverride(Size availableSize)
  243. {
  244. var text = Text;
  245. if (!string.IsNullOrEmpty(text))
  246. {
  247. return base.MeasureOverride(availableSize);
  248. }
  249. else
  250. {
  251. return new FormattedText
  252. {
  253. Text = "X",
  254. Typeface = new Typeface(FontFamily, FontSize, FontStyle, FontWeight),
  255. TextAlignment = TextAlignment,
  256. Constraint = availableSize,
  257. }.Bounds.Size;
  258. }
  259. }
  260. private int CoerceCaretIndex(int value)
  261. {
  262. var text = Text;
  263. var length = text?.Length ?? 0;
  264. return Math.Max(0, Math.Min(length, value));
  265. }
  266. private void CaretTimerTick(object sender, EventArgs e)
  267. {
  268. _caretBlink = !_caretBlink;
  269. InvalidateVisual();
  270. }
  271. }
  272. }