TextPresenter.cs 17 KB

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