2
0

TextFormatter.cs 92 KB

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