TextFormatter.cs 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432
  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. StringBuilder stringBuilder = new();
  1033. ReadOnlySpan<char> remaining = str.AsSpan ();
  1034. while (remaining.Length > 0)
  1035. {
  1036. int nextLineBreakIndex = remaining.IndexOfAny (NewLineSearchValues);
  1037. if (nextLineBreakIndex == -1)
  1038. {
  1039. if (str.Length == remaining.Length)
  1040. {
  1041. return str;
  1042. }
  1043. stringBuilder.Append (remaining);
  1044. break;
  1045. }
  1046. ReadOnlySpan<char> slice = remaining.Slice (0, nextLineBreakIndex);
  1047. stringBuilder.Append (slice);
  1048. // Evaluate how many line break characters to preserve.
  1049. int stride;
  1050. char lineBreakChar = remaining [nextLineBreakIndex];
  1051. if (lineBreakChar == '\n')
  1052. {
  1053. stride = 1;
  1054. if (keepNewLine)
  1055. {
  1056. stringBuilder.Append ('\n');
  1057. }
  1058. }
  1059. else // '\r'
  1060. {
  1061. bool crlf = (nextLineBreakIndex + 1) < remaining.Length && remaining [nextLineBreakIndex + 1] == '\n';
  1062. if (crlf)
  1063. {
  1064. stride = 2;
  1065. if (keepNewLine)
  1066. {
  1067. stringBuilder.Append ('\n');
  1068. }
  1069. }
  1070. else
  1071. {
  1072. stride = 1;
  1073. if (keepNewLine)
  1074. {
  1075. stringBuilder.Append ('\r');
  1076. }
  1077. }
  1078. }
  1079. remaining = remaining.Slice (slice.Length + stride);
  1080. }
  1081. return stringBuilder.ToString ();
  1082. }
  1083. // TODO: Move to StringExtensions?
  1084. internal static string ReplaceCRLFWithSpace (string str)
  1085. {
  1086. List<Rune> runes = str.ToRuneList ();
  1087. for (var i = 0; i < runes.Count; i++)
  1088. {
  1089. switch (runes [i].Value)
  1090. {
  1091. case '\n':
  1092. runes [i] = (Rune)' ';
  1093. break;
  1094. case '\r':
  1095. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  1096. {
  1097. runes [i] = (Rune)' ';
  1098. runes.RemoveAt (i + 1);
  1099. i++;
  1100. }
  1101. else
  1102. {
  1103. runes [i] = (Rune)' ';
  1104. }
  1105. break;
  1106. }
  1107. }
  1108. return StringExtensions.ToString (runes);
  1109. }
  1110. // TODO: Move to StringExtensions?
  1111. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  1112. {
  1113. if (tabWidth == 0)
  1114. {
  1115. return str.Replace ("\t", "");
  1116. }
  1117. return str.Replace ("\t", new (' ', tabWidth));
  1118. }
  1119. // TODO: Move to StringExtensions?
  1120. /// <summary>
  1121. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  1122. /// ending newline.
  1123. /// </summary>
  1124. /// <param name="text">The text.</param>
  1125. /// <returns>A list of text without the newline characters.</returns>
  1126. public static List<string> SplitNewLine (string text)
  1127. {
  1128. List<Rune> runes = text.ToRuneList ();
  1129. List<string> lines = new ();
  1130. var start = 0;
  1131. for (var i = 0; i < runes.Count; i++)
  1132. {
  1133. int end = i;
  1134. switch (runes [i].Value)
  1135. {
  1136. case '\n':
  1137. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1138. i++;
  1139. start = i;
  1140. break;
  1141. case '\r':
  1142. if (i + 1 < runes.Count && runes [i + 1].Value == '\n')
  1143. {
  1144. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1145. i += 2;
  1146. start = i;
  1147. }
  1148. else
  1149. {
  1150. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1151. i++;
  1152. start = i;
  1153. }
  1154. break;
  1155. }
  1156. }
  1157. switch (runes.Count)
  1158. {
  1159. case > 0 when lines.Count == 0:
  1160. lines.Add (StringExtensions.ToString (runes));
  1161. break;
  1162. case > 0 when start < runes.Count:
  1163. lines.Add (StringExtensions.ToString (runes.GetRange (start, runes.Count - start)));
  1164. break;
  1165. default:
  1166. lines.Add ("");
  1167. break;
  1168. }
  1169. return lines;
  1170. }
  1171. // TODO: Move to StringExtensions?
  1172. /// <summary>
  1173. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  1174. /// columns. Note that some unicode characters take 2+ columns
  1175. /// </summary>
  1176. /// <param name="text"></param>
  1177. /// <param name="width"></param>
  1178. /// <returns></returns>
  1179. public static string ClipOrPad (string text, int width)
  1180. {
  1181. if (string.IsNullOrEmpty (text))
  1182. {
  1183. return text;
  1184. }
  1185. // if value is not wide enough
  1186. if (text.EnumerateRunes ().Sum (c => c.GetColumns ()) < width)
  1187. {
  1188. // pad it out with spaces to the given Alignment
  1189. int toPad = width - text.EnumerateRunes ().Sum (c => c.GetColumns ());
  1190. return text + new string (' ', toPad);
  1191. }
  1192. // value is too wide
  1193. return new (text.TakeWhile (c => (width -= ((Rune)c).GetColumns ()) >= 0).ToArray ());
  1194. }
  1195. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  1196. /// <param name="text">The text to word wrap</param>
  1197. /// <param name="width">The number of columns to constrain the text to</param>
  1198. /// <param name="preserveTrailingSpaces">
  1199. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1200. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1201. /// </param>
  1202. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1203. /// <param name="textDirection">The text direction.</param>
  1204. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1205. /// <returns>A list of word wrapped lines.</returns>
  1206. /// <remarks>
  1207. /// <para>This method does not do any alignment.</para>
  1208. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  1209. /// <para>
  1210. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  1211. /// at the end of the last line.
  1212. /// </para>
  1213. /// </remarks>
  1214. /// <returns>A list of lines.</returns>
  1215. public static List<string> WordWrapText (
  1216. string text,
  1217. int width,
  1218. bool preserveTrailingSpaces = false,
  1219. int tabWidth = 0,
  1220. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1221. TextFormatter? textFormatter = null
  1222. )
  1223. {
  1224. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1225. List<string> lines = new ();
  1226. if (string.IsNullOrEmpty (text))
  1227. {
  1228. return lines;
  1229. }
  1230. List<Rune> runes = StripCRLF (text).ToRuneList ();
  1231. int start = Math.Max (
  1232. !runes.Contains ((Rune)' ') && textFormatter is { VerticalAlignment: Alignment.End } && IsVerticalDirection (textDirection)
  1233. ? runes.Count - width
  1234. : 0,
  1235. 0);
  1236. int end;
  1237. if (preserveTrailingSpaces)
  1238. {
  1239. while ((end = start) < runes.Count)
  1240. {
  1241. end = GetNextWhiteSpace (start, width, out bool incomplete);
  1242. if (end == 0 && incomplete)
  1243. {
  1244. start = text.GetRuneCount ();
  1245. break;
  1246. }
  1247. lines.Add (StringExtensions.ToString (runes.GetRange (start, end - start)));
  1248. start = end;
  1249. if (incomplete)
  1250. {
  1251. start = text.GetRuneCount ();
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. else
  1257. {
  1258. if (IsHorizontalDirection (textDirection))
  1259. {
  1260. while ((end = start
  1261. + GetLengthThatFits (
  1262. runes.GetRange (start, runes.Count - start),
  1263. width,
  1264. tabWidth,
  1265. textDirection
  1266. ))
  1267. < runes.Count)
  1268. {
  1269. while (runes [end].Value != ' ' && end > start)
  1270. {
  1271. end--;
  1272. }
  1273. if (end == start)
  1274. {
  1275. end = start
  1276. + GetLengthThatFits (
  1277. runes.GetRange (end, runes.Count - end),
  1278. width,
  1279. tabWidth,
  1280. textDirection
  1281. );
  1282. }
  1283. var str = StringExtensions.ToString (runes.GetRange (start, end - start));
  1284. int zeroLength = text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1285. if (end > start && GetRuneWidth (str, tabWidth, textDirection) <= width + zeroLength)
  1286. {
  1287. lines.Add (str);
  1288. start = end;
  1289. if (runes [end].Value == ' ')
  1290. {
  1291. start++;
  1292. }
  1293. }
  1294. else
  1295. {
  1296. end++;
  1297. start = end;
  1298. }
  1299. }
  1300. }
  1301. else
  1302. {
  1303. while ((end = start + width) < runes.Count)
  1304. {
  1305. while (runes [end].Value != ' ' && end > start)
  1306. {
  1307. end--;
  1308. }
  1309. if (end == start)
  1310. {
  1311. end = start + width;
  1312. }
  1313. var zeroLength = 0;
  1314. for (int i = end; i < runes.Count - start; i++)
  1315. {
  1316. Rune r = runes [i];
  1317. if (r.GetColumns () == 0)
  1318. {
  1319. zeroLength++;
  1320. }
  1321. else
  1322. {
  1323. break;
  1324. }
  1325. }
  1326. lines.Add (
  1327. StringExtensions.ToString (
  1328. runes.GetRange (
  1329. start,
  1330. end - start + zeroLength
  1331. )
  1332. )
  1333. );
  1334. end += zeroLength;
  1335. start = end;
  1336. if (runes [end].Value == ' ')
  1337. {
  1338. start++;
  1339. }
  1340. }
  1341. }
  1342. }
  1343. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1344. {
  1345. int to = from;
  1346. int length = cLength;
  1347. incomplete = false;
  1348. while (length < cWidth && to < runes.Count)
  1349. {
  1350. Rune rune = runes [to];
  1351. if (IsHorizontalDirection (textDirection))
  1352. {
  1353. length += rune.GetColumns ();
  1354. }
  1355. else
  1356. {
  1357. length++;
  1358. }
  1359. if (length > cWidth)
  1360. {
  1361. if (to >= runes.Count || (length > 1 && cWidth <= 1))
  1362. {
  1363. incomplete = true;
  1364. }
  1365. return to;
  1366. }
  1367. switch (rune.Value)
  1368. {
  1369. case ' ' when length == cWidth:
  1370. return to + 1;
  1371. case ' ' when length > cWidth:
  1372. return to;
  1373. case ' ':
  1374. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1375. case '\t':
  1376. {
  1377. length += tabWidth + 1;
  1378. if (length == tabWidth && tabWidth > cWidth)
  1379. {
  1380. return to + 1;
  1381. }
  1382. if (length > cWidth && tabWidth > cWidth)
  1383. {
  1384. return to;
  1385. }
  1386. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1387. }
  1388. default:
  1389. to++;
  1390. break;
  1391. }
  1392. }
  1393. return cLength switch
  1394. {
  1395. > 0 when to < runes.Count && runes [to].Value != ' ' && runes [to].Value != '\t' => from,
  1396. > 0 when to < runes.Count && (runes [to].Value == ' ' || runes [to].Value == '\t') => from,
  1397. _ => to
  1398. };
  1399. }
  1400. if (start < text.GetRuneCount ())
  1401. {
  1402. string str = ReplaceTABWithSpaces (
  1403. StringExtensions.ToString (runes.GetRange (start, runes.Count - start)),
  1404. tabWidth
  1405. );
  1406. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1407. {
  1408. lines.Add (str);
  1409. }
  1410. }
  1411. return lines;
  1412. }
  1413. /// <summary>Justifies text within a specified width.</summary>
  1414. /// <param name="text">The text to justify.</param>
  1415. /// <param name="width">
  1416. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1417. /// clipped.
  1418. /// </param>
  1419. /// <param name="textAlignment">Alignment.</param>
  1420. /// <param name="textDirection">The text direction.</param>
  1421. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1422. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1423. /// <returns>Justified and clipped text.</returns>
  1424. public static string ClipAndJustify (
  1425. string text,
  1426. int width,
  1427. Alignment textAlignment,
  1428. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1429. int tabWidth = 0,
  1430. TextFormatter? textFormatter = null
  1431. )
  1432. {
  1433. return ClipAndJustify (text, width, textAlignment == Alignment.Fill, textDirection, tabWidth, textFormatter);
  1434. }
  1435. /// <summary>Justifies text within a specified width.</summary>
  1436. /// <param name="text">The text to justify.</param>
  1437. /// <param name="width">
  1438. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1439. /// clipped.
  1440. /// </param>
  1441. /// <param name="justify">Justify.</param>
  1442. /// <param name="textDirection">The text direction.</param>
  1443. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1444. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1445. /// <returns>Justified and clipped text.</returns>
  1446. public static string ClipAndJustify (
  1447. string text,
  1448. int width,
  1449. bool justify,
  1450. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1451. int tabWidth = 0,
  1452. TextFormatter? textFormatter = null
  1453. )
  1454. {
  1455. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1456. if (string.IsNullOrEmpty (text))
  1457. {
  1458. return text;
  1459. }
  1460. text = ReplaceTABWithSpaces (text, tabWidth);
  1461. List<Rune> runes = text.ToRuneList ();
  1462. int zeroLength = runes.Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1463. if (runes.Count - zeroLength > width)
  1464. {
  1465. if (IsHorizontalDirection (textDirection))
  1466. {
  1467. if (textFormatter is { Alignment: Alignment.End })
  1468. {
  1469. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1470. }
  1471. if (textFormatter is { Alignment: Alignment.Center })
  1472. {
  1473. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1474. }
  1475. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1476. }
  1477. if (IsVerticalDirection (textDirection))
  1478. {
  1479. if (textFormatter is { VerticalAlignment: Alignment.End })
  1480. {
  1481. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1482. }
  1483. if (textFormatter is { VerticalAlignment: Alignment.Center })
  1484. {
  1485. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1486. }
  1487. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1488. }
  1489. return StringExtensions.ToString (runes.GetRange (0, width + zeroLength));
  1490. }
  1491. if (justify)
  1492. {
  1493. return Justify (text, width, ' ', textDirection, tabWidth);
  1494. }
  1495. if (IsHorizontalDirection (textDirection))
  1496. {
  1497. if (textFormatter is { Alignment: Alignment.End })
  1498. {
  1499. if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1500. {
  1501. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1502. }
  1503. }
  1504. else if (textFormatter is { Alignment: Alignment.Center })
  1505. {
  1506. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1507. }
  1508. else if (GetRuneWidth (text, tabWidth, textDirection) > width)
  1509. {
  1510. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1511. }
  1512. }
  1513. if (IsVerticalDirection (textDirection))
  1514. {
  1515. if (textFormatter is { VerticalAlignment: Alignment.End })
  1516. {
  1517. if (runes.Count - zeroLength > width)
  1518. {
  1519. return GetRangeThatFits (runes, runes.Count - width, text, width, tabWidth, textDirection);
  1520. }
  1521. }
  1522. else if (textFormatter is { VerticalAlignment: Alignment.Center })
  1523. {
  1524. return GetRangeThatFits (runes, Math.Max ((runes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1525. }
  1526. else if (runes.Count - zeroLength > width)
  1527. {
  1528. return GetRangeThatFits (runes, 0, text, width, tabWidth, textDirection);
  1529. }
  1530. }
  1531. return text;
  1532. }
  1533. private static string GetRangeThatFits (List<Rune> runes, int index, string text, int width, int tabWidth, TextDirection textDirection)
  1534. {
  1535. return StringExtensions.ToString (
  1536. runes.GetRange (
  1537. Math.Max (index, 0),
  1538. GetLengthThatFits (text, width, tabWidth, textDirection)
  1539. )
  1540. );
  1541. }
  1542. /// <summary>
  1543. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1544. /// <c>width</c>. Spaces will not be added to the start or end.
  1545. /// </summary>
  1546. /// <param name="text"></param>
  1547. /// <param name="width"></param>
  1548. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1549. /// <param name="textDirection">The text direction.</param>
  1550. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1551. /// <returns>The justified text.</returns>
  1552. public static string Justify (
  1553. string text,
  1554. int width,
  1555. char spaceChar = ' ',
  1556. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1557. int tabWidth = 0
  1558. )
  1559. {
  1560. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1561. if (string.IsNullOrEmpty (text))
  1562. {
  1563. return text;
  1564. }
  1565. text = ReplaceTABWithSpaces (text, tabWidth);
  1566. string [] words = text.Split (' ');
  1567. int textCount;
  1568. if (IsHorizontalDirection (textDirection))
  1569. {
  1570. textCount = words.Sum (arg => GetRuneWidth (arg, tabWidth, textDirection));
  1571. }
  1572. else
  1573. {
  1574. textCount = words.Sum (arg => arg.GetRuneCount ()) - text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1575. }
  1576. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1577. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1578. var s = new StringBuilder ();
  1579. for (var w = 0; w < words.Length; w++)
  1580. {
  1581. string x = words [w];
  1582. s.Append (x);
  1583. if (w + 1 < words.Length)
  1584. {
  1585. for (var i = 0; i < spaces; i++)
  1586. {
  1587. s.Append (spaceChar);
  1588. }
  1589. }
  1590. if (extras > 0)
  1591. {
  1592. for (var i = 0; i < 1; i++)
  1593. {
  1594. s.Append (spaceChar);
  1595. }
  1596. extras--;
  1597. }
  1598. if (w + 1 == words.Length - 1)
  1599. {
  1600. for (var i = 0; i < extras; i++)
  1601. {
  1602. s.Append (spaceChar);
  1603. }
  1604. }
  1605. }
  1606. return s.ToString ();
  1607. }
  1608. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1609. /// <param name="text"></param>
  1610. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1611. /// <param name="textAlignment">Specifies how the text will be aligned horizontally.</param>
  1612. /// <param name="wordWrap">
  1613. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1614. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1615. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1616. /// </param>
  1617. /// <param name="preserveTrailingSpaces">
  1618. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1619. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1620. /// </param>
  1621. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1622. /// <param name="textDirection">The text direction.</param>
  1623. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1624. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1625. /// <returns>A list of word wrapped lines.</returns>
  1626. /// <remarks>
  1627. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1628. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1629. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1630. /// </remarks>
  1631. public static List<string> Format (
  1632. string text,
  1633. int width,
  1634. Alignment textAlignment,
  1635. bool wordWrap,
  1636. bool preserveTrailingSpaces = false,
  1637. int tabWidth = 0,
  1638. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1639. bool multiLine = false,
  1640. TextFormatter? textFormatter = null
  1641. )
  1642. {
  1643. return Format (
  1644. text,
  1645. width,
  1646. textAlignment == Alignment.Fill,
  1647. wordWrap,
  1648. preserveTrailingSpaces,
  1649. tabWidth,
  1650. textDirection,
  1651. multiLine,
  1652. textFormatter
  1653. );
  1654. }
  1655. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1656. /// <param name="text"></param>
  1657. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1658. /// <param name="justify">Specifies whether the text should be justified.</param>
  1659. /// <param name="wordWrap">
  1660. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1661. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1662. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1663. /// </param>
  1664. /// <param name="preserveTrailingSpaces">
  1665. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1666. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1667. /// </param>
  1668. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1669. /// <param name="textDirection">The text direction.</param>
  1670. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1671. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1672. /// <returns>A list of word wrapped lines.</returns>
  1673. /// <remarks>
  1674. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1675. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1676. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1677. /// </remarks>
  1678. public static List<string> Format (
  1679. string text,
  1680. int width,
  1681. bool justify,
  1682. bool wordWrap,
  1683. bool preserveTrailingSpaces = false,
  1684. int tabWidth = 0,
  1685. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1686. bool multiLine = false,
  1687. TextFormatter? textFormatter = null
  1688. )
  1689. {
  1690. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1691. List<string> lineResult = new ();
  1692. if (string.IsNullOrEmpty (text) || width == 0)
  1693. {
  1694. lineResult.Add (string.Empty);
  1695. return lineResult;
  1696. }
  1697. if (!wordWrap)
  1698. {
  1699. text = ReplaceTABWithSpaces (text, tabWidth);
  1700. if (multiLine)
  1701. {
  1702. // Abhorrent case: Just a new line
  1703. if (text == "\n")
  1704. {
  1705. lineResult.Add (string.Empty);
  1706. return lineResult;
  1707. }
  1708. string []? lines = null;
  1709. if (text.Contains ("\r\n"))
  1710. {
  1711. lines = text.Split ("\r\n");
  1712. }
  1713. else if (text.Contains ('\n'))
  1714. {
  1715. lines = text.Split ('\n');
  1716. }
  1717. lines ??= new [] { text };
  1718. foreach (string line in lines)
  1719. {
  1720. lineResult.Add (
  1721. ClipAndJustify (
  1722. PerformCorrectFormatDirection (textDirection, line),
  1723. width,
  1724. justify,
  1725. textDirection,
  1726. tabWidth,
  1727. textFormatter));
  1728. }
  1729. return PerformCorrectFormatDirection (textDirection, lineResult);
  1730. }
  1731. text = ReplaceCRLFWithSpace (text);
  1732. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, text), width, justify, textDirection, tabWidth, textFormatter));
  1733. return PerformCorrectFormatDirection (textDirection, lineResult);
  1734. }
  1735. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1736. int runeCount = runes.Count;
  1737. var lp = 0;
  1738. for (var i = 0; i < runeCount; i++)
  1739. {
  1740. Rune c = runes [i];
  1741. if (c.Value == '\n')
  1742. {
  1743. List<string> wrappedLines =
  1744. WordWrapText (
  1745. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, i - lp))),
  1746. width,
  1747. preserveTrailingSpaces,
  1748. tabWidth,
  1749. textDirection,
  1750. textFormatter
  1751. );
  1752. foreach (string line in wrappedLines)
  1753. {
  1754. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1755. }
  1756. if (wrappedLines.Count == 0)
  1757. {
  1758. lineResult.Add (string.Empty);
  1759. }
  1760. lp = i + 1;
  1761. }
  1762. }
  1763. foreach (string line in WordWrapText (
  1764. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, runeCount - lp))),
  1765. width,
  1766. preserveTrailingSpaces,
  1767. tabWidth,
  1768. textDirection,
  1769. textFormatter
  1770. ))
  1771. {
  1772. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1773. }
  1774. return PerformCorrectFormatDirection (textDirection, lineResult);
  1775. }
  1776. private static string PerformCorrectFormatDirection (TextDirection textDirection, string line)
  1777. {
  1778. return textDirection switch
  1779. {
  1780. TextDirection.RightLeft_BottomTop
  1781. or TextDirection.RightLeft_TopBottom
  1782. or TextDirection.BottomTop_LeftRight
  1783. or TextDirection.BottomTop_RightLeft => StringExtensions.ToString (line.EnumerateRunes ().Reverse ()),
  1784. _ => line
  1785. };
  1786. }
  1787. private static List<Rune> PerformCorrectFormatDirection (TextDirection textDirection, List<Rune> runes)
  1788. {
  1789. return PerformCorrectFormatDirection (textDirection, StringExtensions.ToString (runes)).ToRuneList ();
  1790. }
  1791. private static List<string> PerformCorrectFormatDirection (TextDirection textDirection, List<string> lines)
  1792. {
  1793. return textDirection switch
  1794. {
  1795. TextDirection.TopBottom_RightLeft
  1796. or TextDirection.LeftRight_BottomTop
  1797. or TextDirection.RightLeft_BottomTop
  1798. or TextDirection.BottomTop_RightLeft => lines.ToArray ().Reverse ().ToList (),
  1799. _ => lines
  1800. };
  1801. }
  1802. /// <summary>
  1803. /// Returns the number of columns required to render <paramref name="lines"/> oriented vertically.
  1804. /// </summary>
  1805. /// <remarks>
  1806. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1807. /// glyphs (e.g. Arabic).
  1808. /// </remarks>
  1809. /// <param name="lines">The lines.</param>
  1810. /// <param name="startLine">The line in the list to start with (any lines before will be ignored).</param>
  1811. /// <param name="linesCount">
  1812. /// The number of lines to process (if less than <c>lines.Count</c>, any lines after will be
  1813. /// ignored).
  1814. /// </param>
  1815. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1816. /// <returns>The width required.</returns>
  1817. public static int GetColumnsRequiredForVerticalText (
  1818. List<string> lines,
  1819. int startLine = -1,
  1820. int linesCount = -1,
  1821. int tabWidth = 0
  1822. )
  1823. {
  1824. var max = 0;
  1825. for (int i = startLine == -1 ? 0 : startLine;
  1826. i < (linesCount == -1 ? lines.Count : startLine + linesCount);
  1827. i++)
  1828. {
  1829. string runes = lines [i];
  1830. if (runes.Length > 0)
  1831. {
  1832. max += runes.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1833. }
  1834. }
  1835. return max;
  1836. }
  1837. /// <summary>
  1838. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1839. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1840. /// </summary>
  1841. /// <remarks>
  1842. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1843. /// glyphs (e.g. Arabic).
  1844. /// </remarks>
  1845. /// <param name="text">Text, may contain newlines.</param>
  1846. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1847. /// <returns>The length of the longest line.</returns>
  1848. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1849. {
  1850. List<string> result = SplitNewLine (text);
  1851. return result.Max (x => GetRuneWidth (x, tabWidth));
  1852. }
  1853. /// <summary>
  1854. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1855. /// <paramref name="length"/>.
  1856. /// </summary>
  1857. /// <remarks>
  1858. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1859. /// glyphs (e.g. Arabic).
  1860. /// </remarks>
  1861. /// <param name="text">The text.</param>
  1862. /// <param name="startIndex">The start index.</param>
  1863. /// <param name="length">The length.</param>
  1864. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1865. /// <returns>The maximum characters width.</returns>
  1866. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1867. {
  1868. var max = 0;
  1869. Rune [] runes = text.ToRunes ();
  1870. for (int i = startIndex == -1 ? 0 : startIndex;
  1871. i < (length == -1 ? runes.Length : startIndex + length);
  1872. i++)
  1873. {
  1874. max += GetRuneWidth (runes [i], tabWidth);
  1875. }
  1876. return max;
  1877. }
  1878. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="width"/>.</summary>
  1879. /// <remarks>
  1880. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1881. /// glyphs (e.g. Arabic).
  1882. /// </remarks>
  1883. /// <param name="text">The text.</param>
  1884. /// <param name="width">The width.</param>
  1885. /// <param name="tabWidth">The width used for a tab.</param>
  1886. /// <param name="textDirection">The text direction.</param>
  1887. /// <returns>The index of the text that fit the width.</returns>
  1888. public static int GetLengthThatFits (string text, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1889. {
  1890. return GetLengthThatFits (text?.ToRuneList () ?? [], width, tabWidth, textDirection);
  1891. }
  1892. /// <summary>Gets the number of the Runes in a list of Runes that will fit in <paramref name="width"/>.</summary>
  1893. /// <remarks>
  1894. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1895. /// glyphs (e.g. Arabic).
  1896. /// </remarks>
  1897. /// <param name="runes">The list of runes.</param>
  1898. /// <param name="width">The width.</param>
  1899. /// <param name="tabWidth">The width used for a tab.</param>
  1900. /// <param name="textDirection">The text direction.</param>
  1901. /// <returns>The index of the last Rune in <paramref name="runes"/> that fit in <paramref name="width"/>.</returns>
  1902. public static int GetLengthThatFits (List<Rune> runes, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1903. {
  1904. if (runes is null || runes.Count == 0)
  1905. {
  1906. return 0;
  1907. }
  1908. var runesLength = 0;
  1909. var runeIdx = 0;
  1910. for (; runeIdx < runes.Count; runeIdx++)
  1911. {
  1912. int runeWidth = GetRuneWidth (runes [runeIdx], tabWidth, textDirection);
  1913. if (runesLength + runeWidth > width)
  1914. {
  1915. break;
  1916. }
  1917. runesLength += runeWidth;
  1918. }
  1919. return runeIdx;
  1920. }
  1921. private static int GetRuneWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1922. {
  1923. int runesWidth = 0;
  1924. foreach (Rune rune in str.EnumerateRunes ())
  1925. {
  1926. runesWidth += GetRuneWidth (rune, tabWidth, textDirection);
  1927. }
  1928. return runesWidth;
  1929. }
  1930. private static int GetRuneWidth (Rune rune, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1931. {
  1932. int runeWidth = IsHorizontalDirection (textDirection) ? rune.GetColumns () : rune.GetColumns () == 0 ? 0 : 1;
  1933. if (rune.Value == '\t')
  1934. {
  1935. return tabWidth;
  1936. }
  1937. if (runeWidth < 0 || runeWidth > 0)
  1938. {
  1939. return Math.Max (runeWidth, 1);
  1940. }
  1941. return runeWidth;
  1942. }
  1943. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  1944. /// <remarks>
  1945. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1946. /// glyphs (e.g. Arabic).
  1947. /// </remarks>
  1948. /// <param name="lines">The lines.</param>
  1949. /// <param name="width">The width.</param>
  1950. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1951. /// <returns>The index of the list that fit the width.</returns>
  1952. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  1953. {
  1954. var runesLength = 0;
  1955. var lineIdx = 0;
  1956. for (; lineIdx < lines.Count; lineIdx++)
  1957. {
  1958. List<Rune> runes = lines [lineIdx].ToRuneList ();
  1959. int maxRruneWidth = runes.Count > 0
  1960. ? runes.Max (r => GetRuneWidth (r, tabWidth))
  1961. : 1;
  1962. if (runesLength + maxRruneWidth > width)
  1963. {
  1964. break;
  1965. }
  1966. runesLength += maxRruneWidth;
  1967. }
  1968. return lineIdx;
  1969. }
  1970. /// <summary>Finds the HotKey and its location in text.</summary>
  1971. /// <param name="text">The text to look in.</param>
  1972. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  1973. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  1974. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  1975. /// <param name="firstUpperCase">
  1976. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  1977. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  1978. /// Defaults to <see langword="false"/>.
  1979. /// </param>
  1980. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  1981. public static bool FindHotKey (
  1982. string text,
  1983. Rune hotKeySpecifier,
  1984. out int hotPos,
  1985. out Key hotKey,
  1986. bool firstUpperCase = false
  1987. )
  1988. {
  1989. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  1990. {
  1991. hotPos = -1;
  1992. hotKey = Key.Empty;
  1993. return false;
  1994. }
  1995. var curHotKey = (Rune)0;
  1996. int curHotPos = -1;
  1997. // Use first hot_key char passed into 'hotKey'.
  1998. // TODO: Ignore hot_key of two are provided
  1999. // TODO: Do not support non-alphanumeric chars that can't be typed
  2000. var i = 0;
  2001. foreach (Rune c in text.EnumerateRunes ())
  2002. {
  2003. if ((char)c.Value != 0xFFFD)
  2004. {
  2005. if (c == hotKeySpecifier)
  2006. {
  2007. curHotPos = i;
  2008. }
  2009. else if (curHotPos > -1)
  2010. {
  2011. curHotKey = c;
  2012. break;
  2013. }
  2014. }
  2015. i++;
  2016. }
  2017. // Legacy support - use first upper case char if the specifier was not found
  2018. if (curHotPos == -1 && firstUpperCase)
  2019. {
  2020. i = 0;
  2021. foreach (Rune c in text.EnumerateRunes ())
  2022. {
  2023. if ((char)c.Value != 0xFFFD)
  2024. {
  2025. if (Rune.IsUpper (c))
  2026. {
  2027. curHotKey = c;
  2028. curHotPos = i;
  2029. break;
  2030. }
  2031. }
  2032. i++;
  2033. }
  2034. }
  2035. if (curHotKey != (Rune)0 && curHotPos != -1)
  2036. {
  2037. hotPos = curHotPos;
  2038. var newHotKey = (KeyCode)curHotKey.Value;
  2039. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  2040. {
  2041. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  2042. {
  2043. newHotKey &= ~KeyCode.Space;
  2044. }
  2045. hotKey = newHotKey;
  2046. //hotKey.Scope = KeyBindingScope.HotKey;
  2047. return true;
  2048. }
  2049. }
  2050. hotPos = -1;
  2051. hotKey = KeyCode.Null;
  2052. return false;
  2053. }
  2054. /// <summary>
  2055. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  2056. /// hotkey.
  2057. /// </summary>
  2058. /// <param name="text">The text to tag the hotkey in.</param>
  2059. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  2060. /// <returns>The text with the hotkey tagged.</returns>
  2061. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  2062. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  2063. {
  2064. // Set the high bit
  2065. List<Rune> runes = text.ToRuneList ();
  2066. if (Rune.IsLetterOrDigit (runes [hotPos]))
  2067. {
  2068. runes [hotPos] = new ((uint)runes [hotPos].Value);
  2069. }
  2070. return StringExtensions.ToString (runes);
  2071. }
  2072. /// <summary>Removes the hotkey specifier from text.</summary>
  2073. /// <param name="text">The text to manipulate.</param>
  2074. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  2075. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  2076. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  2077. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  2078. {
  2079. if (string.IsNullOrEmpty (text))
  2080. {
  2081. return text;
  2082. }
  2083. // Scan
  2084. var start = string.Empty;
  2085. var i = 0;
  2086. foreach (Rune c in text.EnumerateRunes ())
  2087. {
  2088. if (c == hotKeySpecifier && i == hotPos)
  2089. {
  2090. i++;
  2091. continue;
  2092. }
  2093. start += c;
  2094. i++;
  2095. }
  2096. return start;
  2097. }
  2098. #endregion // Static Members
  2099. }