TextFormatter.cs 88 KB

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