TextFormatter.cs 77 KB

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