TextFormatter.cs 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584
  1. #nullable enable
  2. using System.Buffers;
  3. using System.Diagnostics;
  4. namespace Terminal.Gui.Text;
  5. /// <summary>
  6. /// Provides text formatting. Supports <see cref="View.HotKey"/>s, horizontal and vertical alignment, text direction,
  7. /// multiple lines, and word-based line wrap.
  8. /// </summary>
  9. public class TextFormatter
  10. {
  11. // Utilized in CRLF related helper methods for faster newline char index search.
  12. private static readonly SearchValues<char> NewlineSearchValues = SearchValues.Create(['\r', '\n']);
  13. // New architecture components
  14. private readonly ITextFormatter _formatter;
  15. private readonly ITextRenderer _renderer;
  16. private Key _hotKey = new ();
  17. private int _hotKeyPos = -1;
  18. private List<string> _lines = new ();
  19. private bool _multiLine;
  20. private bool _preserveTrailingSpaces;
  21. private int _tabWidth = 4;
  22. private string? _text;
  23. private Alignment _textAlignment = Alignment.Start;
  24. private TextDirection _textDirection;
  25. private Alignment _textVerticalAlignment = Alignment.Start;
  26. private bool _wordWrap = true;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="TextFormatter"/> class.
  29. /// </summary>
  30. public TextFormatter()
  31. {
  32. _formatter = new StandardTextFormatter();
  33. _renderer = new StandardTextRenderer();
  34. }
  35. /// <summary>Get or sets the horizontal text alignment.</summary>
  36. /// <value>The text alignment.</value>
  37. public Alignment Alignment
  38. {
  39. get => _textAlignment;
  40. set
  41. {
  42. _textAlignment = EnableNeedsFormat(value);
  43. _formatter.Alignment = value;
  44. }
  45. }
  46. /// <summary>
  47. /// Gets the cursor position of the <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will
  48. /// be positioned over it.
  49. /// </summary>
  50. public int CursorPosition { get; internal set; }
  51. /// <summary>Gets or sets the text-direction.</summary>
  52. /// <value>The text direction.</value>
  53. public TextDirection Direction
  54. {
  55. get => _textDirection;
  56. set
  57. {
  58. _textDirection = EnableNeedsFormat(value);
  59. _formatter.Direction = value;
  60. }
  61. }
  62. /// <summary>Draws the text held by <see cref="TextFormatter"/> to <see cref="IConsoleDriver"/> using the colors specified.</summary>
  63. /// <remarks>
  64. /// Causes the text to be formatted (references <see cref="GetLines"/>). Sets <see cref="NeedsFormat"/> to
  65. /// <c>false</c>.
  66. /// </remarks>
  67. /// <param name="screen">Specifies the screen-relative location and maximum size for drawing the text.</param>
  68. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  69. /// <param name="hotColor">The color to use to draw the hotkey</param>
  70. /// <param name="maximum">Specifies the screen-relative location and maximum container size.</param>
  71. /// <param name="driver">The console driver currently used by the application.</param>
  72. /// <exception cref="ArgumentOutOfRangeException"></exception>
  73. /// <summary>
  74. /// Draws the text using the new architecture (formatter + renderer separation).
  75. /// This method demonstrates the improved design with better performance and extensibility.
  76. /// </summary>
  77. /// <param name="screen">The screen bounds for drawing.</param>
  78. /// <param name="normalColor">The color for normal text.</param>
  79. /// <param name="hotColor">The color for HotKey text.</param>
  80. /// <param name="maximum">The maximum container bounds.</param>
  81. /// <param name="driver">The console driver to use for drawing.</param>
  82. public void DrawWithNewArchitecture(
  83. Rectangle screen,
  84. Attribute normalColor,
  85. Attribute hotColor,
  86. Rectangle maximum = default,
  87. IConsoleDriver? driver = null)
  88. {
  89. // Sync properties with the new formatter
  90. SyncFormatterProperties();
  91. // Format the text using the new architecture
  92. FormattedText formattedText = _formatter.Format();
  93. // Render using the new renderer
  94. _renderer.Draw(formattedText, screen, normalColor, hotColor, FillRemaining, maximum, driver);
  95. }
  96. /// <summary>
  97. /// Gets the draw region using the new architecture.
  98. /// This provides the same functionality as GetDrawRegion but with improved performance.
  99. /// </summary>
  100. /// <param name="screen">The screen bounds.</param>
  101. /// <param name="maximum">The maximum container bounds.</param>
  102. /// <returns>A region representing the areas that would be drawn.</returns>
  103. public Region GetDrawRegionWithNewArchitecture(Rectangle screen, Rectangle maximum = default)
  104. {
  105. SyncFormatterProperties();
  106. FormattedText formattedText = _formatter.Format();
  107. return _renderer.GetDrawRegion(formattedText, screen, maximum);
  108. }
  109. /// <summary>
  110. /// Gets the formatted size using the new architecture.
  111. /// This addresses the Format/Draw decoupling issues mentioned in the architectural problems.
  112. /// </summary>
  113. /// <returns>The size required for the formatted text.</returns>
  114. public Size GetFormattedSizeWithNewArchitecture()
  115. {
  116. SyncFormatterProperties();
  117. return _formatter.GetFormattedSize();
  118. }
  119. private void SyncFormatterProperties()
  120. {
  121. // Ensure the new formatter has all the current property values
  122. _formatter.Text = _text ?? string.Empty;
  123. _formatter.Alignment = _textAlignment;
  124. _formatter.VerticalAlignment = _textVerticalAlignment;
  125. _formatter.Direction = _textDirection;
  126. _formatter.WordWrap = _wordWrap;
  127. _formatter.MultiLine = _multiLine;
  128. _formatter.HotKeySpecifier = HotKeySpecifier;
  129. _formatter.TabWidth = _tabWidth;
  130. _formatter.PreserveTrailingSpaces = _preserveTrailingSpaces;
  131. _formatter.ConstrainToSize = ConstrainToSize;
  132. }
  133. public void Draw (
  134. Rectangle screen,
  135. Attribute normalColor,
  136. Attribute hotColor,
  137. Rectangle maximum = default,
  138. IConsoleDriver? driver = null
  139. )
  140. {
  141. // Use the new architecture - this addresses @tig's feedback that the new architecture wasn't being used
  142. // Sync properties with the new formatter
  143. SyncFormatterProperties();
  144. // Format the text using the new architecture
  145. FormattedText formattedText = _formatter.Format();
  146. // Render using the new renderer
  147. _renderer.Draw(formattedText, screen, normalColor, hotColor, FillRemaining, maximum, driver);
  148. }
  149. /// <summary>
  150. List<string> linesFormatted = GetLines ();
  151. bool isVertical = IsVerticalDirection (Direction);
  152. Rectangle maxScreen = screen;
  153. if (driver is { })
  154. {
  155. // INTENT: What, exactly, is the intent of this?
  156. maxScreen = maximum == default (Rectangle)
  157. ? screen
  158. : new (
  159. Math.Max (maximum.X, screen.X),
  160. Math.Max (maximum.Y, screen.Y),
  161. Math.Max (
  162. Math.Min (maximum.Width, maximum.Right - screen.Left),
  163. 0
  164. ),
  165. Math.Max (
  166. Math.Min (
  167. maximum.Height,
  168. maximum.Bottom - screen.Top
  169. ),
  170. 0
  171. )
  172. );
  173. }
  174. if (maxScreen.Width == 0 || maxScreen.Height == 0)
  175. {
  176. return;
  177. }
  178. int lineOffset = !isVertical && screen.Y < 0 ? Math.Abs (screen.Y) : 0;
  179. for (int line = lineOffset; line < linesFormatted.Count; line++)
  180. {
  181. if ((isVertical && line > screen.Width) || (!isVertical && line > screen.Height))
  182. {
  183. continue;
  184. }
  185. if ((isVertical && line >= maxScreen.Left + maxScreen.Width)
  186. || (!isVertical && line >= maxScreen.Top + maxScreen.Height + lineOffset))
  187. {
  188. break;
  189. }
  190. Rune [] runes = linesFormatted [line].ToRunes ();
  191. // When text is justified, we lost left or right, so we use the direction to align.
  192. int x = 0, y = 0;
  193. // Horizontal Alignment
  194. if (Alignment is Alignment.End)
  195. {
  196. if (isVertical)
  197. {
  198. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, line, linesFormatted.Count - line, TabWidth);
  199. x = screen.Right - runesWidth;
  200. CursorPosition = screen.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  201. }
  202. else
  203. {
  204. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  205. x = screen.Right - runesWidth;
  206. CursorPosition = screen.Width - runesWidth + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  207. }
  208. }
  209. else if (Alignment is Alignment.Start)
  210. {
  211. if (isVertical)
  212. {
  213. int runesWidth = line > 0
  214. ? GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth)
  215. : 0;
  216. x = screen.Left + runesWidth;
  217. }
  218. else
  219. {
  220. x = screen.Left;
  221. }
  222. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  223. }
  224. else if (Alignment is Alignment.Fill)
  225. {
  226. if (isVertical)
  227. {
  228. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  229. int prevLineWidth = line > 0 ? GetColumnsRequiredForVerticalText (linesFormatted, line - 1, 1, TabWidth) : 0;
  230. int firstLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, 1, TabWidth);
  231. int lastLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, linesFormatted.Count - 1, 1, TabWidth);
  232. var interval = (int)Math.Round ((double)(screen.Width + firstLineWidth + lastLineWidth) / linesFormatted.Count);
  233. x = line == 0
  234. ? screen.Left
  235. : line < linesFormatted.Count - 1
  236. ? screen.Width - runesWidth <= lastLineWidth ? screen.Left + prevLineWidth : screen.Left + line * interval
  237. : screen.Right - lastLineWidth;
  238. }
  239. else
  240. {
  241. x = screen.Left;
  242. }
  243. CursorPosition = _hotKeyPos > -1 ? _hotKeyPos : 0;
  244. }
  245. else if (Alignment is Alignment.Center)
  246. {
  247. if (isVertical)
  248. {
  249. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  250. int linesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth);
  251. x = screen.Left + linesWidth + (screen.Width - runesWidth) / 2;
  252. CursorPosition = (screen.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  253. }
  254. else
  255. {
  256. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  257. x = screen.Left + (screen.Width - runesWidth) / 2;
  258. CursorPosition = (screen.Width - runesWidth) / 2 + (_hotKeyPos > -1 ? _hotKeyPos : 0);
  259. }
  260. }
  261. else
  262. {
  263. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  264. return;
  265. }
  266. // Vertical Alignment
  267. if (VerticalAlignment is Alignment.End)
  268. {
  269. if (isVertical)
  270. {
  271. y = screen.Bottom - runes.Length;
  272. }
  273. else
  274. {
  275. y = screen.Bottom - linesFormatted.Count + line;
  276. }
  277. }
  278. else if (VerticalAlignment is Alignment.Start)
  279. {
  280. if (isVertical)
  281. {
  282. y = screen.Top;
  283. }
  284. else
  285. {
  286. y = screen.Top + line;
  287. }
  288. }
  289. else if (VerticalAlignment is Alignment.Fill)
  290. {
  291. if (isVertical)
  292. {
  293. y = screen.Top;
  294. }
  295. else
  296. {
  297. var interval = (int)Math.Round ((double)(screen.Height + 2) / linesFormatted.Count);
  298. y = line == 0 ? screen.Top :
  299. line < linesFormatted.Count - 1 ? screen.Height - interval <= 1 ? screen.Top + 1 : screen.Top + line * interval : screen.Bottom - 1;
  300. }
  301. }
  302. else if (VerticalAlignment is Alignment.Center)
  303. {
  304. if (isVertical)
  305. {
  306. int s = (screen.Height - runes.Length) / 2;
  307. y = screen.Top + s;
  308. }
  309. else
  310. {
  311. int s = (screen.Height - linesFormatted.Count) / 2;
  312. y = screen.Top + line + s;
  313. }
  314. }
  315. else
  316. {
  317. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  318. return;
  319. }
  320. int colOffset = screen.X < 0 ? Math.Abs (screen.X) : 0;
  321. int start = isVertical ? screen.Top : screen.Left;
  322. int size = isVertical ? screen.Height : screen.Width;
  323. int current = start + colOffset;
  324. List<Point?> lastZeroWidthPos = null!;
  325. Rune rune = default;
  326. int zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  327. for (int idx = (isVertical ? start - y : start - x) + colOffset;
  328. current < start + size + zeroLengthCount;
  329. idx++)
  330. {
  331. Rune lastRuneUsed = rune;
  332. if (lastZeroWidthPos is null)
  333. {
  334. if (idx < 0
  335. || (isVertical
  336. ? VerticalAlignment != Alignment.End && current < 0
  337. : Alignment != Alignment.End && x + current + colOffset < 0))
  338. {
  339. current++;
  340. continue;
  341. }
  342. if (!FillRemaining && idx > runes.Length - 1)
  343. {
  344. break;
  345. }
  346. if ((!isVertical
  347. && (current - start > maxScreen.Left + maxScreen.Width - screen.X + colOffset
  348. || (idx < runes.Length && runes [idx].GetColumns () > screen.Width)))
  349. || (isVertical
  350. && ((current > start + size + zeroLengthCount && idx > maxScreen.Top + maxScreen.Height - screen.Y)
  351. || (idx < runes.Length && runes [idx].GetColumns () > screen.Width))))
  352. {
  353. break;
  354. }
  355. }
  356. //if ((!isVertical && idx > maxBounds.Left + maxBounds.Width - viewport.X + colOffset)
  357. // || (isVertical && idx > maxBounds.Top + maxBounds.Height - viewport.Y))
  358. // break;
  359. rune = (Rune)' ';
  360. if (isVertical)
  361. {
  362. if (idx >= 0 && idx < runes.Length)
  363. {
  364. rune = runes [idx];
  365. }
  366. if (lastZeroWidthPos is null)
  367. {
  368. driver?.Move (x, current);
  369. }
  370. else
  371. {
  372. int foundIdx = lastZeroWidthPos.IndexOf (
  373. p =>
  374. p is { } && p.Value.Y == current
  375. );
  376. if (foundIdx > -1)
  377. {
  378. if (rune.IsCombiningMark ())
  379. {
  380. lastZeroWidthPos [foundIdx] =
  381. new Point (
  382. lastZeroWidthPos [foundIdx]!.Value.X + 1,
  383. current
  384. );
  385. driver?.Move (
  386. lastZeroWidthPos [foundIdx]!.Value.X,
  387. current
  388. );
  389. }
  390. else if (!rune.IsCombiningMark () && lastRuneUsed.IsCombiningMark ())
  391. {
  392. current++;
  393. driver?.Move (x, current);
  394. }
  395. else
  396. {
  397. driver?.Move (x, current);
  398. }
  399. }
  400. else
  401. {
  402. driver?.Move (x, current);
  403. }
  404. }
  405. }
  406. else
  407. {
  408. driver?.Move (current, y);
  409. if (idx >= 0 && idx < runes.Length)
  410. {
  411. rune = runes [idx];
  412. }
  413. }
  414. int runeWidth = GetRuneWidth (rune, TabWidth);
  415. if (HotKeyPos > -1 && idx == HotKeyPos)
  416. {
  417. if ((isVertical && VerticalAlignment == Alignment.Fill) || (!isVertical && Alignment == Alignment.Fill))
  418. {
  419. CursorPosition = idx - start;
  420. }
  421. driver?.SetAttribute (hotColor);
  422. driver?.AddRune (rune);
  423. driver?.SetAttribute (normalColor);
  424. }
  425. else
  426. {
  427. if (isVertical)
  428. {
  429. if (runeWidth == 0)
  430. {
  431. if (lastZeroWidthPos is null)
  432. {
  433. lastZeroWidthPos = new ();
  434. }
  435. int foundIdx = lastZeroWidthPos.IndexOf (
  436. p =>
  437. p is { } && p.Value.Y == current
  438. );
  439. if (foundIdx == -1)
  440. {
  441. current--;
  442. lastZeroWidthPos.Add (new Point (x + 1, current));
  443. }
  444. driver?.Move (x + 1, current);
  445. }
  446. }
  447. driver?.AddRune (rune);
  448. }
  449. if (isVertical)
  450. {
  451. if (runeWidth > 0)
  452. {
  453. current++;
  454. }
  455. }
  456. else
  457. {
  458. current += runeWidth;
  459. }
  460. int nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length
  461. ? runes [idx + 1].GetColumns ()
  462. : 0;
  463. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size)
  464. {
  465. break;
  466. }
  467. }
  468. }
  469. }
  470. /// <summary>
  471. /// Determines if the viewport width will be used or only the text width will be used,
  472. /// If <see langword="true"/> all the viewport area will be filled with whitespaces and the same background color
  473. /// showing a perfect rectangle.
  474. /// </summary>
  475. public bool FillRemaining { get; set; }
  476. /// <summary>Returns the formatted text, constrained to <see cref="ConstrainToSize"/>.</summary>
  477. /// <remarks>
  478. /// If <see cref="NeedsFormat"/> is <see langword="true"/>, causes a format, resetting <see cref="NeedsFormat"/>
  479. /// to <see langword="false"/>.
  480. /// </remarks>
  481. /// <returns>The formatted text.</returns>
  482. public string Format ()
  483. {
  484. var sb = new StringBuilder ();
  485. // Lines_get causes a Format
  486. foreach (string line in GetLines ())
  487. {
  488. sb.AppendLine (line);
  489. }
  490. return sb.ToString ().TrimEnd (Environment.NewLine.ToCharArray ());
  491. }
  492. /// <summary>Gets the size required to hold the formatted text, given the constraints placed by <see cref="ConstrainToSize"/>.</summary>
  493. /// <remarks>Causes a format, resetting <see cref="NeedsFormat"/> to <see langword="false"/>.</remarks>
  494. /// <param name="constrainSize">
  495. /// If provided, will cause the text to be constrained to the provided size instead of <see cref="ConstrainToWidth"/> and
  496. /// <see cref="ConstrainToHeight"/>.
  497. /// </param>
  498. /// <returns>The size required to hold the formatted text.</returns>
  499. public Size FormatAndGetSize (Size? constrainSize = null)
  500. {
  501. if (string.IsNullOrEmpty (Text))
  502. {
  503. return System.Drawing.Size.Empty;
  504. }
  505. int? prevWidth = _constrainToWidth;
  506. int? prevHeight = _constrainToHeight;
  507. if (constrainSize is { })
  508. {
  509. _constrainToWidth = constrainSize?.Width;
  510. _constrainToHeight = constrainSize?.Height;
  511. }
  512. // HACK: Fill normally will fill the entire constraint size, but we need to know the actual size of the text.
  513. Alignment prevAlignment = Alignment;
  514. if (Alignment == Alignment.Fill)
  515. {
  516. Alignment = Alignment.Start;
  517. }
  518. Alignment prevVerticalAlignment = VerticalAlignment;
  519. if (VerticalAlignment == Alignment.Fill)
  520. {
  521. VerticalAlignment = Alignment.Start;
  522. }
  523. // This calls Format
  524. List<string> lines = GetLines ();
  525. // Undo hacks
  526. Alignment = prevAlignment;
  527. VerticalAlignment = prevVerticalAlignment;
  528. if (constrainSize is { })
  529. {
  530. _constrainToWidth = prevWidth ?? null;
  531. _constrainToHeight = prevHeight ?? null;
  532. }
  533. if (lines.Count == 0)
  534. {
  535. return System.Drawing.Size.Empty;
  536. }
  537. int width;
  538. int height;
  539. if (IsVerticalDirection (Direction))
  540. {
  541. width = GetColumnsRequiredForVerticalText (lines, 0, lines.Count, TabWidth);
  542. height = lines.Max (static line => line.Length);
  543. }
  544. else
  545. {
  546. width = lines.Max (static line => line.GetColumns ());
  547. height = lines.Count;
  548. }
  549. return new (width, height);
  550. }
  551. /// <summary>
  552. /// Gets the width or height of the <see cref="TextFormatter.HotKeySpecifier"/> characters
  553. /// in the <see cref="Text"/> property.
  554. /// </summary>
  555. /// <remarks>
  556. /// Only the first HotKey specifier found in <see cref="Text"/> is supported.
  557. /// </remarks>
  558. /// <param name="isWidth">
  559. /// If <see langword="true"/> (the default) the width required for the HotKey specifier is returned. Otherwise, the
  560. /// height is returned.
  561. /// </param>
  562. /// <returns>
  563. /// The number of characters required for the <see cref="TextFormatter.HotKeySpecifier"/>. If the text
  564. /// direction specified
  565. /// by <see cref="TextDirection"/> does not match the <paramref name="isWidth"/> parameter, <c>0</c> is returned.
  566. /// </returns>
  567. public int GetHotKeySpecifierLength (bool isWidth = true)
  568. {
  569. if (isWidth)
  570. {
  571. return IsHorizontalDirection (Direction) && Text?.Contains ((char)HotKeySpecifier.Value) == true
  572. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  573. : 0;
  574. }
  575. return IsVerticalDirection (Direction) && Text?.Contains ((char)HotKeySpecifier.Value) == true
  576. ? Math.Max (HotKeySpecifier.GetColumns (), 0)
  577. : 0;
  578. }
  579. /// <summary>Gets a list of formatted lines, constrained to <see cref="ConstrainToSize"/>.</summary>
  580. /// <remarks>
  581. /// <para>
  582. /// If the text needs to be formatted (if <see cref="NeedsFormat"/> is <see langword="true"/>)
  583. /// <see cref="Format()"/> will be called and upon return
  584. /// <see cref="NeedsFormat"/> will be <see langword="false"/>.
  585. /// </para>
  586. /// <para>
  587. /// If either of the dimensions of <see cref="ConstrainToSize"/> are zero, the text will not be formatted and no lines will
  588. /// be returned.
  589. /// </para>
  590. /// </remarks>
  591. public List<string> GetLines ()
  592. {
  593. string text = _text!.ReplaceLineEndings ();
  594. // With this check, we protect against subclasses with overrides of Text
  595. if (string.IsNullOrEmpty (Text) || ConstrainToWidth is 0 || ConstrainToHeight is 0)
  596. {
  597. _lines = [string.Empty];
  598. NeedsFormat = false;
  599. return _lines;
  600. }
  601. if (!NeedsFormat)
  602. {
  603. return _lines;
  604. }
  605. int width = ConstrainToWidth ?? int.MaxValue;
  606. int height = ConstrainToHeight ?? int.MaxValue;
  607. if (FindHotKey (_text!, HotKeySpecifier, out _hotKeyPos, out Key newHotKey))
  608. {
  609. HotKey = newHotKey;
  610. text = RemoveHotKeySpecifier (Text, _hotKeyPos, HotKeySpecifier);
  611. text = ReplaceHotKeyWithTag (text, _hotKeyPos);
  612. }
  613. if (IsVerticalDirection (Direction))
  614. {
  615. int colsWidth = GetSumMaxCharWidth (text, 0, 1, TabWidth);
  616. _lines = Format (
  617. text,
  618. height,
  619. VerticalAlignment == Alignment.Fill,
  620. width > colsWidth && WordWrap,
  621. PreserveTrailingSpaces,
  622. TabWidth,
  623. Direction,
  624. MultiLine,
  625. this
  626. );
  627. colsWidth = GetMaxColsForWidth (_lines, width, TabWidth);
  628. if (_lines.Count > colsWidth)
  629. {
  630. _lines.RemoveRange (colsWidth, _lines.Count - colsWidth);
  631. }
  632. }
  633. else
  634. {
  635. _lines = Format (
  636. text,
  637. width,
  638. Alignment == Alignment.Fill,
  639. height > 1 && WordWrap,
  640. PreserveTrailingSpaces,
  641. TabWidth,
  642. Direction,
  643. MultiLine,
  644. this
  645. );
  646. if (_lines.Count > height)
  647. {
  648. _lines.RemoveRange (height, _lines.Count - height);
  649. }
  650. }
  651. NeedsFormat = false;
  652. return _lines;
  653. }
  654. private int? _constrainToWidth;
  655. /// <summary>Gets or sets the width <see cref="Text"/> will be constrained to when formatted.</summary>
  656. /// <remarks>
  657. /// <para>
  658. /// Does not return the width of the formatted text but the width that will be used to constrain the text when
  659. /// formatted.
  660. /// </para>
  661. /// <para>
  662. /// If <see langword="null"/> the height will be unconstrained. if both <see cref="ConstrainToWidth"/> and <see cref="ConstrainToHeight"/> are <see langword="null"/> the text will be formatted to the size of the text.
  663. /// </para>
  664. /// <para>
  665. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  666. /// </para>
  667. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  668. /// </remarks>
  669. public int? ConstrainToWidth
  670. {
  671. get => _constrainToWidth;
  672. set
  673. {
  674. if (_constrainToWidth == value)
  675. {
  676. return;
  677. }
  678. ArgumentOutOfRangeException.ThrowIfNegative (value.GetValueOrDefault (), nameof (ConstrainToWidth));
  679. _constrainToWidth = EnableNeedsFormat (value);
  680. }
  681. }
  682. private int? _constrainToHeight;
  683. /// <summary>Gets or sets the height <see cref="Text"/> will be constrained to when formatted.</summary>
  684. /// <remarks>
  685. /// <para>
  686. /// Does not return the height of the formatted text but the height that will be used to constrain the text when
  687. /// formatted.
  688. /// </para>
  689. /// <para>
  690. /// If <see langword="null"/> the height will be unconstrained. if both <see cref="ConstrainToWidth"/> and <see cref="ConstrainToHeight"/> are <see langword="null"/> the text will be formatted to the size of the text.
  691. /// </para>
  692. /// <para>
  693. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  694. /// </para>
  695. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  696. /// </remarks>
  697. public int? ConstrainToHeight
  698. {
  699. get => _constrainToHeight;
  700. set
  701. {
  702. if (_constrainToHeight == value)
  703. {
  704. return;
  705. }
  706. ArgumentOutOfRangeException.ThrowIfNegative (value.GetValueOrDefault (), nameof (ConstrainToHeight));
  707. _constrainToHeight = EnableNeedsFormat (value);
  708. }
  709. }
  710. /// <summary>Gets or sets the width and height <see cref="Text"/> will be constrained to when formatted.</summary>
  711. /// <remarks>
  712. /// <para>
  713. /// Does not return the size of the formatted text but the size that will be used to constrain the text when
  714. /// formatted.
  715. /// </para>
  716. /// <para>
  717. /// If <see langword="null"/> both the width and height will be unconstrained and text will be formatted to the size of the text.
  718. /// </para>
  719. /// <para>
  720. /// Setting this property is the same as setting <see cref="ConstrainToWidth"/> and <see cref="ConstrainToHeight"/> separately.
  721. /// </para>
  722. /// <para>
  723. /// Use <see cref="FormatAndGetSize"/> to get the size of the formatted text.
  724. /// </para>
  725. /// <para>When set, <see cref="NeedsFormat"/> is set to <see langword="true"/>.</para>
  726. /// </remarks>
  727. public Size? ConstrainToSize
  728. {
  729. get
  730. {
  731. if (_constrainToWidth is null || _constrainToHeight is null)
  732. {
  733. return null;
  734. }
  735. return new Size (_constrainToWidth.Value, _constrainToHeight.Value);
  736. }
  737. set
  738. {
  739. if (value is null)
  740. {
  741. _constrainToWidth = null;
  742. _constrainToHeight = null;
  743. EnableNeedsFormat (true);
  744. }
  745. else
  746. {
  747. _constrainToWidth = EnableNeedsFormat (value.Value.Width);
  748. _constrainToHeight = EnableNeedsFormat (value.Value.Height);
  749. }
  750. }
  751. }
  752. /// <summary>Gets or sets the hot key. Fires the <see cref="HotKeyChanged"/> event.</summary>
  753. public Key HotKey
  754. {
  755. get => _hotKey;
  756. internal set
  757. {
  758. if (_hotKey != value)
  759. {
  760. Key oldKey = _hotKey;
  761. _hotKey = value;
  762. HotKeyChanged?.Invoke (this, new (oldKey, value));
  763. }
  764. }
  765. }
  766. /// <summary>Event invoked when the <see cref="HotKey"/> is changed.</summary>
  767. public event EventHandler<KeyChangedEventArgs>? HotKeyChanged;
  768. /// <summary>The position in the text of the hot key. The hot key will be rendered using the hot color.</summary>
  769. public int HotKeyPos
  770. {
  771. get => _hotKeyPos;
  772. internal set => _hotKeyPos = value;
  773. }
  774. /// <summary>
  775. /// The specifier character for the hot key (e.g. '_'). Set to '\xffff' to disable hot key support for this View
  776. /// instance. The default is '\xffff'.
  777. /// </summary>
  778. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  779. /// <summary>Gets or sets a value indicating whether multi line is allowed.</summary>
  780. /// <remarks>Multi line is ignored if <see cref="WordWrap"/> is <see langword="true"/>.</remarks>
  781. public bool MultiLine
  782. {
  783. get => _multiLine;
  784. set => _multiLine = EnableNeedsFormat (value);
  785. }
  786. /// <summary>Gets or sets whether the <see cref="TextFormatter"/> needs to format the text.</summary>
  787. /// <remarks>
  788. /// <para>If <see langword="false"/> when Draw is called, the Draw call will be faster.</para>
  789. /// <para>Used by <see cref="Draw"/></para>
  790. /// <para>Set to <see langword="true"/> when any of the properties of <see cref="TextFormatter"/> are set.</para>
  791. /// <para>Set to <see langword="false"/> when the text is formatted (if <see cref="GetLines"/> is accessed).</para>
  792. /// </remarks>
  793. public bool NeedsFormat { get; set; }
  794. /// <summary>
  795. /// Gets or sets whether trailing spaces at the end of word-wrapped lines are preserved or not when
  796. /// <see cref="TextFormatter.WordWrap"/> is enabled. If <see langword="true"/> trailing spaces at the end of wrapped
  797. /// lines will be removed when <see cref="Text"/> is formatted for display. The default is <see langword="false"/>.
  798. /// </summary>
  799. public bool PreserveTrailingSpaces
  800. {
  801. get => _preserveTrailingSpaces;
  802. set => _preserveTrailingSpaces = EnableNeedsFormat (value);
  803. }
  804. /// <summary>Gets or sets the number of columns used for a tab.</summary>
  805. public int TabWidth
  806. {
  807. get => _tabWidth;
  808. set => _tabWidth = EnableNeedsFormat (value);
  809. }
  810. /// <summary>The text to be formatted. This string is never modified.</summary>
  811. public string Text
  812. {
  813. get => _text!;
  814. set
  815. {
  816. _text = EnableNeedsFormat(value);
  817. _formatter.Text = value ?? string.Empty;
  818. }
  819. }
  820. /// <summary>Gets or sets the vertical text-alignment.</summary>
  821. /// <value>The text vertical alignment.</value>
  822. public Alignment VerticalAlignment
  823. {
  824. get => _textVerticalAlignment;
  825. set
  826. {
  827. _textVerticalAlignment = EnableNeedsFormat(value);
  828. _formatter.VerticalAlignment = value;
  829. }
  830. }
  831. /// <summary>Gets or sets whether word wrap will be used to fit <see cref="Text"/> to <see cref="ConstrainToSize"/>.</summary>
  832. public bool WordWrap
  833. {
  834. get => _wordWrap;
  835. set => _wordWrap = EnableNeedsFormat (value);
  836. }
  837. /// <summary>Sets <see cref="NeedsFormat"/> to <see langword="true"/> and returns the value.</summary>
  838. /// <typeparam name="T"></typeparam>
  839. /// <param name="value"></param>
  840. /// <returns></returns>
  841. private T EnableNeedsFormat<T> (T value)
  842. {
  843. NeedsFormat = true;
  844. return value;
  845. }
  846. /// <summary>
  847. /// Calculates and returns a <see cref="Region"/> describing the areas where text would be output, based on the
  848. /// formatting rules of <see cref="TextFormatter"/>.
  849. /// </summary>
  850. /// <remarks>
  851. /// Uses the same formatting logic as <see cref="Draw"/>, including alignment, direction, word wrap, and constraints,
  852. /// but does not perform actual drawing to <see cref="IConsoleDriver"/>.
  853. /// </remarks>
  854. /// <param name="screen">Specifies the screen-relative location and maximum size for drawing the text.</param>
  855. /// <param name="maximum">Specifies the screen-relative location and maximum container size.</param>
  856. /// <returns>A <see cref="Region"/> representing the areas where text would be drawn.</returns>
  857. public Region GetDrawRegion (Rectangle screen, Rectangle maximum = default)
  858. {
  859. Region drawnRegion = new Region ();
  860. // With this check, we protect against subclasses with overrides of Text (like Button)
  861. if (string.IsNullOrEmpty (Text))
  862. {
  863. return drawnRegion;
  864. }
  865. List<string> linesFormatted = GetLines ();
  866. bool isVertical = IsVerticalDirection (Direction);
  867. Rectangle maxScreen = screen;
  868. // INTENT: What, exactly, is the intent of this?
  869. maxScreen = maximum == default (Rectangle)
  870. ? screen
  871. : new (
  872. Math.Max (maximum.X, screen.X),
  873. Math.Max (maximum.Y, screen.Y),
  874. Math.Max (
  875. Math.Min (maximum.Width, maximum.Right - screen.Left),
  876. 0
  877. ),
  878. Math.Max (
  879. Math.Min (
  880. maximum.Height,
  881. maximum.Bottom - screen.Top
  882. ),
  883. 0
  884. )
  885. );
  886. if (maxScreen.Width == 0 || maxScreen.Height == 0)
  887. {
  888. return drawnRegion;
  889. }
  890. int lineOffset = !isVertical && screen.Y < 0 ? Math.Abs (screen.Y) : 0;
  891. for (int line = lineOffset; line < linesFormatted.Count; line++)
  892. {
  893. if ((isVertical && line > screen.Width) || (!isVertical && line > screen.Height))
  894. {
  895. continue;
  896. }
  897. if ((isVertical && line >= maxScreen.Left + maxScreen.Width)
  898. || (!isVertical && line >= maxScreen.Top + maxScreen.Height + lineOffset))
  899. {
  900. break;
  901. }
  902. Rune [] runes = linesFormatted [line].ToRunes ();
  903. // When text is justified, we lost left or right, so we use the direction to align.
  904. int x = 0, y = 0;
  905. switch (Alignment)
  906. {
  907. // Horizontal Alignment
  908. case Alignment.End when isVertical:
  909. {
  910. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, line, linesFormatted.Count - line, TabWidth);
  911. x = screen.Right - runesWidth;
  912. break;
  913. }
  914. case Alignment.End:
  915. {
  916. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  917. x = screen.Right - runesWidth;
  918. break;
  919. }
  920. case Alignment.Start when isVertical:
  921. {
  922. int runesWidth = line > 0
  923. ? GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth)
  924. : 0;
  925. x = screen.Left + runesWidth;
  926. break;
  927. }
  928. case Alignment.Start:
  929. x = screen.Left;
  930. break;
  931. case Alignment.Fill when isVertical:
  932. {
  933. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  934. int prevLineWidth = line > 0 ? GetColumnsRequiredForVerticalText (linesFormatted, line - 1, 1, TabWidth) : 0;
  935. int firstLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, 1, TabWidth);
  936. int lastLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, linesFormatted.Count - 1, 1, TabWidth);
  937. var interval = (int)Math.Round ((double)(screen.Width + firstLineWidth + lastLineWidth) / linesFormatted.Count);
  938. x = line == 0
  939. ? screen.Left
  940. : line < linesFormatted.Count - 1
  941. ? screen.Width - runesWidth <= lastLineWidth ? screen.Left + prevLineWidth : screen.Left + line * interval
  942. : screen.Right - lastLineWidth;
  943. break;
  944. }
  945. case Alignment.Fill:
  946. x = screen.Left;
  947. break;
  948. case Alignment.Center when isVertical:
  949. {
  950. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  951. int linesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth);
  952. x = screen.Left + linesWidth + (screen.Width - runesWidth) / 2;
  953. break;
  954. }
  955. case Alignment.Center:
  956. {
  957. int runesWidth = StringExtensions.ToString (runes).GetColumns ();
  958. x = screen.Left + (screen.Width - runesWidth) / 2;
  959. break;
  960. }
  961. default:
  962. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  963. return drawnRegion;
  964. }
  965. switch (VerticalAlignment)
  966. {
  967. // Vertical Alignment
  968. case Alignment.End when isVertical:
  969. y = screen.Bottom - runes.Length;
  970. break;
  971. case Alignment.End:
  972. y = screen.Bottom - linesFormatted.Count + line;
  973. break;
  974. case Alignment.Start when isVertical:
  975. y = screen.Top;
  976. break;
  977. case Alignment.Start:
  978. y = screen.Top + line;
  979. break;
  980. case Alignment.Fill when isVertical:
  981. y = screen.Top;
  982. break;
  983. case Alignment.Fill:
  984. {
  985. var interval = (int)Math.Round ((double)(screen.Height + 2) / linesFormatted.Count);
  986. y = line == 0 ? screen.Top :
  987. line < linesFormatted.Count - 1 ? screen.Height - interval <= 1 ? screen.Top + 1 : screen.Top + line * interval : screen.Bottom - 1;
  988. break;
  989. }
  990. case Alignment.Center when isVertical:
  991. {
  992. int s = (screen.Height - runes.Length) / 2;
  993. y = screen.Top + s;
  994. break;
  995. }
  996. case Alignment.Center:
  997. {
  998. int s = (screen.Height - linesFormatted.Count) / 2;
  999. y = screen.Top + line + s;
  1000. break;
  1001. }
  1002. default:
  1003. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  1004. return drawnRegion;
  1005. }
  1006. int colOffset = screen.X < 0 ? Math.Abs (screen.X) : 0;
  1007. int start = isVertical ? screen.Top : screen.Left;
  1008. int size = isVertical ? screen.Height : screen.Width;
  1009. int current = start + colOffset;
  1010. int zeroLengthCount = isVertical ? runes.Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  1011. int lineX = x, lineY = y, lineWidth = 0, lineHeight = 1;
  1012. for (int idx = (isVertical ? start - y : start - x) + colOffset;
  1013. current < start + size + zeroLengthCount;
  1014. idx++)
  1015. {
  1016. if (idx < 0
  1017. || (isVertical
  1018. ? VerticalAlignment != Alignment.End && current < 0
  1019. : Alignment != Alignment.End && x + current + colOffset < 0))
  1020. {
  1021. current++;
  1022. continue;
  1023. }
  1024. if (!FillRemaining && idx > runes.Length - 1)
  1025. {
  1026. break;
  1027. }
  1028. if ((!isVertical
  1029. && (current - start > maxScreen.Left + maxScreen.Width - screen.X + colOffset
  1030. || (idx < runes.Length && runes [idx].GetColumns () > screen.Width)))
  1031. || (isVertical
  1032. && ((current > start + size + zeroLengthCount && idx > maxScreen.Top + maxScreen.Height - screen.Y)
  1033. || (idx < runes.Length && runes [idx].GetColumns () > screen.Width))))
  1034. {
  1035. break;
  1036. }
  1037. Rune rune = idx >= 0 && idx < runes.Length ? runes [idx] : (Rune)' ';
  1038. int runeWidth = GetRuneWidth (rune, TabWidth);
  1039. if (isVertical)
  1040. {
  1041. if (runeWidth > 0)
  1042. {
  1043. // Update line height for vertical text (each rune is a column)
  1044. lineHeight = Math.Max (lineHeight, current - y + 1);
  1045. lineWidth = Math.Max (lineWidth, 1); // Width is 1 per rune in vertical
  1046. }
  1047. }
  1048. else
  1049. {
  1050. // Update line width and position for horizontal text
  1051. lineWidth += runeWidth;
  1052. }
  1053. current += isVertical && runeWidth > 0 ? 1 : runeWidth;
  1054. int nextRuneWidth = idx + 1 > -1 && idx + 1 < runes.Length
  1055. ? runes [idx + 1].GetColumns ()
  1056. : 0;
  1057. if (!isVertical && idx + 1 < runes.Length && current + nextRuneWidth > start + size)
  1058. {
  1059. break;
  1060. }
  1061. }
  1062. // Add the line's drawn region to the overall region
  1063. if (lineWidth > 0 && lineHeight > 0)
  1064. {
  1065. drawnRegion.Union (new Rectangle (lineX, lineY, lineWidth, lineHeight));
  1066. }
  1067. }
  1068. return drawnRegion;
  1069. }
  1070. #region Static Members
  1071. /// <summary>Check if it is a horizontal direction</summary>
  1072. public static bool IsHorizontalDirection (TextDirection textDirection)
  1073. {
  1074. return textDirection switch
  1075. {
  1076. TextDirection.LeftRight_TopBottom => true,
  1077. TextDirection.LeftRight_BottomTop => true,
  1078. TextDirection.RightLeft_TopBottom => true,
  1079. TextDirection.RightLeft_BottomTop => true,
  1080. _ => false
  1081. };
  1082. }
  1083. /// <summary>Check if it is a vertical direction</summary>
  1084. public static bool IsVerticalDirection (TextDirection textDirection)
  1085. {
  1086. return textDirection switch
  1087. {
  1088. TextDirection.TopBottom_LeftRight => true,
  1089. TextDirection.TopBottom_RightLeft => true,
  1090. TextDirection.BottomTop_LeftRight => true,
  1091. TextDirection.BottomTop_RightLeft => true,
  1092. _ => false
  1093. };
  1094. }
  1095. /// <summary>Check if it is Left to Right direction</summary>
  1096. public static bool IsLeftToRight (TextDirection textDirection)
  1097. {
  1098. return textDirection switch
  1099. {
  1100. TextDirection.LeftRight_TopBottom => true,
  1101. TextDirection.LeftRight_BottomTop => true,
  1102. _ => false
  1103. };
  1104. }
  1105. /// <summary>Check if it is Top to Bottom direction</summary>
  1106. public static bool IsTopToBottom (TextDirection textDirection)
  1107. {
  1108. return textDirection switch
  1109. {
  1110. TextDirection.TopBottom_LeftRight => true,
  1111. TextDirection.TopBottom_RightLeft => true,
  1112. _ => false
  1113. };
  1114. }
  1115. // TODO: Move to StringExtensions?
  1116. internal static string StripCRLF (string str, bool keepNewLine = false)
  1117. {
  1118. ReadOnlySpan<char> remaining = str.AsSpan ();
  1119. int firstNewlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1120. // Early exit to avoid StringBuilder allocation if there are no newline characters.
  1121. if (firstNewlineCharIndex < 0)
  1122. {
  1123. return str;
  1124. }
  1125. StringBuilder stringBuilder = new();
  1126. ReadOnlySpan<char> firstSegment = remaining[..firstNewlineCharIndex];
  1127. stringBuilder.Append (firstSegment);
  1128. // The first newline is not yet skipped because the "keepNewLine" condition has not been evaluated.
  1129. // This means there will be 1 extra iteration because the same newline index is checked again in the loop.
  1130. remaining = remaining [firstNewlineCharIndex..];
  1131. while (remaining.Length > 0)
  1132. {
  1133. int newlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1134. if (newlineCharIndex == -1)
  1135. {
  1136. break;
  1137. }
  1138. ReadOnlySpan<char> segment = remaining[..newlineCharIndex];
  1139. stringBuilder.Append (segment);
  1140. int stride = segment.Length;
  1141. // Evaluate how many line break characters to preserve.
  1142. char newlineChar = remaining [newlineCharIndex];
  1143. if (newlineChar == '\n')
  1144. {
  1145. stride++;
  1146. if (keepNewLine)
  1147. {
  1148. stringBuilder.Append ('\n');
  1149. }
  1150. }
  1151. else // '\r'
  1152. {
  1153. int nextCharIndex = newlineCharIndex + 1;
  1154. bool crlf = nextCharIndex < remaining.Length && remaining [nextCharIndex] == '\n';
  1155. if (crlf)
  1156. {
  1157. stride += 2;
  1158. if (keepNewLine)
  1159. {
  1160. stringBuilder.Append ('\n');
  1161. }
  1162. }
  1163. else
  1164. {
  1165. stride++;
  1166. if (keepNewLine)
  1167. {
  1168. stringBuilder.Append ('\r');
  1169. }
  1170. }
  1171. }
  1172. remaining = remaining [stride..];
  1173. }
  1174. stringBuilder.Append (remaining);
  1175. return stringBuilder.ToString ();
  1176. }
  1177. // TODO: Move to StringExtensions?
  1178. internal static string ReplaceCRLFWithSpace (string str)
  1179. {
  1180. ReadOnlySpan<char> remaining = str.AsSpan ();
  1181. int firstNewlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1182. // Early exit to avoid StringBuilder allocation if there are no newline characters.
  1183. if (firstNewlineCharIndex < 0)
  1184. {
  1185. return str;
  1186. }
  1187. StringBuilder stringBuilder = new();
  1188. ReadOnlySpan<char> firstSegment = remaining[..firstNewlineCharIndex];
  1189. stringBuilder.Append (firstSegment);
  1190. // The first newline is not yet skipped because the newline type has not been evaluated.
  1191. // This means there will be 1 extra iteration because the same newline index is checked again in the loop.
  1192. remaining = remaining [firstNewlineCharIndex..];
  1193. while (remaining.Length > 0)
  1194. {
  1195. int newlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1196. if (newlineCharIndex == -1)
  1197. {
  1198. break;
  1199. }
  1200. ReadOnlySpan<char> segment = remaining[..newlineCharIndex];
  1201. stringBuilder.Append (segment);
  1202. int stride = segment.Length;
  1203. // Replace newlines
  1204. char newlineChar = remaining [newlineCharIndex];
  1205. if (newlineChar == '\n')
  1206. {
  1207. stride++;
  1208. stringBuilder.Append (' ');
  1209. }
  1210. else // '\r'
  1211. {
  1212. int nextCharIndex = newlineCharIndex + 1;
  1213. bool crlf = nextCharIndex < remaining.Length && remaining [nextCharIndex] == '\n';
  1214. if (crlf)
  1215. {
  1216. stride += 2;
  1217. stringBuilder.Append (' ');
  1218. }
  1219. else
  1220. {
  1221. stride++;
  1222. stringBuilder.Append (' ');
  1223. }
  1224. }
  1225. remaining = remaining [stride..];
  1226. }
  1227. stringBuilder.Append (remaining);
  1228. return stringBuilder.ToString ();
  1229. }
  1230. // TODO: Move to StringExtensions?
  1231. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  1232. {
  1233. if (tabWidth == 0)
  1234. {
  1235. return str.Replace ("\t", "");
  1236. }
  1237. return str.Replace ("\t", new (' ', tabWidth));
  1238. }
  1239. // TODO: Move to StringExtensions?
  1240. /// <summary>
  1241. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  1242. /// ending newline.
  1243. /// </summary>
  1244. /// <param name="text">The text.</param>
  1245. /// <returns>A list of text without the newline characters.</returns>
  1246. public static List<string> SplitNewLine (string text)
  1247. {
  1248. List<Rune> runes = text.ToRuneList ();
  1249. List<string> lines = new ();
  1250. var start = 0;
  1251. for (var i = 0; i < runes.Count; i++)
  1252. {
  1253. int end = i;
  1254. switch (runes [i].Value)
  1255. {
  1256. case '\n':
  1257. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1258. i++;
  1259. start = i;
  1260. break;
  1261. case '\r':
  1262. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  1263. {
  1264. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1265. i += 2;
  1266. start = i;
  1267. }
  1268. else
  1269. {
  1270. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1271. i++;
  1272. start = i;
  1273. }
  1274. break;
  1275. }
  1276. }
  1277. switch (runes.Count)
  1278. {
  1279. case > 0 when lines.Count == 0:
  1280. lines.Add (StringExtensions.ToString (runes));
  1281. break;
  1282. case > 0 when start < runes.Count:
  1283. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  1284. break;
  1285. default:
  1286. lines.Add ("");
  1287. break;
  1288. }
  1289. return lines;
  1290. }
  1291. // TODO: Move to StringExtensions?
  1292. /// <summary>
  1293. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  1294. /// columns. Note that some unicode characters take 2+ columns
  1295. /// </summary>
  1296. /// <param name="text"></param>
  1297. /// <param name="width"></param>
  1298. /// <returns></returns>
  1299. public static string ClipOrPad (string text, int width)
  1300. {
  1301. if (string.IsNullOrEmpty (text))
  1302. {
  1303. return text;
  1304. }
  1305. // if value is not wide enough
  1306. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width)
  1307. {
  1308. // pad it out with spaces to the given Alignment
  1309. int toPad = width - text.EnumerateRunes ().Sum (c => c.GetColumns ());
  1310. return text + new string (' ', toPad);
  1311. }
  1312. // value is too wide
  1313. return new (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  1314. }
  1315. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  1316. /// <param name="text">The text to word wrap</param>
  1317. /// <param name="width">The number of columns to constrain the text to</param>
  1318. /// <param name="preserveTrailingSpaces">
  1319. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1320. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1321. /// </param>
  1322. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1323. /// <param name="textDirection">The text direction.</param>
  1324. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1325. /// <returns>A list of word wrapped lines.</returns>
  1326. /// <remarks>
  1327. /// <para>This method does not do any alignment.</para>
  1328. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  1329. /// <para>
  1330. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  1331. /// at the end of the last line.
  1332. /// </para>
  1333. /// </remarks>
  1334. /// <returns>A list of lines.</returns>
  1335. public static List<string> WordWrapText (
  1336. string text,
  1337. int width,
  1338. bool preserveTrailingSpaces = false,
  1339. int tabWidth = 0,
  1340. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1341. TextFormatter? textFormatter = null
  1342. )
  1343. {
  1344. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1345. List<string> lines = new ();
  1346. if (string.IsNullOrEmpty (text))
  1347. {
  1348. return lines;
  1349. }
  1350. List<Rune> runes = StripCRLF (text).ToRuneList ();
  1351. int start = Math.Max (
  1352. !runes.Contains ((Rune)' ') && textFormatter is { VerticalAlignment: Alignment.End } && IsVerticalDirection (textDirection)
  1353. ? runes.Count - width
  1354. : 0,
  1355. 0);
  1356. int end;
  1357. if (preserveTrailingSpaces)
  1358. {
  1359. while ((end = start) < runes.Count)
  1360. {
  1361. end = GetNextWhiteSpace (start, width, out bool incomplete);
  1362. if (end == 0 && incomplete)
  1363. {
  1364. start = text.GetRuneCount ();
  1365. break;
  1366. }
  1367. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1368. start = end;
  1369. if (incomplete)
  1370. {
  1371. start = text.GetRuneCount ();
  1372. break;
  1373. }
  1374. }
  1375. }
  1376. else
  1377. {
  1378. if (IsHorizontalDirection (textDirection))
  1379. {
  1380. while ((end = start
  1381. + GetLengthThatFits (
  1382. runes.GetRange (start, runes.Count - start),
  1383. width,
  1384. tabWidth,
  1385. textDirection
  1386. ))
  1387. < runes.Count)
  1388. {
  1389. while (runes [end].Value != ' ' && end > start)
  1390. {
  1391. end--;
  1392. }
  1393. if (end == start)
  1394. {
  1395. end = start
  1396. + GetLengthThatFits (
  1397. runes.GetRange (end, runes.Count - end),
  1398. width,
  1399. tabWidth,
  1400. textDirection
  1401. );
  1402. }
  1403. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  1404. int zeroLength = text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1405. if (end > start && GetRuneWidth (str, tabWidth, textDirection) <= width + zeroLength)
  1406. {
  1407. lines.Add (str);
  1408. start = end;
  1409. if (runes [end].Value == ' ')
  1410. {
  1411. start++;
  1412. }
  1413. }
  1414. else
  1415. {
  1416. end++;
  1417. start = end;
  1418. }
  1419. }
  1420. }
  1421. else
  1422. {
  1423. while ((end = start + width) < runes.Count)
  1424. {
  1425. while (runes [end].Value != ' ' && end > start)
  1426. {
  1427. end--;
  1428. }
  1429. if (end == start)
  1430. {
  1431. end = start + width;
  1432. }
  1433. var zeroLength = 0;
  1434. for (int i = end; i < runes.Count - start; i++)
  1435. {
  1436. Rune r = runes [i];
  1437. if (r.GetColumns () == 0)
  1438. {
  1439. zeroLength++;
  1440. }
  1441. else
  1442. {
  1443. break;
  1444. }
  1445. }
  1446. lines.Add (
  1447. StringExtensions.ToString (
  1448. runes.GetRange (
  1449. start,
  1450. end - start + zeroLength
  1451. )
  1452. )
  1453. );
  1454. end += zeroLength;
  1455. start = end;
  1456. if (runes [end].Value == ' ')
  1457. {
  1458. start++;
  1459. }
  1460. }
  1461. }
  1462. }
  1463. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1464. {
  1465. int to = from;
  1466. int length = cLength;
  1467. incomplete = false;
  1468. while (length < cWidth && to < runes.Count)
  1469. {
  1470. Rune rune = runes [to];
  1471. if (IsHorizontalDirection (textDirection))
  1472. {
  1473. length += rune.GetColumns ();
  1474. }
  1475. else
  1476. {
  1477. length++;
  1478. }
  1479. if (length > cWidth)
  1480. {
  1481. if (to >= runes.Count || (length > 1 && cWidth <= 1))
  1482. {
  1483. incomplete = true;
  1484. }
  1485. return to;
  1486. }
  1487. switch (rune.Value)
  1488. {
  1489. case ' ' when length == cWidth:
  1490. return to + 1;
  1491. case ' ' when length > cWidth:
  1492. return to;
  1493. case ' ':
  1494. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1495. case '\t':
  1496. {
  1497. length += tabWidth + 1;
  1498. if (length == tabWidth && tabWidth > cWidth)
  1499. {
  1500. return to + 1;
  1501. }
  1502. if (length > cWidth && tabWidth > cWidth)
  1503. {
  1504. return to;
  1505. }
  1506. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1507. }
  1508. default:
  1509. to++;
  1510. break;
  1511. }
  1512. }
  1513. return cLength switch
  1514. {
  1515. > 0 when to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t' => from,
  1516. > 0 when to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t') => from,
  1517. _ => to
  1518. };
  1519. }
  1520. if (start < text.GetRuneCount ())
  1521. {
  1522. string str = ReplaceTABWithSpaces (
  1523. StringExtensions.ToString (runes.GetRange (start, runes.Count - start)),
  1524. tabWidth
  1525. );
  1526. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1527. {
  1528. lines.Add (str);
  1529. }
  1530. }
  1531. return lines;
  1532. }
  1533. /// <summary>Justifies text within a specified width.</summary>
  1534. /// <param name="text">The text to justify.</param>
  1535. /// <param name="width">
  1536. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1537. /// clipped.
  1538. /// </param>
  1539. /// <param name="textAlignment">Alignment.</param>
  1540. /// <param name="textDirection">The text direction.</param>
  1541. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1542. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1543. /// <returns>Justified and clipped text.</returns>
  1544. public static string ClipAndJustify (
  1545. string text,
  1546. int width,
  1547. Alignment textAlignment,
  1548. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1549. int tabWidth = 0,
  1550. TextFormatter? textFormatter = null
  1551. )
  1552. {
  1553. return ClipAndJustify (text, width, textAlignment == Alignment.Fill, textDirection, tabWidth, textFormatter);
  1554. }
  1555. /// <summary>Justifies text within a specified width.</summary>
  1556. /// <param name="text">The text to justify.</param>
  1557. /// <param name="width">
  1558. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1559. /// clipped.
  1560. /// </param>
  1561. /// <param name="justify">Justify.</param>
  1562. /// <param name="textDirection">The text direction.</param>
  1563. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1564. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1565. /// <returns>Justified and clipped text.</returns>
  1566. public static string ClipAndJustify (
  1567. string text,
  1568. int width,
  1569. bool justify,
  1570. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1571. int tabWidth = 0,
  1572. TextFormatter? textFormatter = null
  1573. )
  1574. {
  1575. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1576. if (string.IsNullOrEmpty (text))
  1577. {
  1578. return text;
  1579. }
  1580. text = ReplaceTABWithSpaces (text, tabWidth);
  1581. List<Rune> runes = text.ToRuneList ();
  1582. int zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1583. if (runes.Count - zeroLength > width)
  1584. {
  1585. if (IsHorizontalDirection (textDirection))
  1586. {
  1587. if (textFormatter is { Alignment: Alignment.End })
  1588. {
  1589. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1590. }
  1591. if (textFormatter is { Alignment: Alignment.Center })
  1592. {
  1593. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1594. }
  1595. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1596. }
  1597. if (IsVerticalDirection (textDirection))
  1598. {
  1599. if (textFormatter is { VerticalAlignment: Alignment.End })
  1600. {
  1601. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1602. }
  1603. if (textFormatter is { VerticalAlignment: Alignment.Center })
  1604. {
  1605. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1606. }
  1607. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1608. }
  1609. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  1610. }
  1611. if (justify)
  1612. {
  1613. return Justify (text, width, ' ', textDirection, tabWidth);
  1614. }
  1615. if (IsHorizontalDirection (textDirection))
  1616. {
  1617. if (textFormatter is { Alignment: Alignment.End })
  1618. {
  1619. if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1620. {
  1621. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1622. }
  1623. }
  1624. else if (textFormatter is { Alignment: Alignment.Center })
  1625. {
  1626. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1627. }
  1628. else if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1629. {
  1630. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1631. }
  1632. }
  1633. if (IsVerticalDirection (textDirection))
  1634. {
  1635. if (textFormatter is { VerticalAlignment: Alignment.End })
  1636. {
  1637. if (runes.Count - zeroLength > width)
  1638. {
  1639. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1640. }
  1641. }
  1642. else if (textFormatter is { VerticalAlignment: Alignment.Center })
  1643. {
  1644. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1645. }
  1646. else if (runes.Count - zeroLength > width)
  1647. {
  1648. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1649. }
  1650. }
  1651. return text;
  1652. }
  1653. private static string GetRangeThatFits (List<Rune> runes, int index, string text, int width, int tabWidth, TextDirection textDirection)
  1654. {
  1655. return StringExtensions.ToString (
  1656. runes.GetRange (
  1657. Math.Max (index, 0),
  1658. GetLengthThatFits (text, width, tabWidth, textDirection)
  1659. )
  1660. );
  1661. }
  1662. /// <summary>
  1663. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1664. /// <c>width</c>. Spaces will not be added to the start or end.
  1665. /// </summary>
  1666. /// <param name="text"></param>
  1667. /// <param name="width"></param>
  1668. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1669. /// <param name="textDirection">The text direction.</param>
  1670. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1671. /// <returns>The justified text.</returns>
  1672. public static string Justify (
  1673. string text,
  1674. int width,
  1675. char spaceChar = ' ',
  1676. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1677. int tabWidth = 0
  1678. )
  1679. {
  1680. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1681. if (string.IsNullOrEmpty (text))
  1682. {
  1683. return text;
  1684. }
  1685. text = ReplaceTABWithSpaces (text, tabWidth);
  1686. string [] words = text.Split (' ');
  1687. int textCount;
  1688. if (IsHorizontalDirection (textDirection))
  1689. {
  1690. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth, textDirection));
  1691. }
  1692. else
  1693. {
  1694. textCount = words.Sum (arg => arg.GetRuneCount ()) - text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1695. }
  1696. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1697. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1698. var s = new StringBuilder ();
  1699. for (var w = 0; w < words.Length; w++)
  1700. {
  1701. string x = words [w];
  1702. s.Append (x);
  1703. if (w + 1 < words.Length)
  1704. {
  1705. for (var i = 0; i < spaces; i++)
  1706. {
  1707. s.Append (spaceChar);
  1708. }
  1709. }
  1710. if (extras > 0)
  1711. {
  1712. for (var i = 0; i < 1; i++)
  1713. {
  1714. s.Append (spaceChar);
  1715. }
  1716. extras--;
  1717. }
  1718. if (w + 1 == words.Length - 1)
  1719. {
  1720. for (var i = 0; i < extras; i++)
  1721. {
  1722. s.Append (spaceChar);
  1723. }
  1724. }
  1725. }
  1726. return s.ToString ();
  1727. }
  1728. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1729. /// <param name="text"></param>
  1730. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1731. /// <param name="textAlignment">Specifies how the text will be aligned horizontally.</param>
  1732. /// <param name="wordWrap">
  1733. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1734. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1735. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1736. /// </param>
  1737. /// <param name="preserveTrailingSpaces">
  1738. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1739. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1740. /// </param>
  1741. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1742. /// <param name="textDirection">The text direction.</param>
  1743. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1744. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1745. /// <returns>A list of word wrapped lines.</returns>
  1746. /// <remarks>
  1747. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1748. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1749. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1750. /// </remarks>
  1751. public static List<string> Format (
  1752. string text,
  1753. int width,
  1754. Alignment textAlignment,
  1755. bool wordWrap,
  1756. bool preserveTrailingSpaces = false,
  1757. int tabWidth = 0,
  1758. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1759. bool multiLine = false,
  1760. TextFormatter? textFormatter = null
  1761. )
  1762. {
  1763. return Format (
  1764. text,
  1765. width,
  1766. textAlignment == Alignment.Fill,
  1767. wordWrap,
  1768. preserveTrailingSpaces,
  1769. tabWidth,
  1770. textDirection,
  1771. multiLine,
  1772. textFormatter
  1773. );
  1774. }
  1775. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1776. /// <param name="text"></param>
  1777. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1778. /// <param name="justify">Specifies whether the text should be justified.</param>
  1779. /// <param name="wordWrap">
  1780. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1781. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1782. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1783. /// </param>
  1784. /// <param name="preserveTrailingSpaces">
  1785. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1786. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1787. /// </param>
  1788. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1789. /// <param name="textDirection">The text direction.</param>
  1790. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1791. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1792. /// <returns>A list of word wrapped lines.</returns>
  1793. /// <remarks>
  1794. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1795. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1796. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1797. /// </remarks>
  1798. public static List<string> Format (
  1799. string text,
  1800. int width,
  1801. bool justify,
  1802. bool wordWrap,
  1803. bool preserveTrailingSpaces = false,
  1804. int tabWidth = 0,
  1805. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1806. bool multiLine = false,
  1807. TextFormatter? textFormatter = null
  1808. )
  1809. {
  1810. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1811. List<string> lineResult = new ();
  1812. if (string.IsNullOrEmpty (text) || width == 0)
  1813. {
  1814. lineResult.Add (string.Empty);
  1815. return lineResult;
  1816. }
  1817. if (!wordWrap)
  1818. {
  1819. text = ReplaceTABWithSpaces (text, tabWidth);
  1820. if (multiLine)
  1821. {
  1822. // Abhorrent case: Just a new line
  1823. if (text == "\n")
  1824. {
  1825. lineResult.Add (string.Empty);
  1826. return lineResult;
  1827. }
  1828. string []? lines = null;
  1829. if (text.Contains ("\r\n"))
  1830. {
  1831. lines = text.Split ("\r\n");
  1832. }
  1833. else if (text.Contains ('\n'))
  1834. {
  1835. lines = text.Split ('\n');
  1836. }
  1837. lines ??= new [] { text };
  1838. foreach (string line in lines)
  1839. {
  1840. lineResult.Add (
  1841. ClipAndJustify (
  1842. PerformCorrectFormatDirection (textDirection, line),
  1843. width,
  1844. justify,
  1845. textDirection,
  1846. tabWidth,
  1847. textFormatter));
  1848. }
  1849. return PerformCorrectFormatDirection (textDirection, lineResult);
  1850. }
  1851. text = ReplaceCRLFWithSpace (text);
  1852. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, text), width, justify, textDirection, tabWidth, textFormatter));
  1853. return PerformCorrectFormatDirection (textDirection, lineResult);
  1854. }
  1855. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1856. int runeCount = runes.Count;
  1857. var lp = 0;
  1858. for (var i = 0; i < runeCount; i++)
  1859. {
  1860. Rune c = runes [i];
  1861. if (c.Value == '\n')
  1862. {
  1863. List<string> wrappedLines =
  1864. WordWrapText (
  1865. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, i - lp))),
  1866. width,
  1867. preserveTrailingSpaces,
  1868. tabWidth,
  1869. textDirection,
  1870. textFormatter
  1871. );
  1872. foreach (string line in wrappedLines)
  1873. {
  1874. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1875. }
  1876. if (wrappedLines.Count == 0)
  1877. {
  1878. lineResult.Add (string.Empty);
  1879. }
  1880. lp = i + 1;
  1881. }
  1882. }
  1883. foreach (string line in WordWrapText (
  1884. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, runeCount - lp))),
  1885. width,
  1886. preserveTrailingSpaces,
  1887. tabWidth,
  1888. textDirection,
  1889. textFormatter
  1890. ))
  1891. {
  1892. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1893. }
  1894. return PerformCorrectFormatDirection (textDirection, lineResult);
  1895. }
  1896. private static string PerformCorrectFormatDirection (TextDirection textDirection, string line)
  1897. {
  1898. return textDirection switch
  1899. {
  1900. TextDirection.RightLeft_BottomTop
  1901. or TextDirection.RightLeft_TopBottom
  1902. or TextDirection.BottomTop_LeftRight
  1903. or TextDirection.BottomTop_RightLeft => StringExtensions.ToString (line.EnumerateRunes ().Reverse ()),
  1904. _ => line
  1905. };
  1906. }
  1907. private static List<Rune> PerformCorrectFormatDirection (TextDirection textDirection, List<Rune> runes)
  1908. {
  1909. return PerformCorrectFormatDirection (textDirection, StringExtensions.ToString (runes)).ToRuneList ();
  1910. }
  1911. private static List<string> PerformCorrectFormatDirection (TextDirection textDirection, List<string> lines)
  1912. {
  1913. return textDirection switch
  1914. {
  1915. TextDirection.TopBottom_RightLeft
  1916. or TextDirection.LeftRight_BottomTop
  1917. or TextDirection.RightLeft_BottomTop
  1918. or TextDirection.BottomTop_RightLeft => lines.ToArray ().Reverse ().ToList (),
  1919. _ => lines
  1920. };
  1921. }
  1922. /// <summary>
  1923. /// Returns the number of columns required to render <paramref name="lines"/> oriented vertically.
  1924. /// </summary>
  1925. /// <remarks>
  1926. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1927. /// glyphs (e.g. Arabic).
  1928. /// </remarks>
  1929. /// <param name="lines">The lines.</param>
  1930. /// <param name="startLine">The line in the list to start with (any lines before will be ignored).</param>
  1931. /// <param name="linesCount">
  1932. /// The number of lines to process (if less than <c>lines.Count</c>, any lines after will be
  1933. /// ignored).
  1934. /// </param>
  1935. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1936. /// <returns>The width required.</returns>
  1937. public static int GetColumnsRequiredForVerticalText (
  1938. List<string> lines,
  1939. int startLine = -1,
  1940. int linesCount = -1,
  1941. int tabWidth = 0
  1942. )
  1943. {
  1944. var max = 0;
  1945. for (int i = startLine == -1 ? 0 : startLine;
  1946. i < (linesCount == -1 ? lines.Count : startLine + linesCount);
  1947. i++)
  1948. {
  1949. string runes = lines [i];
  1950. if (runes.Length > 0)
  1951. {
  1952. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1953. }
  1954. }
  1955. return max;
  1956. }
  1957. /// <summary>
  1958. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1959. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1960. /// </summary>
  1961. /// <remarks>
  1962. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1963. /// glyphs (e.g. Arabic).
  1964. /// </remarks>
  1965. /// <param name="text">Text, may contain newlines.</param>
  1966. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1967. /// <returns>The length of the longest line.</returns>
  1968. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1969. {
  1970. List<string> result = SplitNewLine (text);
  1971. return result.Max (x => GetRuneWidth (x, tabWidth));
  1972. }
  1973. /// <summary>
  1974. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1975. /// <paramref name="length"/>.
  1976. /// </summary>
  1977. /// <remarks>
  1978. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1979. /// glyphs (e.g. Arabic).
  1980. /// </remarks>
  1981. /// <param name="text">The text.</param>
  1982. /// <param name="startIndex">The start index.</param>
  1983. /// <param name="length">The length.</param>
  1984. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1985. /// <returns>The maximum characters width.</returns>
  1986. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1987. {
  1988. var max = 0;
  1989. Rune [] runes = text.ToRunes ();
  1990. for (int i = startIndex == -1 ? 0 : startIndex;
  1991. i < (length == -1 ? runes.Length : startIndex + length);
  1992. i++)
  1993. {
  1994. max += GetRuneWidth (runes [i], tabWidth);
  1995. }
  1996. return max;
  1997. }
  1998. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="width"/>.</summary>
  1999. /// <remarks>
  2000. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  2001. /// glyphs (e.g. Arabic).
  2002. /// </remarks>
  2003. /// <param name="text">The text.</param>
  2004. /// <param name="width">The width.</param>
  2005. /// <param name="tabWidth">The width used for a tab.</param>
  2006. /// <param name="textDirection">The text direction.</param>
  2007. /// <returns>The index of the text that fit the width.</returns>
  2008. public static int GetLengthThatFits (string text, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  2009. {
  2010. return GetLengthThatFits (text?.ToRuneList () ?? [], width, tabWidth, textDirection);
  2011. }
  2012. /// <summary>Gets the number of the Runes in a list of Runes that will fit in <paramref name="width"/>.</summary>
  2013. /// <remarks>
  2014. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  2015. /// glyphs (e.g. Arabic).
  2016. /// </remarks>
  2017. /// <param name="runes">The list of runes.</param>
  2018. /// <param name="width">The width.</param>
  2019. /// <param name="tabWidth">The width used for a tab.</param>
  2020. /// <param name="textDirection">The text direction.</param>
  2021. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="width"/>.</returns>
  2022. public static int GetLengthThatFits (List<Rune> runes, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  2023. {
  2024. if (runes is null || runes.Count == 0)
  2025. {
  2026. return 0;
  2027. }
  2028. var runesLength = 0;
  2029. var runeIdx = 0;
  2030. for (; runeIdx < runes.Count; runeIdx++)
  2031. {
  2032. int runeWidth = GetRuneWidth (runes [runeIdx], tabWidth, textDirection);
  2033. if (runesLength + runeWidth > width)
  2034. {
  2035. break;
  2036. }
  2037. runesLength += runeWidth;
  2038. }
  2039. return runeIdx;
  2040. }
  2041. private static int GetRuneWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  2042. {
  2043. int runesWidth = 0;
  2044. foreach (Rune rune in str.EnumerateRunes ())
  2045. {
  2046. runesWidth += GetRuneWidth (rune, tabWidth, textDirection);
  2047. }
  2048. return runesWidth;
  2049. }
  2050. private static int GetRuneWidth (Rune rune, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  2051. {
  2052. int runeWidth = IsHorizontalDirection (textDirection) ? rune.GetColumns () : rune.GetColumns () == 0 ? 0 : 1;
  2053. if (rune.Value == '\t')
  2054. {
  2055. return tabWidth;
  2056. }
  2057. if (runeWidth < 0 || runeWidth > 0)
  2058. {
  2059. return Math.Max (runeWidth, 1);
  2060. }
  2061. return runeWidth;
  2062. }
  2063. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  2064. /// <remarks>
  2065. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  2066. /// glyphs (e.g. Arabic).
  2067. /// </remarks>
  2068. /// <param name="lines">The lines.</param>
  2069. /// <param name="width">The width.</param>
  2070. /// <param name="tabWidth">The number of columns used for a tab.</param>
  2071. /// <returns>The index of the list that fit the width.</returns>
  2072. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  2073. {
  2074. var runesLength = 0;
  2075. var lineIdx = 0;
  2076. for (; lineIdx < lines.Count; lineIdx++)
  2077. {
  2078. List<Rune> runes = lines [lineIdx].ToRuneList ();
  2079. int maxRruneWidth = runes.Count > 0
  2080. ? runes.Max (r => GetRuneWidth (r, tabWidth))
  2081. : 1;
  2082. if (runesLength + maxRruneWidth > width)
  2083. {
  2084. break;
  2085. }
  2086. runesLength += maxRruneWidth;
  2087. }
  2088. return lineIdx;
  2089. }
  2090. /// <summary>Finds the HotKey and its location in text.</summary>
  2091. /// <param name="text">The text to look in.</param>
  2092. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  2093. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  2094. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  2095. /// <param name="firstUpperCase">
  2096. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  2097. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  2098. /// Defaults to <see langword="false"/>.
  2099. /// </param>
  2100. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  2101. public static bool FindHotKey (
  2102. string text,
  2103. Rune hotKeySpecifier,
  2104. out int hotPos,
  2105. out Key hotKey,
  2106. bool firstUpperCase = false
  2107. )
  2108. {
  2109. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  2110. {
  2111. hotPos = -1;
  2112. hotKey = Key.Empty;
  2113. return false;
  2114. }
  2115. var curHotKey = (Rune)0;
  2116. int curHotPos = -1;
  2117. // Use first hot_key char passed into 'hotKey'.
  2118. // TODO: Ignore hot_key of two are provided
  2119. // TODO: Do not support non-alphanumeric chars that can't be typed
  2120. var i = 0;
  2121. foreach (Rune c in text.EnumerateRunes ())
  2122. {
  2123. if ((char)c.Value != 0xFFFD)
  2124. {
  2125. if (c == hotKeySpecifier)
  2126. {
  2127. curHotPos = i;
  2128. }
  2129. else if (curHotPos > -1)
  2130. {
  2131. curHotKey = c;
  2132. break;
  2133. }
  2134. }
  2135. i++;
  2136. }
  2137. // Legacy support - use first upper case char if the specifier was not found
  2138. if (curHotPos == -1 && firstUpperCase)
  2139. {
  2140. i = 0;
  2141. foreach (Rune c in text.EnumerateRunes ())
  2142. {
  2143. if ((char)c.Value != 0xFFFD)
  2144. {
  2145. if (Rune.IsUpper (c))
  2146. {
  2147. curHotKey = c;
  2148. curHotPos = i;
  2149. break;
  2150. }
  2151. }
  2152. i++;
  2153. }
  2154. }
  2155. if (curHotKey != (Rune)0 && curHotPos != -1)
  2156. {
  2157. hotPos = curHotPos;
  2158. var newHotKey = (KeyCode)curHotKey.Value;
  2159. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  2160. {
  2161. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  2162. {
  2163. newHotKey &= ~KeyCode.Space;
  2164. }
  2165. hotKey = newHotKey;
  2166. //hotKey.Scope = KeyBindingScope.HotKey;
  2167. return true;
  2168. }
  2169. }
  2170. hotPos = -1;
  2171. hotKey = KeyCode.Null;
  2172. return false;
  2173. }
  2174. /// <summary>
  2175. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  2176. /// hotkey.
  2177. /// </summary>
  2178. /// <param name="text">The text to tag the hotkey in.</param>
  2179. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  2180. /// <returns>The text with the hotkey tagged.</returns>
  2181. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  2182. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  2183. {
  2184. // Set the high bit
  2185. List<Rune> runes = text.ToRuneList ();
  2186. if (Rune.IsLetterOrDigit (runes [hotPos]))
  2187. {
  2188. runes [hotPos] = new ((uint)runes [hotPos].Value);
  2189. }
  2190. return StringExtensions.ToString (runes);
  2191. }
  2192. /// <summary>Removes the hotkey specifier from text.</summary>
  2193. /// <param name="text">The text to manipulate.</param>
  2194. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  2195. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  2196. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  2197. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  2198. {
  2199. if (string.IsNullOrEmpty (text))
  2200. {
  2201. return text;
  2202. }
  2203. const int maxStackallocCharBufferSize = 512; // ~1 kB
  2204. char[]? rentedBufferArray = null;
  2205. try
  2206. {
  2207. Span<char> buffer = text.Length <= maxStackallocCharBufferSize
  2208. ? stackalloc char[text.Length]
  2209. : (rentedBufferArray = ArrayPool<char>.Shared.Rent(text.Length));
  2210. int i = 0;
  2211. var remainingBuffer = buffer;
  2212. foreach (Rune c in text.EnumerateRunes ())
  2213. {
  2214. if (c == hotKeySpecifier && i == hotPos)
  2215. {
  2216. i++;
  2217. continue;
  2218. }
  2219. int charsWritten = c.EncodeToUtf16 (remainingBuffer);
  2220. remainingBuffer = remainingBuffer [charsWritten..];
  2221. i++;
  2222. }
  2223. ReadOnlySpan<char> newText = buffer [..^remainingBuffer.Length];
  2224. // If the resulting string would be the same as original then just return the original.
  2225. if (newText.Equals(text, StringComparison.Ordinal))
  2226. {
  2227. return text;
  2228. }
  2229. return new string (newText);
  2230. }
  2231. finally
  2232. {
  2233. if (rentedBufferArray != null)
  2234. {
  2235. ArrayPool<char>.Shared.Return (rentedBufferArray);
  2236. }
  2237. }
  2238. }
  2239. #endregion // Static Members
  2240. }