TextFormatter.cs 91 KB

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