TextFormatter.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using NStack;
  6. namespace Terminal.Gui {
  7. /// <summary>
  8. /// Text alignment enumeration, controls how text is displayed.
  9. /// </summary>
  10. public enum TextAlignment {
  11. /// <summary>
  12. /// Aligns the text to the left of the frame.
  13. /// </summary>
  14. Left,
  15. /// <summary>
  16. /// Aligns the text to the right side of the frame.
  17. /// </summary>
  18. Right,
  19. /// <summary>
  20. /// Centers the text in the frame.
  21. /// </summary>
  22. Centered,
  23. /// <summary>
  24. /// Shows the text as justified text in the frame.
  25. /// </summary>
  26. Justified
  27. }
  28. /// <summary>
  29. /// Vertical text alignment enumeration, controls how text is displayed.
  30. /// </summary>
  31. public enum VerticalTextAlignment {
  32. /// <summary>
  33. /// Aligns the text to the top of the frame.
  34. /// </summary>
  35. Top,
  36. /// <summary>
  37. /// Aligns the text to the bottom of the frame.
  38. /// </summary>
  39. Bottom,
  40. /// <summary>
  41. /// Centers the text verticaly in the frame.
  42. /// </summary>
  43. Middle,
  44. /// <summary>
  45. /// Shows the text as justified text in the frame.
  46. /// </summary>
  47. Justified
  48. }
  49. /// TextDirection [H] = Horizontal [V] = Vertical
  50. /// =============
  51. /// LeftRight_TopBottom [H] Normal
  52. /// TopBottom_LeftRight [V] Normal
  53. ///
  54. /// RightLeft_TopBottom [H] Invert Text
  55. /// TopBottom_RightLeft [V] Invert Lines
  56. ///
  57. /// LeftRight_BottomTop [H] Invert Lines
  58. /// BottomTop_LeftRight [V] Invert Text
  59. ///
  60. /// RightLeft_BottomTop [H] Invert Text + Invert Lines
  61. /// BottomTop_RightLeft [V] Invert Text + Invert Lines
  62. ///
  63. /// <summary>
  64. /// Text direction enumeration, controls how text is displayed.
  65. /// </summary>
  66. public enum TextDirection {
  67. /// <summary>
  68. /// Normal horizontal direction.
  69. /// <code>HELLO<br/>WORLD</code>
  70. /// </summary>
  71. LeftRight_TopBottom,
  72. /// <summary>
  73. /// Normal vertical direction.
  74. /// <code>H W<br/>E O<br/>L R<br/>L L<br/>O D</code>
  75. /// </summary>
  76. TopBottom_LeftRight,
  77. /// <summary>
  78. /// This is a horizontal direction. <br/> RTL
  79. /// <code>OLLEH<br/>DLROW</code>
  80. /// </summary>
  81. RightLeft_TopBottom,
  82. /// <summary>
  83. /// This is a vertical direction.
  84. /// <code>W H<br/>O E<br/>R L<br/>L L<br/>D O</code>
  85. /// </summary>
  86. TopBottom_RightLeft,
  87. /// <summary>
  88. /// This is a horizontal direction.
  89. /// <code>WORLD<br/>HELLO</code>
  90. /// </summary>
  91. LeftRight_BottomTop,
  92. /// <summary>
  93. /// This is a vertical direction.
  94. /// <code>O D<br/>L L<br/>L R<br/>E O<br/>H W</code>
  95. /// </summary>
  96. BottomTop_LeftRight,
  97. /// <summary>
  98. /// This is a horizontal direction.
  99. /// <code>DLROW<br/>OLLEH</code>
  100. /// </summary>
  101. RightLeft_BottomTop,
  102. /// <summary>
  103. /// This is a vertical direction.
  104. /// <code>D O<br/>L L<br/>R L<br/>O E<br/>W H</code>
  105. /// </summary>
  106. BottomTop_RightLeft
  107. }
  108. /// <summary>
  109. /// Provides text formatting capabilities for console apps. Supports, hotkeys, horizontal alignment, multiple lines, and word-based line wrap.
  110. /// </summary>
  111. public class TextFormatter {
  112. List<ustring> lines = new List<ustring> ();
  113. ustring text;
  114. TextAlignment textAlignment;
  115. VerticalTextAlignment textVerticalAlignment;
  116. TextDirection textDirection;
  117. Attribute textColor = -1;
  118. bool needsFormat;
  119. Key hotKey;
  120. Size size;
  121. /// <summary>
  122. /// Event invoked when the <see cref="HotKey"/> is changed.
  123. /// </summary>
  124. public event Action<Key> HotKeyChanged;
  125. /// <summary>
  126. /// The text to be displayed. This text is never modified.
  127. /// </summary>
  128. public virtual ustring Text {
  129. get => text;
  130. set {
  131. text = value;
  132. if (text.RuneCount > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != text.RuneCount)) {
  133. // Provide a default size (width = length of longest line, height = 1)
  134. // TODO: It might makes more sense for the default to be width = length of first line?
  135. Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  136. }
  137. NeedsFormat = true;
  138. }
  139. }
  140. /// <summary>
  141. /// Used by <see cref="Text"/> to resize the view's <see cref="View.Bounds"/> with the <see cref="Size"/>.
  142. /// Setting <see cref="AutoSize"/> to true only work if the <see cref="View.Width"/> and <see cref="View.Height"/> are null or
  143. /// <see cref="LayoutStyle.Absolute"/> values and doesn't work with <see cref="LayoutStyle.Computed"/> layout,
  144. /// to avoid breaking the <see cref="Pos"/> and <see cref="Dim"/> settings.
  145. /// </summary>
  146. public bool AutoSize { get; set; }
  147. // TODO: Add Vertical Text Alignment
  148. /// <summary>
  149. /// Controls the horizontal text-alignment property.
  150. /// </summary>
  151. /// <value>The text alignment.</value>
  152. public TextAlignment Alignment {
  153. get => textAlignment;
  154. set {
  155. textAlignment = value;
  156. NeedsFormat = true;
  157. }
  158. }
  159. /// <summary>
  160. /// Controls the vertical text-alignment property.
  161. /// </summary>
  162. /// <value>The text vertical alignment.</value>
  163. public VerticalTextAlignment VerticalAlignment {
  164. get => textVerticalAlignment;
  165. set {
  166. textVerticalAlignment = value;
  167. NeedsFormat = true;
  168. }
  169. }
  170. /// <summary>
  171. /// Controls the text-direction property.
  172. /// </summary>
  173. /// <value>The text vertical alignment.</value>
  174. public TextDirection Direction {
  175. get => textDirection;
  176. set {
  177. textDirection = value;
  178. NeedsFormat = true;
  179. }
  180. }
  181. /// <summary>
  182. /// Check if it is a horizontal direction
  183. /// </summary>
  184. public static bool IsHorizontalDirection (TextDirection textDirection)
  185. {
  186. switch (textDirection) {
  187. case TextDirection.LeftRight_TopBottom:
  188. case TextDirection.LeftRight_BottomTop:
  189. case TextDirection.RightLeft_TopBottom:
  190. case TextDirection.RightLeft_BottomTop:
  191. return true;
  192. default:
  193. return false;
  194. }
  195. }
  196. /// <summary>
  197. /// Check if it is a vertical direction
  198. /// </summary>
  199. public static bool IsVerticalDirection (TextDirection textDirection)
  200. {
  201. switch (textDirection) {
  202. case TextDirection.TopBottom_LeftRight:
  203. case TextDirection.TopBottom_RightLeft:
  204. case TextDirection.BottomTop_LeftRight:
  205. case TextDirection.BottomTop_RightLeft:
  206. return true;
  207. default:
  208. return false;
  209. }
  210. }
  211. /// <summary>
  212. /// Check if it is Left to Right direction
  213. /// </summary>
  214. public static bool IsLeftToRight (TextDirection textDirection)
  215. {
  216. switch (textDirection) {
  217. case TextDirection.LeftRight_TopBottom:
  218. case TextDirection.LeftRight_BottomTop:
  219. return true;
  220. default:
  221. return false;
  222. }
  223. }
  224. /// <summary>
  225. /// Check if it is Top to Bottom direction
  226. /// </summary>
  227. public static bool IsTopToBottom (TextDirection textDirection)
  228. {
  229. switch (textDirection) {
  230. case TextDirection.TopBottom_LeftRight:
  231. case TextDirection.TopBottom_RightLeft:
  232. return true;
  233. default:
  234. return false;
  235. }
  236. }
  237. /// <summary>
  238. /// Gets or sets the size of the area the text will be constrained to when formatted.
  239. /// </summary>
  240. public Size Size {
  241. get => size;
  242. set {
  243. size = value;
  244. NeedsFormat = true;
  245. }
  246. }
  247. /// <summary>
  248. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  249. /// </summary>
  250. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  251. /// <summary>
  252. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  253. /// </summary>
  254. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  255. /// <summary>
  256. /// Gets the hotkey. Will be an upper case letter or digit.
  257. /// </summary>
  258. public Key HotKey {
  259. get => hotKey;
  260. internal set {
  261. if (hotKey != value) {
  262. var oldKey = hotKey;
  263. hotKey = value;
  264. HotKeyChanged?.Invoke (oldKey);
  265. }
  266. }
  267. }
  268. /// <summary>
  269. /// Specifies the mask to apply to the hotkey to tag it as the hotkey. The default value of <c>0x100000</c> causes
  270. /// the underlying Rune to be identified as a "private use" Unicode character.
  271. /// </summary>HotKeyTagMask
  272. public uint HotKeyTagMask { get; set; } = 0x100000;
  273. /// <summary>
  274. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  275. /// </summary>
  276. public int CursorPosition { get; set; }
  277. /// <summary>
  278. /// Gets the formatted lines.
  279. /// </summary>
  280. /// <remarks>
  281. /// <para>
  282. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  283. /// <see cref="Format(ustring, int, bool, bool, bool, int)"/> will be called internally.
  284. /// </para>
  285. /// </remarks>
  286. public List<ustring> Lines {
  287. get {
  288. // With this check, we protect against subclasses with overrides of Text
  289. if (ustring.IsNullOrEmpty (Text)) {
  290. lines = new List<ustring> ();
  291. lines.Add (ustring.Empty);
  292. NeedsFormat = false;
  293. return lines;
  294. }
  295. if (NeedsFormat) {
  296. var shown_text = text;
  297. if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out Key newHotKey)) {
  298. HotKey = newHotKey;
  299. shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
  300. shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
  301. }
  302. if (Size.IsEmpty) {
  303. throw new InvalidOperationException ("Size must be set before accessing Lines");
  304. }
  305. if (IsVerticalDirection (textDirection)) {
  306. lines = Format (shown_text, Size.Height, textVerticalAlignment == VerticalTextAlignment.Justified, Size.Width > 1);
  307. if (!AutoSize && lines.Count > Size.Width) {
  308. lines.RemoveRange (Size.Width, lines.Count - Size.Width);
  309. }
  310. } else {
  311. lines = Format (shown_text, Size.Width, textAlignment == TextAlignment.Justified, Size.Height > 1);
  312. if (!AutoSize && lines.Count > Size.Height) {
  313. lines.RemoveRange (Size.Height, lines.Count - Size.Height);
  314. }
  315. }
  316. NeedsFormat = false;
  317. }
  318. return lines;
  319. }
  320. }
  321. /// <summary>
  322. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute)"/> is called.
  323. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  324. /// </summary>
  325. /// <remarks>
  326. /// <para>
  327. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  328. /// </para>
  329. /// </remarks>
  330. public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
  331. static ustring StripCRLF (ustring str)
  332. {
  333. var runes = str.ToRuneList ();
  334. for (int i = 0; i < runes.Count; i++) {
  335. switch (runes [i]) {
  336. case '\n':
  337. runes.RemoveAt (i);
  338. break;
  339. case '\r':
  340. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  341. runes.RemoveAt (i);
  342. runes.RemoveAt (i + 1);
  343. i++;
  344. } else {
  345. runes.RemoveAt (i);
  346. }
  347. break;
  348. }
  349. }
  350. return ustring.Make (runes);
  351. }
  352. static ustring ReplaceCRLFWithSpace (ustring str)
  353. {
  354. var runes = str.ToRuneList ();
  355. for (int i = 0; i < runes.Count; i++) {
  356. switch (runes [i]) {
  357. case '\n':
  358. runes [i] = (Rune)' ';
  359. break;
  360. case '\r':
  361. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  362. runes [i] = (Rune)' ';
  363. runes.RemoveAt (i + 1);
  364. i++;
  365. } else {
  366. runes [i] = (Rune)' ';
  367. }
  368. break;
  369. }
  370. }
  371. return ustring.Make (runes);
  372. }
  373. /// <summary>
  374. /// Adds trailing whitespace or truncates <paramref name="text"/>
  375. /// so that it fits exactly <paramref name="width"/> console units.
  376. /// Note that some unicode characters take 2+ columns
  377. /// </summary>
  378. /// <param name="text"></param>
  379. /// <param name="width"></param>
  380. /// <returns></returns>
  381. public static string ClipOrPad (string text, int width)
  382. {
  383. if (string.IsNullOrEmpty (text))
  384. return text;
  385. // if value is not wide enough
  386. if (text.Sum (c => Rune.ColumnWidth (c)) < width) {
  387. // pad it out with spaces to the given alignment
  388. int toPad = width - (text.Sum (c => Rune.ColumnWidth (c)));
  389. return text + new string (' ', toPad);
  390. }
  391. // value is too wide
  392. return new string (text.TakeWhile (c => (width -= Rune.ColumnWidth (c)) >= 0).ToArray ());
  393. }
  394. /// <summary>
  395. /// Formats the provided text to fit within the width provided using word wrapping.
  396. /// </summary>
  397. /// <param name="text">The text to word wrap</param>
  398. /// <param name="width">The width to contain the text to</param>
  399. /// <param name="preserveTrailingSpaces">If <c>true</c>, the wrapped text will keep the trailing spaces.
  400. /// If <c>false</c>, the trailing spaces will be trimmed.</param>
  401. /// <param name="tabWidth">The tab width.</param>
  402. /// <returns>Returns a list of word wrapped lines.</returns>
  403. /// <remarks>
  404. /// <para>
  405. /// This method does not do any justification.
  406. /// </para>
  407. /// <para>
  408. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  409. /// </para>
  410. /// </remarks>
  411. public static List<ustring> WordWrap (ustring text, int width, bool preserveTrailingSpaces = false, int tabWidth = 0)
  412. {
  413. if (width < 0) {
  414. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  415. }
  416. int start = 0, end;
  417. var lines = new List<ustring> ();
  418. if (ustring.IsNullOrEmpty (text)) {
  419. return lines;
  420. }
  421. var runes = StripCRLF (text).ToRuneList ();
  422. if (!preserveTrailingSpaces) {
  423. while ((end = start + width) < runes.Count) {
  424. while (runes [end] != ' ' && end > start)
  425. end--;
  426. if (end == start)
  427. end = start + width;
  428. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  429. start = end;
  430. if (runes [end] == ' ') {
  431. start++;
  432. }
  433. }
  434. } else {
  435. while ((end = start) < runes.Count) {
  436. end = GetNextWhiteSpace (start, width);
  437. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  438. start = end;
  439. }
  440. }
  441. int GetNextWhiteSpace (int from, int cWidth, int cLength = 0)
  442. {
  443. var to = from;
  444. var length = cLength;
  445. while (length < cWidth && to < runes.Count) {
  446. var rune = runes [to];
  447. length += Rune.ColumnWidth (rune);
  448. if (rune == ' ') {
  449. if (length == cWidth) {
  450. return to + 1;
  451. } else if (length > cWidth) {
  452. return to;
  453. } else {
  454. return GetNextWhiteSpace (to + 1, cWidth, length);
  455. }
  456. } else if (rune == '\t') {
  457. length += tabWidth + 1;
  458. if (length == tabWidth && tabWidth > cWidth) {
  459. return to + 1;
  460. } else if (length > cWidth && tabWidth > cWidth) {
  461. return to;
  462. } else {
  463. return GetNextWhiteSpace (to + 1, cWidth, length);
  464. }
  465. }
  466. to++;
  467. }
  468. if (cLength > 0 && to < runes.Count && runes [to] != ' ') {
  469. return from;
  470. } else {
  471. return to;
  472. }
  473. }
  474. if (start < text.RuneCount) {
  475. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  476. }
  477. return lines;
  478. }
  479. /// <summary>
  480. /// Justifies text within a specified width.
  481. /// </summary>
  482. /// <param name="text">The text to justify.</param>
  483. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  484. /// <param name="talign">Alignment.</param>
  485. /// <returns>Justified and clipped text.</returns>
  486. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign)
  487. {
  488. return ClipAndJustify (text, width, talign == TextAlignment.Justified);
  489. }
  490. /// <summary>
  491. /// Justifies text within a specified width.
  492. /// </summary>
  493. /// <param name="text">The text to justify.</param>
  494. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  495. /// <param name="justify">Justify.</param>
  496. /// <returns>Justified and clipped text.</returns>
  497. public static ustring ClipAndJustify (ustring text, int width, bool justify)
  498. {
  499. if (width < 0) {
  500. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  501. }
  502. if (ustring.IsNullOrEmpty (text)) {
  503. return text;
  504. }
  505. var runes = text.ToRuneList ();
  506. int slen = runes.Count;
  507. if (slen > width) {
  508. return ustring.Make (runes.GetRange (0, width));
  509. } else {
  510. if (justify) {
  511. return Justify (text, width);
  512. }
  513. return text;
  514. }
  515. }
  516. /// <summary>
  517. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  518. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  519. /// </summary>
  520. /// <param name="text"></param>
  521. /// <param name="width"></param>
  522. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  523. /// <returns>The justified text.</returns>
  524. public static ustring Justify (ustring text, int width, char spaceChar = ' ')
  525. {
  526. if (width < 0) {
  527. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  528. }
  529. if (ustring.IsNullOrEmpty (text)) {
  530. return text;
  531. }
  532. var words = text.Split (ustring.Make (' '));
  533. int textCount = words.Sum (arg => arg.RuneCount);
  534. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  535. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  536. var s = new System.Text.StringBuilder ();
  537. for (int w = 0; w < words.Length; w++) {
  538. var x = words [w];
  539. s.Append (x);
  540. if (w + 1 < words.Length)
  541. for (int i = 0; i < spaces; i++)
  542. s.Append (spaceChar);
  543. if (extras > 0) {
  544. extras--;
  545. }
  546. }
  547. return ustring.Make (s.ToString ());
  548. }
  549. static char [] whitespace = new char [] { ' ', '\t' };
  550. private int hotKeyPos;
  551. /// <summary>
  552. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  553. /// </summary>
  554. /// <param name="text"></param>
  555. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  556. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  557. /// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
  558. /// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
  559. /// <param name="tabWidth">The tab width.</param>
  560. /// <returns>A list of word wrapped lines.</returns>
  561. /// <remarks>
  562. /// <para>
  563. /// An empty <c>text</c> string will result in one empty line.
  564. /// </para>
  565. /// <para>
  566. /// If <c>width</c> is 0, a single, empty line will be returned.
  567. /// </para>
  568. /// <para>
  569. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  570. /// </para>
  571. /// </remarks>
  572. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap, bool preserveTrailingSpaces = false, int tabWidth = 0)
  573. {
  574. return Format (text, width, talign == TextAlignment.Justified, wordWrap, preserveTrailingSpaces, tabWidth);
  575. }
  576. /// <summary>
  577. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  578. /// </summary>
  579. /// <param name="text"></param>
  580. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  581. /// <param name="justify">Specifies whether the text should be justified.</param>
  582. /// <param name="wordWrap">If <c>true</c>, the text will be wrapped to new lines as need. If <c>false</c>, forces text to fit a single line. Line breaks are converted to spaces. The text will be clipped to <c>width</c></param>
  583. /// <param name="preserveTrailingSpaces">If <c>true</c> and 'wordWrap' also true, the wrapped text will keep the trailing spaces. If <c>false</c>, the trailing spaces will be trimmed.</param>
  584. /// <param name="tabWidth">The tab width.</param>
  585. /// <returns>A list of word wrapped lines.</returns>
  586. /// <remarks>
  587. /// <para>
  588. /// An empty <c>text</c> string will result in one empty line.
  589. /// </para>
  590. /// <para>
  591. /// If <c>width</c> is 0, a single, empty line will be returned.
  592. /// </para>
  593. /// <para>
  594. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  595. /// </para>
  596. /// </remarks>
  597. public static List<ustring> Format (ustring text, int width, bool justify, bool wordWrap,
  598. bool preserveTrailingSpaces = false, int tabWidth = 0)
  599. {
  600. if (width < 0) {
  601. throw new ArgumentOutOfRangeException ("width cannot be negative");
  602. }
  603. if (preserveTrailingSpaces && !wordWrap) {
  604. throw new ArgumentException ("if 'preserveTrailingSpaces' is true, then 'wordWrap' must be true either.");
  605. }
  606. List<ustring> lineResult = new List<ustring> ();
  607. if (ustring.IsNullOrEmpty (text) || width == 0) {
  608. lineResult.Add (ustring.Empty);
  609. return lineResult;
  610. }
  611. if (wordWrap == false) {
  612. text = ReplaceCRLFWithSpace (text);
  613. lineResult.Add (ClipAndJustify (text, width, justify));
  614. return lineResult;
  615. }
  616. var runes = text.ToRuneList ();
  617. int runeCount = runes.Count;
  618. int lp = 0;
  619. for (int i = 0; i < runeCount; i++) {
  620. Rune c = runes [i];
  621. if (c == '\n') {
  622. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width, preserveTrailingSpaces, tabWidth);
  623. foreach (var line in wrappedLines) {
  624. lineResult.Add (ClipAndJustify (line, width, justify));
  625. }
  626. if (wrappedLines.Count == 0) {
  627. lineResult.Add (ustring.Empty);
  628. }
  629. lp = i + 1;
  630. }
  631. }
  632. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width, preserveTrailingSpaces, tabWidth)) {
  633. lineResult.Add (ClipAndJustify (line, width, justify));
  634. }
  635. return lineResult;
  636. }
  637. /// <summary>
  638. /// Computes the number of lines needed to render the specified text given the width.
  639. /// </summary>
  640. /// <returns>Number of lines.</returns>
  641. /// <param name="text">Text, may contain newlines.</param>
  642. /// <param name="width">The minimum width for the text.</param>
  643. public static int MaxLines (ustring text, int width)
  644. {
  645. var result = TextFormatter.Format (text, width, false, true);
  646. return result.Count;
  647. }
  648. /// <summary>
  649. /// Computes the maximum width needed to render the text (single line or multiple lines) given a minimum width.
  650. /// </summary>
  651. /// <returns>Max width of lines.</returns>
  652. /// <param name="text">Text, may contain newlines.</param>
  653. /// <param name="width">The minimum width for the text.</param>
  654. public static int MaxWidth (ustring text, int width)
  655. {
  656. var result = TextFormatter.Format (text, width, false, true);
  657. var max = 0;
  658. result.ForEach (s => {
  659. var m = 0;
  660. s.ToRuneList ().ForEach (r => m += Rune.ColumnWidth (r));
  661. if (m > max) {
  662. max = m;
  663. }
  664. });
  665. return max;
  666. }
  667. /// <summary>
  668. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  669. /// </summary>
  670. /// <param name="x">The x location of the rectangle</param>
  671. /// <param name="y">The y location of the rectangle</param>
  672. /// <param name="text">The text to measure</param>
  673. /// <param name="direction">The text direction.</param>
  674. /// <returns></returns>
  675. public static Rect CalcRect (int x, int y, ustring text, TextDirection direction = TextDirection.LeftRight_TopBottom)
  676. {
  677. if (ustring.IsNullOrEmpty (text)) {
  678. return new Rect (new Point (x, y), Size.Empty);
  679. }
  680. int w, h;
  681. if (IsHorizontalDirection (direction)) {
  682. int mw = 0;
  683. int ml = 1;
  684. int cols = 0;
  685. foreach (var rune in text) {
  686. if (rune == '\n') {
  687. ml++;
  688. if (cols > mw) {
  689. mw = cols;
  690. }
  691. cols = 0;
  692. } else {
  693. if (rune != '\r') {
  694. cols++;
  695. var rw = Rune.ColumnWidth (rune);
  696. if (rw > 0) {
  697. rw--;
  698. }
  699. cols += rw;
  700. }
  701. }
  702. }
  703. if (cols > mw) {
  704. mw = cols;
  705. }
  706. w = mw;
  707. h = ml;
  708. } else {
  709. int vw = 0;
  710. int vh = 0;
  711. int rows = 0;
  712. foreach (var rune in text) {
  713. if (rune == '\n') {
  714. vw++;
  715. if (rows > vh) {
  716. vh = rows;
  717. }
  718. rows = 0;
  719. } else {
  720. if (rune != '\r') {
  721. rows++;
  722. var rw = Rune.ColumnWidth (rune);
  723. if (rw < 0) {
  724. rw++;
  725. }
  726. if (rw > vw) {
  727. vw = rw;
  728. }
  729. }
  730. }
  731. }
  732. if (rows > vh) {
  733. vh = rows;
  734. }
  735. w = vw;
  736. h = vh;
  737. }
  738. return new Rect (x, y, w, h);
  739. }
  740. /// <summary>
  741. /// Finds the hotkey and its location in text.
  742. /// </summary>
  743. /// <param name="text">The text to look in.</param>
  744. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  745. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be enabled.
  746. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precedence.</param>
  747. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  748. /// <param name="hotKey">Outputs the hotKey.</param>
  749. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  750. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  751. {
  752. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  753. hotPos = -1;
  754. hotKey = Key.Unknown;
  755. return false;
  756. }
  757. Rune hot_key = (Rune)0;
  758. int hot_pos = -1;
  759. // Use first hot_key char passed into 'hotKey'.
  760. // TODO: Ignore hot_key of two are provided
  761. // TODO: Do not support non-alphanumeric chars that can't be typed
  762. int i = 0;
  763. foreach (Rune c in text) {
  764. if ((char)c != 0xFFFD) {
  765. if (c == hotKeySpecifier) {
  766. hot_pos = i;
  767. } else if (hot_pos > -1) {
  768. hot_key = c;
  769. break;
  770. }
  771. }
  772. i++;
  773. }
  774. // Legacy support - use first upper case char if the specifier was not found
  775. if (hot_pos == -1 && firstUpperCase) {
  776. i = 0;
  777. foreach (Rune c in text) {
  778. if ((char)c != 0xFFFD) {
  779. if (Rune.IsUpper (c)) {
  780. hot_key = c;
  781. hot_pos = i;
  782. break;
  783. }
  784. }
  785. i++;
  786. }
  787. }
  788. if (hot_key != (Rune)0 && hot_pos != -1) {
  789. hotPos = hot_pos;
  790. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  791. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  792. return true;
  793. }
  794. }
  795. hotPos = -1;
  796. hotKey = Key.Unknown;
  797. return false;
  798. }
  799. /// <summary>
  800. /// Replaces the Rune at the index specified by the <c>hotPos</c> parameter with a tag identifying
  801. /// it as the hotkey.
  802. /// </summary>
  803. /// <param name="text">The text to tag the hotkey in.</param>
  804. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  805. /// <returns>The text with the hotkey tagged.</returns>
  806. /// <remarks>
  807. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  808. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  809. /// </remarks>
  810. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  811. {
  812. // Set the high bit
  813. var runes = text.ToRuneList ();
  814. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  815. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  816. }
  817. return ustring.Make (runes);
  818. }
  819. /// <summary>
  820. /// Removes the hotkey specifier from text.
  821. /// </summary>
  822. /// <param name="text">The text to manipulate.</param>
  823. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  824. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  825. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  826. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  827. {
  828. if (ustring.IsNullOrEmpty (text)) {
  829. return text;
  830. }
  831. // Scan
  832. ustring start = ustring.Empty;
  833. int i = 0;
  834. foreach (Rune c in text) {
  835. if (c == hotKeySpecifier && i == hotPos) {
  836. i++;
  837. continue;
  838. }
  839. start += ustring.Make (c);
  840. i++;
  841. }
  842. return start;
  843. }
  844. /// <summary>
  845. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  846. /// </summary>
  847. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  848. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  849. /// <param name="hotColor">The color to use to draw the hotkey</param>
  850. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor)
  851. {
  852. // With this check, we protect against subclasses with overrides of Text (like Button)
  853. if (ustring.IsNullOrEmpty (text)) {
  854. return;
  855. }
  856. Application.Driver?.SetAttribute (normalColor);
  857. // Use "Lines" to ensure a Format (don't use "lines"))
  858. var linesFormated = Lines;
  859. switch (textDirection) {
  860. case TextDirection.TopBottom_RightLeft:
  861. case TextDirection.LeftRight_BottomTop:
  862. case TextDirection.RightLeft_BottomTop:
  863. case TextDirection.BottomTop_RightLeft:
  864. linesFormated.Reverse ();
  865. break;
  866. }
  867. for (int line = 0; line < linesFormated.Count; line++) {
  868. var isVertical = IsVerticalDirection (textDirection);
  869. if ((isVertical && (line > bounds.Width)) || (!isVertical && (line > bounds.Height)))
  870. continue;
  871. var runes = lines [line].ToRunes ();
  872. switch (textDirection) {
  873. case TextDirection.RightLeft_BottomTop:
  874. case TextDirection.RightLeft_TopBottom:
  875. case TextDirection.BottomTop_LeftRight:
  876. case TextDirection.BottomTop_RightLeft:
  877. runes = runes.Reverse ().ToArray ();
  878. break;
  879. }
  880. // When text is justified, we lost left or right, so we use the direction to align.
  881. int x, y;
  882. // Horizontal Alignment
  883. if (textAlignment == TextAlignment.Right || (textAlignment == TextAlignment.Justified && !IsLeftToRight (textDirection))) {
  884. if (isVertical) {
  885. x = bounds.Right - Lines.Count + line;
  886. CursorPosition = bounds.Width - Lines.Count + hotKeyPos;
  887. } else {
  888. x = bounds.Right - runes.Length;
  889. CursorPosition = bounds.Width - runes.Length + hotKeyPos;
  890. }
  891. } else if (textAlignment == TextAlignment.Left || textAlignment == TextAlignment.Justified) {
  892. if (isVertical) {
  893. x = bounds.Left + line;
  894. } else {
  895. x = bounds.Left;
  896. }
  897. CursorPosition = hotKeyPos;
  898. } else if (textAlignment == TextAlignment.Centered) {
  899. if (isVertical) {
  900. x = bounds.Left + line + ((bounds.Width - Lines.Count) / 2);
  901. CursorPosition = (bounds.Width - Lines.Count) / 2 + hotKeyPos;
  902. } else {
  903. x = bounds.Left + (bounds.Width - runes.Length) / 2;
  904. CursorPosition = (bounds.Width - runes.Length) / 2 + hotKeyPos;
  905. }
  906. } else {
  907. throw new ArgumentOutOfRangeException ();
  908. }
  909. // Vertical Alignment
  910. if (textVerticalAlignment == VerticalTextAlignment.Bottom || (textVerticalAlignment == VerticalTextAlignment.Justified && !IsTopToBottom (textDirection))) {
  911. if (isVertical) {
  912. y = bounds.Bottom - runes.Length;
  913. } else {
  914. y = bounds.Bottom - Lines.Count + line;
  915. }
  916. } else if (textVerticalAlignment == VerticalTextAlignment.Top || textVerticalAlignment == VerticalTextAlignment.Justified) {
  917. if (isVertical) {
  918. y = bounds.Top;
  919. } else {
  920. y = bounds.Top + line;
  921. }
  922. } else if (textVerticalAlignment == VerticalTextAlignment.Middle) {
  923. if (isVertical) {
  924. var s = (bounds.Height - runes.Length) / 2;
  925. y = bounds.Top + s;
  926. } else {
  927. var s = (bounds.Height - Lines.Count) / 2;
  928. y = bounds.Top + line + s;
  929. }
  930. } else {
  931. throw new ArgumentOutOfRangeException ();
  932. }
  933. var start = isVertical ? bounds.Top : bounds.Left;
  934. var size = isVertical ? bounds.Height : bounds.Width;
  935. var current = start;
  936. for (var idx = start; idx < start + size; idx++) {
  937. if (idx < 0) {
  938. current++;
  939. continue;
  940. }
  941. var rune = (Rune)' ';
  942. if (isVertical) {
  943. Application.Driver?.Move (x, current);
  944. if (idx >= y && idx < (y + runes.Length)) {
  945. rune = runes [idx - y];
  946. }
  947. } else {
  948. Application.Driver?.Move (current, y);
  949. if (idx >= x && idx < (x + runes.Length)) {
  950. rune = runes [idx - x];
  951. }
  952. }
  953. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  954. if ((isVertical && textVerticalAlignment == VerticalTextAlignment.Justified) ||
  955. (!isVertical && textAlignment == TextAlignment.Justified)) {
  956. CursorPosition = idx - start;
  957. }
  958. Application.Driver?.SetAttribute (hotColor);
  959. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  960. Application.Driver?.SetAttribute (normalColor);
  961. } else {
  962. Application.Driver?.AddRune (rune);
  963. }
  964. current += Rune.ColumnWidth (rune);
  965. if (idx + 1 < runes.Length && current + Rune.ColumnWidth (runes [idx + 1]) > size) {
  966. break;
  967. }
  968. }
  969. }
  970. }
  971. }
  972. }