TextFormatterImpl.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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,
  14. out var nextLineBreak);
  15. var textRange = GetTextRange(textRuns);
  16. TextLine textLine;
  17. switch (textWrapping)
  18. {
  19. case TextWrapping.NoWrap:
  20. {
  21. textLine = new TextLineImpl(textRuns, textRange, paragraphWidth, paragraphProperties,
  22. 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 fit into available width.
  39. /// </summary>
  40. /// <param name="textCharacters">The text run.</param>
  41. /// <param name="availableWidth">The available width.</param>
  42. /// <param name="count">The count of fitting characters.</param>
  43. /// <returns>
  44. /// <c>true</c> if characters fit into the available width; otherwise, <c>false</c>.
  45. /// </returns>
  46. internal static bool TryMeasureCharacters(ShapedTextCharacters textCharacters, double availableWidth,
  47. out int count)
  48. {
  49. var glyphRun = textCharacters.GlyphRun;
  50. if (glyphRun.Size.Width < availableWidth)
  51. {
  52. count = glyphRun.Characters.Length;
  53. return true;
  54. }
  55. var glyphCount = 0;
  56. var currentWidth = 0.0;
  57. if (glyphRun.GlyphAdvances.IsEmpty)
  58. {
  59. var glyphTypeface = glyphRun.GlyphTypeface;
  60. if (glyphRun.IsLeftToRight)
  61. {
  62. foreach (var glyph in glyphRun.GlyphIndices)
  63. {
  64. var advance = glyphTypeface.GetGlyphAdvance(glyph) * glyphRun.Scale;
  65. if (currentWidth + advance > availableWidth)
  66. {
  67. break;
  68. }
  69. currentWidth += advance;
  70. glyphCount++;
  71. }
  72. }
  73. else
  74. {
  75. for (var index = glyphRun.GlyphClusters.Length - 1; index > 0; index--)
  76. {
  77. var glyph = glyphRun.GlyphIndices[index];
  78. var advance = glyphTypeface.GetGlyphAdvance(glyph) * glyphRun.Scale;
  79. if (currentWidth + advance > availableWidth)
  80. {
  81. break;
  82. }
  83. currentWidth += advance;
  84. glyphCount++;
  85. }
  86. }
  87. }
  88. else
  89. {
  90. if (glyphRun.IsLeftToRight)
  91. {
  92. for (var index = 0; index < glyphRun.GlyphAdvances.Length; index++)
  93. {
  94. var advance = glyphRun.GlyphAdvances[index];
  95. if (currentWidth + advance > availableWidth)
  96. {
  97. break;
  98. }
  99. currentWidth += advance;
  100. glyphCount++;
  101. }
  102. }
  103. else
  104. {
  105. for (var index = glyphRun.GlyphAdvances.Length - 1; index > 0; index--)
  106. {
  107. var advance = glyphRun.GlyphAdvances[index];
  108. if (currentWidth + advance > availableWidth)
  109. {
  110. break;
  111. }
  112. currentWidth += advance;
  113. glyphCount++;
  114. }
  115. }
  116. }
  117. if (glyphCount == 0)
  118. {
  119. count = 0;
  120. return false;
  121. }
  122. if (glyphCount == glyphRun.GlyphIndices.Length)
  123. {
  124. count = glyphRun.Characters.Length;
  125. return true;
  126. }
  127. if (glyphRun.GlyphClusters.IsEmpty)
  128. {
  129. count = glyphCount;
  130. return true;
  131. }
  132. var firstCluster = glyphRun.GlyphClusters[0];
  133. var lastCluster = glyphRun.GlyphClusters[glyphCount];
  134. if (glyphRun.IsLeftToRight)
  135. {
  136. count = lastCluster - firstCluster;
  137. }
  138. else
  139. {
  140. count = firstCluster - lastCluster;
  141. }
  142. return count > 0;
  143. }
  144. /// <summary>
  145. /// Split a sequence of runs into two segments at specified length.
  146. /// </summary>
  147. /// <param name="textRuns">The text run's.</param>
  148. /// <param name="length">The length to split at.</param>
  149. /// <returns>The split text runs.</returns>
  150. internal static SplitTextRunsResult SplitTextRuns(List<ShapedTextCharacters> textRuns, int length)
  151. {
  152. var currentLength = 0;
  153. for (var i = 0; i < textRuns.Count; i++)
  154. {
  155. var currentRun = textRuns[i];
  156. if (currentLength + currentRun.GlyphRun.Characters.Length < length)
  157. {
  158. currentLength += currentRun.GlyphRun.Characters.Length;
  159. continue;
  160. }
  161. var firstCount = currentRun.GlyphRun.Characters.Length >= 1 ? i + 1 : i;
  162. var first = new List<ShapedTextCharacters>(firstCount);
  163. if (firstCount > 1)
  164. {
  165. for (var j = 0; j < i; j++)
  166. {
  167. first.Add(textRuns[j]);
  168. }
  169. }
  170. var secondCount = textRuns.Count - firstCount;
  171. if (currentLength + currentRun.GlyphRun.Characters.Length == length)
  172. {
  173. var second = new List<ShapedTextCharacters>(secondCount);
  174. var offset = currentRun.GlyphRun.Characters.Length > 1 ? 1 : 0;
  175. if (secondCount > 0)
  176. {
  177. for (var j = 0; j < secondCount; j++)
  178. {
  179. second.Add(textRuns[i + j + offset]);
  180. }
  181. }
  182. first.Add(currentRun);
  183. return new SplitTextRunsResult(first, second);
  184. }
  185. else
  186. {
  187. secondCount++;
  188. var second = new List<ShapedTextCharacters>(secondCount);
  189. var split = currentRun.Split(length - currentLength);
  190. first.Add(split.First);
  191. second.Add(split.Second);
  192. if (secondCount > 0)
  193. {
  194. for (var j = 1; j < secondCount; j++)
  195. {
  196. second.Add(textRuns[i + j]);
  197. }
  198. }
  199. return new SplitTextRunsResult(first, second);
  200. }
  201. }
  202. return new SplitTextRunsResult(textRuns, null);
  203. }
  204. /// <summary>
  205. /// Fetches text runs.
  206. /// </summary>
  207. /// <param name="textSource">The text source.</param>
  208. /// <param name="firstTextSourceIndex">The first text source index.</param>
  209. /// <param name="previousLineBreak">Previous line break. Can be null.</param>
  210. /// <param name="nextLineBreak">Next line break. Can be null.</param>
  211. /// <returns>
  212. /// The formatted text runs.
  213. /// </returns>
  214. private static List<ShapedTextCharacters> FetchTextRuns(ITextSource textSource,
  215. int firstTextSourceIndex, TextLineBreak previousLineBreak, out TextLineBreak nextLineBreak)
  216. {
  217. nextLineBreak = default;
  218. var currentLength = 0;
  219. var textRuns = new List<ShapedTextCharacters>();
  220. if (previousLineBreak != null)
  221. {
  222. for (var index = 0; index < previousLineBreak.RemainingCharacters.Count; index++)
  223. {
  224. var shapedCharacters = previousLineBreak.RemainingCharacters[index];
  225. if (shapedCharacters == null)
  226. {
  227. continue;
  228. }
  229. textRuns.Add(shapedCharacters);
  230. if (TryGetLineBreak(shapedCharacters, out var runLineBreak))
  231. {
  232. var splitResult = SplitTextRuns(textRuns, currentLength + runLineBreak.PositionWrap);
  233. if (++index < previousLineBreak.RemainingCharacters.Count)
  234. {
  235. for (; index < previousLineBreak.RemainingCharacters.Count; index++)
  236. {
  237. splitResult.Second.Add(previousLineBreak.RemainingCharacters[index]);
  238. }
  239. }
  240. nextLineBreak = new TextLineBreak(splitResult.Second);
  241. return splitResult.First;
  242. }
  243. currentLength += shapedCharacters.Text.Length;
  244. }
  245. }
  246. firstTextSourceIndex += currentLength;
  247. var textRunEnumerator = new TextRunEnumerator(textSource, firstTextSourceIndex);
  248. while (textRunEnumerator.MoveNext())
  249. {
  250. var textRun = textRunEnumerator.Current;
  251. switch (textRun)
  252. {
  253. case TextCharacters textCharacters:
  254. {
  255. var shapeableRuns = textCharacters.GetShapeableCharacters();
  256. foreach (var run in shapeableRuns)
  257. {
  258. var glyphRun = TextShaper.Current.ShapeText(run.Text, run.Properties.Typeface,
  259. run.Properties.FontRenderingEmSize, run.Properties.CultureInfo);
  260. var shapedCharacters = new ShapedTextCharacters(glyphRun, run.Properties);
  261. textRuns.Add(shapedCharacters);
  262. }
  263. break;
  264. }
  265. case TextEndOfLine textEndOfLine:
  266. nextLineBreak = new TextLineBreak(textEndOfLine);
  267. break;
  268. }
  269. if (TryGetLineBreak(textRun, out var runLineBreak))
  270. {
  271. var splitResult = SplitTextRuns(textRuns, currentLength + runLineBreak.PositionWrap);
  272. nextLineBreak = new TextLineBreak(splitResult.Second);
  273. return splitResult.First;
  274. }
  275. currentLength += textRun.Text.Length;
  276. }
  277. return textRuns;
  278. }
  279. private static bool TryGetLineBreak(TextRun textRun, out LineBreak lineBreak)
  280. {
  281. lineBreak = default;
  282. if (textRun.Text.IsEmpty)
  283. {
  284. return false;
  285. }
  286. var lineBreakEnumerator = new LineBreakEnumerator(textRun.Text);
  287. while (lineBreakEnumerator.MoveNext())
  288. {
  289. if (!lineBreakEnumerator.Current.Required)
  290. {
  291. continue;
  292. }
  293. lineBreak = lineBreakEnumerator.Current;
  294. if (lineBreak.PositionWrap >= textRun.Text.Length)
  295. {
  296. return true;
  297. }
  298. return true;
  299. }
  300. return false;
  301. }
  302. /// <summary>
  303. /// Performs text wrapping returns a list of text lines.
  304. /// </summary>
  305. /// <param name="textRuns">The text run's.</param>
  306. /// <param name="textRange">The text range that is covered by the text runs.</param>
  307. /// <param name="paragraphWidth">The paragraph width.</param>
  308. /// <param name="paragraphProperties">The text paragraph properties.</param>
  309. /// <param name="currentLineBreak">The current line break if the line was explicitly broken.</param>
  310. /// <returns>The wrapped text line.</returns>
  311. private static TextLine PerformTextWrapping(List<ShapedTextCharacters> textRuns, TextRange textRange,
  312. double paragraphWidth, TextParagraphProperties paragraphProperties, TextLineBreak currentLineBreak)
  313. {
  314. var availableWidth = paragraphWidth;
  315. var currentWidth = 0.0;
  316. var measuredLength = 0;
  317. foreach (var currentRun in textRuns)
  318. {
  319. if (currentWidth + currentRun.Size.Width > availableWidth)
  320. {
  321. if (TryMeasureCharacters(currentRun, paragraphWidth - currentWidth, out var count))
  322. {
  323. measuredLength += count;
  324. }
  325. break;
  326. }
  327. currentWidth += currentRun.Size.Width;
  328. measuredLength += currentRun.Text.Length;
  329. }
  330. var currentLength = 0;
  331. var lastWrapPosition = 0;
  332. var currentPosition = 0;
  333. if (measuredLength == 0 && paragraphProperties.TextWrapping != TextWrapping.WrapWithOverflow)
  334. {
  335. measuredLength = 1;
  336. }
  337. else
  338. {
  339. for (var index = 0; index < textRuns.Count; index++)
  340. {
  341. var currentRun = textRuns[index];
  342. var lineBreaker = new LineBreakEnumerator(currentRun.Text);
  343. var breakFound = false;
  344. while (lineBreaker.MoveNext())
  345. {
  346. if (lineBreaker.Current.Required &&
  347. currentLength + lineBreaker.Current.PositionMeasure <= measuredLength)
  348. {
  349. breakFound = true;
  350. currentPosition = currentLength + lineBreaker.Current.PositionWrap;
  351. break;
  352. }
  353. if ((paragraphProperties.TextWrapping != TextWrapping.WrapWithOverflow || lastWrapPosition != 0) &&
  354. currentLength + lineBreaker.Current.PositionMeasure > measuredLength)
  355. {
  356. if (lastWrapPosition > 0)
  357. {
  358. currentPosition = lastWrapPosition;
  359. }
  360. else
  361. {
  362. currentPosition = currentLength + measuredLength;
  363. }
  364. breakFound = true;
  365. break;
  366. }
  367. if (currentLength + lineBreaker.Current.PositionWrap >= measuredLength)
  368. {
  369. currentPosition = currentLength + lineBreaker.Current.PositionWrap;
  370. if (index < textRuns.Count - 1 &&
  371. lineBreaker.Current.PositionWrap == currentRun.Text.Length)
  372. {
  373. var nextRun = textRuns[index + 1];
  374. lineBreaker = new LineBreakEnumerator(nextRun.Text);
  375. if (lineBreaker.MoveNext() &&
  376. lineBreaker.Current.PositionMeasure == 0)
  377. {
  378. currentPosition += lineBreaker.Current.PositionWrap;
  379. }
  380. }
  381. breakFound = true;
  382. break;
  383. }
  384. lastWrapPosition = currentLength + lineBreaker.Current.PositionWrap;
  385. }
  386. if (!breakFound)
  387. {
  388. currentLength += currentRun.Text.Length;
  389. continue;
  390. }
  391. measuredLength = currentPosition;
  392. break;
  393. }
  394. }
  395. var splitResult = SplitTextRuns(textRuns, measuredLength);
  396. textRange = new TextRange(textRange.Start, measuredLength);
  397. var remainingCharacters = splitResult.Second;
  398. var lineBreak = remainingCharacters?.Count > 0 ? new TextLineBreak(remainingCharacters) : null;
  399. if (lineBreak is null && currentLineBreak.TextEndOfLine != null)
  400. {
  401. lineBreak = new TextLineBreak(currentLineBreak.TextEndOfLine);
  402. }
  403. return new TextLineImpl(splitResult.First, textRange, paragraphWidth, paragraphProperties, lineBreak);
  404. }
  405. /// <summary>
  406. /// Gets the text range that is covered by the text runs.
  407. /// </summary>
  408. /// <param name="textRuns">The text runs.</param>
  409. /// <returns>The text range that is covered by the text runs.</returns>
  410. private static TextRange GetTextRange(IReadOnlyList<TextRun> textRuns)
  411. {
  412. if (textRuns is null || textRuns.Count == 0)
  413. {
  414. return new TextRange();
  415. }
  416. var firstTextRun = textRuns[0];
  417. if (textRuns.Count == 1)
  418. {
  419. return new TextRange(firstTextRun.Text.Start, firstTextRun.Text.Length);
  420. }
  421. var start = firstTextRun.Text.Start;
  422. var end = textRuns[textRuns.Count - 1].Text.End + 1;
  423. return new TextRange(start, end - start);
  424. }
  425. internal readonly struct SplitTextRunsResult
  426. {
  427. public SplitTextRunsResult(List<ShapedTextCharacters> first, List<ShapedTextCharacters> second)
  428. {
  429. First = first;
  430. Second = second;
  431. }
  432. /// <summary>
  433. /// Gets the first text runs.
  434. /// </summary>
  435. /// <value>
  436. /// The first text runs.
  437. /// </value>
  438. public List<ShapedTextCharacters> First { get; }
  439. /// <summary>
  440. /// Gets the second text runs.
  441. /// </summary>
  442. /// <value>
  443. /// The second text runs.
  444. /// </value>
  445. public List<ShapedTextCharacters> Second { get; }
  446. }
  447. private struct TextRunEnumerator
  448. {
  449. private readonly ITextSource _textSource;
  450. private int _pos;
  451. public TextRunEnumerator(ITextSource textSource, int firstTextSourceIndex)
  452. {
  453. _textSource = textSource;
  454. _pos = firstTextSourceIndex;
  455. Current = null;
  456. }
  457. // ReSharper disable once MemberHidesStaticFromOuterClass
  458. public TextRun Current { get; private set; }
  459. public bool MoveNext()
  460. {
  461. Current = _textSource.GetTextRun(_pos);
  462. if (Current is null)
  463. {
  464. return false;
  465. }
  466. if (Current.TextSourceLength == 0)
  467. {
  468. return false;
  469. }
  470. _pos += Current.TextSourceLength;
  471. return true;
  472. }
  473. }
  474. }
  475. }