TextFormatter.cs 91 KB

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