TextLayout.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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.Collections.Generic;
  5. using System.Linq;
  6. using Avalonia.Media.Immutable;
  7. using Avalonia.Media.TextFormatting.Unicode;
  8. using Avalonia.Platform;
  9. using Avalonia.Utility;
  10. namespace Avalonia.Media.TextFormatting
  11. {
  12. /// <summary>
  13. /// Represents a multi line text layout.
  14. /// </summary>
  15. public class TextLayout
  16. {
  17. private static readonly ReadOnlySlice<char> s_empty = new ReadOnlySlice<char>(new[] { '\u200B' });
  18. private readonly ReadOnlySlice<char> _text;
  19. private readonly TextParagraphProperties _paragraphProperties;
  20. private readonly IReadOnlyList<TextStyleRun> _textStyleOverrides;
  21. /// <summary>
  22. /// Initializes a new instance of the <see cref="TextLayout" /> class.
  23. /// </summary>
  24. /// <param name="text">The text.</param>
  25. /// <param name="typeface">The typeface.</param>
  26. /// <param name="fontSize">Size of the font.</param>
  27. /// <param name="foreground">The foreground.</param>
  28. /// <param name="textAlignment">The text alignment.</param>
  29. /// <param name="textWrapping">The text wrapping.</param>
  30. /// <param name="textTrimming">The text trimming.</param>
  31. /// <param name="textDecorations">The text decorations.</param>
  32. /// <param name="maxWidth">The maximum width.</param>
  33. /// <param name="maxHeight">The maximum height.</param>
  34. /// <param name="textStyleOverrides">The text style overrides.</param>
  35. public TextLayout(
  36. string text,
  37. Typeface typeface,
  38. double fontSize,
  39. IBrush foreground,
  40. TextAlignment textAlignment = TextAlignment.Left,
  41. TextWrapping textWrapping = TextWrapping.NoWrap,
  42. TextTrimming textTrimming = TextTrimming.None,
  43. TextDecorationCollection textDecorations = null,
  44. double maxWidth = double.PositiveInfinity,
  45. double maxHeight = double.PositiveInfinity,
  46. IReadOnlyList<TextStyleRun> textStyleOverrides = null)
  47. {
  48. _text = string.IsNullOrEmpty(text) ?
  49. new ReadOnlySlice<char>() :
  50. new ReadOnlySlice<char>(text.AsMemory());
  51. _paragraphProperties =
  52. CreateTextParagraphProperties(typeface, fontSize, foreground, textAlignment, textWrapping, textTrimming, textDecorations?.ToImmutable());
  53. _textStyleOverrides = textStyleOverrides;
  54. MaxWidth = maxWidth;
  55. MaxHeight = maxHeight;
  56. UpdateLayout();
  57. }
  58. /// <summary>
  59. /// Gets the maximum width.
  60. /// </summary>
  61. public double MaxWidth { get; }
  62. /// <summary>
  63. /// Gets the maximum height.
  64. /// </summary>
  65. public double MaxHeight { get; }
  66. /// <summary>
  67. /// Gets the text lines.
  68. /// </summary>
  69. /// <value>
  70. /// The text lines.
  71. /// </value>
  72. public IReadOnlyList<TextLine> TextLines { get; private set; }
  73. /// <summary>
  74. /// Gets the bounds of the layout.
  75. /// </summary>
  76. /// <value>
  77. /// The bounds.
  78. /// </value>
  79. public Rect Bounds { get; private set; }
  80. /// <summary>
  81. /// Draws the text layout.
  82. /// </summary>
  83. /// <param name="context">The drawing context.</param>
  84. /// <param name="origin">The origin.</param>
  85. public void Draw(IDrawingContextImpl context, Point origin)
  86. {
  87. if (!TextLines.Any())
  88. {
  89. return;
  90. }
  91. var currentY = origin.Y;
  92. foreach (var textLine in TextLines)
  93. {
  94. textLine.Draw(context, new Point(origin.X, currentY));
  95. currentY += textLine.LineMetrics.Size.Height;
  96. }
  97. }
  98. /// <summary>
  99. /// Creates the default <see cref="TextParagraphProperties"/> that are used by the <see cref="TextFormatter"/>.
  100. /// </summary>
  101. /// <param name="typeface">The typeface.</param>
  102. /// <param name="fontSize">The font size.</param>
  103. /// <param name="foreground">The foreground.</param>
  104. /// <param name="textAlignment">The text alignment.</param>
  105. /// <param name="textWrapping">The text wrapping.</param>
  106. /// <param name="textTrimming">The text trimming.</param>
  107. /// <param name="textDecorations">The text decorations.</param>
  108. /// <returns></returns>
  109. private static TextParagraphProperties CreateTextParagraphProperties(Typeface typeface, double fontSize,
  110. IBrush foreground, TextAlignment textAlignment, TextWrapping textWrapping, TextTrimming textTrimming,
  111. ImmutableTextDecoration[] textDecorations)
  112. {
  113. var textRunStyle = new TextStyle(typeface, fontSize, foreground, textDecorations);
  114. return new TextParagraphProperties(textRunStyle, textAlignment, textWrapping, textTrimming);
  115. }
  116. /// <summary>
  117. /// Updates the current bounds.
  118. /// </summary>
  119. /// <param name="textLine">The text line.</param>
  120. /// <param name="left">The left.</param>
  121. /// <param name="right">The right.</param>
  122. /// <param name="bottom">The bottom.</param>
  123. private static void UpdateBounds(TextLine textLine, ref double left, ref double right, ref double bottom)
  124. {
  125. if (right < textLine.LineMetrics.BaselineOrigin.X + textLine.LineMetrics.Size.Width)
  126. {
  127. right = textLine.LineMetrics.BaselineOrigin.X + textLine.LineMetrics.Size.Width;
  128. }
  129. if (left < textLine.LineMetrics.BaselineOrigin.X)
  130. {
  131. left = textLine.LineMetrics.BaselineOrigin.X;
  132. }
  133. bottom += textLine.LineMetrics.Size.Height;
  134. }
  135. /// <summary>
  136. /// Creates an empty text line.
  137. /// </summary>
  138. /// <returns>The empty text line.</returns>
  139. private TextLine CreateEmptyTextLine(int startingIndex)
  140. {
  141. var textFormat = _paragraphProperties.DefaultTextStyle.TextFormat;
  142. var glyphRun = TextShaper.Current.ShapeText(s_empty, textFormat);
  143. var textRuns = new[] { new ShapedTextRun(glyphRun, _paragraphProperties.DefaultTextStyle) };
  144. return new SimpleTextLine(new TextPointer(startingIndex, 0), textRuns,
  145. TextLineMetrics.Create(textRuns, MaxWidth, _paragraphProperties.TextAlignment));
  146. }
  147. /// <summary>
  148. /// Updates the layout and applies specified text style overrides.
  149. /// </summary>
  150. private void UpdateLayout()
  151. {
  152. if (_text.IsEmpty || Math.Abs(MaxWidth) < double.Epsilon || Math.Abs(MaxHeight) < double.Epsilon)
  153. {
  154. var textLine = CreateEmptyTextLine(0);
  155. TextLines = new List<TextLine> { textLine };
  156. Bounds = new Rect(textLine.LineMetrics.BaselineOrigin.X, 0, 0, textLine.LineMetrics.Size.Height);
  157. }
  158. else
  159. {
  160. var textLines = new List<TextLine>();
  161. double left = 0.0, right = 0.0, bottom = 0.0;
  162. var lineBreaker = new LineBreakEnumerator(_text);
  163. var currentPosition = 0;
  164. while (currentPosition < _text.Length)
  165. {
  166. int length;
  167. if (lineBreaker.MoveNext())
  168. {
  169. if (!lineBreaker.Current.Required)
  170. {
  171. continue;
  172. }
  173. length = lineBreaker.Current.PositionWrap - currentPosition;
  174. if (currentPosition + length < _text.Length)
  175. {
  176. //The line breaker isn't treating \n\r as a pair so we have to fix that here.
  177. if (_text[lineBreaker.Current.PositionMeasure] == '\n'
  178. && _text[lineBreaker.Current.PositionWrap] == '\r')
  179. {
  180. length++;
  181. }
  182. }
  183. }
  184. else
  185. {
  186. length = _text.Length - currentPosition;
  187. }
  188. var remainingLength = length;
  189. while (remainingLength > 0)
  190. {
  191. var textSlice = _text.AsSlice(currentPosition, remainingLength);
  192. var textSource = new FormattedTextSource(textSlice, _paragraphProperties.DefaultTextStyle, _textStyleOverrides);
  193. var textLine = TextFormatter.Current.FormatLine(textSource, 0, MaxWidth, _paragraphProperties);
  194. UpdateBounds(textLine, ref left, ref right, ref bottom);
  195. textLines.Add(textLine);
  196. if (_paragraphProperties.TextTrimming != TextTrimming.None)
  197. {
  198. currentPosition += remainingLength;
  199. break;
  200. }
  201. remainingLength -= textLine.Text.Length;
  202. currentPosition += textLine.Text.Length;
  203. }
  204. if (lineBreaker.Current.Required && currentPosition == _text.Length)
  205. {
  206. var emptyTextLine = CreateEmptyTextLine(currentPosition);
  207. UpdateBounds(emptyTextLine, ref left, ref right, ref bottom);
  208. textLines.Add(emptyTextLine);
  209. break;
  210. }
  211. if (!double.IsPositiveInfinity(MaxHeight) && MaxHeight < Bounds.Height)
  212. {
  213. break;
  214. }
  215. }
  216. Bounds = new Rect(left, 0, right, bottom);
  217. TextLines = textLines;
  218. }
  219. }
  220. private struct FormattedTextSource : ITextSource
  221. {
  222. private readonly ReadOnlySlice<char> _text;
  223. private readonly TextStyle _defaultStyle;
  224. private readonly IReadOnlyList<TextStyleRun> _textStyleOverrides;
  225. public FormattedTextSource(ReadOnlySlice<char> text, TextStyle defaultStyle,
  226. IReadOnlyList<TextStyleRun> textStyleOverrides)
  227. {
  228. _text = text;
  229. _defaultStyle = defaultStyle;
  230. _textStyleOverrides = textStyleOverrides;
  231. }
  232. public TextRun GetTextRun(int textSourceIndex)
  233. {
  234. var runText = _text.Skip(textSourceIndex);
  235. if (runText.IsEmpty)
  236. {
  237. return new TextEndOfLine();
  238. }
  239. var textStyleRun = CreateTextStyleRunWithOverride(runText, _defaultStyle, _textStyleOverrides);
  240. return new TextCharacters(runText.Take(textStyleRun.TextPointer.Length), textStyleRun.Style);
  241. }
  242. /// <summary>
  243. /// Creates a text style run that has overrides applied. Only overrides with equal TextStyle.
  244. /// If optimizeForShaping is <c>true</c> Foreground is ignored.
  245. /// </summary>
  246. /// <param name="text">The text to create the run for.</param>
  247. /// <param name="defaultTextStyle">The default text style for segments that don't have an override.</param>
  248. /// <param name="textStyleOverrides">The text style overrides.</param>
  249. /// <returns>
  250. /// The created text style run.
  251. /// </returns>
  252. private static TextStyleRun CreateTextStyleRunWithOverride(ReadOnlySlice<char> text,
  253. TextStyle defaultTextStyle, IReadOnlyList<TextStyleRun> textStyleOverrides)
  254. {
  255. if(textStyleOverrides == null || textStyleOverrides.Count == 0)
  256. {
  257. return new TextStyleRun(new TextPointer(text.Start, text.Length), defaultTextStyle);
  258. }
  259. var currentTextStyle = defaultTextStyle;
  260. var hasOverride = false;
  261. var i = 0;
  262. var length = 0;
  263. for (; i < textStyleOverrides.Count; i++)
  264. {
  265. var styleOverride = textStyleOverrides[i];
  266. var textPointer = styleOverride.TextPointer;
  267. if (textPointer.End < text.Start)
  268. {
  269. continue;
  270. }
  271. if (textPointer.Start > text.End)
  272. {
  273. length = text.Length;
  274. break;
  275. }
  276. if (textPointer.Start > text.Start)
  277. {
  278. if (styleOverride.Style.TextFormat != currentTextStyle.TextFormat ||
  279. !currentTextStyle.Foreground.Equals(styleOverride.Style.Foreground))
  280. {
  281. length = Math.Min(Math.Abs(textPointer.Start - text.Start), text.Length);
  282. break;
  283. }
  284. }
  285. length += Math.Min(text.Length - length, textPointer.Length);
  286. if (hasOverride)
  287. {
  288. continue;
  289. }
  290. hasOverride = true;
  291. currentTextStyle = styleOverride.Style;
  292. }
  293. if (length < text.Length && i == textStyleOverrides.Count)
  294. {
  295. if (currentTextStyle.Foreground.Equals(defaultTextStyle.Foreground) &&
  296. currentTextStyle.TextFormat == defaultTextStyle.TextFormat)
  297. {
  298. length = text.Length;
  299. }
  300. }
  301. if (length != text.Length)
  302. {
  303. text = text.Take(length);
  304. }
  305. return new TextStyleRun(new TextPointer(text.Start, length), currentTextStyle);
  306. }
  307. }
  308. }
  309. }