TextFormatter.cs 17 KB

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