TextFormatter.cs 70 KB

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