TextFormatter.cs 18 KB

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