TextBlock.cs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084
  1. 
  2. // RichTextKit
  3. // Copyright © 2019-2020 Topten Software. All Rights Reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. // not use this product except in compliance with the License. You may obtain
  7. // a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. // License for the specific language governing permissions and limitations
  15. // under the License.
  16. // Modifications by Alexander Tsyganeko: marked by ATZ
  17. using SkiaSharp;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Diagnostics;
  21. using System.Linq;
  22. using Topten.RichTextKit.Utils;
  23. namespace Topten.RichTextKit
  24. {
  25. /// <summary>
  26. /// Represents a block of formatted, laid out and measurable text
  27. /// </summary>
  28. public partial class TextBlock : StyledText
  29. {
  30. /// <summary>
  31. /// Constructor
  32. /// </summary>
  33. public TextBlock()
  34. {
  35. }
  36. /// <summary>
  37. /// The max width property sets the maximum width of a line, after which
  38. /// the line will be wrapped onto the next line.
  39. /// </summary>
  40. /// <remarks>
  41. /// This property can be set to null, in which case lines won't be wrapped.
  42. /// </remarks>
  43. public float? MaxWidth
  44. {
  45. get => _maxWidth;
  46. set
  47. {
  48. if (value.HasValue && value.Value < 0)
  49. value = 0;
  50. if (_maxWidth != value)
  51. {
  52. _maxWidth = value;
  53. InvalidateLayout();
  54. }
  55. }
  56. }
  57. /// <summary>
  58. /// The maximum height of the TextBlock after which lines will be
  59. /// truncated and the final line will be appended with an
  60. /// ellipsis (`...`) character.
  61. /// </summary>
  62. /// <remarks>
  63. /// This property can be set to null, in which case the vertical height of the text block
  64. /// won't be capped.
  65. /// </remarks>
  66. public float? MaxHeight
  67. {
  68. get => _maxHeight;
  69. set
  70. {
  71. if (value.HasValue && value.Value < 0)
  72. value = 0;
  73. if (value != _maxHeight)
  74. {
  75. _maxHeight = value;
  76. InvalidateLayout();
  77. }
  78. }
  79. }
  80. /// <summary>
  81. /// The maximum number of lines after which lines will be
  82. /// truncated and the final line will be appended with an
  83. /// ellipsis (`...`) character.
  84. /// </summary>
  85. /// <remarks>
  86. /// This property can be set to null, in which case the vertical height of
  87. /// the text block won't be capped.
  88. /// </remarks>
  89. public int? MaxLines
  90. {
  91. get => _maxLines;
  92. set
  93. {
  94. if (value.HasValue && value.Value < 0)
  95. value = 0;
  96. if (value != _maxLines)
  97. {
  98. _maxLines = value;
  99. InvalidateLayout();
  100. }
  101. }
  102. }
  103. /// <summary>
  104. /// Sets the left, right or center alignment of the text block.
  105. /// </summary>
  106. /// <remarks>
  107. /// Set this property to <see cref="TextAlignment.Auto"/> to align
  108. /// the paragraph according to the <see cref="BaseDirection"/>.
  109. ///
  110. /// * If the <see cref="MaxWidth"/> property has been set this will
  111. /// be used for alignment calculations.
  112. /// * If the <see cref="MaxWidth"/> property has not been set, the
  113. /// width of the longest line will be used.
  114. /// </remarks>
  115. public TextAlignment Alignment
  116. {
  117. get => _textAlignment;
  118. set
  119. {
  120. if (_textAlignment != value)
  121. {
  122. _textAlignment = value;
  123. InvalidateLayout();
  124. }
  125. }
  126. }
  127. /// <summary>
  128. /// The base directionality of this text block (whether text is laid out
  129. /// left to right, or right to left)
  130. /// </summary>
  131. public TextDirection BaseDirection
  132. {
  133. get => _baseDirection;
  134. set
  135. {
  136. if (_baseDirection != value)
  137. {
  138. _baseDirection = value;
  139. InvalidateLayout();
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Clear the content of this text block
  145. /// </summary>
  146. public override void Clear()
  147. {
  148. // Reset everything
  149. FontRun.Pool.Value.ReturnAndClear(_fontRuns);
  150. TextLine.Pool.Value.ReturnAndClear(_lines);
  151. _textShapingBuffers.Clear();
  152. base.Clear();
  153. }
  154. /// <summary>
  155. /// Split this text block at the specified code point index
  156. /// </summary>
  157. /// <param name="from">The code point index to copy from</param>
  158. /// <param name="length">The number of code points to copy</param>
  159. /// <returns>A new text block with the RHS split part of the text</returns>
  160. public TextBlock Copy(int from, int length)
  161. {
  162. // Create a new text block with the same attributes as this one
  163. var other = new TextBlock();
  164. other.AllowEllipsis = this.AllowEllipsis; // ATZ
  165. other.Alignment = this.Alignment;
  166. other.BaseDirection = this.BaseDirection;
  167. other.MaxWidth = this.MaxWidth;
  168. other.MaxHeight = this.MaxHeight;
  169. other.MaxLines = this.MaxLines;
  170. // Copy text to the new paragraph
  171. foreach (var subRun in _styleRuns.GetInterectingRuns(from, length))
  172. {
  173. var sr = _styleRuns[subRun.Index];
  174. other.AddText(sr.CodePoints.SubSlice(subRun.Offset, subRun.Length), sr.Style);
  175. }
  176. return other;
  177. }
  178. /// <inheritdoc />
  179. protected override void OnChanged()
  180. {
  181. InvalidateLayout();
  182. base.OnChanged();
  183. }
  184. /// <summary>
  185. /// Appends an ellipsis to this text block
  186. /// </summary>
  187. /// <remarks>
  188. /// This method checks if the text block has already been truncated and if
  189. /// not appends an ellipsis without changing the measured vertical layout of the
  190. /// text block. The ellipsis only remains in effect until the block's layout
  191. /// is recalculated.
  192. ///
  193. /// The text block must have at least one line. If the block contains no text,
  194. /// then use AddText("\n", style) to create a single line with an attached style
  195. /// but no text.
  196. ///
  197. /// The intended purpose of this is to included an ellipsis on this text block
  198. /// when a following text block doesn't fit.
  199. /// </remarks>
  200. public void AddEllipsis()
  201. {
  202. // ATZ
  203. if (!AllowEllipsis)
  204. return;
  205. // Make sure laid out
  206. Layout();
  207. // Already truncated?
  208. if (_truncated)
  209. return;
  210. if (_lines.Count == 0)
  211. throw new InvalidOperationException("Ellipsis can't be appended to a text block with no lines");
  212. // Append the ellipsis
  213. var line = _lines[_lines.Count - 1];
  214. // Because adorning the line with ellipsis resets the XCoord of each font run
  215. // to be left aligned, we need to move the glyphs to be left aligned too
  216. for (int frIndex = 0; frIndex < line.Runs.Count; frIndex++)
  217. {
  218. var fr = line.Runs[frIndex];
  219. fr.MoveGlyphs(-fr.XCoord, 0);
  220. }
  221. // Append the ellipsis to the line and relayout theline
  222. AdornLineWithEllipsis(line, true);
  223. // Work out the new x-alignment
  224. var ta = ResolveTextAlignment();
  225. float xAdjust = 0;
  226. switch (ta)
  227. {
  228. case TextAlignment.Right:
  229. xAdjust = (_maxWidth ?? _measuredWidth) - line.Width;
  230. break;
  231. case TextAlignment.Center:
  232. xAdjust = ((_maxWidth ?? _measuredWidth) - line.Width) / 2;
  233. break;
  234. }
  235. // Adjust the measured width if the adorned line is the widest line
  236. if (line.Width > _measuredWidth)
  237. _measuredWidth = line.Width;
  238. // Reposition each run to the correct location
  239. for (int frIndex = 0; frIndex < line.Runs.Count; frIndex++)
  240. {
  241. var fr = line.Runs[frIndex];
  242. fr.Line = line;
  243. fr.XCoord += xAdjust;
  244. if (fr.RunKind == FontRunKind.Ellipsis)
  245. {
  246. // The ellipsis has it's xcoord setup, but it's glyphs have never
  247. // been positioned so need to handle this a little differently
  248. fr.MoveGlyphs(fr.XCoord, line.YCoord + line.BaseLine);
  249. }
  250. else
  251. {
  252. // Move the glyphs back to corectly aligned position
  253. fr.MoveGlyphs(fr.XCoord, 0);
  254. }
  255. }
  256. }
  257. /// <summary>
  258. /// Updates the internal layout of the text block
  259. /// </summary>
  260. /// <remarks>
  261. /// Generally you don't need to call this method as the layout
  262. /// will be automatically updated as needed.
  263. /// </remarks>
  264. public void Layout()
  265. {
  266. // Needed?
  267. if (!_needsLayout)
  268. return;
  269. _needsLayout = false;
  270. // Resolve max width/height
  271. _maxWidthResolved = _maxWidth ?? float.MaxValue;
  272. _maxHeightResolved = _maxHeight ?? float.MaxValue;
  273. _maxLinesResolved = _maxLines ?? int.MaxValue;
  274. // Reset layout state
  275. _textShapingBuffers.Clear();
  276. _fontRuns.Clear();
  277. _lines.Clear();
  278. _caretIndicies.Clear();
  279. _wordBoundaryIndicies.Clear();
  280. _measuredHeight = 0;
  281. _measuredWidth = 0;
  282. _leftOverhang = null;
  283. _rightOverhang = null;
  284. _truncated = false;
  285. // Only layout if actually have some text
  286. if (_codePoints.Length != 0)
  287. {
  288. // Build font runs
  289. BuildFontRuns();
  290. // Break font runs into lines
  291. BreakLines();
  292. // Finalize lines
  293. FinalizeLines();
  294. }
  295. }
  296. /// <summary>
  297. /// Get all font runs for this text block
  298. /// </summary>
  299. public IReadOnlyList<FontRun> FontRuns
  300. {
  301. get
  302. {
  303. Layout();
  304. return _fontRuns;
  305. }
  306. }
  307. /// <summary>
  308. /// Get all the lines for this text block
  309. /// </summary>
  310. public IReadOnlyList<TextLine> Lines
  311. {
  312. get
  313. {
  314. Layout();
  315. return _lines;
  316. }
  317. }
  318. /// <summary>
  319. /// Paint this text block
  320. /// </summary>
  321. /// <param name="canvas">The Skia canvas to paint to</param>
  322. /// <param name="options">Options controlling the paint operation</param>
  323. public void Paint(SKCanvas canvas, TextPaintOptions options = null)
  324. {
  325. // Ensure have options
  326. if (options == null)
  327. options = TextPaintOptions.Default;
  328. // Ensure layout done
  329. Layout();
  330. // Create context
  331. var ctx = new PaintTextContext()
  332. {
  333. Canvas = canvas,
  334. Options = options,
  335. };
  336. // Prepare selection
  337. if (options.Selection.HasValue)
  338. {
  339. ctx.SelectionStart = options.Selection.Value.Minimum;
  340. ctx.SelectionEnd = options.Selection.Value.Maximum;
  341. ctx.PaintSelectionBackground = new SKPaint()
  342. {
  343. Color = options.SelectionColor,
  344. IsStroke = false,
  345. IsAntialias = false,
  346. };
  347. if (options.SelectionHandleScale != 0 && options.SelectionHandleColor.Alpha > 0)
  348. {
  349. ctx.SelectionHandleScale = options.SelectionHandleScale;
  350. ctx.PaintSelectionHandle = new SKPaint()
  351. {
  352. Color = options.SelectionHandleColor,
  353. IsStroke = false,
  354. IsAntialias = true,
  355. };
  356. }
  357. }
  358. else
  359. {
  360. ctx.SelectionStart = -1;
  361. ctx.SelectionEnd = -1;
  362. }
  363. // Paint each line
  364. foreach (var l in _lines)
  365. {
  366. l.Paint(ctx);
  367. }
  368. // Clean up
  369. ctx.PaintSelectionBackground?.Dispose();
  370. }
  371. /// <summary>
  372. /// Paint this text block
  373. /// </summary>
  374. /// <param name="canvas">The Skia canvas to paint to</param>
  375. /// <param name="position">The top left position within the canvas to draw at</param>
  376. /// <param name="options">Options controlling the paint operation</param>
  377. public void Paint(SKCanvas canvas, SKPoint position, TextPaintOptions options = null)
  378. {
  379. // Translate
  380. canvas.Save();
  381. canvas.Translate(position.X, position.Y);
  382. // Paint it
  383. Paint(canvas, options);
  384. // Restore and done!
  385. canvas.Restore();
  386. }
  387. /// <summary>
  388. /// The total height of all lines.
  389. /// </summary>
  390. public float MeasuredHeight
  391. {
  392. get
  393. {
  394. Layout();
  395. return _measuredHeight;
  396. }
  397. }
  398. /// <summary>
  399. /// The length of the displayed text (in code points)
  400. /// </summary>
  401. /// <remarks>
  402. /// If the text is truncated, this is the index of the point
  403. /// at which the ellipsis was inserted. If the text it not
  404. /// truncated, is the length of all added text.
  405. /// </remarks>
  406. public int MeasuredLength
  407. {
  408. get
  409. {
  410. Layout();
  411. if (_lines.Count == 0)
  412. return 0;
  413. return _lines[_lines.Count - 1].End;
  414. }
  415. }
  416. /// <summary>
  417. /// The number of lines in the text
  418. /// </summary>
  419. public int LineCount
  420. {
  421. get
  422. {
  423. Layout();
  424. return _lines.Count;
  425. }
  426. }
  427. /// <summary>
  428. /// The width of the widest line of text.
  429. /// </summary>
  430. /// <remarks>
  431. /// The returned width does not include any overhang.
  432. /// </remarks>
  433. public float MeasuredWidth
  434. {
  435. get
  436. {
  437. Layout();
  438. return _measuredWidth;
  439. }
  440. }
  441. /// <summary>
  442. /// Indicates if the text was truncated due to max height or max lines
  443. /// constraints
  444. /// </summary>
  445. public bool Truncated
  446. {
  447. get
  448. {
  449. Layout();
  450. return _truncated;
  451. }
  452. }
  453. /// <summary>
  454. /// Gets the size of any unused space around the text.
  455. /// </summary>
  456. /// <remarks>
  457. /// If MaxWidth is not set, the left and right padding will always be zero.
  458. ///
  459. /// This property also returns a bottom padding amount if MaxHeight is set.
  460. ///
  461. /// The returned top padding is always zero.
  462. ///
  463. /// The return rectangle describes padding amounts for each edge - not
  464. /// rectangle co-ordinates.
  465. /// </remarks>
  466. public SKRect MeasuredPadding
  467. {
  468. get
  469. {
  470. var r = new SKRect();
  471. // Bottom padding?
  472. if (_maxHeight.HasValue)
  473. {
  474. r.Bottom = _maxHeight.Value - _measuredHeight;
  475. }
  476. if (!_maxWidth.HasValue)
  477. return r;
  478. Layout();
  479. switch (ResolveTextAlignment())
  480. {
  481. case TextAlignment.Left:
  482. r.Left = 0;
  483. r.Right = _maxWidthResolved - _measuredWidth;
  484. return r;
  485. case TextAlignment.Right:
  486. r.Left = _maxWidthResolved - _measuredWidth;
  487. r.Right = 0;
  488. return r;
  489. case TextAlignment.Center:
  490. r.Left = (_maxWidthResolved - _measuredWidth) / 2;
  491. r.Right = (_maxWidthResolved - _measuredWidth) / 2;
  492. return r;
  493. }
  494. throw new InvalidOperationException();
  495. }
  496. }
  497. /// <summary>
  498. /// Gets the actual measured overhang in each direction based on the
  499. /// fonts used, and the supplied text.
  500. /// </summary>
  501. /// <remarks>
  502. /// The return rectangle describes overhang amounts for each edge - not
  503. /// rectangle co-ordinates.
  504. /// </remarks>
  505. public SKRect MeasuredOverhang
  506. {
  507. get
  508. {
  509. Layout();
  510. if (!_leftOverhang.HasValue)
  511. {
  512. var right = _maxWidth ?? MeasuredWidth;
  513. float leftOverhang = 0;
  514. float rightOverhang = 0;
  515. foreach (var l in _lines)
  516. {
  517. l.UpdateOverhang(right, ref leftOverhang, ref rightOverhang);
  518. }
  519. _leftOverhang = leftOverhang;
  520. _rightOverhang = rightOverhang;
  521. }
  522. return new SKRect(_leftOverhang.Value, 0, _rightOverhang.Value, 0);
  523. }
  524. }
  525. /// <summary>
  526. /// Hit test this block of text
  527. /// </summary>
  528. /// <param name="lineIndex">The line to be hit test</param>
  529. /// <param name="x">The x-coordinate relative to top left of the block</param>
  530. /// <returns>A HitTestResult</returns>
  531. public HitTestResult HitTestLine(int lineIndex, float x)
  532. {
  533. return _lines[lineIndex].HitTest(x);
  534. }
  535. /// <summary>
  536. /// Hit test this block of text
  537. /// </summary>
  538. /// <param name="x">The x-coordinate relative to top left of the block</param>
  539. /// <param name="y">The x-coordinate relative to top left of the block</param>
  540. /// <returns>A HitTestResult</returns>
  541. public HitTestResult HitTest(float x, float y)
  542. {
  543. Layout();
  544. var htr = new HitTestResult();
  545. // Work out which line number we're over
  546. htr.OverLine = -1;
  547. htr.OverCodePointIndex = -1;
  548. for (int i = 0; i < _lines.Count; i++)
  549. {
  550. var l = _lines[i];
  551. if (y >= l.YCoord && y < l.YCoord + l.Height)
  552. {
  553. htr.OverLine = i;
  554. }
  555. }
  556. // Work out the closest line
  557. if (htr.OverLine >= 0)
  558. {
  559. htr.ClosestLine = htr.OverLine;
  560. }
  561. else if (y < 0)
  562. {
  563. htr.ClosestLine = 0;
  564. }
  565. else
  566. {
  567. htr.ClosestLine = _lines.Count - 1;
  568. }
  569. // Hit test each cluster
  570. if (htr.ClosestLine >= 0 && htr.ClosestLine < _lines.Count)
  571. {
  572. // Hit test the line
  573. var l = _lines[htr.ClosestLine];
  574. l.HitTest(x, ref htr);
  575. }
  576. // If we're not over the line, we're also not over the character
  577. if (htr.OverLine < 0)
  578. htr.OverCodePointIndex = -1;
  579. if (htr.ClosestCodePointIndex < 0)
  580. {
  581. if (htr.ClosestLine == _lines.Count - 1 && _lines.Count > 0)
  582. htr.ClosestCodePointIndex = _lines[_lines.Count - 1].End - 1;
  583. else
  584. htr.ClosestCodePointIndex = 0;
  585. }
  586. return htr;
  587. }
  588. /// <summary>
  589. /// Build map of all caret positions
  590. /// </summary>
  591. void BuildCaretIndicies()
  592. {
  593. Layout();
  594. if (_caretIndicies.Count == 0)
  595. {
  596. foreach (var r in _lines.SelectMany(x => x.Runs))
  597. {
  598. for (int i = 0; i < r.Clusters.Length; i++)
  599. {
  600. _caretIndicies.Add(r.Clusters[i]);
  601. }
  602. }
  603. _caretIndicies.Add(MeasuredLength);
  604. _caretIndicies = _caretIndicies.OrderBy(x => x).Distinct().ToList();
  605. }
  606. }
  607. /// <summary>
  608. /// Retrieves a list of all valid caret positions
  609. /// </summary>
  610. public IReadOnlyList<int> CaretIndicies
  611. {
  612. get
  613. {
  614. BuildCaretIndicies();
  615. return _caretIndicies;
  616. }
  617. }
  618. /// <summary>
  619. /// Retrieves a list of all valid caret positions
  620. /// </summary>
  621. public IReadOnlyList<int> WordBoundaryIndicies
  622. {
  623. get
  624. {
  625. // Find word boundaries (if not already done)
  626. if (_wordBoundaryIndicies.Count == 0)
  627. {
  628. _wordBoundaryIndicies = WordBoundaryAlgorithm.FindWordBoundaries(_codePoints.AsSlice()).ToList();
  629. }
  630. return _wordBoundaryIndicies;
  631. }
  632. }
  633. /// <summary>
  634. /// Retrieves a list of the indicies of the first code point in each line
  635. /// </summary>
  636. public IReadOnlyList<int> LineIndicies
  637. {
  638. get
  639. {
  640. return _lines.Select(x => x.Start).ToList();
  641. }
  642. }
  643. /// <summary>
  644. /// Given a code point index, find the index in the CaretIndicies
  645. /// </summary>
  646. /// <param name="codePointIndex">The code point index to lookup</param>
  647. /// <returns>The index in the code point idnex in the CaretIndicies array</returns>
  648. public int LookupCaretIndex(int codePointIndex)
  649. {
  650. BuildCaretIndicies();
  651. int index = _caretIndicies.BinarySearch(codePointIndex);
  652. if (index < 0)
  653. index = ~index;
  654. return index;
  655. }
  656. /// <summary>
  657. /// Calculates useful information for displaying a caret
  658. /// </summary>
  659. /// <remarks>
  660. /// When altPosition is true, if the code point index indicates the first
  661. /// code point after a line break, the returned caret position will be the
  662. /// end of the previous line (instead of the start of the next line)
  663. /// </remarks>
  664. /// <param name="position">The caret position</param>
  665. /// <returns>A CaretInfo struct</returns>
  666. public CaretInfo GetCaretInfo(CaretPosition position)
  667. {
  668. // Empty text block?
  669. if (_codePoints.Length == 0 || position.CodePointIndex < 0 || _lines.Count == 0)
  670. {
  671. return CaretInfo.None;
  672. }
  673. // Past the measured length?
  674. if (position.CodePointIndex > MeasuredLength)
  675. {
  676. return CaretInfo.None;
  677. }
  678. // Look up the caret index
  679. int cpii = LookupCaretIndex(position.CodePointIndex);
  680. // Create caret info
  681. var ci = new CaretInfo();
  682. ci.CodePointIndex = _caretIndicies[cpii];
  683. var frIndex = FindFontRunForCodePointIndex(position.CodePointIndex);
  684. FontRun fr = null;
  685. if (frIndex >= 0)
  686. {
  687. fr = _fontRuns[frIndex];
  688. if (fr.Start == position.CodePointIndex && frIndex > 0)
  689. {
  690. var frPrior = _fontRuns[frIndex - 1];
  691. if (frPrior.End == position.CodePointIndex)
  692. {
  693. if (position.AltPosition ||
  694. (frPrior.Direction == TextDirection.RTL &&
  695. frPrior.RunKind != FontRunKind.TrailingWhitespace))
  696. {
  697. fr = frPrior;
  698. }
  699. }
  700. }
  701. }
  702. else
  703. {
  704. var lastLine = _lines[_lines.Count - 1];
  705. if (lastLine.RunsInternal.Count > 0)
  706. fr = lastLine.RunsInternal[lastLine.RunsInternal.Count - 1];
  707. }
  708. if (fr == null)
  709. return CaretInfo.None;
  710. // Setup caret coordinates
  711. ci.CaretXCoord = ci.CodePointIndex < 0 ? 0 : fr.GetXCoordOfCodePointIndex(ci.CodePointIndex);
  712. ci.CaretRectangle = CalculateCaretRectangle(ci, fr);
  713. ci.LineIndex = _lines.IndexOf(fr.Line);
  714. return ci;
  715. }
  716. SKRect CalculateCaretRectangle(CaretInfo ci, FontRun fr)
  717. {
  718. if (ci.CodePointIndex < 0)
  719. return SKRect.Empty;
  720. // Get the font run to be used for caret metrics
  721. fr = GetFontRunForCaretMetrics(ci, fr);
  722. // Setup the basic rectangle
  723. var rect = new SKRect();
  724. rect.Left = ci.CaretXCoord;
  725. rect.Top = fr.Line.YCoord + fr.Line.BaseLine + fr.Ascent;
  726. rect.Right = rect.Left;
  727. rect.Bottom = fr.Line.YCoord + fr.Line.BaseLine + fr.Descent;
  728. // Apply slant if italic
  729. if (fr.Style.FontItalic)
  730. {
  731. rect.Left -= rect.Height / 14;
  732. rect.Right = rect.Left + rect.Height / 5;
  733. }
  734. return rect;
  735. }
  736. /// <summary>
  737. /// Internal helper to get the font run that should
  738. /// be used for caret metrics.
  739. /// </summary>
  740. /// <remarks>
  741. /// The returned font run is the font run of the previous
  742. /// character, or the same character if the first font run
  743. /// on the line.
  744. /// </remarks>
  745. /// <returns>The determined font run</returns>
  746. FontRun GetFontRunForCaretMetrics(CaretInfo ci, FontRun fr)
  747. {
  748. // Same font run?
  749. if (ci.CodePointIndex > fr.Start)
  750. return fr;
  751. // Try to get the previous font run in this line
  752. var lineRuns = fr.Line.Runs as List<FontRun>;
  753. int index = lineRuns.IndexOf(fr);
  754. if (index <= 0)
  755. return fr;
  756. // Use the previous font run
  757. return lineRuns[index - 1];
  758. }
  759. /// <summary>
  760. /// Find the font run holding a code point index
  761. /// </summary>
  762. /// <param name="codePointIndex"></param>
  763. /// <returns></returns>
  764. public int FindFontRunForCodePointIndex(int codePointIndex)
  765. {
  766. // Past end of text?
  767. if (codePointIndex > MeasuredLength)
  768. return -1;
  769. // Look up font run
  770. int frIndex = FontRuns.BinarySearch(codePointIndex, (run, value) =>
  771. {
  772. return (run.End - 1) - codePointIndex;
  773. });
  774. if (frIndex < 0)
  775. frIndex = ~frIndex;
  776. if (frIndex == _fontRuns.Count)
  777. frIndex = _fontRuns.Count - 1;
  778. if (frIndex < 0)
  779. return -1;
  780. // Return the font run
  781. var fr = _fontRuns[frIndex];
  782. System.Diagnostics.Debug.Assert(codePointIndex >= fr.Start);
  783. System.Diagnostics.Debug.Assert(codePointIndex <= fr.End);
  784. return frIndex;
  785. }
  786. /// <summary>
  787. /// Invalidate the layout
  788. /// </summary>
  789. void InvalidateLayout()
  790. {
  791. // Make sure style runs are valid (debug only)
  792. _styleRuns.CheckValid(_codePoints.Length);
  793. // Set layout flag
  794. _needsLayout = true;
  795. }
  796. /// <summary>
  797. /// Set if the current layout is dirty
  798. /// </summary>
  799. bool _needsLayout = true;
  800. /// <summary>
  801. /// Maximum width (wrap point, or null for no wrapping)
  802. /// </summary>
  803. float? _maxWidth;
  804. /// <summary>
  805. /// Width at which to wrap content
  806. /// </summary>
  807. float _maxWidthResolved = float.MaxValue;
  808. /// <summary>
  809. /// Maximum height (crop lines after this)
  810. /// </summary>
  811. float? _maxHeight;
  812. /// <summary>
  813. /// Maximum layout height
  814. /// </summary>
  815. float _maxHeightResolved = float.MaxValue;
  816. /// <summary>
  817. /// Maximum number of lines
  818. /// </summary>
  819. int? _maxLines;
  820. /// <summary>
  821. /// Maximum number of lines
  822. /// </summary>
  823. int _maxLinesResolved = int.MaxValue;
  824. /// <summary>
  825. /// Text alignment
  826. /// </summary>
  827. TextAlignment _textAlignment = TextAlignment.Auto;
  828. /// <summary>
  829. /// Base direction as set by user
  830. /// </summary>
  831. TextDirection _baseDirection = TextDirection.Auto;
  832. /// <summary>
  833. /// Base direction as resolved if auto
  834. /// </summary>
  835. TextDirection _resolvedBaseDirection;
  836. /// <summary>
  837. /// Re-usable buffers for text shaping results
  838. /// </summary>
  839. readonly TextShaper.ResultBufferSet _textShapingBuffers = new TextShaper.ResultBufferSet();
  840. /// <summary>
  841. /// Reusable buffer for bidi data
  842. /// </summary>
  843. readonly BidiData _bidiData = new BidiData();
  844. /// <summary>
  845. /// A list of font runs, after splitting by directionality, user styles and font fallback
  846. /// </summary>
  847. readonly List<FontRun> _fontRuns = new List<FontRun>();
  848. /// <summary>
  849. /// Helper for splitting code into linebreaks
  850. /// </summary>
  851. readonly LineBreaker _lineBreaker = new LineBreaker();
  852. /// <summary>
  853. /// The measured height
  854. /// </summary>
  855. float _measuredHeight;
  856. /// <summary>
  857. /// The measured width
  858. /// </summary>
  859. float _measuredWidth;
  860. /// <summary>
  861. /// The required left overhang
  862. /// </summary>
  863. float? _leftOverhang = null;
  864. /// <summary>
  865. /// The required left overhang
  866. /// </summary>
  867. float? _rightOverhang = null;
  868. /// <summary>
  869. /// Indicates if the text was truncated by max height/max lines limitations
  870. /// </summary>
  871. bool _truncated;
  872. /// <summary>
  873. /// The final laid out set of lines
  874. /// </summary>
  875. List<TextLine> _lines = new List<TextLine>();
  876. /// <summary>
  877. /// Calculated valid caret indicies
  878. /// </summary>
  879. List<int> _caretIndicies = new List<int>();
  880. /// <summary>
  881. /// Calculated word boundary caret indicies
  882. /// </summary>
  883. List<int> _wordBoundaryIndicies = new List<int>();
  884. /// <summary>
  885. /// Resolve the text alignment when set to Auto
  886. /// </summary>
  887. /// <returns>Resolved text alignment (left, right or center)</returns>
  888. internal TextAlignment ResolveTextAlignment()
  889. {
  890. if (_textAlignment == TextAlignment.Auto)
  891. return _resolvedBaseDirection == TextDirection.LTR ? TextAlignment.Left : TextAlignment.Right;
  892. else
  893. return _textAlignment;
  894. }
  895. // Use the shared Bidi algo instance
  896. readonly Bidi _bidi = Bidi.Instance.Value;
  897. /// <summary>
  898. /// Split into runs based on directionality and style switch points
  899. /// </summary>
  900. void BuildFontRuns()
  901. {
  902. var originalLength = _codePoints.Length;
  903. try
  904. {
  905. // Clearn unshaped run buffer
  906. _unshapedRuns.Clear();
  907. // Break supplied text into directionality runs
  908. _bidiData.Init(_codePoints.AsSlice(), (sbyte)_baseDirection);
  909. // If we have embedded directional overrides then change those
  910. // ranges to neutral
  911. if (_hasTextDirectionOverrides)
  912. {
  913. // Save types
  914. _bidiData.SaveTypes();
  915. for (int i = 0; i < _styleRuns.Count; i++)
  916. {
  917. // Get the run
  918. var sr = _styleRuns[i];
  919. // Does it have a direction override?
  920. if (sr.Style.TextDirection == TextDirection.Auto)
  921. continue;
  922. // Change the range to neutral with no brackets
  923. _bidiData.Types.SubSlice(sr.Start, sr.Length).Fill(Directionality.ON);
  924. _bidiData.PairedBracketTypes.SubSlice(sr.Start, sr.Length).Fill(PairedBracketType.n);
  925. }
  926. }
  927. // Process bidi
  928. _bidi.Process(_bidiData);
  929. var resolvedLevels = _bidi.ResolvedLevels;
  930. // Get resolved direction
  931. _resolvedBaseDirection = (TextDirection)_bidi.ResolvedParagraphEmbeddingLevel;
  932. // Now process the embedded runs
  933. if (_hasTextDirectionOverrides)
  934. {
  935. // Restore types
  936. _bidiData.RestoreTypes();
  937. // Process each run individually
  938. for (int i = 0; i < _styleRuns.Count; i++)
  939. {
  940. // Get the run
  941. var sr = _styleRuns[i];
  942. // Does it have a direction override?
  943. if (sr.Style.TextDirection == TextDirection.Auto)
  944. continue;
  945. // Get the style run bidi data
  946. var types = _bidiData.Types.SubSlice(sr.Start, sr.Length);
  947. var pbts = _bidiData.PairedBracketTypes.SubSlice(sr.Start, sr.Length);
  948. var pbvs = _bidiData.PairedBracketValues.SubSlice(sr.Start, sr.Length);
  949. // Get a temp buffer to store the results
  950. // (We can't use the Bidi's built in buffer because we're about to patch it)
  951. var levels = _bidiData.GetTempLevelBuffer(sr.Length);
  952. // Process this style run
  953. _bidi.Process(types, pbts, pbvs, (sbyte)sr.Style.TextDirection, _bidiData.HasBrackets, _bidiData.HasEmbeddings, _bidiData.HasIsolates, levels);
  954. // Copy result levels back to the full level set
  955. resolvedLevels.SubSlice(sr.Start, sr.Length).Set(levels);
  956. }
  957. }
  958. // Get the list of directional runs
  959. var bidiRuns = BidiRun.CoalescLevels(resolvedLevels).ToList();
  960. // Split...
  961. var pos = 0;
  962. int bidiRun = 0;
  963. int styleRun = 0;
  964. while (pos < _codePoints.Length)
  965. {
  966. // Move to next bidi/style run
  967. if (pos == bidiRuns[bidiRun].End)
  968. bidiRun++;
  969. if (pos == _styleRuns[styleRun].End)
  970. styleRun++;
  971. // Work out where this run ends
  972. int nextPos = Math.Min(bidiRuns[bidiRun].End, _styleRuns[styleRun].End);
  973. // Add the run
  974. var dir = bidiRuns[bidiRun].Direction == Directionality.L ? TextDirection.LTR : TextDirection.RTL;
  975. AddDirectionalRun(_styleRuns[styleRun], pos, nextPos - pos, dir, _styleRuns[styleRun].Style);
  976. // Move to next position
  977. pos = nextPos;
  978. }
  979. System.Diagnostics.Debug.Assert(bidiRun == bidiRuns.Count - 1);
  980. System.Diagnostics.Debug.Assert(styleRun == _styleRuns.Count - 1);
  981. // Add the final run
  982. var dir2 = bidiRuns[bidiRun].Direction == Directionality.L ? TextDirection.LTR : TextDirection.RTL;
  983. AddDirectionalRun(_styleRuns[_styleRuns.Count - 1], pos, _codePoints.Length - pos, dir2, _styleRuns[styleRun].Style);
  984. // Flush runs
  985. FlushUnshapedRuns();
  986. }
  987. catch (Exception x)
  988. {
  989. throw new InvalidOperationException($"Exception in BuildFontRuns() with original length of {originalLength} now {_codePoints.Length}, style run count {_styleRuns.Count}, font run count {_fontRuns.Count}, direction overrides: {_hasTextDirectionOverrides}", x);
  990. }
  991. }
  992. /// <summary>
  993. /// Gets the Skia type face for a IStyle
  994. /// </summary>
  995. /// <param name="style">The style</param>
  996. /// <param name="ignoreFontVariants">When true, doesn't embolden super/sub scripts</param>
  997. /// <returns>The Skia typeface</returns>
  998. SKTypeface TypefaceFromStyle(IStyle style, bool ignoreFontVariants = false)
  999. {
  1000. return (FontMapper ?? FontMapper.Default).TypefaceFromStyle(style, ignoreFontVariants);
  1001. }
  1002. /// <summary>
  1003. /// Gets or sets the font mapper to be used by this TextBlock instance
  1004. /// </summary>
  1005. /// <remarks>
  1006. /// When null, the default font mapper (FontMapper.Default) is used.
  1007. /// </remarks>
  1008. public FontMapper FontMapper
  1009. {
  1010. get;
  1011. set;
  1012. }
  1013. /// <summary>
  1014. /// Adds a run of directional text
  1015. /// </summary>
  1016. /// <param name="styleRun">The style run the directional run was created from</param>
  1017. /// <param name="start">Index of the first code point _codePoints buffer</param>
  1018. /// <param name="length">Number of code points in this run</param>
  1019. /// <param name="direction">The direction of the text</param>
  1020. /// <param name="style">The user supplied style for this run</param>
  1021. void AddDirectionalRun(StyleRun styleRun, int start, int length, TextDirection direction, IStyle style)
  1022. {
  1023. // Quit if redundant...
  1024. if (length == 0)
  1025. return;
  1026. // Get the typeface
  1027. var typeface = TypefaceFromStyle(style);
  1028. // Get the slice of code points
  1029. var codePointsSlice = _codePoints.SubSlice(start, length);
  1030. // Split into font fallback runs
  1031. foreach (var fontRun in FontFallback.GetFontRuns(codePointsSlice, typeface, style.ReplacementCharacter))
  1032. {
  1033. // Add this run
  1034. AddFontRun(styleRun, start + fontRun.Start, fontRun.Length, direction, style, fontRun.Typeface, typeface);
  1035. }
  1036. }
  1037. /// <summary>
  1038. /// Adds a run of single font text
  1039. /// </summary>
  1040. /// <param name="styleRun">The style run the directional run was created from</param>
  1041. /// <param name="start">Index of the first code point _codePoints buffer</param>
  1042. /// <param name="length">Number of code points in this run</param>
  1043. /// <param name="direction">The direction of the text</param>
  1044. /// <param name="style">The user supplied style for this run</param>
  1045. /// <param name="typeface">The typeface of the run</param>
  1046. /// <param name="asFallbackFor">The typeface this is a fallback for</param>
  1047. void AddFontRun(StyleRun styleRun, int start, int length, TextDirection direction, IStyle style, SKTypeface typeface, SKTypeface asFallbackFor)
  1048. {
  1049. // Coalesc added font runs such that those with the exact same font, direction etc... are
  1050. // all shaped together such that kerning is correct for the entire run - regardless of
  1051. // non-typographic style changes (eg: underline, color etc...).
  1052. var usr = new UnshapedRun()
  1053. {
  1054. styleRun = styleRun,
  1055. start = start,
  1056. length = length,
  1057. direction = direction,
  1058. style = style,
  1059. typeface = typeface,
  1060. asFallbackFor = asFallbackFor,
  1061. };
  1062. // If this run can't be shaped with the previous one then flush those accumlated so far
  1063. if (_unshapedRuns.Count > 0 && !_unshapedRuns[_unshapedRuns.Count - 1].CanShapeWith(usr))
  1064. {
  1065. FlushUnshapedRuns();
  1066. }
  1067. // Store it for now, actually shape it once we determine the next run is really
  1068. // a different font
  1069. _unshapedRuns.Add(usr);
  1070. }
  1071. void FlushUnshapedRuns()
  1072. {
  1073. // Quit if nothing to do?
  1074. if (_unshapedRuns.Count == 0)
  1075. return;
  1076. if (_unshapedRuns.Count == 1)
  1077. {
  1078. // If there's only one accumulated shape run then we can shape and add it directly
  1079. var usr = _unshapedRuns[0];
  1080. _fontRuns.Add(CreateFontRun(usr.styleRun, _codePoints.SubSlice(usr.start, usr.length), usr.direction, usr.style, usr.typeface, usr.asFallbackFor));
  1081. }
  1082. else
  1083. {
  1084. // There are multiple styled runs, but they're all using the exact same type face
  1085. // so shape them all together to maintain correct kerning, but then break them
  1086. // apart so they're rendered separately with correct style for each piece.
  1087. var first = _unshapedRuns[0];
  1088. var last = _unshapedRuns[_unshapedRuns.Count - 1];
  1089. var spanningRun = CreateFontRun(first.styleRun, _codePoints.SubSlice(first.start, last.start + last.length - first.start), first.direction, first.style, first.typeface, first.asFallbackFor);
  1090. for (int i = 1; i < _unshapedRuns.Count; i++)
  1091. {
  1092. var newRun = spanningRun.Split(_unshapedRuns[i].start);
  1093. spanningRun.StyleRun = _unshapedRuns[i - 1].styleRun;
  1094. spanningRun.Style = _unshapedRuns[i - 1].style;
  1095. _fontRuns.Add(spanningRun);
  1096. spanningRun = newRun;
  1097. }
  1098. spanningRun.StyleRun = _unshapedRuns[_unshapedRuns.Count-1].styleRun;
  1099. spanningRun.Style = _unshapedRuns[_unshapedRuns.Count-1].style;
  1100. _fontRuns.Add(spanningRun);
  1101. }
  1102. _unshapedRuns.Clear();
  1103. }
  1104. List<UnshapedRun> _unshapedRuns = new List<UnshapedRun>();
  1105. class UnshapedRun
  1106. {
  1107. public StyleRun styleRun;
  1108. public int start;
  1109. public int length;
  1110. public TextDirection direction;
  1111. public IStyle style;
  1112. public SKTypeface typeface;
  1113. public SKTypeface asFallbackFor;
  1114. // Check if this unshaped run can be shaped with the next one
  1115. public bool CanShapeWith(UnshapedRun next)
  1116. {
  1117. return typeface == next.typeface &&
  1118. style.FontSize == next.style.FontSize &&
  1119. asFallbackFor == next.asFallbackFor &&
  1120. direction == next.direction &&
  1121. start + length == next.start;
  1122. }
  1123. }
  1124. /// <summary>
  1125. /// Helper to create a font run
  1126. /// </summary>
  1127. /// <param name="styleRun">The style run owning this font run</param>
  1128. /// <param name="codePoints">The code points of the run</param>
  1129. /// <param name="direction">The run direction</param>
  1130. /// <param name="style">The user supplied style for this run</param>
  1131. /// <param name="typeface">The typeface of the run</param>
  1132. /// <param name="asFallbackFor">The original typeface this is a fallback for</param>
  1133. /// <returns>A FontRun</returns>
  1134. FontRun CreateFontRun(StyleRun styleRun, Slice<int> codePoints, TextDirection direction, IStyle style, SKTypeface typeface, SKTypeface asFallbackFor)
  1135. {
  1136. // Shape the text
  1137. var shaper = TextShaper.ForTypeface(typeface);
  1138. TextShaper.Result shaped;
  1139. if (style.ReplacementCharacter == '\0')
  1140. shaped = shaper.Shape(_textShapingBuffers, codePoints, style, direction, codePoints.Start, asFallbackFor, ResolveTextAlignment());
  1141. else
  1142. shaped = shaper.ShapeReplacement(_textShapingBuffers, codePoints, style, codePoints.Start);
  1143. // Create the run
  1144. var fontRun = FontRun.Pool.Value.Get();
  1145. fontRun.StyleRun = styleRun;
  1146. fontRun.CodePointBuffer = _codePoints;
  1147. fontRun.Start = codePoints.Start;
  1148. fontRun.Length = codePoints.Length;
  1149. fontRun.Style = style;
  1150. fontRun.Direction = direction;
  1151. fontRun.Typeface = typeface;
  1152. fontRun.Glyphs = shaped.GlyphIndicies;
  1153. fontRun.GlyphPositions = shaped.GlyphPositions;
  1154. fontRun.RelativeCodePointXCoords = shaped.CodePointXCoords;
  1155. fontRun.Clusters = shaped.Clusters;
  1156. fontRun.Ascent = shaped.Ascent;
  1157. fontRun.Descent = shaped.Descent;
  1158. fontRun.Leading = shaped.Leading;
  1159. fontRun.Width = shaped.EndXCoord.X;
  1160. return fontRun;
  1161. }
  1162. // ATZ
  1163. public bool WordWrap { get; set; } = true;
  1164. /// <summary>
  1165. /// Break the list of font runs into lines
  1166. /// </summary>
  1167. void BreakLines()
  1168. {
  1169. // Work out possible line break positions
  1170. _lineBreaker.Reset(_codePoints.AsSlice());
  1171. var lineBreakPositions = _lineBreaker.GetBreaks(!WordWrap);// !_maxWidth.HasValue);
  1172. int frIndexStartOfLine = 0; // Index of the first font run in the current line
  1173. int frIndex = 0; // Index of the current font run
  1174. int lbrIndex = 0; // Index of the next unconsumed linebreak
  1175. float consumedWidth = 0; // Total width of all font runs placed on this line
  1176. int frSplitIndex = -1; // Index of the last font run that contained fitting break point
  1177. int codePointIndexSplit = -1; // Code point index of the last fitting break point measure position
  1178. int codePointIndexWrap = -1; // Code point index of the last fitting breaj point wrap position
  1179. if (!CheckHeightConstraints())
  1180. return;
  1181. while (frIndex < _fontRuns.Count)
  1182. {
  1183. // Get the font run, update it's position
  1184. // and move to next
  1185. var fr = _fontRuns[frIndex];
  1186. fr.XCoord = consumedWidth;
  1187. consumedWidth += fr.Width;
  1188. // ATZ: handle tabs
  1189. if (fr.Length == 1 && fr.CodePoints[0] == '\t')
  1190. {
  1191. float offs = GetTabStopPositionOffset(consumedWidth);
  1192. fr.Width += offs;
  1193. fr.RunKind = FontRunKind.TrailingWhitespace;
  1194. consumedWidth += offs;
  1195. }
  1196. float totalWidthToThisBreakPoint = 0;
  1197. // Skip line breaks
  1198. bool breakLine = false;
  1199. while (lbrIndex < lineBreakPositions.Count)
  1200. {
  1201. // Past this run?
  1202. var lbr = lineBreakPositions[lbrIndex];
  1203. if (lbr.PositionMeasure < fr.Start)
  1204. {
  1205. lbrIndex++;
  1206. continue;
  1207. }
  1208. if (lbr.PositionMeasure >= fr.End)
  1209. break;
  1210. // Do we need to break
  1211. totalWidthToThisBreakPoint = fr.XCoord + fr.LeadingWidth(lbr.PositionMeasure);
  1212. if (totalWidthToThisBreakPoint > _maxWidthResolved)
  1213. {
  1214. breakLine = true;
  1215. break;
  1216. }
  1217. // It fits, remember that
  1218. lbrIndex++;
  1219. // Only mark that we have something that fits if we actually know something has (or will be) been consumed
  1220. if (totalWidthToThisBreakPoint > 0 || lbr.PositionWrap > lbr.PositionMeasure)
  1221. {
  1222. frSplitIndex = frIndex;
  1223. codePointIndexSplit = lbr.PositionMeasure;
  1224. codePointIndexWrap = lbr.PositionWrap;
  1225. }
  1226. if (lbr.Required)
  1227. {
  1228. breakLine = true;
  1229. break;
  1230. }
  1231. }
  1232. // If we're on the last run and we've exceeded the width limit then force a break
  1233. if (!breakLine && frIndex + 1 == _fontRuns.Count && consumedWidth > _maxWidthResolved && WordWrap)
  1234. breakLine = true;
  1235. // Break the line here?
  1236. if (!breakLine)
  1237. {
  1238. frIndex++;
  1239. continue;
  1240. }
  1241. // If there wasn't a line break anywhere in the line, then we need to force one
  1242. // on a character boundary. Also do this is we know we're on the last available line.
  1243. if (frSplitIndex < 0 || (_maxLines.HasValue && _lines.Count == _maxLines.Value - 1))
  1244. {
  1245. // Get the last run that partially fitted
  1246. frIndex = frIndexStartOfLine;
  1247. fr = _fontRuns[frIndex];
  1248. var room = _maxWidthResolved - fr.XCoord;
  1249. frSplitIndex = frIndex;
  1250. codePointIndexSplit = fr.FindBreakPosition(room, frSplitIndex == frIndexStartOfLine);
  1251. codePointIndexWrap = codePointIndexSplit;
  1252. while (codePointIndexWrap < _codePoints.Length && UnicodeClasses.LineBreakClass(_codePoints[codePointIndexWrap]) == LineBreakClass.SP)
  1253. codePointIndexWrap++;
  1254. }
  1255. // Split it
  1256. fr = _fontRuns[frSplitIndex];
  1257. if (codePointIndexSplit == fr.Start)
  1258. {
  1259. // Split exactly before the run
  1260. }
  1261. else if (codePointIndexSplit == fr.End)
  1262. {
  1263. // Split exactly after the run
  1264. frSplitIndex++;
  1265. }
  1266. else
  1267. {
  1268. // Split in the middle of the run
  1269. frSplitIndex++;
  1270. _fontRuns.Insert(frSplitIndex, fr.Split(codePointIndexSplit));
  1271. }
  1272. // Trailing whitespace
  1273. int frTrailingWhiteSpaceIndex = frSplitIndex;
  1274. while (frTrailingWhiteSpaceIndex < _fontRuns.Count && _fontRuns[frTrailingWhiteSpaceIndex].Start < codePointIndexWrap)
  1275. {
  1276. if (codePointIndexWrap < _fontRuns[frTrailingWhiteSpaceIndex].End)
  1277. {
  1278. var fr2 = _fontRuns[frTrailingWhiteSpaceIndex].Split(codePointIndexWrap);
  1279. _fontRuns.Insert(frTrailingWhiteSpaceIndex + 1, fr2);
  1280. }
  1281. frTrailingWhiteSpaceIndex++;
  1282. }
  1283. // Build the final line
  1284. BuildLine(frIndexStartOfLine, frSplitIndex, frTrailingWhiteSpaceIndex);
  1285. // Reset for the next line
  1286. frSplitIndex = -1;
  1287. frIndex = frTrailingWhiteSpaceIndex;
  1288. frIndexStartOfLine = frIndex;
  1289. consumedWidth = 0;
  1290. // Check height constraints and quit if finished
  1291. if (!CheckHeightConstraints())
  1292. return;
  1293. }
  1294. // Build the final line
  1295. if (frIndexStartOfLine < _fontRuns.Count)
  1296. {
  1297. BuildLine(frIndexStartOfLine, _fontRuns.Count, _fontRuns.Count);
  1298. CheckHeightConstraints();
  1299. }
  1300. }
  1301. /// <summary>
  1302. /// Construct a single line from the specified font run indicies
  1303. /// </summary>
  1304. /// <param name="frIndexStartOfLine">Index of the first font run in the line</param>
  1305. /// <param name="frSplitIndex">Index of the last type</param>
  1306. /// <param name="frTrailingWhiteSpaceIndex"></param>
  1307. void BuildLine(int frIndexStartOfLine, int frSplitIndex, int frTrailingWhiteSpaceIndex)
  1308. {
  1309. // Create the line
  1310. var line = TextLine.Pool.Value.Get();
  1311. line.TextBlock = this;
  1312. line.YCoord = _measuredHeight;
  1313. // Add runs
  1314. for (int i = frIndexStartOfLine; i < frTrailingWhiteSpaceIndex; i++)
  1315. {
  1316. // Tag trailing whitespace appropriately
  1317. if (i >= frSplitIndex)
  1318. {
  1319. var fr = _fontRuns[i];
  1320. fr.RunKind = FontRunKind.TrailingWhitespace;
  1321. if (fr.Direction != _resolvedBaseDirection)
  1322. {
  1323. // What is this a fallback for?
  1324. var asFallbackFor = TypefaceFromStyle(fr.Style, false);
  1325. // Create a new font run over the same text span but using the base direction
  1326. _fontRuns[i] = CreateFontRun(fr.StyleRun, fr.CodePoints, _resolvedBaseDirection, fr.Style, fr.Typeface, asFallbackFor);
  1327. }
  1328. }
  1329. line.RunsInternal.Add(_fontRuns[i]);
  1330. }
  1331. // Add the line to the collection
  1332. _lines.Add(line);
  1333. // Lay it out
  1334. LayoutLine(line);
  1335. // Update y position
  1336. _measuredHeight += line.Height;
  1337. }
  1338. /// <summary>
  1339. /// Layout the font runs within a line
  1340. /// </summary>
  1341. /// <param name="line">The line to layout</param>
  1342. void LayoutLine(TextLine line)
  1343. {
  1344. // How much to x-adjust all runs by to position correctly
  1345. float xAdjust;
  1346. // Which direction?
  1347. if (_resolvedBaseDirection == TextDirection.LTR)
  1348. {
  1349. xAdjust = LayoutLineLTR(line);
  1350. }
  1351. else
  1352. {
  1353. /*
  1354. if (_useMSWordStyleRtlLayout)
  1355. {
  1356. xAdjust = LayoutLineRTLWordStyle(line);
  1357. }
  1358. else
  1359. */
  1360. {
  1361. xAdjust = LayoutLineRTL(line);
  1362. }
  1363. }
  1364. // Process all runs, setting their final left-aligned x-position and
  1365. // calculating metrics for the line as a whole
  1366. float maxAbove = 0;
  1367. float maxBelow = 0;
  1368. float maxAscent = 0;
  1369. float maxDescent = 0;
  1370. for (int frIndex = 0; frIndex < line.Runs.Count; frIndex++)
  1371. {
  1372. // Get the run
  1373. var fr = line.Runs[frIndex];
  1374. // Adjust run position
  1375. fr.XCoord += xAdjust;
  1376. var above = -fr.Ascent + fr.HalfLeading;
  1377. var below = fr.Descent + fr.HalfLeading;
  1378. if (above > maxAbove)
  1379. maxAbove = above;
  1380. if (below > maxBelow)
  1381. maxBelow = below;
  1382. if (fr.Ascent < maxAscent)
  1383. maxAscent = fr.Ascent;
  1384. if (fr.Descent > maxDescent)
  1385. maxDescent = fr.Descent;
  1386. }
  1387. // Store line metrics
  1388. line.MaxAscent = maxAscent;
  1389. line.MaxDescent = maxDescent;
  1390. line.Height = maxAbove + maxBelow;
  1391. line.BaseLine = maxAbove;
  1392. }
  1393. /// <summary>
  1394. /// Layout a line (LTR edition)
  1395. /// </summary>
  1396. /// <param name="line">The line to be laid out</param>
  1397. /// <returns>A final x-adjustment to be applied to the line's font runs</returns>
  1398. private float LayoutLineLTR(TextLine line)
  1399. {
  1400. float x = 0;
  1401. float trailingWhitespaceWidth = 0;
  1402. for (int i = 0; i < line.Runs.Count; i++)
  1403. {
  1404. var fr = line.Runs[i];
  1405. if (fr.Direction == TextDirection.LTR)
  1406. {
  1407. fr.XCoord = x;
  1408. x += fr.Width;
  1409. if (fr.RunKind == FontRunKind.TrailingWhitespace)
  1410. trailingWhitespaceWidth += fr.Width;
  1411. }
  1412. else
  1413. {
  1414. System.Diagnostics.Debug.Assert(fr.RunKind == FontRunKind.Normal);
  1415. int j = i;
  1416. while (j + 1 < line.Runs.Count && line.Runs[j + 1].Direction == TextDirection.RTL)
  1417. j++;
  1418. int continueFrom = j;
  1419. while (j >= i)
  1420. {
  1421. fr = line.Runs[j];
  1422. fr.XCoord = x;
  1423. x += fr.Width;
  1424. j--;
  1425. }
  1426. i = continueFrom;
  1427. }
  1428. }
  1429. // Store content width
  1430. line.Width = x - trailingWhitespaceWidth;
  1431. return 0;
  1432. }
  1433. /// <summary>
  1434. /// Layout a line (RTL edition)
  1435. /// </summary>
  1436. /// <param name="line">The line to be laid out</param>
  1437. /// <returns>A final x-adjustment to be applied to the line's font runs</returns>
  1438. private float LayoutLineRTL(TextLine line)
  1439. {
  1440. float x = 0;
  1441. float trailingWhitespaceWidth = 0;
  1442. for (int i = 0; i < line.Runs.Count; i++)
  1443. {
  1444. var fr = line.Runs[i];
  1445. if (fr.Direction == TextDirection.RTL)
  1446. {
  1447. x -= fr.Width;
  1448. fr.XCoord = x;
  1449. if (fr.RunKind == FontRunKind.TrailingWhitespace)
  1450. trailingWhitespaceWidth += fr.Width;
  1451. }
  1452. else
  1453. {
  1454. System.Diagnostics.Debug.Assert(fr.RunKind == FontRunKind.Normal);
  1455. int j = i;
  1456. while (j + 1 < line.Runs.Count && line.Runs[j + 1].Direction == TextDirection.LTR)
  1457. j++;
  1458. int continueFrom = j;
  1459. while (j >= i)
  1460. {
  1461. fr = line.Runs[j];
  1462. x -= fr.Width;
  1463. fr.XCoord = x;
  1464. j--;
  1465. }
  1466. i = continueFrom;
  1467. }
  1468. }
  1469. // Work out final width
  1470. float totalWidth = -x - trailingWhitespaceWidth;
  1471. // Store content width
  1472. line.Width = totalWidth;
  1473. // Everything is currently laid out from 0 to the left, so we
  1474. // need to shift right to make it left aligned
  1475. return totalWidth;
  1476. }
  1477. /// <summary>
  1478. /// Layout a line (MS Word RTL edition)
  1479. /// </summary>
  1480. /// <param name="line">The line to be laid out</param>
  1481. /// <returns>A final x-adjustment to be applied to the line's font runs</returns>
  1482. private float LayoutLineRTLWordStyle(TextLine line)
  1483. {
  1484. float xPos = 0;
  1485. float totalWidth = 0;
  1486. float trailingWhitespaceWidth = 0;
  1487. for (int i = 0; i < line.Runs.Count; i++)
  1488. {
  1489. // Get the direction of this group
  1490. var groupDirection = line.Runs[i].Direction;
  1491. // Count the number of runs with the same directionality
  1492. int j = i;
  1493. float groupWidth = 0;
  1494. while (j < line.Runs.Count && line.Runs[j].Direction == groupDirection)
  1495. {
  1496. if (line.Runs[i].RunKind == FontRunKind.TrailingWhitespace)
  1497. trailingWhitespaceWidth += line.Runs[i].Width;
  1498. groupWidth += line.Runs[j].Width;
  1499. j++;
  1500. }
  1501. totalWidth += groupWidth;
  1502. // How many runs in the group
  1503. var runsInGroup = j - i;
  1504. // Place the runs in the group
  1505. if (groupDirection == TextDirection.LTR)
  1506. {
  1507. // Left to right group
  1508. for (; i < j; i++)
  1509. {
  1510. line.Runs[i].XCoord = xPos;
  1511. xPos += line.Runs[i].Width;
  1512. }
  1513. }
  1514. else
  1515. {
  1516. // Right to left group
  1517. xPos += groupWidth;
  1518. var x = xPos;
  1519. for (; i < j; i++)
  1520. {
  1521. x -= line.Runs[i].Width;
  1522. line.Runs[i].XCoord = x;
  1523. }
  1524. }
  1525. i = j - 1;
  1526. }
  1527. line.Width = xPos - trailingWhitespaceWidth;
  1528. return _maxWidthResolved - (xPos - trailingWhitespaceWidth);
  1529. }
  1530. /// <summary>
  1531. /// Finalize lines, positioning for horizontal alignment and
  1532. /// moving all glyphs into position (relative to the text block top left)
  1533. /// </summary>
  1534. void FinalizeLines()
  1535. {
  1536. // Work out the measured width
  1537. foreach (var l in _lines)
  1538. {
  1539. if (l.Width > _measuredWidth)
  1540. _measuredWidth = l.Width;
  1541. }
  1542. var ta = ResolveTextAlignment();
  1543. foreach (var line in _lines)
  1544. {
  1545. // Work out x-alignement adjust for this line
  1546. float xAdjust = 0;
  1547. switch (ta)
  1548. {
  1549. case TextAlignment.Right:
  1550. xAdjust = (_maxWidth ?? _measuredWidth) - line.Width;
  1551. break;
  1552. case TextAlignment.Center:
  1553. xAdjust = ((_maxWidth ?? _measuredWidth) - line.Width) / 2;
  1554. break;
  1555. }
  1556. // Position each run
  1557. for (int frIndex = 0; frIndex < line.Runs.Count; frIndex++)
  1558. {
  1559. var fr = line.Runs[frIndex];
  1560. fr.Line = line;
  1561. fr.XCoord += xAdjust;
  1562. fr.MoveGlyphs(fr.XCoord, line.YCoord + line.BaseLine);
  1563. }
  1564. }
  1565. // Remove the font runs that weren't assigned to a line because the text
  1566. // was truncated
  1567. while (_fontRuns.Count > 0 && _fontRuns[_fontRuns.Count-1].Line == null)
  1568. {
  1569. _fontRuns.RemoveAt(_fontRuns.Count - 1);
  1570. }
  1571. }
  1572. /// <summary>
  1573. /// Finds the font run containing a specified code point index
  1574. /// </summary>
  1575. /// <param name="from">The font run index to start from</param>
  1576. /// <param name="codePointIndex">The code point index being searched for</param>
  1577. /// <returns>The index of the font run containing the specified code point
  1578. /// index, or font run count if past the end</returns>
  1579. int FindFontRunForCodePointIndex(int from, int codePointIndex)
  1580. {
  1581. int frIndex = from;
  1582. while (true)
  1583. {
  1584. var fr = _fontRuns[frIndex];
  1585. if (codePointIndex < fr.Start)
  1586. {
  1587. System.Diagnostics.Debug.Assert(frIndex > 0);
  1588. frIndex--;
  1589. }
  1590. else if (codePointIndex >= fr.End)
  1591. {
  1592. frIndex++;
  1593. if (frIndex == _fontRuns.Count)
  1594. {
  1595. System.Diagnostics.Debug.Assert(codePointIndex == _codePoints.Length);
  1596. return _codePoints.Length;
  1597. }
  1598. }
  1599. else
  1600. {
  1601. return frIndex;
  1602. }
  1603. }
  1604. }
  1605. /// <summary>
  1606. /// Re-usable buffer holding just the ellipsis character
  1607. /// </summary>
  1608. static Utf32Buffer ellipsis = new Utf32Buffer("…");
  1609. /// <summary>
  1610. /// Create a special font run containing the ellipsis character
  1611. /// based on an existing run
  1612. /// </summary>
  1613. /// <param name="basedOn">The run to base the styling on</param>
  1614. /// <returns>A new font run containing the ellipsis character</returns>
  1615. FontRun CreateEllipsisRun(FontRun basedOn)
  1616. {
  1617. // Get the type face
  1618. var typeface = TypefaceFromStyle(basedOn.Style, true);
  1619. // Split into font fallback runs (there should only ever be just one)
  1620. var fontRun = FontFallback.GetFontRuns(ellipsis.AsSlice(), typeface).Single();
  1621. // Create the new run and mark is as a special run type for ellipsis
  1622. var fr = CreateFontRun(basedOn.StyleRun, ellipsis.SubSlice(fontRun.Start, fontRun.Length), _resolvedBaseDirection, basedOn.Style, fontRun.Typeface, typeface);
  1623. fr.RunKind = FontRunKind.Ellipsis;
  1624. // Done
  1625. return fr;
  1626. }
  1627. /// <summary>
  1628. /// Update the current line with a new font run containing the trailing ellipsis
  1629. /// </summary>
  1630. /// <param name="line">The line to be updated</param>
  1631. /// <param name="postLayout">True if the ellipsis is being added post layout via a user call to AddEllipsis()</param>
  1632. void AdornLineWithEllipsis(TextLine line, bool postLayout = false)
  1633. {
  1634. // ATZ
  1635. if (!AllowEllipsis)
  1636. return;
  1637. var lastRun = line.Runs[line.Runs.Count - 1];
  1638. // Don't add ellipsis if the last run actually
  1639. // has all the text...
  1640. if (!postLayout && lastRun.End == _codePoints.Length)
  1641. return;
  1642. // Remove all trailing whitespace from the line
  1643. for (int i = line.Runs.Count - 1; i >= 0; i--)
  1644. {
  1645. var r = line.Runs[i];
  1646. if (r.RunKind == FontRunKind.TrailingWhitespace)
  1647. {
  1648. line.RunsInternal.RemoveAt(i);
  1649. if (postLayout)
  1650. {
  1651. _fontRuns.Remove(r);
  1652. }
  1653. }
  1654. }
  1655. // Calculate the total width of the line
  1656. float totalWidth = 0;
  1657. for (int i = 0; i < line.Runs.Count; i++)
  1658. {
  1659. totalWidth += line.Runs[i].Width;
  1660. }
  1661. // Get the new last run (if any)
  1662. if (line.Runs.Count> 0)
  1663. lastRun = line.Runs[line.Runs.Count - 1];
  1664. // Create a new run for the ellipsis
  1665. var ellipsisRun = CreateEllipsisRun(lastRun);
  1666. // Work out how much room we've got. If this is user request
  1667. // to append the ellipsis and MaxWidth isn't set then make sure
  1668. // we don't change our previously measured width be using that
  1669. // previous measurement as the limit
  1670. var maxWidth = _maxWidthResolved;
  1671. var removeWidth = totalWidth + ellipsisRun.Width - maxWidth;
  1672. if (removeWidth > 0)
  1673. {
  1674. for (int i = line.Runs.Count-1; i>=0; i--)
  1675. {
  1676. var fr = line.Runs[i];
  1677. // Does this run have enough to remove?
  1678. // No, remove it all
  1679. if (fr.Width < removeWidth)
  1680. {
  1681. removeWidth -= fr.Width;
  1682. line.RunsInternal.RemoveAt(i);
  1683. if (postLayout)
  1684. _fontRuns.Remove(fr);
  1685. continue;
  1686. }
  1687. // Work out where to split this run
  1688. int pos = fr.FindBreakPosition(fr.Width - removeWidth, false);
  1689. if (pos == fr.Start)
  1690. {
  1691. // Nothing fits, remove it all
  1692. line.RunsInternal.RemoveAt(i);
  1693. if (postLayout)
  1694. _fontRuns.Remove(fr);
  1695. }
  1696. else
  1697. {
  1698. // Split it
  1699. var remaining = fr.Split(pos);
  1700. // Keep the remaining part in case we need it later (not sure why,
  1701. // but seems wise).
  1702. if (!postLayout)
  1703. {
  1704. _fontRuns.Insert(_fontRuns.IndexOf(fr) + 1, remaining);
  1705. // _fontRuns.Remove(fr);
  1706. }
  1707. }
  1708. break;
  1709. }
  1710. }
  1711. // Add it to the line
  1712. line.RunsInternal.Add(ellipsisRun);
  1713. if (postLayout)
  1714. {
  1715. // No layout adjustmenst if this is post layout change
  1716. LayoutLine(line);
  1717. }
  1718. else
  1719. {
  1720. // Remember old line height
  1721. var oldHeight = line.Height;
  1722. _measuredHeight -= line.Height;
  1723. // Layout the line again
  1724. LayoutLine(line);
  1725. // Adjust height just in case it changed
  1726. _measuredHeight += line.Height;
  1727. }
  1728. }
  1729. /// <summary>
  1730. /// Check if the current layout has exceeded any height restrictions
  1731. /// and if so, remove any offending lines and optionally create the
  1732. /// ellipsis at the end indicating the text has been truncated
  1733. /// </summary>
  1734. /// <returns>True if can continue adding lines; otherwise false</returns>
  1735. bool CheckHeightConstraints()
  1736. {
  1737. // ATZ
  1738. if (!LineLimit)
  1739. {
  1740. // line is partially visible
  1741. if (_lines.Count > 0 &&
  1742. _measuredHeight > _maxHeightResolved &&
  1743. _measuredHeight - _lines[_lines.Count - 1].Height < _maxHeightResolved)
  1744. return true;
  1745. }
  1746. // Special case for the first line not fitting
  1747. if (_lines.Count == 1 && _measuredHeight > _maxHeightResolved)
  1748. {
  1749. _truncated = true;
  1750. // ATZ
  1751. //_measuredWidth = 0;
  1752. //_lines.RemoveAt(0);
  1753. return false;
  1754. }
  1755. // Have we exceeded the height limit
  1756. if (_measuredHeight > _maxHeightResolved || _maxHeightResolved <= 0)
  1757. {
  1758. // Remove the last line (unless it's the only line)
  1759. if (_lines.Count > 1)
  1760. {
  1761. _measuredHeight -= _lines[_lines.Count - 1].Height;
  1762. _lines.RemoveAt(_lines.Count - 1);
  1763. }
  1764. if (_lines.Count > 0)
  1765. {
  1766. AdornLineWithEllipsis(_lines[_lines.Count - 1]);
  1767. }
  1768. _truncated = true;
  1769. return false;
  1770. }
  1771. // Have we hit the line count limit?
  1772. if (_lines.Count >= _maxLinesResolved)
  1773. {
  1774. if (_lines.Count > 0)
  1775. {
  1776. AdornLineWithEllipsis(_lines[_lines.Count - 1]);
  1777. }
  1778. _truncated = true;
  1779. return false;
  1780. }
  1781. return true;
  1782. }
  1783. /// <summary>
  1784. /// Resets and internal object and memory pools.
  1785. /// </summary>
  1786. /// <remarks>
  1787. /// For performance reasons and to reduce pressure on the
  1788. /// garbage collector, RichTextKit maintains several internal
  1789. /// per-thread memory and object pools.
  1790. ///
  1791. /// If you create a very large text block, these pools will be
  1792. /// enlarged to cope with content of larger text blocks.
  1793. ///
  1794. /// This method can be used to reset those pools to reclaim the
  1795. /// extra memory they consumed.
  1796. ///
  1797. /// In general you can ignore this method, unless you know you're
  1798. /// working with very large text blocks (which you shouldn't be
  1799. /// anyway, since a text block is only supposed to be a single
  1800. /// paragraph).
  1801. /// /// </remarks>
  1802. public static void ResetPooledMemory()
  1803. {
  1804. TextLine.Pool.Value = new ObjectPool<TextLine>();
  1805. FontRun.Pool.Value = new ObjectPool<FontRun>();
  1806. StyleRun.Pool.Value = new ObjectPool<StyleRun>();
  1807. Bidi.Instance.Value = new Bidi();
  1808. }
  1809. }
  1810. }