2
0

TextFormatter.cs 15 KB

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