TextFormatter.cs 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519
  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. string [] graphemes = GraphemeHelper.GetGraphemes (strings).ToArray ();
  837. // When text is justified, we lost left or right, so we use the direction to align.
  838. int x = 0, y = 0;
  839. switch (Alignment)
  840. {
  841. // Horizontal Alignment
  842. case Alignment.End when isVertical:
  843. {
  844. int runesWidth = GetColumnsRequiredForVerticalText (linesFormatted, line, linesFormatted.Count - line, TabWidth);
  845. x = screen.Right - runesWidth;
  846. break;
  847. }
  848. case Alignment.End:
  849. {
  850. int stringsWidth = strings.GetColumns ();
  851. x = screen.Right - stringsWidth;
  852. break;
  853. }
  854. case Alignment.Start when isVertical:
  855. {
  856. int stringsWidth = line > 0
  857. ? GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth)
  858. : 0;
  859. x = screen.Left + stringsWidth;
  860. break;
  861. }
  862. case Alignment.Start:
  863. x = screen.Left;
  864. break;
  865. case Alignment.Fill when isVertical:
  866. {
  867. int stringsWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  868. int prevLineWidth = line > 0 ? GetColumnsRequiredForVerticalText (linesFormatted, line - 1, 1, TabWidth) : 0;
  869. int firstLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, 1, TabWidth);
  870. int lastLineWidth = GetColumnsRequiredForVerticalText (linesFormatted, linesFormatted.Count - 1, 1, TabWidth);
  871. var interval = (int)Math.Round ((double)(screen.Width + firstLineWidth + lastLineWidth) / linesFormatted.Count);
  872. x = line == 0
  873. ? screen.Left
  874. : line < linesFormatted.Count - 1
  875. ? screen.Width - stringsWidth <= lastLineWidth ? screen.Left + prevLineWidth : screen.Left + line * interval
  876. : screen.Right - lastLineWidth;
  877. break;
  878. }
  879. case Alignment.Fill:
  880. x = screen.Left;
  881. break;
  882. case Alignment.Center when isVertical:
  883. {
  884. int stringsWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, linesFormatted.Count, TabWidth);
  885. int linesWidth = GetColumnsRequiredForVerticalText (linesFormatted, 0, line, TabWidth);
  886. x = screen.Left + linesWidth + (screen.Width - stringsWidth) / 2;
  887. break;
  888. }
  889. case Alignment.Center:
  890. {
  891. int stringsWidth = strings.GetColumns ();
  892. x = screen.Left + (screen.Width - stringsWidth) / 2;
  893. break;
  894. }
  895. default:
  896. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  897. return drawnRegion;
  898. }
  899. switch (VerticalAlignment)
  900. {
  901. // Vertical Alignment
  902. case Alignment.End when isVertical:
  903. y = screen.Bottom - graphemes.Length;
  904. break;
  905. case Alignment.End:
  906. y = screen.Bottom - linesFormatted.Count + line;
  907. break;
  908. case Alignment.Start when isVertical:
  909. y = screen.Top;
  910. break;
  911. case Alignment.Start:
  912. y = screen.Top + line;
  913. break;
  914. case Alignment.Fill when isVertical:
  915. y = screen.Top;
  916. break;
  917. case Alignment.Fill:
  918. {
  919. var interval = (int)Math.Round ((double)(screen.Height + 2) / linesFormatted.Count);
  920. y = line == 0 ? screen.Top :
  921. line < linesFormatted.Count - 1 ? screen.Height - interval <= 1 ? screen.Top + 1 : screen.Top + line * interval : screen.Bottom - 1;
  922. break;
  923. }
  924. case Alignment.Center when isVertical:
  925. {
  926. int s = (screen.Height - graphemes.Length) / 2;
  927. y = screen.Top + s;
  928. break;
  929. }
  930. case Alignment.Center:
  931. {
  932. int s = (screen.Height - linesFormatted.Count) / 2;
  933. y = screen.Top + line + s;
  934. break;
  935. }
  936. default:
  937. Debug.WriteLine ($"Unsupported Alignment: {nameof (VerticalAlignment)}");
  938. return drawnRegion;
  939. }
  940. int colOffset = screen.X < 0 ? Math.Abs (screen.X) : 0;
  941. int start = isVertical ? screen.Top : screen.Left;
  942. int size = isVertical ? screen.Height : screen.Width;
  943. int current = start + colOffset;
  944. int zeroLengthCount = isVertical ? strings.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0) : 0;
  945. int lineX = x, lineY = y, lineWidth = 0, lineHeight = 1;
  946. for (int idx = (isVertical ? start - y : start - x) + colOffset;
  947. current < start + size + zeroLengthCount;
  948. idx++)
  949. {
  950. if (idx < 0
  951. || (isVertical
  952. ? VerticalAlignment != Alignment.End && current < 0
  953. : Alignment != Alignment.End && x + current + colOffset < 0))
  954. {
  955. current++;
  956. continue;
  957. }
  958. if (!FillRemaining && idx > graphemes.Length - 1)
  959. {
  960. break;
  961. }
  962. if ((!isVertical
  963. && (current - start > maxScreen.Left + maxScreen.Width - screen.X + colOffset
  964. || (idx < graphemes.Length && graphemes [idx].GetColumns () > screen.Width)))
  965. || (isVertical
  966. && ((current > start + size + zeroLengthCount && idx > maxScreen.Top + maxScreen.Height - screen.Y)
  967. || (idx < graphemes.Length && graphemes [idx].GetColumns () > screen.Width))))
  968. {
  969. break;
  970. }
  971. string text = idx >= 0 && idx < graphemes.Length ? graphemes [idx] : " ";
  972. int runeWidth = GetStringWidth (text, TabWidth);
  973. if (isVertical)
  974. {
  975. if (runeWidth > 0)
  976. {
  977. // Update line height for vertical text (each rune is a column)
  978. lineHeight = Math.Max (lineHeight, current - y + 1);
  979. lineWidth = Math.Max (lineWidth, 1); // Width is 1 per rune in vertical
  980. }
  981. }
  982. else
  983. {
  984. // Update line width and position for horizontal text
  985. lineWidth += runeWidth;
  986. }
  987. current += isVertical && runeWidth > 0 ? 1 : runeWidth;
  988. int nextStringWidth = idx + 1 > -1 && idx + 1 < graphemes.Length
  989. ? graphemes [idx + 1].GetColumns ()
  990. : 0;
  991. if (!isVertical && idx + 1 < graphemes.Length && current + nextStringWidth > start + size)
  992. {
  993. break;
  994. }
  995. }
  996. // Add the line's drawn region to the overall region
  997. if (lineWidth > 0 && lineHeight > 0)
  998. {
  999. drawnRegion.Union (new Rectangle (lineX, lineY, lineWidth, lineHeight));
  1000. }
  1001. }
  1002. return drawnRegion;
  1003. }
  1004. #region Static Members
  1005. /// <summary>Check if it is a horizontal direction</summary>
  1006. public static bool IsHorizontalDirection (TextDirection textDirection)
  1007. {
  1008. return textDirection switch
  1009. {
  1010. TextDirection.LeftRight_TopBottom => true,
  1011. TextDirection.LeftRight_BottomTop => true,
  1012. TextDirection.RightLeft_TopBottom => true,
  1013. TextDirection.RightLeft_BottomTop => true,
  1014. _ => false
  1015. };
  1016. }
  1017. /// <summary>Check if it is a vertical direction</summary>
  1018. public static bool IsVerticalDirection (TextDirection textDirection)
  1019. {
  1020. return textDirection switch
  1021. {
  1022. TextDirection.TopBottom_LeftRight => true,
  1023. TextDirection.TopBottom_RightLeft => true,
  1024. TextDirection.BottomTop_LeftRight => true,
  1025. TextDirection.BottomTop_RightLeft => true,
  1026. _ => false
  1027. };
  1028. }
  1029. /// <summary>Check if it is Left to Right direction</summary>
  1030. public static bool IsLeftToRight (TextDirection textDirection)
  1031. {
  1032. return textDirection switch
  1033. {
  1034. TextDirection.LeftRight_TopBottom => true,
  1035. TextDirection.LeftRight_BottomTop => true,
  1036. _ => false
  1037. };
  1038. }
  1039. /// <summary>Check if it is Top to Bottom direction</summary>
  1040. public static bool IsTopToBottom (TextDirection textDirection)
  1041. {
  1042. return textDirection switch
  1043. {
  1044. TextDirection.TopBottom_LeftRight => true,
  1045. TextDirection.TopBottom_RightLeft => true,
  1046. _ => false
  1047. };
  1048. }
  1049. // TODO: Move to StringExtensions?
  1050. internal static string StripCRLF (string str, bool keepNewLine = false)
  1051. {
  1052. ReadOnlySpan<char> remaining = str.AsSpan ();
  1053. int firstNewlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1054. // Early exit to avoid StringBuilder allocation if there are no newline characters.
  1055. if (firstNewlineCharIndex < 0)
  1056. {
  1057. return str;
  1058. }
  1059. StringBuilder stringBuilder = new ();
  1060. ReadOnlySpan<char> firstSegment = remaining [..firstNewlineCharIndex];
  1061. stringBuilder.Append (firstSegment);
  1062. // The first newline is not yet skipped because the "keepNewLine" condition has not been evaluated.
  1063. // This means there will be 1 extra iteration because the same newline index is checked again in the loop.
  1064. remaining = remaining [firstNewlineCharIndex..];
  1065. while (remaining.Length > 0)
  1066. {
  1067. int newlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1068. if (newlineCharIndex == -1)
  1069. {
  1070. break;
  1071. }
  1072. ReadOnlySpan<char> segment = remaining [..newlineCharIndex];
  1073. stringBuilder.Append (segment);
  1074. int stride = segment.Length;
  1075. // Evaluate how many line break characters to preserve.
  1076. char newlineChar = remaining [newlineCharIndex];
  1077. if (newlineChar == '\n')
  1078. {
  1079. stride++;
  1080. if (keepNewLine)
  1081. {
  1082. stringBuilder.Append ('\n');
  1083. }
  1084. }
  1085. else // '\r'
  1086. {
  1087. int nextCharIndex = newlineCharIndex + 1;
  1088. bool crlf = nextCharIndex < remaining.Length && remaining [nextCharIndex] == '\n';
  1089. if (crlf)
  1090. {
  1091. stride += 2;
  1092. if (keepNewLine)
  1093. {
  1094. stringBuilder.Append ('\n');
  1095. }
  1096. }
  1097. else
  1098. {
  1099. stride++;
  1100. if (keepNewLine)
  1101. {
  1102. stringBuilder.Append ('\r');
  1103. }
  1104. }
  1105. }
  1106. remaining = remaining [stride..];
  1107. }
  1108. stringBuilder.Append (remaining);
  1109. return stringBuilder.ToString ();
  1110. }
  1111. // TODO: Move to StringExtensions?
  1112. internal static string ReplaceCRLFWithSpace (string str)
  1113. {
  1114. ReadOnlySpan<char> remaining = str.AsSpan ();
  1115. int firstNewlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1116. // Early exit to avoid StringBuilder allocation if there are no newline characters.
  1117. if (firstNewlineCharIndex < 0)
  1118. {
  1119. return str;
  1120. }
  1121. StringBuilder stringBuilder = new ();
  1122. ReadOnlySpan<char> firstSegment = remaining [..firstNewlineCharIndex];
  1123. stringBuilder.Append (firstSegment);
  1124. // The first newline is not yet skipped because the newline type has not been evaluated.
  1125. // This means there will be 1 extra iteration because the same newline index is checked again in the loop.
  1126. remaining = remaining [firstNewlineCharIndex..];
  1127. while (remaining.Length > 0)
  1128. {
  1129. int newlineCharIndex = remaining.IndexOfAny (NewlineSearchValues);
  1130. if (newlineCharIndex == -1)
  1131. {
  1132. break;
  1133. }
  1134. ReadOnlySpan<char> segment = remaining [..newlineCharIndex];
  1135. stringBuilder.Append (segment);
  1136. int stride = segment.Length;
  1137. // Replace newlines
  1138. char newlineChar = remaining [newlineCharIndex];
  1139. if (newlineChar == '\n')
  1140. {
  1141. stride++;
  1142. stringBuilder.Append (' ');
  1143. }
  1144. else // '\r'
  1145. {
  1146. int nextCharIndex = newlineCharIndex + 1;
  1147. bool crlf = nextCharIndex < remaining.Length && remaining [nextCharIndex] == '\n';
  1148. if (crlf)
  1149. {
  1150. stride += 2;
  1151. stringBuilder.Append (' ');
  1152. }
  1153. else
  1154. {
  1155. stride++;
  1156. stringBuilder.Append (' ');
  1157. }
  1158. }
  1159. remaining = remaining [stride..];
  1160. }
  1161. stringBuilder.Append (remaining);
  1162. return stringBuilder.ToString ();
  1163. }
  1164. // TODO: Move to StringExtensions?
  1165. private static string ReplaceTABWithSpaces (string str, int tabWidth)
  1166. {
  1167. if (tabWidth == 0)
  1168. {
  1169. return str.Replace ("\t", "");
  1170. }
  1171. return str.Replace ("\t", new (' ', tabWidth));
  1172. }
  1173. // TODO: Move to StringExtensions?
  1174. /// <summary>
  1175. /// Splits all newlines in the <paramref name="text"/> into a list and supports both CRLF and LF, preserving the
  1176. /// ending newline.
  1177. /// </summary>
  1178. /// <param name="text">The text.</param>
  1179. /// <returns>A list of text without the newline characters.</returns>
  1180. public static List<string> SplitNewLine (string text)
  1181. {
  1182. List<string> graphemes = GraphemeHelper.GetGraphemes (text).ToList ();
  1183. List<string> lines = new ();
  1184. var start = 0;
  1185. for (var i = 0; i < graphemes.Count; i++)
  1186. {
  1187. int end = i;
  1188. switch (graphemes [i])
  1189. {
  1190. case "\n":
  1191. case "\r\n":
  1192. lines.Add (StringExtensions.ToString (graphemes.GetRange (start, end - start)));
  1193. i++;
  1194. start = i;
  1195. break;
  1196. case "\r":
  1197. if (i + 1 < graphemes.Count && graphemes [i + 1] == "\n")
  1198. {
  1199. lines.Add (StringExtensions.ToString (graphemes.GetRange (start, end - start)));
  1200. i += 2;
  1201. start = i;
  1202. }
  1203. else
  1204. {
  1205. lines.Add (StringExtensions.ToString (graphemes.GetRange (start, end - start)));
  1206. i++;
  1207. start = i;
  1208. }
  1209. break;
  1210. }
  1211. }
  1212. switch (graphemes.Count)
  1213. {
  1214. case > 0 when lines.Count == 0:
  1215. lines.Add (StringExtensions.ToString (graphemes));
  1216. break;
  1217. case > 0 when start < graphemes.Count:
  1218. lines.Add (StringExtensions.ToString (graphemes.GetRange (start, graphemes.Count - start)));
  1219. break;
  1220. default:
  1221. lines.Add ("");
  1222. break;
  1223. }
  1224. return lines;
  1225. }
  1226. // TODO: Move to StringExtensions?
  1227. /// <summary>
  1228. /// Adds trailing whitespace or truncates <paramref name="text"/> so that it fits exactly <paramref name="width"/>
  1229. /// columns. Note that some unicode characters take 2+ columns
  1230. /// </summary>
  1231. /// <param name="text"></param>
  1232. /// <param name="width"></param>
  1233. /// <returns></returns>
  1234. public static string ClipOrPad (string text, int width)
  1235. {
  1236. if (string.IsNullOrEmpty (text))
  1237. {
  1238. return text;
  1239. }
  1240. // if value is not wide enough
  1241. string [] graphemes = GraphemeHelper.GetGraphemes (text).ToArray ();
  1242. int totalColumns = graphemes.Sum (s => s.GetColumns ());
  1243. if (totalColumns < width)
  1244. {
  1245. // pad it out with spaces to the given Alignment
  1246. int toPad = width - totalColumns;
  1247. return text + new string (' ', toPad);
  1248. }
  1249. // value is too wide
  1250. return string.Concat (graphemes.TakeWhile (t => (width -= t.GetColumns ()) >= 0));
  1251. }
  1252. /// <summary>Formats the provided text to fit within the width provided using word wrapping.</summary>
  1253. /// <param name="text">The text to word wrap</param>
  1254. /// <param name="width">The number of columns to constrain the text to</param>
  1255. /// <param name="preserveTrailingSpaces">
  1256. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1257. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1258. /// </param>
  1259. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1260. /// <param name="textDirection">The text direction.</param>
  1261. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1262. /// <returns>A list of word wrapped lines.</returns>
  1263. /// <remarks>
  1264. /// <para>This method does not do any alignment.</para>
  1265. /// <para>This method strips Newline ('\n' and '\r\n') sequences before processing.</para>
  1266. /// <para>
  1267. /// If <paramref name="preserveTrailingSpaces"/> is <see langword="false"/> at most one space will be preserved
  1268. /// at the end of the last line.
  1269. /// </para>
  1270. /// </remarks>
  1271. /// <returns>A list of lines.</returns>
  1272. public static List<string> WordWrapText (
  1273. string text,
  1274. int width,
  1275. bool preserveTrailingSpaces = false,
  1276. int tabWidth = 0,
  1277. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1278. TextFormatter? textFormatter = null
  1279. )
  1280. {
  1281. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1282. List<string> lines = new ();
  1283. if (string.IsNullOrEmpty (text))
  1284. {
  1285. return lines;
  1286. }
  1287. List<string> graphemes = GraphemeHelper.GetGraphemes (StripCRLF (text)).ToList ();
  1288. int start = Math.Max (
  1289. !graphemes.Contains (" ") && textFormatter is { VerticalAlignment: Alignment.End } && IsVerticalDirection (textDirection)
  1290. ? graphemes.Count - width
  1291. : 0,
  1292. 0);
  1293. int end;
  1294. if (preserveTrailingSpaces)
  1295. {
  1296. while (start < graphemes.Count)
  1297. {
  1298. end = GetNextWhiteSpace (start, width, out bool incomplete);
  1299. if (end == 0 && incomplete)
  1300. {
  1301. start = text.GetRuneCount ();
  1302. break;
  1303. }
  1304. lines.Add (StringExtensions.ToString (graphemes.GetRange (start, end - start)));
  1305. start = end;
  1306. if (incomplete)
  1307. {
  1308. start = text.GetRuneCount ();
  1309. break;
  1310. }
  1311. }
  1312. }
  1313. else
  1314. {
  1315. if (IsHorizontalDirection (textDirection))
  1316. {
  1317. while ((end = start
  1318. + GetLengthThatFits (
  1319. string.Concat (graphemes.GetRange (start, graphemes.Count - start)),
  1320. width,
  1321. tabWidth,
  1322. textDirection
  1323. ))
  1324. < graphemes.Count)
  1325. {
  1326. while (graphemes [end] != " " && end > start)
  1327. {
  1328. end--;
  1329. }
  1330. if (end == start)
  1331. {
  1332. end = start
  1333. + GetLengthThatFits (
  1334. string.Concat (graphemes.GetRange (end, graphemes.Count - end)),
  1335. width,
  1336. tabWidth,
  1337. textDirection
  1338. );
  1339. }
  1340. var str = StringExtensions.ToString (graphemes.GetRange (start, end - start));
  1341. int zeroLength = text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1342. if (end > start && GetTextWidth (str, tabWidth, textDirection) <= width + zeroLength)
  1343. {
  1344. lines.Add (str);
  1345. start = end;
  1346. if (graphemes [end] == " ")
  1347. {
  1348. start++;
  1349. }
  1350. }
  1351. else
  1352. {
  1353. end++;
  1354. start = end;
  1355. }
  1356. }
  1357. }
  1358. else
  1359. {
  1360. while ((end = start + width) < graphemes.Count)
  1361. {
  1362. while (graphemes [end] != " " && end > start)
  1363. {
  1364. end--;
  1365. }
  1366. if (end == start)
  1367. {
  1368. end = start + width;
  1369. }
  1370. var zeroLength = 0;
  1371. for (int i = end; i < graphemes.Count - start; i++)
  1372. {
  1373. string s = graphemes [i];
  1374. if (s.GetColumns () == 0)
  1375. {
  1376. zeroLength++;
  1377. }
  1378. else
  1379. {
  1380. break;
  1381. }
  1382. }
  1383. lines.Add (
  1384. StringExtensions.ToString (
  1385. graphemes.GetRange (
  1386. start,
  1387. end - start + zeroLength
  1388. )
  1389. )
  1390. );
  1391. end += zeroLength;
  1392. start = end;
  1393. if (graphemes [end] == " ")
  1394. {
  1395. start++;
  1396. }
  1397. }
  1398. }
  1399. }
  1400. int GetNextWhiteSpace (int from, int cWidth, out bool incomplete, int cLength = 0)
  1401. {
  1402. int to = from;
  1403. int length = cLength;
  1404. incomplete = false;
  1405. while (length < cWidth && to < graphemes.Count)
  1406. {
  1407. string grapheme = graphemes [to];
  1408. if (IsHorizontalDirection (textDirection))
  1409. {
  1410. length += grapheme.GetColumns (false);
  1411. }
  1412. else
  1413. {
  1414. length++;
  1415. }
  1416. if (length > cWidth)
  1417. {
  1418. if (to >= graphemes.Count || (length > 1 && cWidth <= 1))
  1419. {
  1420. incomplete = true;
  1421. }
  1422. return to;
  1423. }
  1424. switch (grapheme)
  1425. {
  1426. case " " when length == cWidth:
  1427. return to + 1;
  1428. case " " when length > cWidth:
  1429. return to;
  1430. case " ":
  1431. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1432. case "\t":
  1433. {
  1434. length += tabWidth + 1;
  1435. if (length == tabWidth && tabWidth > cWidth)
  1436. {
  1437. return to + 1;
  1438. }
  1439. if (length > cWidth && tabWidth > cWidth)
  1440. {
  1441. return to;
  1442. }
  1443. return GetNextWhiteSpace (to + 1, cWidth, out incomplete, length);
  1444. }
  1445. default:
  1446. to++;
  1447. break;
  1448. }
  1449. }
  1450. return cLength switch
  1451. {
  1452. > 0 when to < graphemes.Count && graphemes [to] != " " && graphemes [to] != "\t" => from,
  1453. > 0 when to < graphemes.Count && (graphemes [to] == " " || graphemes [to] == "\t") => from,
  1454. _ => to
  1455. };
  1456. }
  1457. if (start < text.GetRuneCount ())
  1458. {
  1459. string str = ReplaceTABWithSpaces (
  1460. StringExtensions.ToString (graphemes.GetRange (start, graphemes.Count - start)),
  1461. tabWidth
  1462. );
  1463. if (IsVerticalDirection (textDirection) || preserveTrailingSpaces || str.GetColumns () <= width)
  1464. {
  1465. lines.Add (str);
  1466. }
  1467. }
  1468. return lines;
  1469. }
  1470. /// <summary>Justifies text within a specified width.</summary>
  1471. /// <param name="text">The text to justify.</param>
  1472. /// <param name="width">
  1473. /// The number of columns to clip the text to. Text longer than <paramref name="width"/> will be
  1474. /// clipped.
  1475. /// </param>
  1476. /// <param name="textAlignment">Alignment.</param>
  1477. /// <param name="textDirection">The text direction.</param>
  1478. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1479. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1480. /// <returns>Justified and clipped text.</returns>
  1481. public static string ClipAndJustify (
  1482. string text,
  1483. int width,
  1484. Alignment textAlignment,
  1485. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1486. int tabWidth = 0,
  1487. TextFormatter? textFormatter = null
  1488. )
  1489. {
  1490. return ClipAndJustify (text, width, textAlignment == Alignment.Fill, textDirection, tabWidth, textFormatter);
  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="justify">Justify.</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. bool justify,
  1507. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1508. int tabWidth = 0,
  1509. TextFormatter? textFormatter = null
  1510. )
  1511. {
  1512. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1513. if (string.IsNullOrEmpty (text))
  1514. {
  1515. return text;
  1516. }
  1517. text = ReplaceTABWithSpaces (text, tabWidth);
  1518. List<string> graphemes = GraphemeHelper.GetGraphemes (text).ToList ();
  1519. int zeroLength = graphemes.Sum (s => s.EnumerateRunes ().Sum (r => r.GetColumns() == 0 ? 1 : 0));
  1520. if (graphemes.Count - zeroLength > width)
  1521. {
  1522. if (IsHorizontalDirection (textDirection))
  1523. {
  1524. if (textFormatter is { Alignment: Alignment.End })
  1525. {
  1526. return GetRangeThatFits (graphemes, graphemes.Count - width, text, width, tabWidth, textDirection);
  1527. }
  1528. if (textFormatter is { Alignment: Alignment.Center })
  1529. {
  1530. return GetRangeThatFits (graphemes, Math.Max ((graphemes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1531. }
  1532. return GetRangeThatFits (graphemes, 0, text, width, tabWidth, textDirection);
  1533. }
  1534. if (IsVerticalDirection (textDirection))
  1535. {
  1536. if (textFormatter is { VerticalAlignment: Alignment.End })
  1537. {
  1538. return GetRangeThatFits (graphemes, graphemes.Count - width, text, width, tabWidth, textDirection);
  1539. }
  1540. if (textFormatter is { VerticalAlignment: Alignment.Center })
  1541. {
  1542. return GetRangeThatFits (graphemes, Math.Max ((graphemes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1543. }
  1544. return GetRangeThatFits (graphemes, 0, text, width, tabWidth, textDirection);
  1545. }
  1546. return StringExtensions.ToString (graphemes.GetRange (0, width + zeroLength));
  1547. }
  1548. if (justify)
  1549. {
  1550. return Justify (text, width, ' ', textDirection, tabWidth);
  1551. }
  1552. if (IsHorizontalDirection (textDirection))
  1553. {
  1554. if (textFormatter is { Alignment: Alignment.End })
  1555. {
  1556. if (GetTextWidth (text, tabWidth, textDirection) > width)
  1557. {
  1558. return GetRangeThatFits (graphemes, graphemes.Count - width, text, width, tabWidth, textDirection);
  1559. }
  1560. }
  1561. else if (textFormatter is { Alignment: Alignment.Center })
  1562. {
  1563. return GetRangeThatFits (graphemes, Math.Max ((graphemes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1564. }
  1565. else if (GetTextWidth (text, tabWidth, textDirection) > width)
  1566. {
  1567. return GetRangeThatFits (graphemes, 0, text, width, tabWidth, textDirection);
  1568. }
  1569. }
  1570. if (IsVerticalDirection (textDirection))
  1571. {
  1572. if (textFormatter is { VerticalAlignment: Alignment.End })
  1573. {
  1574. if (graphemes.Count - zeroLength > width)
  1575. {
  1576. return GetRangeThatFits (graphemes, graphemes.Count - width, text, width, tabWidth, textDirection);
  1577. }
  1578. }
  1579. else if (textFormatter is { VerticalAlignment: Alignment.Center })
  1580. {
  1581. return GetRangeThatFits (graphemes, Math.Max ((graphemes.Count - width - zeroLength) / 2, 0), text, width, tabWidth, textDirection);
  1582. }
  1583. else if (graphemes.Count - zeroLength > width)
  1584. {
  1585. return GetRangeThatFits (graphemes, 0, text, width, tabWidth, textDirection);
  1586. }
  1587. }
  1588. return text;
  1589. }
  1590. private static string GetRangeThatFits (List<string> strings, int index, string text, int width, int tabWidth, TextDirection textDirection)
  1591. {
  1592. return StringExtensions.ToString (
  1593. strings.GetRange (
  1594. Math.Max (index, 0),
  1595. GetLengthThatFits (text, width, tabWidth, textDirection)
  1596. )
  1597. );
  1598. }
  1599. /// <summary>
  1600. /// Justifies the text to fill the width provided. Space will be added between words to make the text just fit
  1601. /// <c>width</c>. Spaces will not be added to the start or end.
  1602. /// </summary>
  1603. /// <param name="text"></param>
  1604. /// <param name="width"></param>
  1605. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  1606. /// <param name="textDirection">The text direction.</param>
  1607. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1608. /// <returns>The justified text.</returns>
  1609. public static string Justify (
  1610. string text,
  1611. int width,
  1612. char spaceChar = ' ',
  1613. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1614. int tabWidth = 0
  1615. )
  1616. {
  1617. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1618. if (string.IsNullOrEmpty (text))
  1619. {
  1620. return text;
  1621. }
  1622. text = ReplaceTABWithSpaces (text, tabWidth);
  1623. string [] words = text.Split (' ');
  1624. int textCount;
  1625. if (IsHorizontalDirection (textDirection))
  1626. {
  1627. textCount = words.Sum (arg => GetTextWidth (arg, tabWidth, textDirection));
  1628. }
  1629. else
  1630. {
  1631. textCount = words.Sum (arg => arg.GetRuneCount ()) - text.EnumerateRunes ().Sum (r => r.GetColumns () == 0 ? 1 : 0);
  1632. }
  1633. int spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  1634. int extras = words.Length > 1 ? (width - textCount) % (words.Length - 1) : 0;
  1635. var s = new StringBuilder ();
  1636. for (var w = 0; w < words.Length; w++)
  1637. {
  1638. string x = words [w];
  1639. s.Append (x);
  1640. if (w + 1 < words.Length)
  1641. {
  1642. for (var i = 0; i < spaces; i++)
  1643. {
  1644. s.Append (spaceChar);
  1645. }
  1646. }
  1647. if (extras > 0)
  1648. {
  1649. for (var i = 0; i < 1; i++)
  1650. {
  1651. s.Append (spaceChar);
  1652. }
  1653. extras--;
  1654. }
  1655. if (w + 1 == words.Length - 1)
  1656. {
  1657. for (var i = 0; i < extras; i++)
  1658. {
  1659. s.Append (spaceChar);
  1660. }
  1661. }
  1662. }
  1663. return s.ToString ();
  1664. }
  1665. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1666. /// <param name="text"></param>
  1667. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1668. /// <param name="textAlignment">Specifies how the text will be aligned horizontally.</param>
  1669. /// <param name="wordWrap">
  1670. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1671. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1672. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1673. /// </param>
  1674. /// <param name="preserveTrailingSpaces">
  1675. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1676. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1677. /// </param>
  1678. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1679. /// <param name="textDirection">The text direction.</param>
  1680. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1681. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1682. /// <returns>A list of word wrapped lines.</returns>
  1683. /// <remarks>
  1684. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1685. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1686. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1687. /// </remarks>
  1688. public static List<string> Format (
  1689. string text,
  1690. int width,
  1691. Alignment textAlignment,
  1692. bool wordWrap,
  1693. bool preserveTrailingSpaces = false,
  1694. int tabWidth = 0,
  1695. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1696. bool multiLine = false,
  1697. TextFormatter? textFormatter = null
  1698. )
  1699. {
  1700. return Format (
  1701. text,
  1702. width,
  1703. textAlignment == Alignment.Fill,
  1704. wordWrap,
  1705. preserveTrailingSpaces,
  1706. tabWidth,
  1707. textDirection,
  1708. multiLine,
  1709. textFormatter
  1710. );
  1711. }
  1712. /// <summary>Formats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.</summary>
  1713. /// <param name="text"></param>
  1714. /// <param name="width">The number of columns to constrain the text to for word wrapping and clipping.</param>
  1715. /// <param name="justify">Specifies whether the text should be justified.</param>
  1716. /// <param name="wordWrap">
  1717. /// If <see langword="true"/>, the text will be wrapped to new lines no longer than
  1718. /// <paramref name="width"/>. If <see langword="false"/>, forces text to fit a single line. Line breaks are converted
  1719. /// to spaces. The text will be clipped to <paramref name="width"/>.
  1720. /// </param>
  1721. /// <param name="preserveTrailingSpaces">
  1722. /// If <see langword="true"/> trailing spaces at the end of wrapped lines will be
  1723. /// preserved. If <see langword="false"/> , trailing spaces at the end of wrapped lines will be trimmed.
  1724. /// </param>
  1725. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1726. /// <param name="textDirection">The text direction.</param>
  1727. /// <param name="multiLine">If <see langword="true"/> new lines are allowed.</param>
  1728. /// <param name="textFormatter"><see cref="TextFormatter"/> instance to access any of his objects.</param>
  1729. /// <returns>A list of word wrapped lines.</returns>
  1730. /// <remarks>
  1731. /// <para>An empty <paramref name="text"/> string will result in one empty line.</para>
  1732. /// <para>If <paramref name="width"/> is 0, a single, empty line will be returned.</para>
  1733. /// <para>If <paramref name="width"/> is int.MaxValue, the text will be formatted to the maximum width possible.</para>
  1734. /// </remarks>
  1735. public static List<string> Format (
  1736. string text,
  1737. int width,
  1738. bool justify,
  1739. bool wordWrap,
  1740. bool preserveTrailingSpaces = false,
  1741. int tabWidth = 0,
  1742. TextDirection textDirection = TextDirection.LeftRight_TopBottom,
  1743. bool multiLine = false,
  1744. TextFormatter? textFormatter = null
  1745. )
  1746. {
  1747. ArgumentOutOfRangeException.ThrowIfNegative (width, nameof (width));
  1748. List<string> lineResult = new ();
  1749. if (string.IsNullOrEmpty (text) || width == 0)
  1750. {
  1751. lineResult.Add (string.Empty);
  1752. return lineResult;
  1753. }
  1754. if (!wordWrap)
  1755. {
  1756. text = ReplaceTABWithSpaces (text, tabWidth);
  1757. if (multiLine)
  1758. {
  1759. // Abhorrent case: Just a new line
  1760. if (text == "\n")
  1761. {
  1762. lineResult.Add (string.Empty);
  1763. return lineResult;
  1764. }
  1765. string []? lines = null;
  1766. if (text.Contains ("\r\n"))
  1767. {
  1768. lines = text.Split ("\r\n");
  1769. }
  1770. else if (text.Contains ('\n'))
  1771. {
  1772. lines = text.Split ('\n');
  1773. }
  1774. lines ??= new [] { text };
  1775. foreach (string line in lines)
  1776. {
  1777. lineResult.Add (
  1778. ClipAndJustify (
  1779. PerformCorrectFormatDirection (textDirection, line),
  1780. width,
  1781. justify,
  1782. textDirection,
  1783. tabWidth,
  1784. textFormatter));
  1785. }
  1786. return PerformCorrectFormatDirection (textDirection, lineResult);
  1787. }
  1788. text = ReplaceCRLFWithSpace (text);
  1789. lineResult.Add (ClipAndJustify (PerformCorrectFormatDirection (textDirection, text), width, justify, textDirection, tabWidth, textFormatter));
  1790. return PerformCorrectFormatDirection (textDirection, lineResult);
  1791. }
  1792. List<Rune> runes = StripCRLF (text, true).ToRuneList ();
  1793. int runeCount = runes.Count;
  1794. var lp = 0;
  1795. for (var i = 0; i < runeCount; i++)
  1796. {
  1797. Rune c = runes [i];
  1798. if (c.Value == '\n')
  1799. {
  1800. List<string> wrappedLines =
  1801. WordWrapText (
  1802. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, i - lp))),
  1803. width,
  1804. preserveTrailingSpaces,
  1805. tabWidth,
  1806. textDirection,
  1807. textFormatter
  1808. );
  1809. foreach (string line in wrappedLines)
  1810. {
  1811. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1812. }
  1813. if (wrappedLines.Count == 0)
  1814. {
  1815. lineResult.Add (string.Empty);
  1816. }
  1817. lp = i + 1;
  1818. }
  1819. }
  1820. foreach (string line in WordWrapText (
  1821. StringExtensions.ToString (PerformCorrectFormatDirection (textDirection, runes.GetRange (lp, runeCount - lp))),
  1822. width,
  1823. preserveTrailingSpaces,
  1824. tabWidth,
  1825. textDirection,
  1826. textFormatter
  1827. ))
  1828. {
  1829. lineResult.Add (ClipAndJustify (line, width, justify, textDirection, tabWidth));
  1830. }
  1831. return PerformCorrectFormatDirection (textDirection, lineResult);
  1832. }
  1833. private static string PerformCorrectFormatDirection (TextDirection textDirection, string line)
  1834. {
  1835. return textDirection switch
  1836. {
  1837. TextDirection.RightLeft_BottomTop
  1838. or TextDirection.RightLeft_TopBottom
  1839. or TextDirection.BottomTop_LeftRight
  1840. or TextDirection.BottomTop_RightLeft => StringExtensions.ToString (line.EnumerateRunes ().Reverse ()),
  1841. _ => line
  1842. };
  1843. }
  1844. private static List<Rune> PerformCorrectFormatDirection (TextDirection textDirection, List<Rune> runes)
  1845. {
  1846. return PerformCorrectFormatDirection (textDirection, StringExtensions.ToString (runes)).ToRuneList ();
  1847. }
  1848. private static List<string> PerformCorrectFormatDirection (TextDirection textDirection, List<string> lines)
  1849. {
  1850. return textDirection switch
  1851. {
  1852. TextDirection.TopBottom_RightLeft
  1853. or TextDirection.LeftRight_BottomTop
  1854. or TextDirection.RightLeft_BottomTop
  1855. or TextDirection.BottomTop_RightLeft => lines.ToArray ().Reverse ().ToList (),
  1856. _ => lines
  1857. };
  1858. }
  1859. /// <summary>
  1860. /// Returns the number of columns required to render <paramref name="lines"/> oriented vertically.
  1861. /// </summary>
  1862. /// <remarks>
  1863. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1864. /// glyphs (e.g. Arabic).
  1865. /// </remarks>
  1866. /// <param name="lines">The lines.</param>
  1867. /// <param name="startLine">The line in the list to start with (any lines before will be ignored).</param>
  1868. /// <param name="linesCount">
  1869. /// The number of lines to process (if less than <c>lines.Count</c>, any lines after will be
  1870. /// ignored).
  1871. /// </param>
  1872. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1873. /// <returns>The width required.</returns>
  1874. public static int GetColumnsRequiredForVerticalText (
  1875. List<string> lines,
  1876. int startLine = -1,
  1877. int linesCount = -1,
  1878. int tabWidth = 0
  1879. )
  1880. {
  1881. var max = 0;
  1882. for (int i = startLine == -1 ? 0 : startLine;
  1883. i < (linesCount == -1 ? lines.Count : startLine + linesCount);
  1884. i++)
  1885. {
  1886. string strings = lines [i];
  1887. if (strings.Length > 0)
  1888. {
  1889. max += strings.EnumerateRunes ().Max (r => GetRuneWidth (r, tabWidth));
  1890. }
  1891. }
  1892. return max;
  1893. }
  1894. /// <summary>
  1895. /// Returns the number of columns in the widest line in the text, without word wrap, accounting for wide-glyphs
  1896. /// (uses <see cref="StringExtensions.GetColumns"/>). <paramref name="text"/> if it contains newlines.
  1897. /// </summary>
  1898. /// <remarks>
  1899. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1900. /// glyphs (e.g. Arabic).
  1901. /// </remarks>
  1902. /// <param name="text">Text, may contain newlines.</param>
  1903. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1904. /// <returns>The length of the longest line.</returns>
  1905. public static int GetWidestLineLength (string text, int tabWidth = 0)
  1906. {
  1907. List<string> result = SplitNewLine (text);
  1908. return result.Max (x => GetTextWidth (x, tabWidth));
  1909. }
  1910. /// <summary>
  1911. /// Gets the maximum number of columns from the text based on the <paramref name="startIndex"/> and the
  1912. /// <paramref name="length"/>.
  1913. /// </summary>
  1914. /// <remarks>
  1915. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  1916. /// glyphs (e.g. Arabic).
  1917. /// </remarks>
  1918. /// <param name="text">The text.</param>
  1919. /// <param name="startIndex">The start index.</param>
  1920. /// <param name="length">The length.</param>
  1921. /// <param name="tabWidth">The number of columns used for a tab.</param>
  1922. /// <returns>The maximum characters width.</returns>
  1923. public static int GetSumMaxCharWidth (string text, int startIndex = -1, int length = -1, int tabWidth = 0)
  1924. {
  1925. var max = 0;
  1926. string [] graphemes = GraphemeHelper.GetGraphemes (text).ToArray ();
  1927. for (int i = startIndex == -1 ? 0 : startIndex;
  1928. i < (length == -1 ? graphemes.Length : startIndex + length);
  1929. i++)
  1930. {
  1931. max += GetStringWidth (graphemes [i], tabWidth);
  1932. }
  1933. return max;
  1934. }
  1935. /// <summary>Gets the number of the Runes in the text that will fit in <paramref name="width"/>.</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="width">The width.</param>
  1942. /// <param name="tabWidth">The width used for a tab.</param>
  1943. /// <param name="textDirection">The text direction.</param>
  1944. /// <returns>The index of the text that fit the width.</returns>
  1945. public static int GetLengthThatFits (string text, int width, int tabWidth = 0, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1946. {
  1947. if (string.IsNullOrEmpty (text))
  1948. {
  1949. return 0;
  1950. }
  1951. var textLength = 0;
  1952. var stringIdx = 0;
  1953. foreach (string grapheme in GraphemeHelper.GetGraphemes (text))
  1954. {
  1955. int textWidth = GetStringWidth (grapheme, tabWidth, textDirection);
  1956. if (textLength + textWidth > width)
  1957. {
  1958. break;
  1959. }
  1960. textLength += textWidth;
  1961. stringIdx++;
  1962. }
  1963. return stringIdx;
  1964. }
  1965. private static int GetTextWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1966. {
  1967. int runesWidth = 0;
  1968. foreach (string grapheme in GraphemeHelper.GetGraphemes (str))
  1969. {
  1970. runesWidth += GetStringWidth (grapheme, tabWidth, textDirection);
  1971. }
  1972. return runesWidth;
  1973. }
  1974. private static int GetRuneWidth (Rune rune, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1975. {
  1976. int runeWidth = IsHorizontalDirection (textDirection) ? rune.GetColumns () : rune.GetColumns () == 0 ? 0 : 1;
  1977. if (rune.Value == '\t')
  1978. {
  1979. return tabWidth;
  1980. }
  1981. if (runeWidth < 0 || runeWidth > 0)
  1982. {
  1983. return Math.Max (runeWidth, 1);
  1984. }
  1985. return runeWidth;
  1986. }
  1987. private static int GetStringWidth (string str, int tabWidth, TextDirection textDirection = TextDirection.LeftRight_TopBottom)
  1988. {
  1989. int textWidth = IsHorizontalDirection (textDirection) ? str.GetColumns (false) : str.GetColumns () == 0 ? 0 : 1;
  1990. if (str == "\t")
  1991. {
  1992. return tabWidth;
  1993. }
  1994. if (textWidth is < 0 or > 0)
  1995. {
  1996. return Math.Max (textWidth, 1);
  1997. }
  1998. return textWidth;
  1999. }
  2000. /// <summary>Gets the index position from the list based on the <paramref name="width"/>.</summary>
  2001. /// <remarks>
  2002. /// This API will return incorrect results if the text includes glyphs whose width is dependent on surrounding
  2003. /// glyphs (e.g. Arabic).
  2004. /// </remarks>
  2005. /// <param name="lines">The lines.</param>
  2006. /// <param name="width">The width.</param>
  2007. /// <param name="tabWidth">The number of columns used for a tab.</param>
  2008. /// <returns>The index of the list that fit the width.</returns>
  2009. public static int GetMaxColsForWidth (List<string> lines, int width, int tabWidth = 0)
  2010. {
  2011. var textLength = 0;
  2012. var lineIdx = 0;
  2013. for (; lineIdx < lines.Count; lineIdx++)
  2014. {
  2015. string [] graphemes = GraphemeHelper.GetGraphemes (lines [lineIdx]).ToArray ();
  2016. int maxTextWidth = graphemes.Length > 0
  2017. ? graphemes.Max (r => GetStringWidth (r, tabWidth))
  2018. : 1;
  2019. if (textLength + maxTextWidth > width)
  2020. {
  2021. break;
  2022. }
  2023. textLength += maxTextWidth;
  2024. }
  2025. return lineIdx;
  2026. }
  2027. /// <summary>Finds the HotKey and its location in text.</summary>
  2028. /// <param name="text">The text to look in.</param>
  2029. /// <param name="hotKeySpecifier">The HotKey specifier (e.g. '_') to look for.</param>
  2030. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  2031. /// <param name="hotKey">Outputs the hotKey. <see cref="Key.Empty"/> if not found.</param>
  2032. /// <param name="firstUpperCase">
  2033. /// If <c>true</c> the legacy behavior of identifying the first upper case character as the
  2034. /// HotKey will be enabled. Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.
  2035. /// Defaults to <see langword="false"/>.
  2036. /// </param>
  2037. /// <returns><c>true</c> if a HotKey was found; <c>false</c> otherwise.</returns>
  2038. public static bool FindHotKey (
  2039. string text,
  2040. Rune hotKeySpecifier,
  2041. out int hotPos,
  2042. out Key hotKey,
  2043. bool firstUpperCase = false
  2044. )
  2045. {
  2046. if (string.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF)
  2047. {
  2048. hotPos = -1;
  2049. hotKey = Key.Empty;
  2050. return false;
  2051. }
  2052. var curHotKey = (Rune)0;
  2053. int curHotPos = -1;
  2054. // Use first hot_key char passed into 'hotKey'.
  2055. // TODO: Ignore hot_key of two are provided
  2056. // TODO: Do not support non-alphanumeric chars that can't be typed
  2057. var i = 0;
  2058. foreach (Rune c in text.EnumerateRunes ())
  2059. {
  2060. if ((char)c.Value != 0xFFFD)
  2061. {
  2062. if (c == hotKeySpecifier)
  2063. {
  2064. curHotPos = i;
  2065. }
  2066. else if (curHotPos > -1)
  2067. {
  2068. curHotKey = c;
  2069. break;
  2070. }
  2071. }
  2072. i++;
  2073. }
  2074. // Legacy support - use first upper case char if the specifier was not found
  2075. if (curHotPos == -1 && firstUpperCase)
  2076. {
  2077. i = 0;
  2078. foreach (Rune c in text.EnumerateRunes ())
  2079. {
  2080. if ((char)c.Value != 0xFFFD)
  2081. {
  2082. if (Rune.IsUpper (c))
  2083. {
  2084. curHotKey = c;
  2085. curHotPos = i;
  2086. break;
  2087. }
  2088. }
  2089. i++;
  2090. }
  2091. }
  2092. if (curHotKey != (Rune)0 && curHotPos != -1)
  2093. {
  2094. hotPos = curHotPos;
  2095. var newHotKey = (KeyCode)curHotKey.Value;
  2096. if (newHotKey != KeyCode.Null && !(newHotKey == KeyCode.Space || Rune.IsControl (curHotKey)))
  2097. {
  2098. if ((newHotKey & ~KeyCode.Space) is >= KeyCode.A and <= KeyCode.Z)
  2099. {
  2100. newHotKey &= ~KeyCode.Space;
  2101. }
  2102. hotKey = newHotKey;
  2103. //hotKey.Scope = KeyBindingScope.HotKey;
  2104. return true;
  2105. }
  2106. }
  2107. hotPos = -1;
  2108. hotKey = KeyCode.Null;
  2109. return false;
  2110. }
  2111. /// <summary>
  2112. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying it as the
  2113. /// hotkey.
  2114. /// </summary>
  2115. /// <param name="text">The text to tag the hotkey in.</param>
  2116. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  2117. /// <returns>The text with the hotkey tagged.</returns>
  2118. /// <remarks>The returned string will not render correctly without first un-doing the tag. To undo the tag, search for</remarks>
  2119. public static string ReplaceHotKeyWithTag (string text, int hotPos)
  2120. {
  2121. // Set the high bit
  2122. List<Rune> runes = text.ToRuneList ();
  2123. if (Rune.IsLetterOrDigit (runes [hotPos]))
  2124. {
  2125. runes [hotPos] = new ((uint)runes [hotPos].Value);
  2126. }
  2127. return StringExtensions.ToString (runes);
  2128. }
  2129. /// <summary>Removes the hotkey specifier from text.</summary>
  2130. /// <param name="text">The text to manipulate.</param>
  2131. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  2132. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  2133. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  2134. public static string RemoveHotKeySpecifier (string text, int hotPos, Rune hotKeySpecifier)
  2135. {
  2136. if (string.IsNullOrEmpty (text))
  2137. {
  2138. return text;
  2139. }
  2140. const int maxStackallocCharBufferSize = 512; // ~1 kB
  2141. char []? rentedBufferArray = null;
  2142. try
  2143. {
  2144. Span<char> buffer = text.Length <= maxStackallocCharBufferSize
  2145. ? stackalloc char [text.Length]
  2146. : (rentedBufferArray = ArrayPool<char>.Shared.Rent (text.Length));
  2147. int i = 0;
  2148. var remainingBuffer = buffer;
  2149. foreach (Rune c in text.EnumerateRunes ())
  2150. {
  2151. if (c == hotKeySpecifier && i == hotPos)
  2152. {
  2153. i++;
  2154. continue;
  2155. }
  2156. int charsWritten = c.EncodeToUtf16 (remainingBuffer);
  2157. remainingBuffer = remainingBuffer [charsWritten..];
  2158. i++;
  2159. }
  2160. ReadOnlySpan<char> newText = buffer [..^remainingBuffer.Length];
  2161. // If the resulting string would be the same as original then just return the original.
  2162. if (newText.Equals (text, StringComparison.Ordinal))
  2163. {
  2164. return text;
  2165. }
  2166. return new string (newText);
  2167. }
  2168. finally
  2169. {
  2170. if (rentedBufferArray != null)
  2171. {
  2172. ArrayPool<char>.Shared.Return (rentedBufferArray);
  2173. }
  2174. }
  2175. }
  2176. #endregion // Static Members
  2177. }