TextFormatter.cs 94 KB

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