TextFormatter.cs 92 KB

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