TextFormatter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. /// Provides text formatting capabilities for console apps. Supports, hotkeys, horizontal alignment, multille lines, and word-based line wrap.
  30. /// </summary>
  31. public class TextFormatter {
  32. List<ustring> lines = new List<ustring> ();
  33. ustring text;
  34. TextAlignment textAlignment;
  35. Attribute textColor = -1;
  36. bool needsFormat;
  37. Key hotKey;
  38. Size size;
  39. /// <summary>
  40. /// The text to be displayed. This text is never modified.
  41. /// </summary>
  42. public virtual ustring Text {
  43. get => text;
  44. set {
  45. text = value;
  46. if (text.RuneCount > 0 && (Size.Width == 0 || Size.Height == 0 || Size.Width != text.RuneCount)) {
  47. // Proivde a default size (width = length of longest line, height = 1)
  48. // TODO: It might makem more sense for the default to be width = length of first line?
  49. Size = new Size (TextFormatter.MaxWidth (Text, int.MaxValue), 1);
  50. }
  51. NeedsFormat = true;
  52. }
  53. }
  54. // TODO: Add Vertical Text Alignment
  55. /// <summary>
  56. /// Controls the horizontal text-alignment property.
  57. /// </summary>
  58. /// <value>The text alignment.</value>
  59. public TextAlignment Alignment {
  60. get => textAlignment;
  61. set {
  62. textAlignment = value;
  63. NeedsFormat = true;
  64. }
  65. }
  66. /// <summary>
  67. /// Gets or sets the size of the area the text will be constrainted to when formatted.
  68. /// </summary>
  69. public Size Size {
  70. get => size;
  71. set {
  72. size = value;
  73. NeedsFormat = true;
  74. }
  75. }
  76. /// <summary>
  77. /// The specifier character for the hotkey (e.g. '_'). Set to '\xffff' to disable hotkey support for this View instance. The default is '\xffff'.
  78. /// </summary>
  79. public Rune HotKeySpecifier { get; set; } = (Rune)0xFFFF;
  80. /// <summary>
  81. /// The position in the text of the hotkey. The hotkey will be rendered using the hot color.
  82. /// </summary>
  83. public int HotKeyPos { get => hotKeyPos; set => hotKeyPos = value; }
  84. /// <summary>
  85. /// Gets the hotkey. Will be an upper case letter or digit.
  86. /// </summary>
  87. public Key HotKey { get => hotKey; internal set => hotKey = value; }
  88. /// <summary>
  89. /// Specifies the mask to apply to the hotkey to tag it as the hotkey. The default value of <c>0x100000</c> causes
  90. /// the underlying Rune to be identified as a "private use" Unicode character.
  91. /// </summary>HotKeyTagMask
  92. public uint HotKeyTagMask { get; set; } = 0x100000;
  93. /// <summary>
  94. /// Gets the cursor position from <see cref="HotKey"/>. If the <see cref="HotKey"/> is defined, the cursor will be positioned over it.
  95. /// </summary>
  96. public int CursorPosition { get; set; }
  97. /// <summary>
  98. /// Gets the formatted lines.
  99. /// </summary>
  100. /// <remarks>
  101. /// <para>
  102. /// Upon a 'get' of this property, if the text needs to be formatted (if <see cref="NeedsFormat"/> is <c>true</c>)
  103. /// <see cref="Format(ustring, int, TextAlignment, bool)"/> will be called internally.
  104. /// </para>
  105. /// </remarks>
  106. public List<ustring> Lines {
  107. get {
  108. // With this check, we protect against subclasses with overrides of Text
  109. if (ustring.IsNullOrEmpty (Text)) {
  110. lines = new List<ustring> ();
  111. lines.Add (ustring.Empty);
  112. NeedsFormat = false;
  113. return lines;
  114. }
  115. if (NeedsFormat) {
  116. var shown_text = text;
  117. if (FindHotKey (text, HotKeySpecifier, true, out hotKeyPos, out hotKey)) {
  118. shown_text = RemoveHotKeySpecifier (Text, hotKeyPos, HotKeySpecifier);
  119. shown_text = ReplaceHotKeyWithTag (shown_text, hotKeyPos);
  120. }
  121. if (Size.IsEmpty) {
  122. throw new InvalidOperationException ("Size must be set before accessing Lines");
  123. }
  124. lines = Format (shown_text, Size.Width, textAlignment, Size.Height > 1);
  125. NeedsFormat = false;
  126. }
  127. return lines;
  128. }
  129. }
  130. /// <summary>
  131. /// Gets or sets whether the <see cref="TextFormatter"/> needs to format the text when <see cref="Draw(Rect, Attribute, Attribute)"/> is called.
  132. /// If it is <c>false</c> when Draw is called, the Draw call will be faster.
  133. /// </summary>
  134. /// <remarks>
  135. /// <para>
  136. /// This is set to true when the properties of <see cref="TextFormatter"/> are set.
  137. /// </para>
  138. /// </remarks>
  139. public bool NeedsFormat { get => needsFormat; set => needsFormat = value; }
  140. static ustring StripCRLF (ustring str)
  141. {
  142. var runes = str.ToRuneList ();
  143. for (int i = 0; i < runes.Count; i++) {
  144. switch (runes [i]) {
  145. case '\n':
  146. runes.RemoveAt (i);
  147. break;
  148. case '\r':
  149. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  150. runes.RemoveAt (i);
  151. runes.RemoveAt (i + 1);
  152. i++;
  153. } else {
  154. runes.RemoveAt (i);
  155. }
  156. break;
  157. }
  158. }
  159. return ustring.Make (runes);
  160. }
  161. static ustring ReplaceCRLFWithSpace (ustring str)
  162. {
  163. var runes = str.ToRuneList ();
  164. for (int i = 0; i < runes.Count; i++) {
  165. switch (runes [i]) {
  166. case '\n':
  167. runes [i] = (Rune)' ';
  168. break;
  169. case '\r':
  170. if ((i + 1) < runes.Count && runes [i + 1] == '\n') {
  171. runes [i] = (Rune)' ';
  172. runes.RemoveAt (i + 1);
  173. i++;
  174. } else {
  175. runes [i] = (Rune)' ';
  176. }
  177. break;
  178. }
  179. }
  180. return ustring.Make (runes); ;
  181. }
  182. /// <summary>
  183. /// Formats the provided text to fit within the width provided using word wrapping.
  184. /// </summary>
  185. /// <param name="text">The text to word wrap</param>
  186. /// <param name="width">The width to contrain the text to</param>
  187. /// <returns>Returns a list of word wrapped lines.</returns>
  188. /// <remarks>
  189. /// <para>
  190. /// This method does not do any justification.
  191. /// </para>
  192. /// <para>
  193. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  194. /// </para>
  195. /// </remarks>
  196. public static List<ustring> WordWrap (ustring text, int width)
  197. {
  198. if (width < 0) {
  199. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  200. }
  201. int start = 0, end;
  202. var lines = new List<ustring> ();
  203. if (ustring.IsNullOrEmpty (text)) {
  204. return lines;
  205. }
  206. var runes = StripCRLF (text).ToRuneList ();
  207. while ((end = start + width) < runes.Count) {
  208. while (runes [end] != ' ' && end > start)
  209. end -= 1;
  210. if (end == start)
  211. end = start + width;
  212. lines.Add (ustring.Make (runes.GetRange (start, end - start)));
  213. start = end;
  214. if (runes[end] == ' ') {
  215. start++;
  216. }
  217. }
  218. if (start < text.RuneCount) {
  219. lines.Add (ustring.Make (runes.GetRange (start, runes.Count - start)));
  220. }
  221. return lines;
  222. }
  223. /// <summary>
  224. /// Justifies text within a specified width.
  225. /// </summary>
  226. /// <param name="text">The text to justify.</param>
  227. /// <param name="width">If the text length is greater that <c>width</c> it will be clipped.</param>
  228. /// <param name="talign">Alignment.</param>
  229. /// <returns>Justified and clipped text.</returns>
  230. public static ustring ClipAndJustify (ustring text, int width, TextAlignment talign)
  231. {
  232. if (width < 0) {
  233. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  234. }
  235. if (ustring.IsNullOrEmpty (text)) {
  236. return text;
  237. }
  238. var runes = text.ToRuneList ();
  239. int slen = runes.Count;
  240. if (slen > width) {
  241. return ustring.Make (runes.GetRange (0, width));
  242. } else {
  243. if (talign == TextAlignment.Justified) {
  244. return Justify (text, width);
  245. }
  246. return text;
  247. }
  248. }
  249. /// <summary>
  250. /// Justifies the text to fill the width provided. Space will be added between words (demarked by spaces and tabs) to
  251. /// make the text just fit <c>width</c>. Spaces will not be added to the ends.
  252. /// </summary>
  253. /// <param name="text"></param>
  254. /// <param name="width"></param>
  255. /// <param name="spaceChar">Character to replace whitespace and pad with. For debugging purposes.</param>
  256. /// <returns>The justifed text.</returns>
  257. public static ustring Justify (ustring text, int width, char spaceChar = ' ')
  258. {
  259. if (width < 0) {
  260. throw new ArgumentOutOfRangeException ("Width cannot be negative.");
  261. }
  262. if (ustring.IsNullOrEmpty (text)) {
  263. return text;
  264. }
  265. var words = text.Split (ustring.Make (' '));
  266. int textCount = words.Sum (arg => arg.RuneCount);
  267. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  268. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  269. var s = new System.Text.StringBuilder ();
  270. for (int w = 0; w < words.Length; w++) {
  271. var x = words [w];
  272. s.Append (x);
  273. if (w + 1 < words.Length)
  274. for (int i = 0; i < spaces; i++)
  275. s.Append (spaceChar);
  276. if (extras > 0) {
  277. extras--;
  278. }
  279. }
  280. return ustring.Make (s.ToString ());
  281. }
  282. static char [] whitespace = new char [] { ' ', '\t' };
  283. private int hotKeyPos;
  284. /// <summary>
  285. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  286. /// </summary>
  287. /// <param name="text"></param>
  288. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  289. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  290. /// <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>
  291. /// <returns>A list of word wrapped lines.</returns>
  292. /// <remarks>
  293. /// <para>
  294. /// An empty <c>text</c> string will result in one empty line.
  295. /// </para>
  296. /// <para>
  297. /// If <c>width</c> is 0, a single, empty line will be returned.
  298. /// </para>
  299. /// <para>
  300. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  301. /// </para>
  302. /// </remarks>
  303. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap)
  304. {
  305. if (width < 0) {
  306. throw new ArgumentOutOfRangeException ("width cannot be negative");
  307. }
  308. List<ustring> lineResult = new List<ustring> ();
  309. if (ustring.IsNullOrEmpty (text) || width == 0) {
  310. lineResult.Add (ustring.Empty);
  311. return lineResult;
  312. }
  313. if (wordWrap == false) {
  314. text = ReplaceCRLFWithSpace (text);
  315. lineResult.Add (ClipAndJustify (text, width, talign));
  316. return lineResult;
  317. }
  318. var runes = text.ToRuneList ();
  319. int runeCount = runes.Count;
  320. int lp = 0;
  321. for (int i = 0; i < runeCount; i++) {
  322. Rune c = runes [i];
  323. if (c == '\n') {
  324. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width);
  325. foreach (var line in wrappedLines) {
  326. lineResult.Add (ClipAndJustify (line, width, talign));
  327. }
  328. if (wrappedLines.Count == 0) {
  329. lineResult.Add (ustring.Empty);
  330. }
  331. lp = i + 1;
  332. }
  333. }
  334. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width)) {
  335. lineResult.Add (ClipAndJustify (line, width, talign));
  336. }
  337. return lineResult;
  338. }
  339. /// <summary>
  340. /// Computes the number of lines needed to render the specified text given the width.
  341. /// </summary>
  342. /// <returns>Number of lines.</returns>
  343. /// <param name="text">Text, may contain newlines.</param>
  344. /// <param name="width">The minimum width for the text.</param>
  345. public static int MaxLines (ustring text, int width)
  346. {
  347. var result = TextFormatter.Format (text, width, TextAlignment.Left, true);
  348. return result.Count;
  349. }
  350. /// <summary>
  351. /// Computes the maximum width needed to render the text (single line or multple lines) given a minimum width.
  352. /// </summary>
  353. /// <returns>Max width of lines.</returns>
  354. /// <param name="text">Text, may contain newlines.</param>
  355. /// <param name="width">The minimum width for the text.</param>
  356. public static int MaxWidth (ustring text, int width)
  357. {
  358. var result = TextFormatter.Format (text, width, TextAlignment.Left, true);
  359. return result.Max (s => s.RuneCount);
  360. }
  361. /// <summary>
  362. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  363. /// </summary>
  364. /// <param name="x">The x location of the rectangle</param>
  365. /// <param name="y">The y location of the rectangle</param>
  366. /// <param name="text">The text to measure</param>
  367. /// <returns></returns>
  368. public static Rect CalcRect (int x, int y, ustring text)
  369. {
  370. if (ustring.IsNullOrEmpty (text))
  371. return new Rect (new Point (x, y), Size.Empty);
  372. int mw = 0;
  373. int ml = 1;
  374. int cols = 0;
  375. foreach (var rune in text) {
  376. if (rune == '\n') {
  377. ml++;
  378. if (cols > mw)
  379. mw = cols;
  380. cols = 0;
  381. } else {
  382. if (rune != '\r') {
  383. cols++;
  384. }
  385. }
  386. }
  387. if (cols > mw)
  388. mw = cols;
  389. return new Rect (x, y, mw, ml);
  390. }
  391. /// <summary>
  392. /// Finds the hotkey and its location in text.
  393. /// </summary>
  394. /// <param name="text">The text to look in.</param>
  395. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  396. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be eanbled.
  397. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precidence.</param>
  398. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  399. /// <param name="hotKey">Outputs the hotKey.</param>
  400. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  401. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  402. {
  403. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  404. hotPos = -1;
  405. hotKey = Key.Unknown;
  406. return false;
  407. }
  408. Rune hot_key = (Rune)0;
  409. int hot_pos = -1;
  410. // Use first hot_key char passed into 'hotKey'.
  411. // TODO: Ignore hot_key of two are provided
  412. // TODO: Do not support non-alphanumeric chars that can't be typed
  413. int i = 0;
  414. foreach (Rune c in text) {
  415. if ((char)c != 0xFFFD) {
  416. if (c == hotKeySpecifier) {
  417. hot_pos = i;
  418. } else if (hot_pos > -1) {
  419. hot_key = c;
  420. break;
  421. }
  422. }
  423. i++;
  424. }
  425. // Legacy support - use first upper case char if the specifier was not found
  426. if (hot_pos == -1 && firstUpperCase) {
  427. i = 0;
  428. foreach (Rune c in text) {
  429. if ((char)c != 0xFFFD) {
  430. if (Rune.IsUpper (c)) {
  431. hot_key = c;
  432. hot_pos = i;
  433. break;
  434. }
  435. }
  436. i++;
  437. }
  438. }
  439. if (hot_key != (Rune)0 && hot_pos != -1) {
  440. hotPos = hot_pos;
  441. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  442. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  443. return true;
  444. }
  445. }
  446. hotPos = -1;
  447. hotKey = Key.Unknown;
  448. return false;
  449. }
  450. /// <summary>
  451. /// Replaces the Rune at the index specfiied by the <c>hotPos</c> parameter with a tag identifying
  452. /// it as the hotkey.
  453. /// </summary>
  454. /// <param name="text">The text to tag the hotkey in.</param>
  455. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  456. /// <returns>The text with the hotkey tagged.</returns>
  457. /// <remarks>
  458. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  459. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  460. /// </remarks>
  461. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  462. {
  463. // Set the high bit
  464. var runes = text.ToRuneList ();
  465. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  466. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  467. }
  468. return ustring.Make (runes);
  469. }
  470. /// <summary>
  471. /// Removes the hotkey specifier from text.
  472. /// </summary>
  473. /// <param name="text">The text to manipulate.</param>
  474. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  475. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  476. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  477. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  478. {
  479. if (ustring.IsNullOrEmpty (text)) {
  480. return text;
  481. }
  482. // Scan
  483. ustring start = ustring.Empty;
  484. int i = 0;
  485. foreach (Rune c in text) {
  486. if (c == hotKeySpecifier && i == hotPos) {
  487. i++;
  488. continue;
  489. }
  490. start += ustring.Make (c);
  491. i++;
  492. }
  493. return start;
  494. }
  495. /// <summary>
  496. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  497. /// </summary>
  498. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  499. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  500. /// <param name="hotColor">The color to use to draw the hotkey</param>
  501. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor)
  502. {
  503. // With this check, we protect against subclasses with overrides of Text (like Button)
  504. if (ustring.IsNullOrEmpty (text)) {
  505. return;
  506. }
  507. Application.Driver?.SetAttribute (normalColor);
  508. // Use "Lines" to ensure a Format (don't use "lines"))
  509. for (int line = 0; line < Lines.Count; line++) {
  510. if (line > bounds.Height)
  511. continue;
  512. var runes = lines [line].ToRunes ();
  513. int x;
  514. switch (textAlignment) {
  515. case TextAlignment.Left:
  516. case TextAlignment.Justified:
  517. x = bounds.Left;
  518. CursorPosition = hotKeyPos;
  519. break;
  520. case TextAlignment.Right:
  521. x = bounds.Right - runes.Length;
  522. CursorPosition = bounds.Width - runes.Length + hotKeyPos;
  523. break;
  524. case TextAlignment.Centered:
  525. x = bounds.Left + (bounds.Width - runes.Length) / 2;
  526. CursorPosition = (bounds.Width - runes.Length) / 2 + hotKeyPos;
  527. break;
  528. default:
  529. throw new ArgumentOutOfRangeException ();
  530. }
  531. for (var col = bounds.Left; col < bounds.Left + bounds.Width; col++) {
  532. Application.Driver?.Move (col, bounds.Top + line);
  533. var rune = (Rune)' ';
  534. if (col >= x && col < (x + runes.Length)) {
  535. rune = runes [col - x];
  536. }
  537. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  538. if (textAlignment == TextAlignment.Justified) {
  539. CursorPosition = col - bounds.Left;
  540. }
  541. Application.Driver?.SetAttribute (hotColor);
  542. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  543. Application.Driver?.SetAttribute (normalColor);
  544. } else {
  545. Application.Driver?.AddRune (rune);
  546. }
  547. }
  548. }
  549. }
  550. }
  551. }