TextFormatter.cs 91 KB

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