TextFormatter.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 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 wrap</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. /// This method strips Newline ('\n' and '\r\n') sequences before processing.
  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)));
  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)));
  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. var words = text.Split (ustring.Make (' '));
  262. int textCount = words.Sum (arg => arg.RuneCount);
  263. var spaces = words.Length > 1 ? (width - textCount) / (words.Length - 1) : 0;
  264. var extras = words.Length > 1 ? (width - textCount) % words.Length : 0;
  265. var s = new System.Text.StringBuilder ();
  266. for (int w = 0; w < words.Length; w++) {
  267. var x = words [w];
  268. s.Append (x);
  269. if (w + 1 < words.Length)
  270. for (int i = 0; i < spaces; i++)
  271. s.Append (spaceChar);
  272. if (extras > 0) {
  273. extras--;
  274. }
  275. }
  276. return ustring.Make (s.ToString ());
  277. }
  278. static char [] whitespace = new char [] { ' ', '\t' };
  279. private int hotKeyPos;
  280. /// <summary>
  281. /// Reformats text into lines, applying text alignment and optionally wrapping text to new lines on word boundaries.
  282. /// </summary>
  283. /// <param name="text"></param>
  284. /// <param name="width">The width to bound the text to for word wrapping and clipping.</param>
  285. /// <param name="talign">Specifies how the text will be aligned horizontally.</param>
  286. /// <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>
  287. /// <returns>A list of word wrapped lines.</returns>
  288. /// <remarks>
  289. /// <para>
  290. /// An empty <c>text</c> string will result in one empty line.
  291. /// </para>
  292. /// <para>
  293. /// If <c>width</c> is 0, a single, empty line will be returned.
  294. /// </para>
  295. /// <para>
  296. /// If <c>width</c> is int.MaxValue, the text will be formatted to the maximum width possible.
  297. /// </para>
  298. /// </remarks>
  299. public static List<ustring> Format (ustring text, int width, TextAlignment talign, bool wordWrap)
  300. {
  301. if (width < 0) {
  302. throw new ArgumentOutOfRangeException ("width cannot be negative");
  303. }
  304. List<ustring> lineResult = new List<ustring> ();
  305. if (ustring.IsNullOrEmpty (text) || width == 0) {
  306. lineResult.Add (ustring.Empty);
  307. return lineResult;
  308. }
  309. if (wordWrap == false) {
  310. text = ReplaceCRLFWithSpace (text);
  311. lineResult.Add (ClipAndJustify (text, width, talign));
  312. return lineResult;
  313. }
  314. var runes = text.ToRuneList ();
  315. int runeCount = runes.Count;
  316. int lp = 0;
  317. for (int i = 0; i < runeCount; i++) {
  318. Rune c = runes [i];
  319. if (c == '\n') {
  320. var wrappedLines = WordWrap (ustring.Make (runes.GetRange (lp, i - lp)), width);
  321. foreach (var line in wrappedLines) {
  322. lineResult.Add (ClipAndJustify (line, width, talign));
  323. }
  324. if (wrappedLines.Count == 0) {
  325. lineResult.Add (ustring.Empty);
  326. }
  327. lp = i + 1;
  328. }
  329. }
  330. foreach (var line in WordWrap (ustring.Make (runes.GetRange (lp, runeCount - lp)), width)) {
  331. lineResult.Add (ClipAndJustify (line, width, talign));
  332. }
  333. return lineResult;
  334. }
  335. /// <summary>
  336. /// Computes the number of lines needed to render the specified text given the width.
  337. /// </summary>
  338. /// <returns>Number of lines.</returns>
  339. /// <param name="text">Text, may contain newlines.</param>
  340. /// <param name="width">The minimum width for the text.</param>
  341. public static int MaxLines (ustring text, int width)
  342. {
  343. var result = TextFormatter.Format (text, width, TextAlignment.Left, true);
  344. return result.Count;
  345. }
  346. /// <summary>
  347. /// Computes the maximum width needed to render the text (single line or multple lines) given a minimum width.
  348. /// </summary>
  349. /// <returns>Max width of lines.</returns>
  350. /// <param name="text">Text, may contain newlines.</param>
  351. /// <param name="width">The minimum width for the text.</param>
  352. public static int MaxWidth (ustring text, int width)
  353. {
  354. var result = TextFormatter.Format (text, width, TextAlignment.Left, true);
  355. return result.Max (s => s.RuneCount);
  356. }
  357. /// <summary>
  358. /// Calculates the rectangle required to hold text, assuming no word wrapping.
  359. /// </summary>
  360. /// <param name="x">The x location of the rectangle</param>
  361. /// <param name="y">The y location of the rectangle</param>
  362. /// <param name="text">The text to measure</param>
  363. /// <returns></returns>
  364. public static Rect CalcRect (int x, int y, ustring text)
  365. {
  366. if (ustring.IsNullOrEmpty (text))
  367. return new Rect (new Point (x, y), Size.Empty);
  368. int mw = 0;
  369. int ml = 1;
  370. int cols = 0;
  371. foreach (var rune in text) {
  372. if (rune == '\n') {
  373. ml++;
  374. if (cols > mw)
  375. mw = cols;
  376. cols = 0;
  377. } else {
  378. if (rune != '\r') {
  379. cols++;
  380. }
  381. }
  382. }
  383. if (cols > mw)
  384. mw = cols;
  385. return new Rect (x, y, mw, ml);
  386. }
  387. /// <summary>
  388. /// Finds the hotkey and its location in text.
  389. /// </summary>
  390. /// <param name="text">The text to look in.</param>
  391. /// <param name="hotKeySpecifier">The hotkey specifier (e.g. '_') to look for.</param>
  392. /// <param name="firstUpperCase">If <c>true</c> the legacy behavior of identifying the first upper case character as the hotkey will be eanbled.
  393. /// Regardless of the value of this parameter, <c>hotKeySpecifier</c> takes precidence.</param>
  394. /// <param name="hotPos">Outputs the Rune index into <c>text</c>.</param>
  395. /// <param name="hotKey">Outputs the hotKey.</param>
  396. /// <returns><c>true</c> if a hotkey was found; <c>false</c> otherwise.</returns>
  397. public static bool FindHotKey (ustring text, Rune hotKeySpecifier, bool firstUpperCase, out int hotPos, out Key hotKey)
  398. {
  399. if (ustring.IsNullOrEmpty (text) || hotKeySpecifier == (Rune)0xFFFF) {
  400. hotPos = -1;
  401. hotKey = Key.Unknown;
  402. return false;
  403. }
  404. Rune hot_key = (Rune)0;
  405. int hot_pos = -1;
  406. // Use first hot_key char passed into 'hotKey'.
  407. // TODO: Ignore hot_key of two are provided
  408. // TODO: Do not support non-alphanumeric chars that can't be typed
  409. int i = 0;
  410. foreach (Rune c in text) {
  411. if ((char)c != 0xFFFD) {
  412. if (c == hotKeySpecifier) {
  413. hot_pos = i;
  414. } else if (hot_pos > -1) {
  415. hot_key = c;
  416. break;
  417. }
  418. }
  419. i++;
  420. }
  421. // Legacy support - use first upper case char if the specifier was not found
  422. if (hot_pos == -1 && firstUpperCase) {
  423. i = 0;
  424. foreach (Rune c in text) {
  425. if ((char)c != 0xFFFD) {
  426. if (Rune.IsUpper (c)) {
  427. hot_key = c;
  428. hot_pos = i;
  429. break;
  430. }
  431. }
  432. i++;
  433. }
  434. }
  435. if (hot_key != (Rune)0 && hot_pos != -1) {
  436. hotPos = hot_pos;
  437. if (hot_key.IsValid && char.IsLetterOrDigit ((char)hot_key)) {
  438. hotKey = (Key)char.ToUpperInvariant ((char)hot_key);
  439. return true;
  440. }
  441. }
  442. hotPos = -1;
  443. hotKey = Key.Unknown;
  444. return false;
  445. }
  446. /// <summary>
  447. /// Replaces the Rune at the index specfiied by the <c>hotPos</c> parameter with a tag identifying
  448. /// it as the hotkey.
  449. /// </summary>
  450. /// <param name="text">The text to tag the hotkey in.</param>
  451. /// <param name="hotPos">The Rune index of the hotkey in <c>text</c>.</param>
  452. /// <returns>The text with the hotkey tagged.</returns>
  453. /// <remarks>
  454. /// The returned string will not render correctly without first un-doing the tag. To undo the tag, search for
  455. /// Runes with a bitmask of <c>otKeyTagMask</c> and remove that bitmask.
  456. /// </remarks>
  457. public ustring ReplaceHotKeyWithTag (ustring text, int hotPos)
  458. {
  459. // Set the high bit
  460. var runes = text.ToRuneList ();
  461. if (Rune.IsLetterOrNumber (runes [hotPos])) {
  462. runes [hotPos] = new Rune ((uint)runes [hotPos] | HotKeyTagMask);
  463. }
  464. return ustring.Make (runes);
  465. }
  466. /// <summary>
  467. /// Removes the hotkey specifier from text.
  468. /// </summary>
  469. /// <param name="text">The text to manipulate.</param>
  470. /// <param name="hotKeySpecifier">The hot-key specifier (e.g. '_') to look for.</param>
  471. /// <param name="hotPos">Returns the position of the hot-key in the text. -1 if not found.</param>
  472. /// <returns>The input text with the hotkey specifier ('_') removed.</returns>
  473. public static ustring RemoveHotKeySpecifier (ustring text, int hotPos, Rune hotKeySpecifier)
  474. {
  475. if (ustring.IsNullOrEmpty (text)) {
  476. return text;
  477. }
  478. // Scan
  479. ustring start = ustring.Empty;
  480. int i = 0;
  481. foreach (Rune c in text) {
  482. if (c == hotKeySpecifier && i == hotPos) {
  483. i++;
  484. continue;
  485. }
  486. start += ustring.Make (c);
  487. i++;
  488. }
  489. return start;
  490. }
  491. /// <summary>
  492. /// Draws the text held by <see cref="TextFormatter"/> to <see cref="Application.Driver"/> using the colors specified.
  493. /// </summary>
  494. /// <param name="bounds">Specifies the screen-relative location and maximum size for drawing the text.</param>
  495. /// <param name="normalColor">The color to use for all text except the hotkey</param>
  496. /// <param name="hotColor">The color to use to draw the hotkey</param>
  497. public void Draw (Rect bounds, Attribute normalColor, Attribute hotColor)
  498. {
  499. // With this check, we protect against subclasses with overrides of Text (like Button)
  500. if (ustring.IsNullOrEmpty (text)) {
  501. return;
  502. }
  503. Application.Driver?.SetAttribute (normalColor);
  504. // Use "Lines" to ensure a Format (don't use "lines"))
  505. for (int line = 0; line < Lines.Count; line++) {
  506. if (line > bounds.Height)
  507. continue;
  508. var runes = lines [line].ToRunes ();
  509. int x;
  510. switch (textAlignment) {
  511. case TextAlignment.Left:
  512. x = bounds.Left;
  513. break;
  514. case TextAlignment.Justified:
  515. x = bounds.Left;
  516. break;
  517. case TextAlignment.Right:
  518. x = bounds.Right - runes.Length;
  519. break;
  520. case TextAlignment.Centered:
  521. x = bounds.Left + (bounds.Width - runes.Length) / 2;
  522. break;
  523. default:
  524. throw new ArgumentOutOfRangeException ();
  525. }
  526. for (var col = bounds.Left; col < bounds.Left + bounds.Width; col++) {
  527. Application.Driver?.Move (col, bounds.Top + line);
  528. var rune = (Rune)' ';
  529. if (col >= x && col < (x + runes.Length)) {
  530. rune = runes [col - x];
  531. }
  532. if ((rune & HotKeyTagMask) == HotKeyTagMask) {
  533. Application.Driver?.SetAttribute (hotColor);
  534. Application.Driver?.AddRune ((Rune)((uint)rune & ~HotKeyTagMask));
  535. Application.Driver?.SetAttribute (normalColor);
  536. } else {
  537. Application.Driver?.AddRune (rune);
  538. }
  539. }
  540. }
  541. }
  542. }
  543. }