TextFormatter.cs 89 KB

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