TextFormatter.cs 70 KB

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