TextFormatterImpl.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. using System;
  2. using System.Collections.Generic;
  3. using Avalonia.Media.TextFormatting.Unicode;
  4. namespace Avalonia.Media.TextFormatting
  5. {
  6. internal class TextFormatterImpl : TextFormatter
  7. {
  8. /// <inheritdoc cref="TextFormatter.FormatLine"/>
  9. public override TextLine FormatLine(ITextSource textSource, int firstTextSourceIndex, double paragraphWidth,
  10. TextParagraphProperties paragraphProperties, TextLineBreak previousLineBreak = null)
  11. {
  12. var textWrapping = paragraphProperties.TextWrapping;
  13. var textRuns = FetchTextRuns(textSource, firstTextSourceIndex, previousLineBreak, out var nextLineBreak);
  14. var textRange = GetTextRange(textRuns);
  15. TextLine textLine;
  16. switch (textWrapping)
  17. {
  18. case TextWrapping.NoWrap:
  19. {
  20. var textLineMetrics =
  21. TextLineMetrics.Create(textRuns, textRange, paragraphWidth, paragraphProperties);
  22. textLine = new TextLineImpl(textRuns, textLineMetrics, nextLineBreak);
  23. break;
  24. }
  25. case TextWrapping.WrapWithOverflow:
  26. case TextWrapping.Wrap:
  27. {
  28. textLine = PerformTextWrapping(textRuns, textRange, paragraphWidth, paragraphProperties,
  29. nextLineBreak);
  30. break;
  31. }
  32. default:
  33. throw new ArgumentOutOfRangeException();
  34. }
  35. return textLine;
  36. }
  37. /// <summary>
  38. /// Measures the number of characters that fits into available width.
  39. /// </summary>
  40. /// <param name="textCharacters">The text run.</param>
  41. /// <param name="availableWidth">The available width.</param>
  42. /// <returns></returns>
  43. internal static int MeasureCharacters(ShapedTextCharacters textCharacters, double availableWidth)
  44. {
  45. var glyphRun = textCharacters.GlyphRun;
  46. if (glyphRun.Bounds.Width < availableWidth)
  47. {
  48. return glyphRun.Characters.Length;
  49. }
  50. var glyphCount = 0;
  51. var currentWidth = 0.0;
  52. if (glyphRun.GlyphAdvances.IsEmpty)
  53. {
  54. var glyphTypeface = glyphRun.GlyphTypeface;
  55. for (var i = 0; i < glyphRun.GlyphClusters.Length; i++)
  56. {
  57. var glyph = glyphRun.GlyphIndices[i];
  58. var advance = glyphTypeface.GetGlyphAdvance(glyph) * glyphRun.Scale;
  59. if (currentWidth + advance > availableWidth)
  60. {
  61. break;
  62. }
  63. currentWidth += advance;
  64. glyphCount++;
  65. }
  66. }
  67. else
  68. {
  69. foreach (var advance in glyphRun.GlyphAdvances)
  70. {
  71. if (currentWidth + advance > availableWidth)
  72. {
  73. break;
  74. }
  75. currentWidth += advance;
  76. glyphCount++;
  77. }
  78. }
  79. if (glyphCount == glyphRun.GlyphIndices.Length)
  80. {
  81. return glyphRun.Characters.Length;
  82. }
  83. if (glyphRun.GlyphClusters.IsEmpty)
  84. {
  85. return glyphCount;
  86. }
  87. var firstCluster = glyphRun.GlyphClusters[0];
  88. var lastCluster = glyphRun.GlyphClusters[glyphCount];
  89. return lastCluster - firstCluster;
  90. }
  91. /// <summary>
  92. /// Split a sequence of runs into two segments at specified length.
  93. /// </summary>
  94. /// <param name="textRuns">The text run's.</param>
  95. /// <param name="length">The length to split at.</param>
  96. /// <returns>The split text runs.</returns>
  97. internal static SplitTextRunsResult SplitTextRuns(List<ShapedTextCharacters> textRuns, int length)
  98. {
  99. var currentLength = 0;
  100. for (var i = 0; i < textRuns.Count; i++)
  101. {
  102. var currentRun = textRuns[i];
  103. if (currentLength + currentRun.GlyphRun.Characters.Length < length)
  104. {
  105. currentLength += currentRun.GlyphRun.Characters.Length;
  106. continue;
  107. }
  108. var firstCount = currentRun.GlyphRun.Characters.Length >= 1 ? i + 1 : i;
  109. var first = new List<ShapedTextCharacters>(firstCount);
  110. if (firstCount > 1)
  111. {
  112. for (var j = 0; j < i; j++)
  113. {
  114. first.Add(textRuns[j]);
  115. }
  116. }
  117. var secondCount = textRuns.Count - firstCount;
  118. if (currentLength + currentRun.GlyphRun.Characters.Length == length)
  119. {
  120. var second = new List<ShapedTextCharacters>(secondCount);
  121. var offset = currentRun.GlyphRun.Characters.Length > 1 ? 1 : 0;
  122. if (secondCount > 0)
  123. {
  124. for (var j = 0; j < secondCount; j++)
  125. {
  126. second.Add(textRuns[i + j + offset]);
  127. }
  128. }
  129. first.Add(currentRun);
  130. return new SplitTextRunsResult(first, second);
  131. }
  132. else
  133. {
  134. secondCount++;
  135. var second = new List<ShapedTextCharacters>(secondCount);
  136. var split = currentRun.Split(length - currentLength);
  137. first.Add(split.First);
  138. second.Add(split.Second);
  139. if (secondCount > 0)
  140. {
  141. for (var j = 1; j < secondCount; j++)
  142. {
  143. second.Add(textRuns[i + j]);
  144. }
  145. }
  146. return new SplitTextRunsResult(first, second);
  147. }
  148. }
  149. return new SplitTextRunsResult(textRuns, null);
  150. }
  151. /// <summary>
  152. /// Fetches text runs.
  153. /// </summary>
  154. /// <param name="textSource">The text source.</param>
  155. /// <param name="firstTextSourceIndex">The first text source index.</param>
  156. /// <param name="previousLineBreak">Previous line break. Can be null.</param>
  157. /// <param name="nextLineBreak">Next line break. Can be null.</param>
  158. /// <returns>
  159. /// The formatted text runs.
  160. /// </returns>
  161. private static List<ShapedTextCharacters> FetchTextRuns(ITextSource textSource,
  162. int firstTextSourceIndex, TextLineBreak previousLineBreak, out TextLineBreak nextLineBreak)
  163. {
  164. nextLineBreak = default;
  165. var currentLength = 0;
  166. var textRuns = new List<ShapedTextCharacters>();
  167. if (previousLineBreak != null)
  168. {
  169. for (var index = 0; index < previousLineBreak.RemainingCharacters.Count; index++)
  170. {
  171. var shapedCharacters = previousLineBreak.RemainingCharacters[index];
  172. if (shapedCharacters == null)
  173. {
  174. continue;
  175. }
  176. textRuns.Add(shapedCharacters);
  177. if (TryGetLineBreak(shapedCharacters, out var runLineBreak))
  178. {
  179. var splitResult = SplitTextRuns(textRuns, currentLength + runLineBreak.PositionWrap);
  180. if (++index < previousLineBreak.RemainingCharacters.Count)
  181. {
  182. for (; index < previousLineBreak.RemainingCharacters.Count; index++)
  183. {
  184. splitResult.Second.Add(previousLineBreak.RemainingCharacters[index]);
  185. }
  186. }
  187. nextLineBreak = new TextLineBreak(splitResult.Second);
  188. return splitResult.First;
  189. }
  190. currentLength += shapedCharacters.Text.Length;
  191. }
  192. }
  193. firstTextSourceIndex += currentLength;
  194. var textRunEnumerator = new TextRunEnumerator(textSource, firstTextSourceIndex);
  195. while (textRunEnumerator.MoveNext())
  196. {
  197. var textRun = textRunEnumerator.Current;
  198. switch (textRun)
  199. {
  200. case TextCharacters textCharacters:
  201. {
  202. var shapeableRuns = textCharacters.GetShapeableCharacters();
  203. foreach (var run in shapeableRuns)
  204. {
  205. var glyphRun = TextShaper.Current.ShapeText(run.Text, run.Properties.Typeface,
  206. run.Properties.FontRenderingEmSize, run.Properties.CultureInfo);
  207. var shapedCharacters = new ShapedTextCharacters(glyphRun, run.Properties);
  208. textRuns.Add(shapedCharacters);
  209. }
  210. break;
  211. }
  212. }
  213. if (TryGetLineBreak(textRun, out var runLineBreak))
  214. {
  215. var splitResult = SplitTextRuns(textRuns, currentLength + runLineBreak.PositionWrap);
  216. nextLineBreak = new TextLineBreak(splitResult.Second);
  217. return splitResult.First;
  218. }
  219. currentLength += textRun.Text.Length;
  220. }
  221. return textRuns;
  222. }
  223. private static bool TryGetLineBreak(TextRun textRun, out LineBreak lineBreak)
  224. {
  225. lineBreak = default;
  226. if (textRun.Text.IsEmpty)
  227. {
  228. return false;
  229. }
  230. var lineBreakEnumerator = new LineBreakEnumerator(textRun.Text);
  231. while (lineBreakEnumerator.MoveNext())
  232. {
  233. if (!lineBreakEnumerator.Current.Required)
  234. {
  235. continue;
  236. }
  237. lineBreak = lineBreakEnumerator.Current;
  238. if (lineBreak.PositionWrap >= textRun.Text.Length)
  239. {
  240. return true;
  241. }
  242. //The line breaker isn't treating \n\r as a pair so we have to fix that here.
  243. if (textRun.Text[lineBreak.PositionMeasure] == '\n'
  244. && textRun.Text[lineBreak.PositionWrap] == '\r')
  245. {
  246. lineBreak = new LineBreak(lineBreak.PositionMeasure, lineBreak.PositionWrap + 1,
  247. lineBreak.Required);
  248. }
  249. return true;
  250. }
  251. return false;
  252. }
  253. /// <summary>
  254. /// Performs text wrapping returns a list of text lines.
  255. /// </summary>
  256. /// <param name="textRuns">The text run's.</param>
  257. /// <param name="textRange">The text range that is covered by the text runs.</param>
  258. /// <param name="paragraphWidth">The paragraph width.</param>
  259. /// <param name="paragraphProperties">The text paragraph properties.</param>
  260. /// <param name="currentLineBreak">The current line break if the line was explicitly broken.</param>
  261. /// <returns>The wrapped text line.</returns>
  262. private static TextLine PerformTextWrapping(List<ShapedTextCharacters> textRuns, TextRange textRange,
  263. double paragraphWidth, TextParagraphProperties paragraphProperties, TextLineBreak currentLineBreak)
  264. {
  265. var availableWidth = paragraphWidth;
  266. var currentWidth = 0.0;
  267. var runIndex = 0;
  268. var currentLength = 0;
  269. while (runIndex < textRuns.Count)
  270. {
  271. var currentRun = textRuns[runIndex];
  272. if (currentWidth + currentRun.GlyphRun.Bounds.Width > availableWidth)
  273. {
  274. var measuredLength = MeasureCharacters(currentRun, paragraphWidth - currentWidth);
  275. var breakFound = false;
  276. var currentBreakPosition = 0;
  277. if (measuredLength < currentRun.Text.Length)
  278. {
  279. var lineBreaker = new LineBreakEnumerator(currentRun.Text);
  280. while (currentBreakPosition < measuredLength && lineBreaker.MoveNext())
  281. {
  282. var nextBreakPosition = lineBreaker.Current.PositionWrap;
  283. if (nextBreakPosition == 0 || nextBreakPosition > measuredLength)
  284. {
  285. break;
  286. }
  287. breakFound = lineBreaker.Current.Required ||
  288. lineBreaker.Current.PositionWrap != currentRun.Text.Length;
  289. currentBreakPosition = nextBreakPosition;
  290. }
  291. }
  292. if (breakFound)
  293. {
  294. measuredLength = currentBreakPosition;
  295. }
  296. else
  297. {
  298. if (paragraphProperties.TextWrapping == TextWrapping.WrapWithOverflow)
  299. {
  300. var lineBreaker = new LineBreakEnumerator(currentRun.Text.Skip(currentBreakPosition));
  301. if (lineBreaker.MoveNext())
  302. {
  303. measuredLength = currentBreakPosition + lineBreaker.Current.PositionWrap;
  304. }
  305. }
  306. }
  307. currentLength += measuredLength;
  308. var splitResult = SplitTextRuns(textRuns, currentLength);
  309. var textLineMetrics = TextLineMetrics.Create(splitResult.First,
  310. new TextRange(textRange.Start, currentLength), paragraphWidth, paragraphProperties);
  311. var remainingCharacters = splitResult.Second;
  312. if (currentLineBreak?.RemainingCharacters != null)
  313. {
  314. if (remainingCharacters != null)
  315. {
  316. remainingCharacters.AddRange(currentLineBreak.RemainingCharacters);
  317. }
  318. else
  319. {
  320. remainingCharacters = new List<ShapedTextCharacters>(currentLineBreak.RemainingCharacters);
  321. }
  322. }
  323. var lineBreak = remainingCharacters != null && remainingCharacters.Count > 0 ?
  324. new TextLineBreak(remainingCharacters) :
  325. null;
  326. return new TextLineImpl(splitResult.First, textLineMetrics, lineBreak);
  327. }
  328. currentWidth += currentRun.GlyphRun.Bounds.Width;
  329. currentLength += currentRun.GlyphRun.Characters.Length;
  330. runIndex++;
  331. }
  332. return new TextLineImpl(textRuns,
  333. TextLineMetrics.Create(textRuns, textRange, paragraphWidth, paragraphProperties),
  334. currentLineBreak?.RemainingCharacters != null ?
  335. new TextLineBreak(currentLineBreak.RemainingCharacters) :
  336. null);
  337. }
  338. /// <summary>
  339. /// Gets the text range that is covered by the text runs.
  340. /// </summary>
  341. /// <param name="textRuns">The text runs.</param>
  342. /// <returns>The text range that is covered by the text runs.</returns>
  343. private static TextRange GetTextRange(IReadOnlyList<TextRun> textRuns)
  344. {
  345. if (textRuns is null || textRuns.Count == 0)
  346. {
  347. return new TextRange();
  348. }
  349. var firstTextRun = textRuns[0];
  350. if (textRuns.Count == 1)
  351. {
  352. return new TextRange(firstTextRun.Text.Start, firstTextRun.Text.Length);
  353. }
  354. var start = firstTextRun.Text.Start;
  355. var end = textRuns[textRuns.Count - 1].Text.End + 1;
  356. return new TextRange(start, end - start);
  357. }
  358. internal readonly struct SplitTextRunsResult
  359. {
  360. public SplitTextRunsResult(List<ShapedTextCharacters> first, List<ShapedTextCharacters> second)
  361. {
  362. First = first;
  363. Second = second;
  364. }
  365. /// <summary>
  366. /// Gets the first text runs.
  367. /// </summary>
  368. /// <value>
  369. /// The first text runs.
  370. /// </value>
  371. public List<ShapedTextCharacters> First { get; }
  372. /// <summary>
  373. /// Gets the second text runs.
  374. /// </summary>
  375. /// <value>
  376. /// The second text runs.
  377. /// </value>
  378. public List<ShapedTextCharacters> Second { get; }
  379. }
  380. private struct TextRunEnumerator
  381. {
  382. private readonly ITextSource _textSource;
  383. private int _pos;
  384. public TextRunEnumerator(ITextSource textSource, int firstTextSourceIndex)
  385. {
  386. _textSource = textSource;
  387. _pos = firstTextSourceIndex;
  388. Current = null;
  389. }
  390. // ReSharper disable once MemberHidesStaticFromOuterClass
  391. public TextRun Current { get; private set; }
  392. public bool MoveNext()
  393. {
  394. Current = _textSource.GetTextRun(_pos);
  395. if (Current is null)
  396. {
  397. return false;
  398. }
  399. if (Current.TextSourceLength == 0)
  400. {
  401. return false;
  402. }
  403. _pos += Current.TextSourceLength;
  404. return !(Current is TextEndOfLine);
  405. }
  406. }
  407. }
  408. }