FormattedText.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  1. using System;
  2. using System.Collections;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Globalization;
  6. using Avalonia.Media.TextFormatting;
  7. using Avalonia.Utilities;
  8. namespace Avalonia.Media
  9. {
  10. /// <summary>
  11. /// The FormattedText class is targeted at programmers needing to add some simple text to a MIL visual.
  12. /// </summary>
  13. public class FormattedText
  14. {
  15. public const double DefaultRealToIdeal = 28800.0 / 96;
  16. public const double DefaultIdealToReal = 1 / DefaultRealToIdeal;
  17. public const int IdealInfiniteWidth = 0x3FFFFFFE;
  18. public const double RealInfiniteWidth = IdealInfiniteWidth * DefaultIdealToReal;
  19. public const double GreatestMultiplierOfEm = 100;
  20. private const double MaxFontEmSize = RealInfiniteWidth / GreatestMultiplierOfEm;
  21. // properties and format runs
  22. private ReadOnlySlice<char> _text;
  23. private readonly SpanVector _formatRuns = new SpanVector(null);
  24. private SpanPosition _latestPosition;
  25. private GenericTextParagraphProperties _defaultParaProps;
  26. private double _maxTextWidth = double.PositiveInfinity;
  27. private double[]? _maxTextWidths;
  28. private double _maxTextHeight = double.PositiveInfinity;
  29. private int _maxLineCount = int.MaxValue;
  30. private TextTrimming _trimming = TextTrimming.WordEllipsis;
  31. // text source callbacks
  32. private TextSourceImplementation? _textSourceImpl;
  33. // cached metrics
  34. private CachedMetrics? _metrics;
  35. /// <summary>
  36. /// Construct a FormattedText object.
  37. /// </summary>
  38. /// <param name="textToFormat">String of text to be displayed.</param>
  39. /// <param name="culture">Culture of text.</param>
  40. /// <param name="flowDirection">Flow direction of text.</param>
  41. /// <param name="typeface">Type face used to display text.</param>
  42. /// <param name="emSize">Font em size in visual units (1/96 of an inch).</param>
  43. /// <param name="foreground">Foreground brush used to render text.</param>
  44. public FormattedText(
  45. string textToFormat,
  46. CultureInfo culture,
  47. FlowDirection flowDirection,
  48. Typeface typeface,
  49. double emSize,
  50. IBrush? foreground)
  51. {
  52. if (culture is null)
  53. {
  54. throw new ArgumentNullException(nameof(culture));
  55. }
  56. ValidateFlowDirection(flowDirection, nameof(flowDirection));
  57. ValidateFontSize(emSize);
  58. _text = textToFormat != null ?
  59. new ReadOnlySlice<char>(textToFormat.AsMemory()) :
  60. throw new ArgumentNullException(nameof(textToFormat));
  61. var runProps = new GenericTextRunProperties(
  62. typeface,
  63. emSize,
  64. null, // decorations
  65. foreground,
  66. null, // highlight background
  67. BaselineAlignment.Baseline,
  68. culture
  69. );
  70. _latestPosition = _formatRuns.SetValue(0, _text.Length, runProps, _latestPosition);
  71. _defaultParaProps = new GenericTextParagraphProperties(
  72. flowDirection,
  73. TextAlignment.Left,
  74. false,
  75. false,
  76. runProps,
  77. TextWrapping.WrapWithOverflow,
  78. 0, // line height not specified
  79. 0 // indentation not specified
  80. );
  81. InvalidateMetrics();
  82. }
  83. private static void ValidateFontSize(double emSize)
  84. {
  85. if (emSize <= 0)
  86. {
  87. throw new ArgumentOutOfRangeException(nameof(emSize), "The parameter value must be greater than zero.");
  88. }
  89. if (emSize > MaxFontEmSize)
  90. {
  91. throw new ArgumentOutOfRangeException(nameof(emSize), $"The parameter value cannot be greater than '{MaxFontEmSize}'");
  92. }
  93. if (double.IsNaN(emSize))
  94. {
  95. throw new ArgumentOutOfRangeException(nameof(emSize), "The parameter value must be a number.");
  96. }
  97. }
  98. private static void ValidateFlowDirection(FlowDirection flowDirection, string parameterName)
  99. {
  100. if ((int)flowDirection < 0 || (int)flowDirection > (int)FlowDirection.RightToLeft)
  101. {
  102. throw new InvalidEnumArgumentException(parameterName, (int)flowDirection, typeof(FlowDirection));
  103. }
  104. }
  105. private int ValidateRange(int startIndex, int count)
  106. {
  107. if (startIndex < 0 || startIndex > _text.Length)
  108. {
  109. throw new ArgumentOutOfRangeException(nameof(startIndex));
  110. }
  111. var limit = startIndex + count;
  112. if (count < 0 || limit < startIndex || limit > _text.Length)
  113. {
  114. throw new ArgumentOutOfRangeException(nameof(count));
  115. }
  116. return limit;
  117. }
  118. private void InvalidateMetrics()
  119. {
  120. _metrics = null;
  121. }
  122. /// <summary>
  123. /// Sets foreground brush used for drawing text
  124. /// </summary>
  125. /// <param name="foregroundBrush">Foreground brush</param>
  126. public void SetForegroundBrush(IBrush foregroundBrush)
  127. {
  128. SetForegroundBrush(foregroundBrush, 0, _text.Length);
  129. }
  130. /// <summary>
  131. /// Sets foreground brush used for drawing text
  132. /// </summary>
  133. /// <param name="foregroundBrush">Foreground brush</param>
  134. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  135. /// <param name="count">The number of characters the change should be applied to.</param>
  136. public void SetForegroundBrush(IBrush? foregroundBrush, int startIndex, int count)
  137. {
  138. var limit = ValidateRange(startIndex, count);
  139. for (var i = startIndex; i < limit;)
  140. {
  141. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  142. i = Math.Min(limit, i + formatRider.Length);
  143. #pragma warning disable 6506
  144. // Presharp warns that runProps is not validated, but it can never be null
  145. // because the rider is already checked to be in range
  146. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  147. {
  148. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  149. }
  150. if (runProps.ForegroundBrush == foregroundBrush)
  151. {
  152. continue;
  153. }
  154. var newProps = new GenericTextRunProperties(
  155. runProps.Typeface,
  156. runProps.FontRenderingEmSize,
  157. runProps.TextDecorations,
  158. foregroundBrush,
  159. runProps.BackgroundBrush,
  160. runProps.BaselineAlignment,
  161. runProps.CultureInfo
  162. );
  163. #pragma warning restore 6506
  164. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition,
  165. newProps, formatRider.SpanPosition);
  166. }
  167. }
  168. /// <summary>
  169. /// Sets or changes the font family for the text object
  170. /// </summary>
  171. /// <param name="fontFamily">Font family name</param>
  172. public void SetFontFamily(string fontFamily)
  173. {
  174. SetFontFamily(fontFamily, 0, _text.Length);
  175. }
  176. /// <summary>
  177. /// Sets or changes the font family for the text object
  178. /// </summary>
  179. /// <param name="fontFamily">Font family name</param>
  180. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  181. /// <param name="count">The number of characters the change should be applied to.</param>
  182. public void SetFontFamily(string fontFamily, int startIndex, int count)
  183. {
  184. if (fontFamily == null)
  185. {
  186. throw new ArgumentNullException(nameof(fontFamily));
  187. }
  188. SetFontFamily(new FontFamily(fontFamily), startIndex, count);
  189. }
  190. /// <summary>
  191. /// Sets or changes the font family for the text object
  192. /// </summary>
  193. /// <param name="fontFamily">Font family</param>
  194. public void SetFontFamily(FontFamily fontFamily)
  195. {
  196. SetFontFamily(fontFamily, 0, _text.Length);
  197. }
  198. /// <summary>
  199. /// Sets or changes the font family for the text object
  200. /// </summary>
  201. /// <param name="fontFamily">Font family</param>
  202. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  203. /// <param name="count">The number of characters the change should be applied to.</param>
  204. public void SetFontFamily(FontFamily fontFamily, int startIndex, int count)
  205. {
  206. if (fontFamily == null)
  207. {
  208. throw new ArgumentNullException(nameof(fontFamily));
  209. }
  210. var limit = ValidateRange(startIndex, count);
  211. for (var i = startIndex; i < limit;)
  212. {
  213. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  214. i = Math.Min(limit, i + formatRider.Length);
  215. #pragma warning disable 6506
  216. // Presharp warns that runProps is not validated, but it can never be null
  217. // because the rider is already checked to be in range
  218. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  219. {
  220. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  221. }
  222. var oldTypeface = runProps.Typeface;
  223. if (fontFamily.Equals(oldTypeface.FontFamily))
  224. {
  225. continue;
  226. }
  227. var newProps = new GenericTextRunProperties(
  228. new Typeface(fontFamily, oldTypeface.Style, oldTypeface.Weight),
  229. runProps.FontRenderingEmSize,
  230. runProps.TextDecorations,
  231. runProps.ForegroundBrush,
  232. runProps.BackgroundBrush,
  233. runProps.BaselineAlignment,
  234. runProps.CultureInfo
  235. );
  236. #pragma warning restore 6506
  237. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition,
  238. newProps, formatRider.SpanPosition);
  239. InvalidateMetrics();
  240. }
  241. }
  242. /// <summary>
  243. /// Sets or changes the font em size measured in MIL units
  244. /// </summary>
  245. /// <param name="emSize">Font em size</param>
  246. public void SetFontSize(double emSize)
  247. {
  248. SetFontSize(emSize, 0, _text.Length);
  249. }
  250. /// <summary>
  251. /// Sets or changes the font em size measured in MIL units
  252. /// </summary>
  253. /// <param name="emSize">Font em size</param>
  254. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  255. /// <param name="count">The number of characters the change should be applied to.</param>
  256. public void SetFontSize(double emSize, int startIndex, int count)
  257. {
  258. ValidateFontSize(emSize);
  259. var limit = ValidateRange(startIndex, count);
  260. for (var i = startIndex; i < limit;)
  261. {
  262. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  263. i = Math.Min(limit, i + formatRider.Length);
  264. #pragma warning disable 6506
  265. // Presharp warns that runProps is not validated, but it can never be null
  266. // because the rider is already checked to be in range
  267. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  268. {
  269. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  270. }
  271. if (runProps.FontRenderingEmSize == emSize)
  272. {
  273. continue;
  274. }
  275. var newProps = new GenericTextRunProperties(
  276. runProps.Typeface,
  277. emSize,
  278. runProps.TextDecorations,
  279. runProps.ForegroundBrush,
  280. runProps.BackgroundBrush,
  281. runProps.BaselineAlignment,
  282. runProps.CultureInfo
  283. );
  284. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition,
  285. newProps, formatRider.SpanPosition);
  286. #pragma warning restore 6506
  287. InvalidateMetrics();
  288. }
  289. }
  290. /// <summary>
  291. /// Sets or changes the culture for the text object.
  292. /// </summary>
  293. /// <param name="culture">The new culture for the text object.</param>
  294. public void SetCulture(CultureInfo culture)
  295. {
  296. SetCulture(culture, 0, _text.Length);
  297. }
  298. /// <summary>
  299. /// Sets or changes the culture for the text object.
  300. /// </summary>
  301. /// <param name="culture">The new culture for the text object.</param>
  302. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  303. /// <param name="count">The number of characters the change should be applied to.</param>
  304. public void SetCulture(CultureInfo culture, int startIndex, int count)
  305. {
  306. if (culture is null)
  307. {
  308. throw new ArgumentNullException(nameof(culture));
  309. }
  310. var limit = ValidateRange(startIndex, count);
  311. for (var i = startIndex; i < limit;)
  312. {
  313. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  314. i = Math.Min(limit, i + formatRider.Length);
  315. #pragma warning disable 6506
  316. // Presharp warns that runProps is not validated, but it can never be null
  317. // because the rider is already checked to be in range
  318. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  319. {
  320. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  321. }
  322. if (runProps.CultureInfo == culture)
  323. {
  324. continue;
  325. }
  326. var newProps = new GenericTextRunProperties(
  327. runProps.Typeface,
  328. runProps.FontRenderingEmSize,
  329. runProps.TextDecorations,
  330. runProps.ForegroundBrush,
  331. runProps.BackgroundBrush,
  332. runProps.BaselineAlignment,
  333. culture
  334. );
  335. #pragma warning restore 6506
  336. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition,
  337. newProps, formatRider.SpanPosition);
  338. InvalidateMetrics();
  339. }
  340. }
  341. /// <summary>
  342. /// Sets or changes the font weight
  343. /// </summary>
  344. /// <param name="weight">Font weight</param>
  345. public void SetFontWeight(FontWeight weight)
  346. {
  347. SetFontWeight(weight, 0, _text.Length);
  348. }
  349. /// <summary>
  350. /// Sets or changes the font weight
  351. /// </summary>
  352. /// <param name="weight">Font weight</param>
  353. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  354. /// <param name="count">The number of characters the change should be applied to.</param>
  355. public void SetFontWeight(FontWeight weight, int startIndex, int count)
  356. {
  357. var limit = ValidateRange(startIndex, count);
  358. for (var i = startIndex; i < limit;)
  359. {
  360. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  361. i = Math.Min(limit, i + formatRider.Length);
  362. #pragma warning disable 6506
  363. // Presharp warns that runProps is not validated, but it can never be null
  364. // because the rider is already checked to be in range
  365. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  366. {
  367. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  368. }
  369. var oldTypeface = runProps.Typeface;
  370. if (oldTypeface.Weight == weight)
  371. {
  372. continue;
  373. }
  374. var newProps = new GenericTextRunProperties(
  375. new Typeface(oldTypeface.FontFamily, oldTypeface.Style, weight),
  376. runProps.FontRenderingEmSize,
  377. runProps.TextDecorations,
  378. runProps.ForegroundBrush,
  379. runProps.BackgroundBrush,
  380. runProps.BaselineAlignment,
  381. runProps.CultureInfo
  382. );
  383. #pragma warning restore 6506
  384. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition, newProps, formatRider.SpanPosition);
  385. InvalidateMetrics();
  386. }
  387. }
  388. /// <summary>
  389. /// Sets or changes the font style
  390. /// </summary>
  391. /// <param name="style">Font style</param>
  392. public void SetFontStyle(FontStyle style)
  393. {
  394. SetFontStyle(style, 0, _text.Length);
  395. }
  396. /// <summary>
  397. /// Sets or changes the font style
  398. /// </summary>
  399. /// <param name="style">Font style</param>
  400. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  401. /// <param name="count">The number of characters the change should be applied to.</param>
  402. public void SetFontStyle(FontStyle style, int startIndex, int count)
  403. {
  404. var limit = ValidateRange(startIndex, count);
  405. for (var i = startIndex; i < limit;)
  406. {
  407. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  408. i = Math.Min(limit, i + formatRider.Length);
  409. #pragma warning disable 6506
  410. // Presharp warns that runProps is not validated, but it can never be null
  411. // because the rider is already checked to be in range
  412. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  413. {
  414. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  415. }
  416. var oldTypeface = runProps.Typeface;
  417. if (oldTypeface.Style == style)
  418. {
  419. continue;
  420. }
  421. var newProps = new GenericTextRunProperties(
  422. new Typeface(oldTypeface.FontFamily, style, oldTypeface.Weight),
  423. runProps.FontRenderingEmSize,
  424. runProps.TextDecorations,
  425. runProps.ForegroundBrush,
  426. runProps.BackgroundBrush,
  427. runProps.BaselineAlignment,
  428. runProps.CultureInfo
  429. );
  430. #pragma warning restore 6506
  431. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition, newProps, formatRider.SpanPosition);
  432. InvalidateMetrics(); // invalidate cached metrics
  433. }
  434. }
  435. /// <summary>
  436. /// Sets or changes the type face
  437. /// </summary>
  438. /// <param name="typeface">Typeface</param>
  439. public void SetFontTypeface(Typeface typeface)
  440. {
  441. SetFontTypeface(typeface, 0, _text.Length);
  442. }
  443. /// <summary>
  444. /// Sets or changes the type face
  445. /// </summary>
  446. /// <param name="typeface">Typeface</param>
  447. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  448. /// <param name="count">The number of characters the change should be applied to.</param>
  449. public void SetFontTypeface(Typeface typeface, int startIndex, int count)
  450. {
  451. var limit = ValidateRange(startIndex, count);
  452. for (var i = startIndex; i < limit;)
  453. {
  454. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  455. i = Math.Min(limit, i + formatRider.Length);
  456. #pragma warning disable 6506
  457. // Presharp warns that runProps is not validated, but it can never be null
  458. // because the rider is already checked to be in range
  459. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  460. {
  461. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  462. }
  463. if (runProps.Typeface == typeface)
  464. {
  465. continue;
  466. }
  467. var newProps = new GenericTextRunProperties(
  468. typeface,
  469. runProps.FontRenderingEmSize,
  470. runProps.TextDecorations,
  471. runProps.ForegroundBrush,
  472. runProps.BackgroundBrush,
  473. runProps.BaselineAlignment,
  474. runProps.CultureInfo
  475. );
  476. #pragma warning restore 6506
  477. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition,
  478. newProps, formatRider.SpanPosition);
  479. InvalidateMetrics();
  480. }
  481. }
  482. /// <summary>
  483. /// Sets or changes the text decorations
  484. /// </summary>
  485. /// <param name="textDecorations">Text decorations</param>
  486. public void SetTextDecorations(TextDecorationCollection textDecorations)
  487. {
  488. SetTextDecorations(textDecorations, 0, _text.Length);
  489. }
  490. /// <summary>
  491. /// Sets or changes the text decorations
  492. /// </summary>
  493. /// <param name="textDecorations">Text decorations</param>
  494. /// <param name="startIndex">The start index of initial character to apply the change to.</param>
  495. /// <param name="count">The number of characters the change should be applied to.</param>
  496. public void SetTextDecorations(TextDecorationCollection textDecorations, int startIndex, int count)
  497. {
  498. var limit = ValidateRange(startIndex, count);
  499. for (var i = startIndex; i < limit;)
  500. {
  501. var formatRider = new SpanRider(_formatRuns, _latestPosition, i);
  502. i = Math.Min(limit, i + formatRider.Length);
  503. #pragma warning disable 6506
  504. // Presharp warns that runProps is not validated, but it can never be null
  505. // because the rider is already checked to be in range
  506. if (!(formatRider.CurrentElement is GenericTextRunProperties runProps))
  507. {
  508. throw new NotSupportedException($"{nameof(runProps)} can not be null.");
  509. }
  510. if (runProps.TextDecorations == textDecorations)
  511. {
  512. continue;
  513. }
  514. var newProps = new GenericTextRunProperties(
  515. runProps.Typeface,
  516. runProps.FontRenderingEmSize,
  517. textDecorations,
  518. runProps.ForegroundBrush,
  519. runProps.BackgroundBrush,
  520. runProps.BaselineAlignment,
  521. runProps.CultureInfo
  522. );
  523. #pragma warning restore 6506
  524. _latestPosition = _formatRuns.SetValue(formatRider.CurrentPosition, i - formatRider.CurrentPosition,
  525. newProps, formatRider.SpanPosition);
  526. }
  527. }
  528. /// Note: enumeration is temporarily made private
  529. /// because of PS #828532
  530. ///
  531. /// <summary>
  532. /// Strongly typed enumerator used for enumerating text lines
  533. /// </summary>
  534. private struct LineEnumerator : IEnumerator, IDisposable
  535. {
  536. private int _lineCount;
  537. private double _totalHeight;
  538. private TextLine? _nextLine;
  539. private readonly TextFormatter _formatter;
  540. private readonly FormattedText _that;
  541. private readonly ITextSource _textSource;
  542. // these are needed because _currentLine can be disposed before the next MoveNext() call
  543. private double _previousHeight;
  544. // line break before _currentLine, needed in case we have to reformat it with collapsing symbol
  545. private TextLineBreak? _previousLineBreak;
  546. internal LineEnumerator(FormattedText text)
  547. {
  548. _previousHeight = 0;
  549. Length = 0;
  550. _previousLineBreak = null;
  551. Position = 0;
  552. _lineCount = 0;
  553. _totalHeight = 0;
  554. Current = null;
  555. _nextLine = null;
  556. _formatter = TextFormatter.Current;
  557. _that = text;
  558. _textSource = _that._textSourceImpl ??= new TextSourceImplementation(_that);
  559. }
  560. public void Dispose()
  561. {
  562. Current = null;
  563. _nextLine = null;
  564. }
  565. private int Position { get; set; }
  566. private int Length { get; set; }
  567. /// <summary>
  568. /// Gets the current text line in the collection
  569. /// </summary>
  570. public TextLine? Current { get; private set; }
  571. /// <summary>
  572. /// Gets the current text line in the collection
  573. /// </summary>
  574. object? IEnumerator.Current => Current;
  575. /// <summary>
  576. /// Gets the paragraph width used to format the current text line
  577. /// </summary>
  578. internal double CurrentParagraphWidth
  579. {
  580. get
  581. {
  582. return MaxLineLength(_lineCount);
  583. }
  584. }
  585. private double MaxLineLength(int line)
  586. {
  587. if (_that._maxTextWidths == null)
  588. return _that._maxTextWidth;
  589. return _that._maxTextWidths[Math.Min(line, _that._maxTextWidths.Length - 1)];
  590. }
  591. /// <summary>
  592. /// Advances the enumerator to the next text line of the collection
  593. /// </summary>
  594. /// <returns>true if the enumerator was successfully advanced to the next element;
  595. /// false if the enumerator has passed the end of the collection</returns>
  596. public bool MoveNext()
  597. {
  598. if (Current == null)
  599. { // this is the first line
  600. if (_that._text.Length == 0)
  601. {
  602. return false;
  603. }
  604. Current = FormatLine(
  605. _textSource,
  606. Position,
  607. MaxLineLength(_lineCount),
  608. _that._defaultParaProps!,
  609. null // no previous line break
  610. );
  611. // check if this line fits the text height
  612. if (_totalHeight + Current.Height > _that._maxTextHeight)
  613. {
  614. Current = null;
  615. return false;
  616. }
  617. Debug.Assert(_nextLine == null);
  618. }
  619. else
  620. {
  621. // there is no next line or it didn't fit
  622. // either way we're finished
  623. if (_nextLine == null)
  624. {
  625. return false;
  626. }
  627. _totalHeight += _previousHeight;
  628. Position += Length;
  629. ++_lineCount;
  630. Current = _nextLine;
  631. _nextLine = null;
  632. }
  633. var currentLineBreak = Current.TextLineBreak;
  634. // this line is guaranteed to fit the text height
  635. Debug.Assert(_totalHeight + Current.Height <= _that._maxTextHeight);
  636. // now, check if the next line fits, we need to do this on this iteration
  637. // because we might need to add ellipsis to the current line
  638. // as a result of the next line measurement
  639. // maybe there is no next line at all
  640. if (Position + Current.Length < _that._text.Length)
  641. {
  642. bool nextLineFits;
  643. if (_lineCount + 1 >= _that._maxLineCount)
  644. {
  645. nextLineFits = false;
  646. }
  647. else
  648. {
  649. _nextLine = FormatLine(
  650. _textSource,
  651. Position + Current.Length,
  652. MaxLineLength(_lineCount + 1),
  653. _that._defaultParaProps,
  654. currentLineBreak
  655. );
  656. nextLineFits = (_totalHeight + Current.Height + _nextLine.Height <= _that._maxTextHeight);
  657. }
  658. if (!nextLineFits)
  659. {
  660. _nextLine = null;
  661. if (_that._trimming != TextTrimming.None && !Current.HasCollapsed)
  662. {
  663. // recreate the current line with ellipsis added
  664. // Note: Paragraph ellipsis is not supported today. We'll workaround
  665. // it here by faking a non-wrap text on finite column width.
  666. var currentWrap = _that._defaultParaProps!.TextWrapping;
  667. _that._defaultParaProps.SetTextWrapping(TextWrapping.NoWrap);
  668. Current = FormatLine(
  669. _that._textSourceImpl!,
  670. Position,
  671. MaxLineLength(_lineCount),
  672. _that._defaultParaProps,
  673. _previousLineBreak
  674. );
  675. currentLineBreak = Current.TextLineBreak;
  676. _that._defaultParaProps.SetTextWrapping(currentWrap);
  677. }
  678. }
  679. }
  680. _previousHeight = Current.Height;
  681. Length = Current.Length;
  682. _previousLineBreak = currentLineBreak;
  683. return true;
  684. }
  685. /// <summary>
  686. /// Wrapper of TextFormatter.FormatLine that auto-collapses the line if needed.
  687. /// </summary>
  688. private TextLine FormatLine(ITextSource textSource, int textSourcePosition, double maxLineLength, TextParagraphProperties paraProps, TextLineBreak? lineBreak)
  689. {
  690. var line = _formatter.FormatLine(
  691. textSource,
  692. textSourcePosition,
  693. maxLineLength,
  694. paraProps,
  695. lineBreak
  696. );
  697. if (_that._trimming != TextTrimming.None && line.HasOverflowed && line.Length > 0)
  698. {
  699. // what I really need here is the last displayed text run of the line
  700. // textSourcePosition + line.Length - 1 works except the end of paragraph case,
  701. // where line length includes the fake paragraph break run
  702. Debug.Assert(_that._text.Length > 0 && textSourcePosition + line.Length <= _that._text.Length + 1);
  703. var thatFormatRider = new SpanRider(
  704. _that._formatRuns,
  705. _that._latestPosition,
  706. Math.Min(textSourcePosition + line.Length - 1, _that._text.Length - 1)
  707. );
  708. var lastRunProps = (GenericTextRunProperties)thatFormatRider.CurrentElement!;
  709. TextCollapsingProperties collapsingProperties = _that._trimming.CreateCollapsingProperties(new TextCollapsingCreateInfo(maxLineLength, lastRunProps));
  710. var collapsedLine = line.Collapse(collapsingProperties);
  711. line = collapsedLine;
  712. }
  713. return line;
  714. }
  715. /// <summary>
  716. /// Sets the enumerator to its initial position,
  717. /// which is before the first element in the collection
  718. /// </summary>
  719. public void Reset()
  720. {
  721. Position = 0;
  722. _lineCount = 0;
  723. _totalHeight = 0;
  724. Current = null;
  725. _nextLine = null;
  726. }
  727. }
  728. /// <summary>
  729. /// Returns an enumerator that can iterate through the text line collection
  730. /// </summary>
  731. private LineEnumerator GetEnumerator()
  732. {
  733. return new LineEnumerator(this);
  734. }
  735. #if NEVER
  736. /// <summary>
  737. /// Returns an enumerator that can iterate through the text line collection
  738. /// </summary>
  739. IEnumerator IEnumerable.GetEnumerator()
  740. {
  741. return GetEnumerator();
  742. }
  743. #endif
  744. private void AdvanceLineOrigin(ref Point lineOrigin, TextLine currentLine)
  745. {
  746. var height = currentLine.Height;
  747. // advance line origin according to the flow direction
  748. switch (_defaultParaProps.FlowDirection)
  749. {
  750. case FlowDirection.LeftToRight:
  751. case FlowDirection.RightToLeft:
  752. lineOrigin = lineOrigin.WithY(lineOrigin.Y + height);
  753. break;
  754. }
  755. }
  756. private class CachedMetrics
  757. {
  758. // vertical
  759. public double Height;
  760. public double Baseline;
  761. // horizontal
  762. public double Width;
  763. public double WidthIncludingTrailingWhitespace;
  764. // vertical bounding box metrics
  765. public double Extent;
  766. public double OverhangAfter;
  767. // horizontal bounding box metrics
  768. public double OverhangLeading;
  769. public double OverhangTrailing;
  770. }
  771. /// <summary>
  772. /// Defines the flow direction
  773. /// </summary>
  774. public FlowDirection FlowDirection
  775. {
  776. set
  777. {
  778. ValidateFlowDirection(value, "value");
  779. _defaultParaProps.SetFlowDirection(value);
  780. InvalidateMetrics();
  781. }
  782. get
  783. {
  784. return _defaultParaProps.FlowDirection;
  785. }
  786. }
  787. /// <summary>
  788. /// Defines the alignment of text within the column
  789. /// </summary>
  790. public TextAlignment TextAlignment
  791. {
  792. set
  793. {
  794. _defaultParaProps.SetTextAlignment(value);
  795. InvalidateMetrics();
  796. }
  797. get
  798. {
  799. return _defaultParaProps.TextAlignment;
  800. }
  801. }
  802. /// <summary>
  803. /// Gets or sets the height of, or the spacing between, each line where
  804. /// zero represents the default line height.
  805. /// </summary>
  806. public double LineHeight
  807. {
  808. set
  809. {
  810. if (value < 0)
  811. {
  812. throw new ArgumentOutOfRangeException(nameof(value), "Parameter must be greater than or equal to zero.");
  813. }
  814. _defaultParaProps.SetLineHeight(value);
  815. InvalidateMetrics();
  816. }
  817. get
  818. {
  819. return _defaultParaProps.LineHeight;
  820. }
  821. }
  822. /// <summary>
  823. /// The MaxTextWidth property defines the alignment edges for the FormattedText.
  824. /// For example, left aligned text is wrapped such that the leftmost glyph alignment point
  825. /// on each line falls exactly on the left edge of the rectangle.
  826. /// Note that for many fonts, especially in italic style, some glyph strokes may extend beyond the edges of the alignment rectangle.
  827. /// For this reason, it is recommended that clients draw text with at least 1/6 em (i.e of the font size) unused margin space either side.
  828. /// Zero value of MaxTextWidth is equivalent to the maximum possible paragraph width.
  829. /// </summary>
  830. public double MaxTextWidth
  831. {
  832. set
  833. {
  834. if (value < 0)
  835. {
  836. throw new ArgumentOutOfRangeException(nameof(value), "Parameter must be greater than or equal to zero.");
  837. }
  838. _maxTextWidth = value;
  839. InvalidateMetrics();
  840. }
  841. get
  842. {
  843. return _maxTextWidth;
  844. }
  845. }
  846. /// <summary>
  847. /// Sets the array of lengths,
  848. /// which will be applied to each line of text in turn.
  849. /// If the text covers more lines than there are entries in the length array,
  850. /// the last entry is reused as many times as required.
  851. /// The maxTextWidths array overrides the MaxTextWidth property.
  852. /// </summary>
  853. /// <param name="maxTextWidths">The max text width array</param>
  854. public void SetMaxTextWidths(double[] maxTextWidths)
  855. {
  856. if (maxTextWidths == null || maxTextWidths.Length <= 0)
  857. {
  858. throw new ArgumentNullException(nameof(maxTextWidths));
  859. }
  860. _maxTextWidths = maxTextWidths;
  861. InvalidateMetrics();
  862. }
  863. /// <summary>
  864. /// Obtains a copy of the array of lengths,
  865. /// which will be applied to each line of text in turn.
  866. /// If the text covers more lines than there are entries in the length array,
  867. /// the last entry is reused as many times as required.
  868. /// The maxTextWidths array overrides the MaxTextWidth property.
  869. /// </summary>
  870. /// <returns>The copy of max text width array</returns>
  871. public double[] GetMaxTextWidths()
  872. {
  873. return _maxTextWidths != null ? (double[])_maxTextWidths.Clone() : Array.Empty<double>();
  874. }
  875. /// <summary>
  876. /// Sets the maximum length of a column of text.
  877. /// The last line of text displayed is the last whole line that will fit within this limit,
  878. /// or the nth line as specified by MaxLineCount, whichever occurs first.
  879. /// Use the Trimming property to control how the omission of text is indicated.
  880. /// </summary>
  881. public double MaxTextHeight
  882. {
  883. set
  884. {
  885. if (value <= 0)
  886. {
  887. throw new ArgumentOutOfRangeException(nameof(value), $"'{nameof(MaxTextHeight)}' property value must be greater than zero.");
  888. }
  889. if (double.IsNaN(value))
  890. {
  891. throw new ArgumentOutOfRangeException(nameof(value), $"'{nameof(MaxTextHeight)}' property value cannot be NaN.");
  892. }
  893. _maxTextHeight = value;
  894. InvalidateMetrics();
  895. }
  896. get
  897. {
  898. return _maxTextHeight;
  899. }
  900. }
  901. /// <summary>
  902. /// Defines the maximum number of lines to display.
  903. /// The last line of text displayed is the lineCount-1'th line,
  904. /// or the last whole line that will fit within the count set by MaxTextHeight,
  905. /// whichever occurs first.
  906. /// Use the Trimming property to control how the omission of text is indicated
  907. /// </summary>
  908. public int MaxLineCount
  909. {
  910. set
  911. {
  912. if (value <= 0)
  913. {
  914. throw new ArgumentOutOfRangeException(nameof(value), "The parameter value must be greater than zero.");
  915. }
  916. _maxLineCount = value;
  917. InvalidateMetrics();
  918. }
  919. get
  920. {
  921. return _maxLineCount;
  922. }
  923. }
  924. /// <summary>
  925. /// Defines how omission of text is indicated.
  926. /// CharacterEllipsis trimming allows partial words to be displayed,
  927. /// while WordEllipsis removes whole words to fit.
  928. /// Both guarantee to include an ellipsis ('...') at the end of the lines
  929. /// where text has been trimmed as a result of line and column limits.
  930. /// </summary>
  931. public TextTrimming Trimming
  932. {
  933. set
  934. {
  935. _trimming = value;
  936. _defaultParaProps.SetTextWrapping(_trimming == TextTrimming.None ?
  937. TextWrapping.Wrap :
  938. TextWrapping.WrapWithOverflow);
  939. InvalidateMetrics();
  940. }
  941. get
  942. {
  943. return _trimming;
  944. }
  945. }
  946. /// <summary>
  947. /// Lazily initializes the cached metrics EXCEPT for black box metrics and
  948. /// returns the CachedMetrics structure.
  949. /// </summary>
  950. private CachedMetrics Metrics
  951. {
  952. get
  953. {
  954. return _metrics ??= DrawAndCalculateMetrics(
  955. null, // drawing context
  956. new Point(), // drawing offset
  957. false);
  958. }
  959. }
  960. /// <summary>
  961. /// Lazily initializes the cached metrics INCLUDING black box metrics and
  962. /// returns the CachedMetrics structure.
  963. /// </summary>
  964. private CachedMetrics BlackBoxMetrics
  965. {
  966. get
  967. {
  968. if (_metrics == null || double.IsNaN(_metrics.Extent))
  969. {
  970. // We need to obtain the metrics, including black box metrics.
  971. _metrics = DrawAndCalculateMetrics(
  972. null, // drawing context
  973. new Point(), // drawing offset
  974. true); // calculate black box metrics
  975. }
  976. return _metrics;
  977. }
  978. }
  979. /// <summary>
  980. /// The distance from the top of the first line to the bottom of the last line.
  981. /// </summary>
  982. public double Height
  983. {
  984. get
  985. {
  986. return Metrics.Height;
  987. }
  988. }
  989. /// <summary>
  990. /// The distance from the topmost black pixel of the first line
  991. /// to the bottommost black pixel of the last line.
  992. /// </summary>
  993. public double Extent
  994. {
  995. get
  996. {
  997. return BlackBoxMetrics.Extent;
  998. }
  999. }
  1000. /// <summary>
  1001. /// The distance from the top of the first line to the baseline of the first line.
  1002. /// </summary>
  1003. public double Baseline
  1004. {
  1005. get
  1006. {
  1007. return Metrics.Baseline;
  1008. }
  1009. }
  1010. /// <summary>
  1011. /// The distance from the bottom of the last line to the extent bottom.
  1012. /// </summary>
  1013. public double OverhangAfter
  1014. {
  1015. get
  1016. {
  1017. return BlackBoxMetrics.OverhangAfter;
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// The maximum distance from the leading black pixel to the leading alignment point of a line.
  1022. /// </summary>
  1023. public double OverhangLeading
  1024. {
  1025. get
  1026. {
  1027. return BlackBoxMetrics.OverhangLeading;
  1028. }
  1029. }
  1030. /// <summary>
  1031. /// The maximum distance from the trailing black pixel to the trailing alignment point of a line.
  1032. /// </summary>
  1033. public double OverhangTrailing
  1034. {
  1035. get
  1036. {
  1037. return BlackBoxMetrics.OverhangTrailing;
  1038. }
  1039. }
  1040. /// <summary>
  1041. /// The maximum advance width between the leading and trailing alignment points of a line,
  1042. /// excluding the width of whitespace characters at the end of the line.
  1043. /// </summary>
  1044. public double Width
  1045. {
  1046. get
  1047. {
  1048. return Metrics.Width;
  1049. }
  1050. }
  1051. /// <summary>
  1052. /// The maximum advance width between the leading and trailing alignment points of a line,
  1053. /// including the width of whitespace characters at the end of the line.
  1054. /// </summary>
  1055. public double WidthIncludingTrailingWhitespace
  1056. {
  1057. get
  1058. {
  1059. return Metrics.WidthIncludingTrailingWhitespace;
  1060. }
  1061. }
  1062. /// <summary>
  1063. /// Obtains geometry for the text, including underlines and strikethroughs.
  1064. /// </summary>
  1065. /// <param name="origin">The left top origin of the resulting geometry.</param>
  1066. /// <returns>The geometry returned contains the combined geometry
  1067. /// of all of the glyphs, underlines and strikeThroughs that represent the formatted text.
  1068. /// Overlapping contours are merged by performing a Boolean union operation.</returns>
  1069. public Geometry? BuildGeometry(Point origin)
  1070. {
  1071. GeometryGroup? accumulatedGeometry = null;
  1072. var lineOrigin = origin;
  1073. DrawingGroup drawing = new DrawingGroup();
  1074. using (var ctx = drawing.Open())
  1075. {
  1076. using (var enumerator = GetEnumerator())
  1077. {
  1078. while (enumerator.MoveNext())
  1079. {
  1080. var currentLine = enumerator.Current;
  1081. if (currentLine != null)
  1082. {
  1083. currentLine.Draw(ctx, lineOrigin);
  1084. AdvanceLineOrigin(ref lineOrigin, currentLine);
  1085. }
  1086. }
  1087. }
  1088. }
  1089. Transform? transform = new TranslateTransform(origin.X, origin.Y);
  1090. // recursively go down the DrawingGroup to build up the geometry
  1091. CombineGeometryRecursive(drawing, ref transform, ref accumulatedGeometry);
  1092. return accumulatedGeometry;
  1093. }
  1094. /// <summary>
  1095. /// Draws the text object
  1096. /// </summary>
  1097. internal void Draw(DrawingContext drawingContext, Point origin)
  1098. {
  1099. var lineOrigin = origin;
  1100. if (_metrics != null && !double.IsNaN(_metrics.Extent))
  1101. {
  1102. // we can't use foreach because it requires GetEnumerator and associated classes to be public
  1103. // foreach (TextLine currentLine in this)
  1104. using (var enumerator = GetEnumerator())
  1105. {
  1106. while (enumerator.MoveNext())
  1107. {
  1108. var currentLine = enumerator.Current!;
  1109. currentLine.Draw(drawingContext, lineOrigin);
  1110. AdvanceLineOrigin(ref lineOrigin, currentLine);
  1111. }
  1112. }
  1113. }
  1114. else
  1115. {
  1116. // Calculate metrics as we draw to avoid formatting again if we need metrics later; we compute
  1117. // black box metrics too because these are already known as a side-effect of drawing
  1118. _metrics = DrawAndCalculateMetrics(drawingContext, origin, true);
  1119. }
  1120. }
  1121. private void CombineGeometryRecursive(Drawing drawing, ref Transform? transform, ref GeometryGroup? accumulatedGeometry)
  1122. {
  1123. if (drawing is DrawingGroup group)
  1124. {
  1125. transform = group.Transform;
  1126. if (group.Children is DrawingCollection children)
  1127. {
  1128. // recursively go down for DrawingGroup
  1129. foreach (var child in children)
  1130. {
  1131. CombineGeometryRecursive(child, ref transform, ref accumulatedGeometry);
  1132. }
  1133. }
  1134. }
  1135. else
  1136. {
  1137. if (drawing is GlyphRunDrawing glyphRunDrawing)
  1138. {
  1139. // process glyph run
  1140. var glyphRun = glyphRunDrawing.GlyphRun;
  1141. if (glyphRun != null)
  1142. {
  1143. var glyphRunGeometry = glyphRun.BuildGeometry();
  1144. glyphRunGeometry.Transform = transform;
  1145. if (accumulatedGeometry == null)
  1146. {
  1147. accumulatedGeometry = new GeometryGroup
  1148. {
  1149. FillRule = FillRule.NonZero
  1150. };
  1151. }
  1152. accumulatedGeometry.Children.Add(glyphRunGeometry);
  1153. }
  1154. }
  1155. else
  1156. {
  1157. if (drawing is GeometryDrawing geometryDrawing)
  1158. {
  1159. // process geometry (i.e. TextDecoration on the line)
  1160. var geometry = geometryDrawing.Geometry;
  1161. if (geometry != null)
  1162. {
  1163. geometry.Transform = transform;
  1164. if (geometry is LineGeometry lineGeometry)
  1165. {
  1166. // For TextDecoration drawn by DrawLine(), the geometry is a LineGeometry which has no
  1167. // bounding area. So this line won't show up. Work aroud it by increase the Bounding rect
  1168. // to be Pen's thickness
  1169. var bounds = lineGeometry.Bounds;
  1170. if (bounds.Height == 0)
  1171. {
  1172. bounds = bounds.WithHeight(geometryDrawing.Pen?.Thickness ?? 0);
  1173. }
  1174. else if (bounds.Width == 0)
  1175. {
  1176. bounds = bounds.WithWidth(geometryDrawing.Pen?.Thickness ?? 0);
  1177. }
  1178. // convert the line geometry into a rectangle geometry
  1179. // we lost line cap info here
  1180. geometry = new RectangleGeometry(bounds);
  1181. }
  1182. if (accumulatedGeometry == null)
  1183. {
  1184. accumulatedGeometry = new GeometryGroup
  1185. {
  1186. FillRule = FillRule.NonZero
  1187. };
  1188. }
  1189. accumulatedGeometry.Children.Add(geometry);
  1190. }
  1191. }
  1192. }
  1193. }
  1194. }
  1195. private CachedMetrics DrawAndCalculateMetrics(DrawingContext? drawingContext, Point drawingOffset, bool getBlackBoxMetrics)
  1196. {
  1197. var metrics = new CachedMetrics();
  1198. if (_text.Length == 0)
  1199. {
  1200. return metrics;
  1201. }
  1202. // we can't use foreach because it requires GetEnumerator and associated classes to be public
  1203. // foreach (TextLine currentLine in this)
  1204. using (var enumerator = GetEnumerator())
  1205. {
  1206. var first = true;
  1207. double accBlackBoxLeft, accBlackBoxTop, accBlackBoxRight, accBlackBoxBottom;
  1208. accBlackBoxLeft = accBlackBoxTop = double.MaxValue;
  1209. accBlackBoxRight = accBlackBoxBottom = double.MinValue;
  1210. var origin = new Point(0, 0);
  1211. // Holds the TextLine.Start of the longest line. Thus it will hold the minimum value
  1212. // of TextLine.Start among all the lines that forms the text. The overhangs (leading and trailing)
  1213. // are calculated with an offset as a result of the same issue with TextLine.Start.
  1214. // So, we compute this offset and remove it later from the values of the overhangs.
  1215. var lineStartOfLongestLine = double.MaxValue;
  1216. while (enumerator.MoveNext())
  1217. {
  1218. // enumerator will dispose the currentLine
  1219. var currentLine = enumerator.Current!;
  1220. // if we're drawing, do it first as this will compute black box metrics as a side-effect
  1221. if (drawingContext != null)
  1222. {
  1223. currentLine.Draw(drawingContext,
  1224. new Point(origin.X + drawingOffset.X, origin.Y + drawingOffset.Y));
  1225. }
  1226. if (getBlackBoxMetrics)
  1227. {
  1228. var blackBoxLeft = origin.X + currentLine.Start + currentLine.OverhangLeading;
  1229. var blackBoxRight = origin.X + currentLine.Start + currentLine.Width - currentLine.OverhangTrailing;
  1230. var blackBoxBottom = origin.Y + currentLine.Height + currentLine.OverhangAfter;
  1231. var blackBoxTop = blackBoxBottom - currentLine.Extent;
  1232. accBlackBoxLeft = Math.Min(accBlackBoxLeft, blackBoxLeft);
  1233. accBlackBoxRight = Math.Max(accBlackBoxRight, blackBoxRight);
  1234. accBlackBoxBottom = Math.Max(accBlackBoxBottom, blackBoxBottom);
  1235. accBlackBoxTop = Math.Min(accBlackBoxTop, blackBoxTop);
  1236. metrics.OverhangAfter = currentLine.OverhangAfter;
  1237. }
  1238. metrics.Height += currentLine.Height;
  1239. metrics.Width = Math.Max(metrics.Width, currentLine.Width);
  1240. metrics.WidthIncludingTrailingWhitespace = Math.Max(metrics.WidthIncludingTrailingWhitespace, currentLine.WidthIncludingTrailingWhitespace);
  1241. lineStartOfLongestLine = Math.Min(lineStartOfLongestLine, currentLine.Start);
  1242. if (first)
  1243. {
  1244. metrics.Baseline = currentLine.Baseline;
  1245. first = false;
  1246. }
  1247. AdvanceLineOrigin(ref origin, currentLine);
  1248. }
  1249. if (getBlackBoxMetrics)
  1250. {
  1251. metrics.Extent = accBlackBoxBottom - accBlackBoxTop;
  1252. metrics.OverhangLeading = accBlackBoxLeft - lineStartOfLongestLine;
  1253. metrics.OverhangTrailing = metrics.Width - (accBlackBoxRight - lineStartOfLongestLine);
  1254. }
  1255. else
  1256. {
  1257. // indicate that black box metrics are not known
  1258. metrics.Extent = double.NaN;
  1259. }
  1260. }
  1261. return metrics;
  1262. }
  1263. private class TextSourceImplementation : ITextSource
  1264. {
  1265. private readonly FormattedText _that;
  1266. public TextSourceImplementation(FormattedText text)
  1267. {
  1268. _that = text;
  1269. }
  1270. /// <inheritdoc/>
  1271. public TextRun? GetTextRun(int textSourceCharacterIndex)
  1272. {
  1273. if (textSourceCharacterIndex >= _that._text.Length)
  1274. {
  1275. return null;
  1276. }
  1277. var thatFormatRider = new SpanRider(_that._formatRuns, _that._latestPosition, textSourceCharacterIndex);
  1278. TextRunProperties properties = (GenericTextRunProperties)thatFormatRider.CurrentElement!;
  1279. var textCharacters = new TextCharacters(_that._text, textSourceCharacterIndex, thatFormatRider.Length,
  1280. properties);
  1281. return textCharacters;
  1282. }
  1283. }
  1284. }
  1285. }