TextFormatter.cs 17 KB

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