TextPresenter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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.Metadata;
  7. using Avalonia.Threading;
  8. using Avalonia.VisualTree;
  9. namespace Avalonia.Controls.Presenters
  10. {
  11. public class TextPresenter : Control
  12. {
  13. public static readonly DirectProperty<TextPresenter, int> CaretIndexProperty =
  14. TextBox.CaretIndexProperty.AddOwner<TextPresenter>(
  15. o => o.CaretIndex,
  16. (o, v) => o.CaretIndex = v);
  17. public static readonly StyledProperty<char> PasswordCharProperty =
  18. AvaloniaProperty.Register<TextPresenter, char>(nameof(PasswordChar));
  19. public static readonly StyledProperty<IBrush> SelectionBrushProperty =
  20. AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionBrushProperty));
  21. public static readonly StyledProperty<IBrush> SelectionForegroundBrushProperty =
  22. AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(SelectionForegroundBrushProperty));
  23. public static readonly StyledProperty<IBrush> CaretBrushProperty =
  24. AvaloniaProperty.Register<TextPresenter, IBrush>(nameof(CaretBrushProperty));
  25. public static readonly DirectProperty<TextPresenter, int> SelectionStartProperty =
  26. TextBox.SelectionStartProperty.AddOwner<TextPresenter>(
  27. o => o.SelectionStart,
  28. (o, v) => o.SelectionStart = v);
  29. public static readonly DirectProperty<TextPresenter, int> SelectionEndProperty =
  30. TextBox.SelectionEndProperty.AddOwner<TextPresenter>(
  31. o => o.SelectionEnd,
  32. (o, v) => o.SelectionEnd = v);
  33. /// <summary>
  34. /// Defines the <see cref="Text"/> property.
  35. /// </summary>
  36. public static readonly DirectProperty<TextPresenter, string> TextProperty =
  37. AvaloniaProperty.RegisterDirect<TextPresenter, string>(
  38. nameof(Text),
  39. o => o.Text,
  40. (o, v) => o.Text = v);
  41. /// <summary>
  42. /// Defines the <see cref="TextAlignment"/> property.
  43. /// </summary>
  44. public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
  45. TextBlock.TextAlignmentProperty.AddOwner<TextPresenter>();
  46. /// <summary>
  47. /// Defines the <see cref="TextWrapping"/> property.
  48. /// </summary>
  49. public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
  50. TextBlock.TextWrappingProperty.AddOwner<TextPresenter>();
  51. /// <summary>
  52. /// Defines the <see cref="Background"/> property.
  53. /// </summary>
  54. public static readonly StyledProperty<IBrush> BackgroundProperty =
  55. Border.BackgroundProperty.AddOwner<TextPresenter>();
  56. private readonly DispatcherTimer _caretTimer;
  57. private int _caretIndex;
  58. private int _selectionStart;
  59. private int _selectionEnd;
  60. private bool _caretBlink;
  61. private string _text;
  62. private FormattedText _formattedText;
  63. private Size _constraint;
  64. static TextPresenter()
  65. {
  66. AffectsRender<TextPresenter>(PasswordCharProperty,
  67. SelectionBrushProperty, SelectionForegroundBrushProperty,
  68. SelectionStartProperty, SelectionEndProperty);
  69. Observable.Merge(
  70. TextProperty.Changed,
  71. SelectionStartProperty.Changed,
  72. SelectionEndProperty.Changed,
  73. PasswordCharProperty.Changed
  74. ).AddClassHandler<TextPresenter>((x,_) => x.InvalidateFormattedText());
  75. CaretIndexProperty.Changed.AddClassHandler<TextPresenter>((x, e) => x.CaretIndexChanged((int)e.NewValue));
  76. }
  77. public TextPresenter()
  78. {
  79. _text = string.Empty;
  80. _caretTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
  81. _caretTimer.Tick += CaretTimerTick;
  82. }
  83. /// <summary>
  84. /// Gets or sets a brush used to paint the control's background.
  85. /// </summary>
  86. public IBrush Background
  87. {
  88. get => GetValue(BackgroundProperty);
  89. set => SetValue(BackgroundProperty, value);
  90. }
  91. /// <summary>
  92. /// Gets or sets the text.
  93. /// </summary>
  94. [Content]
  95. public string Text
  96. {
  97. get => _text;
  98. set => SetAndRaise(TextProperty, ref _text, value);
  99. }
  100. /// <summary>
  101. /// Gets or sets the font family.
  102. /// </summary>
  103. public FontFamily FontFamily
  104. {
  105. get => TextBlock.GetFontFamily(this);
  106. set => TextBlock.SetFontFamily(this, value);
  107. }
  108. /// <summary>
  109. /// Gets or sets the font size.
  110. /// </summary>
  111. public double FontSize
  112. {
  113. get => TextBlock.GetFontSize(this);
  114. set => TextBlock.SetFontSize(this, value);
  115. }
  116. /// <summary>
  117. /// Gets or sets the font style.
  118. /// </summary>
  119. public FontStyle FontStyle
  120. {
  121. get => TextBlock.GetFontStyle(this);
  122. set => TextBlock.SetFontStyle(this, value);
  123. }
  124. /// <summary>
  125. /// Gets or sets the font weight.
  126. /// </summary>
  127. public FontWeight FontWeight
  128. {
  129. get => TextBlock.GetFontWeight(this);
  130. set => TextBlock.SetFontWeight(this, value);
  131. }
  132. /// <summary>
  133. /// Gets or sets a brush used to paint the text.
  134. /// </summary>
  135. public IBrush Foreground
  136. {
  137. get => TextBlock.GetForeground(this);
  138. set => TextBlock.SetForeground(this, value);
  139. }
  140. /// <summary>
  141. /// Gets or sets the control's text wrapping mode.
  142. /// </summary>
  143. public TextWrapping TextWrapping
  144. {
  145. get => GetValue(TextWrappingProperty);
  146. set => SetValue(TextWrappingProperty, value);
  147. }
  148. /// <summary>
  149. /// Gets or sets the text alignment.
  150. /// </summary>
  151. public TextAlignment TextAlignment
  152. {
  153. get => GetValue(TextAlignmentProperty);
  154. set => SetValue(TextAlignmentProperty, value);
  155. }
  156. /// <summary>
  157. /// Gets the <see cref="FormattedText"/> used to render the text.
  158. /// </summary>
  159. public FormattedText FormattedText
  160. {
  161. get
  162. {
  163. return _formattedText ?? (_formattedText = CreateFormattedText(Bounds.Size, Text));
  164. }
  165. }
  166. public int CaretIndex
  167. {
  168. get
  169. {
  170. return _caretIndex;
  171. }
  172. set
  173. {
  174. value = CoerceCaretIndex(value);
  175. SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
  176. }
  177. }
  178. public char PasswordChar
  179. {
  180. get => GetValue(PasswordCharProperty);
  181. set => SetValue(PasswordCharProperty, value);
  182. }
  183. public IBrush SelectionBrush
  184. {
  185. get => GetValue(SelectionBrushProperty);
  186. set => SetValue(SelectionBrushProperty, value);
  187. }
  188. public IBrush SelectionForegroundBrush
  189. {
  190. get => GetValue(SelectionForegroundBrushProperty);
  191. set => SetValue(SelectionForegroundBrushProperty, value);
  192. }
  193. public IBrush CaretBrush
  194. {
  195. get => GetValue(CaretBrushProperty);
  196. set => SetValue(CaretBrushProperty, value);
  197. }
  198. public int SelectionStart
  199. {
  200. get
  201. {
  202. return _selectionStart;
  203. }
  204. set
  205. {
  206. value = CoerceCaretIndex(value);
  207. SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
  208. }
  209. }
  210. public int SelectionEnd
  211. {
  212. get
  213. {
  214. return _selectionEnd;
  215. }
  216. set
  217. {
  218. value = CoerceCaretIndex(value);
  219. SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
  220. }
  221. }
  222. public int GetCaretIndex(Point point)
  223. {
  224. var hit = FormattedText.HitTestPoint(point);
  225. return hit.TextPosition + (hit.IsTrailing ? 1 : 0);
  226. }
  227. /// <summary>
  228. /// Creates the <see cref="FormattedText"/> used to render the text.
  229. /// </summary>
  230. /// <param name="constraint">The constraint of the text.</param>
  231. /// <param name="text">The text to format.</param>
  232. /// <returns>A <see cref="FormattedText"/> object.</returns>
  233. private FormattedText CreateFormattedTextInternal(Size constraint, string text)
  234. {
  235. return new FormattedText
  236. {
  237. Constraint = constraint,
  238. Typeface = FontManager.Current?.GetOrAddTypeface(FontFamily, FontWeight, FontStyle),
  239. FontSize = FontSize,
  240. Text = text ?? string.Empty,
  241. TextAlignment = TextAlignment,
  242. TextWrapping = TextWrapping,
  243. };
  244. }
  245. /// <summary>
  246. /// Invalidates <see cref="FormattedText"/>.
  247. /// </summary>
  248. protected void InvalidateFormattedText()
  249. {
  250. if (_formattedText != null)
  251. {
  252. _constraint = _formattedText.Constraint;
  253. _formattedText = null;
  254. }
  255. InvalidateVisual();
  256. }
  257. /// <summary>
  258. /// Renders the <see cref="TextPresenter"/> to a drawing context.
  259. /// </summary>
  260. /// <param name="context">The drawing context.</param>
  261. private void RenderInternal(DrawingContext context)
  262. {
  263. var background = Background;
  264. if (background != null)
  265. {
  266. context.FillRectangle(background, new Rect(Bounds.Size));
  267. }
  268. FormattedText.Constraint = Bounds.Size;
  269. context.DrawText(Foreground, new Point(), FormattedText);
  270. }
  271. public override void Render(DrawingContext context)
  272. {
  273. var selectionStart = SelectionStart;
  274. var selectionEnd = SelectionEnd;
  275. if (selectionStart != selectionEnd)
  276. {
  277. var start = Math.Min(selectionStart, selectionEnd);
  278. var length = Math.Max(selectionStart, selectionEnd) - start;
  279. // issue #600: set constraint before any FormattedText manipulation
  280. // see base.Render(...) implementation
  281. FormattedText.Constraint = _constraint;
  282. var rects = FormattedText.HitTestTextRange(start, length);
  283. foreach (var rect in rects)
  284. {
  285. context.FillRectangle(SelectionBrush, rect);
  286. }
  287. }
  288. RenderInternal(context);
  289. if (selectionStart == selectionEnd)
  290. {
  291. var caretBrush = CaretBrush;
  292. if (caretBrush is null)
  293. {
  294. var backgroundColor = (Background as SolidColorBrush)?.Color;
  295. if (backgroundColor.HasValue)
  296. {
  297. byte red = (byte)~(backgroundColor.Value.R);
  298. byte green = (byte)~(backgroundColor.Value.G);
  299. byte blue = (byte)~(backgroundColor.Value.B);
  300. caretBrush = new SolidColorBrush(Color.FromRgb(red, green, blue));
  301. }
  302. else
  303. caretBrush = Brushes.Black;
  304. }
  305. if (_caretBlink)
  306. {
  307. var charPos = FormattedText.HitTestTextPosition(CaretIndex);
  308. var x = Math.Floor(charPos.X) + 0.5;
  309. var y = Math.Floor(charPos.Y) + 0.5;
  310. var b = Math.Ceiling(charPos.Bottom) - 0.5;
  311. context.DrawLine(
  312. new Pen(caretBrush, 1),
  313. new Point(x, y),
  314. new Point(x, b));
  315. }
  316. }
  317. }
  318. public void ShowCaret()
  319. {
  320. _caretBlink = true;
  321. _caretTimer.Start();
  322. InvalidateVisual();
  323. }
  324. public void HideCaret()
  325. {
  326. _caretBlink = false;
  327. _caretTimer.Stop();
  328. InvalidateVisual();
  329. }
  330. internal void CaretIndexChanged(int caretIndex)
  331. {
  332. if (this.GetVisualParent() != null)
  333. {
  334. if (_caretTimer.IsEnabled)
  335. {
  336. _caretBlink = true;
  337. _caretTimer.Stop();
  338. _caretTimer.Start();
  339. InvalidateVisual();
  340. }
  341. else
  342. {
  343. _caretTimer.Start();
  344. InvalidateVisual();
  345. _caretTimer.Stop();
  346. }
  347. if (IsMeasureValid)
  348. {
  349. var rect = FormattedText.HitTestTextPosition(caretIndex);
  350. this.BringIntoView(rect);
  351. }
  352. else
  353. {
  354. // The measure is currently invalid so there's no point trying to bring the
  355. // current char into view until a measure has been carried out as the scroll
  356. // viewer extents may not be up-to-date.
  357. Dispatcher.UIThread.Post(
  358. () =>
  359. {
  360. var rect = FormattedText.HitTestTextPosition(caretIndex);
  361. this.BringIntoView(rect);
  362. },
  363. DispatcherPriority.Render);
  364. }
  365. }
  366. }
  367. /// <summary>
  368. /// Creates the <see cref="FormattedText"/> used to render the text.
  369. /// </summary>
  370. /// <param name="constraint">The constraint of the text.</param>
  371. /// <param name="text">The text to generated the <see cref="FormattedText"/> for.</param>
  372. /// <returns>A <see cref="FormattedText"/> object.</returns>
  373. protected virtual FormattedText CreateFormattedText(Size constraint, string text)
  374. {
  375. FormattedText result = null;
  376. if (PasswordChar != default(char))
  377. {
  378. result = CreateFormattedTextInternal(constraint, new string(PasswordChar, text?.Length ?? 0));
  379. }
  380. else
  381. {
  382. result = CreateFormattedTextInternal(constraint, text);
  383. }
  384. var selectionStart = SelectionStart;
  385. var selectionEnd = SelectionEnd;
  386. var start = Math.Min(selectionStart, selectionEnd);
  387. var length = Math.Max(selectionStart, selectionEnd) - start;
  388. if (length > 0)
  389. {
  390. result.Spans = new[]
  391. {
  392. new FormattedTextStyleSpan(start, length, SelectionForegroundBrush),
  393. };
  394. }
  395. return result;
  396. }
  397. /// <summary>
  398. /// Measures the control.
  399. /// </summary>
  400. /// <param name="availableSize">The available size for the control.</param>
  401. /// <returns>The desired size.</returns>
  402. private Size MeasureInternal(Size availableSize)
  403. {
  404. if (!string.IsNullOrEmpty(Text))
  405. {
  406. if (TextWrapping == TextWrapping.Wrap)
  407. {
  408. FormattedText.Constraint = new Size(availableSize.Width, double.PositiveInfinity);
  409. }
  410. else
  411. {
  412. FormattedText.Constraint = Size.Infinity;
  413. }
  414. return FormattedText.Bounds.Size;
  415. }
  416. return new Size();
  417. }
  418. protected override Size MeasureOverride(Size availableSize)
  419. {
  420. var text = Text;
  421. if (!string.IsNullOrEmpty(text))
  422. {
  423. return MeasureInternal(availableSize);
  424. }
  425. else
  426. {
  427. return new FormattedText
  428. {
  429. Text = "X",
  430. Typeface = FontManager.Current?.GetOrAddTypeface(FontFamily, FontWeight, FontStyle),
  431. FontSize = FontSize,
  432. TextAlignment = TextAlignment,
  433. Constraint = availableSize,
  434. }.Bounds.Size;
  435. }
  436. }
  437. private int CoerceCaretIndex(int value)
  438. {
  439. var text = Text;
  440. var length = text?.Length ?? 0;
  441. return Math.Max(0, Math.Min(length, value));
  442. }
  443. private void CaretTimerTick(object sender, EventArgs e)
  444. {
  445. _caretBlink = !_caretBlink;
  446. InvalidateVisual();
  447. }
  448. }
  449. }